file_path
stringlengths 32
153
| content
stringlengths 0
3.14M
|
---|---|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnWidgetClicked.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 contextlib import suppress
import omni.graph.core as og
from omni.graph.ui.ogn.OgnOnWidgetClickedDatabase import OgnOnWidgetClickedDatabase
from . import UINodeCommon
class OgnOnWidgetClicked:
@staticmethod
def internal_state():
return UINodeCommon.OgnUIEventNodeInternalState()
@staticmethod
def compute(db) -> bool:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
return True
event_name = "clicked_" + widget_identifier
if db.internal_state.first_time_subscribe(db.node, event_name):
return True
payload = db.internal_state.try_pop_event()
if payload is None:
return True
# Currently payload is an empty dictionary
db.outputs.clicked = og.ExecutionAttributeState.ENABLED
return True
# ----------------------------------------------------------------------------
@staticmethod
def release(node):
# Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing
# after the node has been released.
with suppress(og.OmniGraphError):
state = OgnOnWidgetClickedDatabase.per_node_internal_state(node)
state.release()
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/CameraState.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "CameraState.h"
#include <carb/settings/ISettings.h>
#include <omni/timeline/ITimeline.h>
#include <omni/usd/UsdUtils.h>
using namespace omni::graph::ui;
static const PXR_NS::TfToken kCenterOfInterest("omni:kit:centerOfInterest");
static bool checkPositionAndTarget(const PXR_NS::GfVec3d& position, const PXR_NS::GfVec3d& target)
{
// If position and target are coincident, fail
if ((position - target).GetLengthSq() <= std::numeric_limits<double>::epsilon())
{
return false;
}
return true;
}
static PXR_NS::GfVec3d getCameraUp(PXR_NS::UsdStageRefPtr stage)
{
PXR_NS::TfToken upAxis = PXR_NS::UsdGeomGetStageUpAxis(stage);
if (upAxis == PXR_NS::UsdGeomTokens->x)
{
return { 1, 0, 0 };
}
if (upAxis == PXR_NS::UsdGeomTokens->z)
{
return { 0, 0, 1 };
}
return { 0, 1, 0 };
}
CameraState::CameraState(PXR_NS::UsdGeomCamera camera, const PXR_NS::UsdTimeCode* time)
: m_camera(std::move(camera))
, m_timeCode(time ? *time : omni::timeline::getTimeline()->getCurrentTime() * m_camera.GetPrim().GetStage()->GetTimeCodesPerSecond())
{
}
void CameraState::getCameraPosition(carb::Double3& position) const
{
PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear();
PXR_NS::GfVec3d worldPos = worldXform.Transform(PXR_NS::GfVec3d(0, 0, 0));
position = { worldPos[0], worldPos[1], worldPos[2] };
}
void CameraState::getCameraTarget(carb::Double3& target) const
{
PXR_NS::GfVec3d localCenterOfInterest;
PXR_NS::UsdAttribute coiAttr = m_camera.GetPrim().GetAttribute(kCenterOfInterest);
if (!coiAttr || !coiAttr.Get(&localCenterOfInterest, m_timeCode))
{
localCenterOfInterest = { 0, 0, -1 };
}
PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear();
PXR_NS::GfVec3d worldCenterOfInterest = worldXform.Transform(localCenterOfInterest);
target = { worldCenterOfInterest[0], worldCenterOfInterest[1], worldCenterOfInterest[2] };
}
bool CameraState::setCameraPosition(const carb::Double3& worldPosition, bool rotate)
{
PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear();
PXR_NS::GfMatrix4d parentXform = m_camera.ComputeParentToWorldTransform(m_timeCode);
PXR_NS::GfMatrix4d invParentXform = parentXform.GetInverse();
PXR_NS::GfMatrix4d initialLocalXform = worldXform * invParentXform;
PXR_NS::GfVec3d posInParent = invParentXform.Transform(PXR_NS::GfVec3d(worldPosition.x, worldPosition.y, worldPosition.z));
PXR_NS::UsdPrim camPrim = m_camera.GetPrim();
PXR_NS::UsdAttribute coiAttr;
PXR_NS::GfVec3d prevLocalCenterOfInterest;
PXR_NS::GfMatrix4d newLocalXform;
if (rotate)
{
const PXR_NS::GfVec3d camUp = getCameraUp(camPrim.GetStage());
coiAttr = camPrim.GetAttribute(kCenterOfInterest);
if (!coiAttr || !coiAttr.Get(&prevLocalCenterOfInterest, m_timeCode))
{
prevLocalCenterOfInterest = { 0, 0, -1 };
}
PXR_NS::GfVec3d coiInParent = invParentXform.Transform(worldXform.Transform(prevLocalCenterOfInterest));
if (!checkPositionAndTarget(posInParent, coiInParent))
{
return false;
}
newLocalXform = PXR_NS::GfMatrix4d(1).SetLookAt(posInParent, coiInParent, camUp).GetInverse();
}
else
{
newLocalXform = initialLocalXform;
}
newLocalXform.SetTranslateOnly(posInParent);
omni::usd::UsdUtils::setLocalTransformMatrix(camPrim, newLocalXform, m_timeCode);
if (coiAttr)
{
PXR_NS::GfVec3d prevWorldCOI = worldXform.Transform(prevLocalCenterOfInterest);
PXR_NS::GfVec3d newLocalCOI = (newLocalXform * parentXform).GetInverse().Transform(prevWorldCOI);
omni::usd::UsdUtils::setAttribute(coiAttr, newLocalCOI, m_timeCode);
}
return true;
}
bool CameraState::setCameraTarget(const carb::Double3& worldTarget, bool rotate)
{
PXR_NS::UsdPrim camPrim = m_camera.GetPrim();
PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear();
PXR_NS::GfMatrix4d parentXform = m_camera.ComputeParentToWorldTransform(m_timeCode);
PXR_NS::GfMatrix4d invParentXform = parentXform.GetInverse();
PXR_NS::GfMatrix4d initialLocalXform = worldXform * invParentXform;
PXR_NS::GfVec3d gfWorldTarget(worldTarget.x, worldTarget.y, worldTarget.z);
PXR_NS::GfVec3d prevLocalCenterOfInterest;
PXR_NS::UsdAttribute coiAttr = camPrim.GetAttribute(kCenterOfInterest);
if (!coiAttr || !coiAttr.Get(&prevLocalCenterOfInterest, m_timeCode))
{
prevLocalCenterOfInterest = { 0, 0, -1 };
}
PXR_NS::GfVec3d posInParent = invParentXform.Transform(initialLocalXform.Transform(PXR_NS::GfVec3d(0, 0, 0)));
PXR_NS::GfMatrix4d newLocalXform;
PXR_NS::GfVec3d newLocalCenterOfInterest;
if (rotate)
{
// Rotate camera to look at new target, leaving it where it is
PXR_NS::GfVec3d camUp = getCameraUp(camPrim.GetStage());
PXR_NS::GfVec3d coiInParent = invParentXform.Transform(gfWorldTarget);
if (!checkPositionAndTarget(posInParent, coiInParent))
{
return false;
}
newLocalXform = PXR_NS::GfMatrix4d(1).SetLookAt(posInParent, coiInParent, camUp).GetInverse();
newLocalCenterOfInterest = (newLocalXform * parentXform).GetInverse().Transform(gfWorldTarget);
}
else
{
// Camera keeps orientation and distance relative to target
// Calculate movement of center-of-interest in parent's space
PXR_NS::GfVec3d targetMove = invParentXform.Transform(gfWorldTarget) - invParentXform.Transform(worldXform.Transform(prevLocalCenterOfInterest));
// Copy the camera's local transform
newLocalXform = initialLocalXform;
// And move it by the delta
newLocalXform.SetTranslateOnly(posInParent + targetMove);
}
if (rotate)
{
omni::usd::UsdUtils::setAttribute(coiAttr, newLocalCenterOfInterest, m_timeCode);
}
omni::usd::UsdUtils::setLocalTransformMatrix(camPrim, newLocalXform, m_timeCode);
return true;
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportPressed.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnOnViewportPressedDatabase.h>
#include "ViewportPressNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnOnViewportPressed
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr pressBeganSub;
carb::events::ISubscriptionPtr pressEndedSub;
ViewportPressEventPayloads eventPayloads;
ViewportPressEventStates eventStates;
} m_internalState;
static void initialize(GraphContextObj const&, NodeObj const& nodeObj)
{
OgnOnViewportPressed& state = OgnOnViewportPressedDatabase::sm_stateManagerOgnOnViewportPressed
.getState<OgnOnViewportPressed>(nodeObj.nodeHandle);
// Subscribe to press events
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.pressBeganSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kPressBeganEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnOnViewportPressed& state = OgnOnViewportPressedDatabase::sm_stateManagerOgnOnViewportPressed
.getState<OgnOnViewportPressed>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setPressBeganPayload(e->payload);
if (nodeObj.iNode->isValid(nodeObj))
nodeObj.iNode->requestCompute(nodeObj);
}
}
);
state.m_internalState.pressEndedSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kPressEndedEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnOnViewportPressed& state = OgnOnViewportPressedDatabase::sm_stateManagerOgnOnViewportPressed
.getState<OgnOnViewportPressed>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setPressEndedPayload(e->payload);
if (nodeObj.iNode->isValid(nodeObj))
nodeObj.iNode->requestCompute(nodeObj);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnOnViewportPressed& state = OgnOnViewportPressedDatabase::sm_stateManagerOgnOnViewportPressed
.getState<OgnOnViewportPressed>(nodeObj.nodeHandle);
// Unsubscribe from press events
if (state.m_internalState.pressBeganSub.get())
state.m_internalState.pressBeganSub.detach()->unsubscribe();
if (state.m_internalState.pressEndedSub.get())
state.m_internalState.pressEndedSub.detach()->unsubscribe();
}
static bool compute(OgnOnViewportPressedDatabase& db)
{
if (checkNodeDisabledForOnlyPlay(db))
return true;
OgnOnViewportPressed& state = db.internalState<OgnOnViewportPressed>();
if (state.m_internalState.eventPayloads.empty())
return true;
// Get the targeted viewport and gesture
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
char const* const gestureName = db.tokenToString(db.inputs.gesture());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
// Process event payloads and update event state
bool pressBegan = false;
for (auto const& pressBeganPayload : state.m_internalState.eventPayloads.pressBeganPayloads())
{
if (!pressBeganPayload.second.isValid)
continue;
auto& eventStateValue = state.m_internalState.eventStates[pressBeganPayload.first];
eventStateValue.pressPositionNorm = pressBeganPayload.second.pressPositionNorm;
eventStateValue.pressPositionPixel = pressBeganPayload.second.pressPositionPixel;
eventStateValue.releasePositionNorm = {0.0, 0.0};
eventStateValue.releasePositionPixel = {0.0, 0.0};
eventStateValue.isPressed = true;
eventStateValue.isReleasePositionValid = false;
if (std::strcmp(viewportWindowName, pressBeganPayload.first.viewportWindowName) == 0
&& std::strcmp(gestureName, pressBeganPayload.first.gestureName) == 0)
{
pressBegan = true;
}
}
bool pressEnded = false;
for (auto const& pressEndedPayload : state.m_internalState.eventPayloads.pressEndedPayloads())
{
if (!pressEndedPayload.second.isValid)
continue;
auto& eventStateValue = state.m_internalState.eventStates[pressEndedPayload.first];
if (eventStateValue.isPressed)
{
eventStateValue.releasePositionNorm = pressEndedPayload.second.releasePositionNorm;
eventStateValue.releasePositionPixel = pressEndedPayload.second.releasePositionPixel;
eventStateValue.isPressed = false;
eventStateValue.isReleasePositionValid = pressEndedPayload.second.isReleasePositionValid;
if (std::strcmp(viewportWindowName, pressEndedPayload.first.viewportWindowName) == 0
&& std::strcmp(gestureName, pressEndedPayload.first.gestureName) == 0)
{
pressEnded = true;
}
}
}
state.m_internalState.eventPayloads.clear();
// Get event state and set outputs
auto it = state.m_internalState.eventStates.find({viewportWindowName, gestureName});
if (it != state.m_internalState.eventStates.end())
{
if (pressEnded)
{
db.outputs.pressed() = kExecutionAttributeStateDisabled;
db.outputs.released() = kExecutionAttributeStateEnabled;
db.outputs.pressPosition() = db.inputs.useNormalizedCoords() ? it->second.pressPositionNorm : it->second.pressPositionPixel;
db.outputs.releasePosition() = db.inputs.useNormalizedCoords() ? it->second.releasePositionNorm : it->second.releasePositionPixel;
db.outputs.isReleasePositionValid() = it->second.isReleasePositionValid;
}
else if (pressBegan)
{
db.outputs.pressed() = kExecutionAttributeStateEnabled;
db.outputs.released() = kExecutionAttributeStateDisabled;
db.outputs.pressPosition() = db.inputs.useNormalizedCoords() ? it->second.pressPositionNorm : it->second.pressPositionPixel;
db.outputs.releasePosition() = {0.0, 0.0};
db.outputs.isReleasePositionValid() = false;
}
else
{
db.outputs.pressed() = kExecutionAttributeStateDisabled;
db.outputs.released() = kExecutionAttributeStateDisabled;
}
}
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnGetActiveViewportCamera.py | """
This is the implementation of the OGN node defined in OgnGetActiveViewportCamera.ogn
"""
from omni.kit.viewport.utility import get_viewport_window_camera_string
class OgnGetActiveViewportCamera:
"""
Gets a viewport's actively bound camera
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
viewport_name = db.inputs.viewport
active_camera = get_viewport_window_camera_string(viewport_name)
db.outputs.camera = active_camera
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
return True
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadViewportScrollState.ogn | {
"ReadViewportScrollState": {
"version": 1,
"description": [
"Read the state of the last viewport scroll event from the specified viewport.",
"Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."
],
"uiName": "Read Viewport Scroll State (BETA)",
"categories": ["ui"],
"inputs": {
"useNormalizedCoords": {
"type": "bool",
"description": [
"When true, the components of the 2D position output are scaled to between 0 and 1,",
"where 0 is top/left and 1 is bottom/right.",
"When false, components are in viewport render resolution pixels."
],
"uiName": "Use Normalized Coords",
"default": false
},
"viewport": {
"type": "token",
"description": "Name of the viewport window to watch for scroll events",
"uiName": "Viewport",
"default": "Viewport"
}
},
"outputs": {
"scrollValue": {
"type": "float",
"description": "The number of mouse wheel clicks scrolled up if positive, or scrolled down if negative",
"uiName": "Scroll Value"
},
"position": {
"type": "double[2]",
"description": "The last position at which a viewport scroll event occurred in the specified viewport",
"uiName": "Position"
},
"isValid": {
"type": "bool",
"description": "True if a valid event state was detected and the outputs of this node are valid, and false otherwise",
"uiName": "Is Valid"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnNewFrame.ogn | {
"OnNewFrame": {
"description": [
"Triggers when there is a new frame available for the given viewport. Note that the graph will",
"run asynchronously to the new frame event"
],
"version": 1,
"uiName": "On New Frame",
"language": "Python",
"scheduling": "compute-on-request",
"categories": ["graph:action", "event"],
"state": {
},
"inputs": {
"viewport": {
"type": "token",
"description": "Name of the viewport, or empty for the default viewport",
"metadata": {
"displayGroup": "parameters"
}
}
},
"outputs": {
"execOut": {
"type": "execution",
"description": "Output Execution"
},
"frameNumber": {
"type": "int",
"description": "The number of the frame which is available"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/UINodeCommon.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import ast
from typing import Dict, List, Optional, Tuple, Type, Union
import carb.events
import omni.client
import omni.graph.core as og
import omni.kit.app
import omni.ui as ui
import omni.usd
from omni.ui_query import OmniUIQuery
# TODO: Uncomment this when Viewport 2.0 becomes the default Viewport
# import omni.kit.viewport.window as vp
class OgnUINodeInternalState:
# This class is used by old widget nodes which have not yet been converted to use
# OgWidgetNode. It will be removed once they are all converted.
def __init__(self):
self.created_widget = None
self.created_frame = None
class OgWidgetNodeCallbacks:
"""
!!!BETA: DO NOT USE!!!
A base class for callbacks used by nodes which create omni.ui widgets.
"""
@staticmethod
def get_property_names(widget: ui.Widget, writeable: bool) -> Optional[List[str]]:
"""
Returns a dictionary containing those properties which are common to all ui.Widget.
If 'writeable' is True then only those properties whose values can be set will be
returned, otherwise only those whose value can be read will be returned.
If 'widget' is not a valid widget a warning will be issued and None returned.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to retrieve property names from non-widget object '{widget}'.")
return None
# Read/write properties
props = [
"enabled", # bool
"height", # ui.Length
"name", # str
"opaque_for_mouse_events", # bool
"selected", # bool
"skip_draw_when_clipped", # bool
"style_type_name_override", # str
"tooltip", # str
"tooltip_offset_x", # float
"tooltip_offset_y", # float
"visible", # bool
"visible_max", # float
"visible_min", # float
"width", # ui.Length
]
if not writeable:
# Read-only properties
props += [
"computed_content_height", # float
"computed_content_width", # float
"computed_height", # float
"computed_width", # float
"dragging", # bool
"identifier", # str
"screen_position_x", # float
"screen_position_y", # float
]
return props
@staticmethod
def resolve_output_property(widget: ui.Widget, property_name: str, attribute: og.Attribute) -> bool:
"""
Resolves the type of an output property based on a widget attribute.
This assumes the output attribute has the 'unvalidated' metadata set to true
Returns True on success, False on failure.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to resolve property on non-widget object '{widget}'.")
return False
widget_desc = widget.identifier or repr(widget)
if not hasattr(widget, property_name):
carb.log_warn(f"Widget '{widget_desc}' has no property '{property_name}'.")
return False
prop_value = getattr(widget, property_name)
if isinstance(prop_value, bool):
out_type = "bool"
elif isinstance(prop_value, int):
out_type = "int"
elif isinstance(prop_value, float):
out_type = "double"
elif isinstance(prop_value, (str, ui.Length, ui.Direction)):
out_type = "string"
else:
carb.log_warn(f"Cannot resolve output type: {type(prop_value)}")
return False
attr_type = og.AttributeType.type_from_ogn_type_name(out_type)
attr_type_valid = attr_type.base_type != og.BaseDataType.UNKNOWN
if attribute.get_resolved_type().base_type != og.BaseDataType.UNKNOWN and (
not attr_type_valid or attr_type != attribute.get_resolved_type()
):
attribute.set_resolved_type(og.Type(og.BaseDataType.UNKNOWN))
if attr_type_valid and attribute.get_resolved_type().base_type == og.BaseDataType.UNKNOWN:
attribute.set_resolved_type(attr_type)
return True
@staticmethod
def get_property_value(widget: ui.Widget, property_name: str, attribute: og.RuntimeAttribute) -> bool:
"""
Retrieves the value of a property from a widget and writes it to the given node attribute.
Returns True on success, False on failure.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to get property value from non-widget object '{widget}'.")
return False
widget_desc = widget.identifier or repr(widget)
if not hasattr(widget, property_name):
carb.log_warn(f"Widget '{widget_desc}' has no property '{property_name}'.")
return False
prop_value = getattr(widget, property_name)
prop_type = type(prop_value)
if prop_type in (bool, int, float, str):
try:
attribute.value = prop_value
return True
except ValueError:
pass
# XXX: To preserve the 'units' (px, fr, %) we may want to split the output of these into a (value, unit) pair
elif prop_type in (ui.Length, ui.Direction):
try:
attribute.value = str(prop_value)
return True
except ValueError:
pass
else:
carb.log_warn(f"Unsupported property type: {prop_type}")
return False
@staticmethod
def set_property_value(widget: ui.Widget, property_name: str, attribute: og.RuntimeAttribute) -> bool:
"""
Retrieves the value of a node attribute and writes it to the given widget property.
Returns True on success, False on failure.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to set property value on non-widget object '{widget}'.")
return False
widget_desc = widget.identifier or repr(widget)
if not hasattr(widget, property_name):
carb.log_warn(f"Widget '{widget_desc}' has no property '{property_name}'.")
return False
value = attribute.value
prop_type = type(getattr(widget, property_name))
if prop_type == str and property_name == "image_url":
try:
setattr(widget, property_name, resolve_image_url(prop_type(value)))
return True
except ValueError:
pass
elif prop_type in (bool, int, float, str):
try:
setattr(widget, property_name, prop_type(value))
return True
except ValueError:
pass
elif prop_type == ui.Length:
length = to_ui_length(value)
if length is not None:
try:
setattr(widget, property_name, length)
return True
except ValueError:
pass
return True
elif prop_type == ui.Direction:
direction = to_ui_direction(value)
if direction is not None:
try:
setattr(widget, property_name, direction)
return True
except ValueError:
pass
return True
else:
carb.log_warn(f"Unsupported property type: {prop_type}")
return False
if isinstance(value, str) and prop_type != str:
carb.log_warn(
f"Cannot set value onto widget '{widget_desc}' property '{property_name}': "
f"string value '{value}' cannot be converted to {prop_type}."
)
else:
carb.log_warn(
f"Cannot set value of type {type(value)} onto widget '{widget_desc}' "
f"property '{property_name}' (type {prop_type})"
)
if prop_type == ui.Length:
carb.log_warn(
f"{prop_type} properties may be set from int or float values, or from string values containing "
"an int or float optionally followed by 'px' for pixels (e.g. '5px'), 'fr' for fractional amounts "
"('0.3fr') or '%' for percentages ('30%'). If no suffix is given then 'px' is assumed."
)
return False
@staticmethod
def get_style_element_names(widget: ui.Widget, writeable: bool) -> List[str]:
"""
Returns the names of those style elements which are common to all ui.Widget.
If 'writeable' is True then only those elements whose values can be set will be
returned, otherwise only those whose value can be read will be returned.
If 'widget' is not a valid widget a warning will be issued and None returned.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to retrieve style element names from non-widget object '{widget}'.")
return None
# There are currently no style elements common to all widgets.
return []
@staticmethod
def get_style_value(widget: ui.Widget, element_name: str, attribute: og.RuntimeAttribute) -> bool:
"""
Retrieves the value of a style element from a widget and writes it to the given node attribute.
Returns True on success, False on failure.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to get style element from non-widget object '{widget}'.")
return None
# TBD
return False
@staticmethod
def set_style_value(widget: ui.Widget, element_name: str, attribute: og.RuntimeAttribute) -> bool:
"""
Retrieves the value of a style element from a node attribute and sets it on the given widget.
Returns True on success, False on failure.
"""
if not isinstance(widget, ui.Widget):
carb.log_warn(f"Attempt to set style element on non-widget object '{widget}'.")
return None
# TBD
return False
class OgWidgetNode(OgWidgetNodeCallbacks):
"""
!!!BETA: DO NOT USE!!!
A base class for nodes which create omni.ui widgets.
"""
@classmethod
def register_widget(cls, context: og.GraphContext, widget_id: str, widget: omni.ui.Widget):
"""
Register a widget by the GraphContext in which it was generated and a unique id within that context.
"""
register_widget(context, widget_id, widget, cls)
@classmethod
def deregister_widget(cls, context: og.GraphContext, widget_id: str):
"""
Deregister a previously registered widget.
"""
if context and widget_id:
remove_registered_widgets(context, widget_id)
######################################################################################################
#
# Widget Registry
#
# The widget registry provides a mapping between a widget identifier and the widget itself. Widget
# identifiers are specific to the graph context in which their widgets were created. This helps to avoid clashing
# identifiers, particularly when graphs are instanced.
#
# TODO: Internally we use the widget's full path string to identify the widget uniquely within the application.
# This is quite inefficient as it requires traversing the entire widget tree of the application each
# time we want to convert a path to a widget or vice-versa.
#
# We cannot store the widget object itself in the registry because that would increment its
# reference count and keep the widget (and its window) alive after they should have been destroyed.
#
# Using a weak reference won't work either because the widget objects we see in Python are just temporary
# wrappers around the actual C++ objects. A weak reference would be invalidated as soon as the wrapper was
# destroyed, even though the widget itself might still be alive.
#
# get_registered_widget() ensures that the widget registry for a given context does not
# grow without bound, but we still need a way to either automatically clear a widget's entry when it is
# destroyed, or completely clear the entries for a given context when that context is destroyed.
# One approach would be to have the SetViewportMode node clear the registry of all widgets in its graph
# context when it destroys its OG overlay, however since its extension doesn't depend on this one, it would
# have to monitor the loading and unloading of the omni.graph.action extension.
def register_widget(
context: og.GraphContext, widget_id: str, widget: ui.Widget, callbacks: Type[OgWidgetNodeCallbacks]
):
"""
!!!BETA: DO NOT USE!!!
Register a widget by the GraphContext in which it was generated and a unique id within that context.
'callbacks' is either a sub-class of OgWidgetNode or some other object which provides the same set of
static methods (the class methods are not necessary).
"""
if context and widget_id and widget:
path = find_widget_path(widget)
if path:
_widget_registry[(context, widget_id)] = path
_widget_callbacks[path] = callbacks
def get_registered_widget(context: og.GraphContext, widget_id: str) -> Optional[ui.Widget]:
"""
!!!BETA: DO NOT USE!!!
Returns a widget given the GraphContext in which it was created and its unique id within that context.
If there is no such widget then None is returned.
"""
path = _widget_registry.get((context, widget_id))
if path:
widget = find_widget_among_all_windows(path)
if not widget:
# This must be a deleted widget. Remove it from the registry.
remove_registered_widgets(context, widget_id)
return widget
return None
def get_registered_widgets(context: og.GraphContext = None, widget_id: str = None) -> List[ui.Widget]:
"""
!!!BETA: DO NOT USE!!!
Returns all the widgets which match the search parameters. If 'context' is None then all contexts
will be searched. If 'id' is None then all widgets within the searched context(s) will be returned.
"""
return [
find_widget_among_all_windows(path)
for (_context, _id), path in _widget_registry.items()
if (context is None or _context == context) and (widget_id is None or _id == widget_id)
]
def remove_registered_widgets(context: og.GraphContext, widget_id: str = None):
"""
!!!BETA: DO NOT USE!!!
Removes the specified widget from the registry. If 'widget_id' is not specified then all widgets
registered under the given context will be removed.
"""
if widget_id:
keys_to_remove = [(context, widget_id)]
else:
keys_to_remove = [(_ctx, _id) for (_ctx, _id) in _widget_registry if _ctx == context]
for key in keys_to_remove:
path = _widget_registry.pop(key)
_widget_callbacks.pop(path, None)
def get_widget_callbacks(widget: ui.Widget) -> Optional[Type[OgWidgetNodeCallbacks]]:
"""
!!!BETA: DO NOT USE!!!
Returns the callbacks object for a registered widget or None if no such widget is registered.
"""
return _widget_callbacks.get(find_widget_path(widget))
def get_unique_widget_identifier(db: og.Database) -> str:
"""
!!!BETA: DO NOT USE!!!
Returns a widget identifier which is unique within the current GraphContext.
The identifier is taken from the 'widgetIdentifier' input attribute, or the name
of the node if 'widgetIdentifier' is not set. If the identifier is already in
use then a suffix will be added to make it unique.
"""
base_id = db.inputs.widgetIdentifier or db.node.get_prim_path().replace("/", ":")
counter = 0
final_id = base_id
while get_registered_widget(db.abi_context, final_id) is not None:
counter += 1
final_id = base_id + "_" + str(counter)
return final_id
# Mapping between widget identifiers and widgets.
#
# Key: (graph context, widget identifier)
# Value: full path to the widget
_widget_registry: Dict[Tuple[og.GraphContext, str], str] = {}
# Callbacks to operate on per-widget data (e.g. properites)
#
# Key: full path to the widget
# Value: class object derived from OgWidgetNodeCallbacks
_widget_callbacks: Dict[str, Type[OgWidgetNodeCallbacks]] = {}
######################################################################################################
def to_ui_direction(value: str) -> ui.Direction:
"""
!!!BETA: DO NOT USE!!!
Convert the input value to a ui.Direction.
"""
if value == "LEFT_TO_RIGHT":
return ui.Direction.LEFT_TO_RIGHT
if value == "RIGHT_TO_LEFT":
return ui.Direction.RIGHT_TO_LEFT
if value == "TOP_TO_BOTTOM":
return ui.Direction.TOP_TO_BOTTOM
if value == "BOTTOM_TO_TOP":
return ui.Direction.BOTTOM_TO_TOP
if value == "BACK_TO_FRONT":
return ui.Direction.BACK_TO_FRONT
if value == "FRONT_TO_BACK":
return ui.Direction.FRONT_TO_BACK
return None
def to_ui_length(value: Union[float, int, str]) -> ui.Length:
"""
!!!BETA: DO NOT USE!!!
Convert the input value to a ui.Length.
"""
if isinstance(value, (float, int)):
return ui.Length(value)
if not isinstance(value, str):
return None
unit_type = ui.UnitType.PIXEL
if value.endswith("fr"):
unit_type = ui.UnitType.FRACTION
value = value[:-2]
elif value.endswith("%"):
unit_type = ui.UnitType.PERCENT
value = value[:-1]
elif value.endswith("px"):
value = value[:-2]
try:
return ui.Length(int(value), unit_type)
except ValueError:
try:
return ui.Length(float(value), unit_type)
except ValueError:
return None
def resolve_image_url(url: str) -> str:
if not url:
return url
edit_layer = omni.usd.get_context().get_stage().GetEditTarget().GetLayer()
if edit_layer.anonymous:
return url
return omni.client.combine_urls(edit_layer.realPath, url).replace("\\", "/")
def resolve_style_image_urls(style_dict: Optional[Dict]) -> Optional[Dict]:
if not style_dict:
return style_dict
edit_layer = omni.usd.get_context().get_stage().GetEditTarget().GetLayer()
if edit_layer.anonymous:
return style_dict
for value in style_dict.values():
if isinstance(value, dict):
url = value.get("image_url")
if url:
value["image_url"] = omni.client.combine_urls(edit_layer.realPath, url).replace("\\", "/")
return style_dict
def to_ui_style(style_string: str) -> Optional[Dict]:
"""
!!!BETA: DO NOT USE!!!
Converts a string containing a style description into a Python dictionary suitable for use with
ui.Widget.set_style().
Returns None if style_string is empty.
Raises SyntaxError if the string contains invalid style syntax.
Raises ValueError if 'style_string' is not a string.
"""
def fmt_syntax_err(err):
# Syntax errors are not very descriptive. Let's do a bit better.
msg = "Invalid style syntax"
# Don't include the message if it's just "invalid syntax".
if err.msg.lower() != "invalid syntax":
msg += " (" + err.msg + ")"
# Include the text of the line where the error was found, with an indicator at the point of the error.
# It would be nice to output this as two lines with the indicator indented beneath the error, but by the
# time the message reached the node's tooltip all such formatting would be lost. So we settle for an
# inline indicator.
text = err.text[: err.offset] + "^^^" + err.text[err.offset :]
# If the line is too long, elide the start and/or end of it.
if len(text) > 50:
right = min(err.offset + 25, len(text))
left = max(right - 50, 0)
if len(text) - right > 5:
text = text[:right] + "..."
if left > 5:
text = "..." + text[left:]
# Include the line number and offset so that the callers don't all have to do it themselves.
return msg + f": line {err.lineno} offset {err.offset}: " + text
def fmt_value_err(err):
# Value errors generally reflect some bad internal state of the parser. They only give us a message with
# no indication of where in input the error occurred.
return f"Invalid style syntax ({err.args[0]})."
if not style_string:
return None
if not isinstance(style_string, str):
raise ValueError(f"Style must be a string, not type {type(style_string)}.")
try:
return resolve_style_image_urls(ast.literal_eval(style_string))
except SyntaxError as err:
err.msg = fmt_syntax_err(err)
raise
except ValueError as err:
syn_err = SyntaxError(fmt_value_err(err))
syn_err.text = style_string
raise syn_err from err
######################################################################################################
# All code in this block deal with Viewport 1.0
# TODO: Remove this block of code when Viewport 2.0 becomes the default Viewport
def _parse_input(query, search_among_all_windows=False):
"""A variation of OmniUIQuery._parse_input that allows you to search among all windows with the same name"""
tokens = query.split("//")
window_name = tokens[0] if len(tokens) > 1 else None
widget_predicate = ""
widget_part = tokens[1] if len(tokens) > 1 else tokens[0]
widget_part_list = widget_part.split(".", maxsplit=1)
widget_path = widget_part_list[0]
if len(widget_part_list) > 1:
widget_predicate = widget_part_list[1]
window = None
if window_name:
windows = ui.Workspace.get_windows()
window_list = []
for window in windows:
if window.title == window_name:
window_list.append(window)
if not window_list:
carb.log_warn(f"Failed to find window: '{window_name}'")
return False, None, [], widget_predicate
if search_among_all_windows:
window = []
for current_window in window_list:
if isinstance(current_window, ui.Window):
window.append(current_window)
if len(window) == 0:
carb.log_warn(f"Failed to find a ui.Window named {window_name}, query only works on ui.Window")
return False, None, [], widget_predicate
else:
if len(window_list) == 1:
window = window_list[0]
else:
carb.log_warn(
f"found {len(window_list)} windows named '{window_name}'. Using first visible window found"
)
window = None
for win in window_list:
if win.visible:
window = win
break
if not window:
carb.log_warn(f"Failed to find visible window: '{window_name}'")
return False, None, [], widget_predicate
if not isinstance(window, ui.Window) and not isinstance(window, ui.ToolBar):
carb.log_warn(f"window: {window_name} is not a ui.Window, query only works on ui.Window")
return False, None, [], widget_predicate
widget_tokens = widget_path.split("/")
if window and not (widget_tokens[0] == "Frame" or widget_tokens[0] == "Frame[0]"):
carb.log_warn("Query with a window currently only supports '<WindowName>//Frame/*' type query")
return False, None, [], widget_predicate
if widget_tokens[-1] == "":
widget_tokens = widget_tokens[:-1]
return True, window, widget_tokens, widget_predicate
def __search_for_widget_in_window(window: ui.Window, widget_tokens: List[str]) -> Optional[ui.Widget]:
current_child = window.frame
for token in widget_tokens[1:]:
child = OmniUIQuery._child_widget(current_child, token, show_warnings=False) # noqa: PLW0212
if not child: # Unable to find the widget in the current window
return None
current_child = child
return current_child
def find_widget_among_all_windows(query):
"""Find a single widget given a full widget path.
If there are multiple windows with the same name, search among all of them."""
validate_status, windows, widget_tokens, _ = _parse_input(query, search_among_all_windows=True)
if not validate_status:
return None
if len(widget_tokens) == 1:
return windows[0].frame
for window in windows:
search_result = __search_for_widget_in_window(window, widget_tokens)
if search_result is not None:
return search_result
return None
def get_widget_window(widget_or_path: Union[ui.Widget, str]) -> Optional[ui.Window]:
if isinstance(widget_or_path, ui.Widget):
for window in ui.Workspace.get_windows():
if isinstance(window, ui.Window) and OmniUIQuery.get_widget_path(window, widget_or_path) is not None:
return window
elif isinstance(widget_or_path, str):
found_it, windows, widget_tokens, _ = _parse_input(widget_or_path, search_among_all_windows=True)
if not found_it:
return None
if len(widget_tokens) == 1:
return windows[0]
for window in windows:
search_result = __search_for_widget_in_window(window, widget_tokens)
if search_result is not None:
return window
return None
def get_parent_widget(db: og.Database):
"""Given the path to the parent widget db.inputs.parentWidgetPath, find the parent widget at that path.
If the path is empty, then the parent widget will be the viewport frame."""
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
# This widget is a direct child of the viewport frame
if not hasattr(db.internal_state, "window"):
db.internal_state.window = ui.Window("Viewport")
db.internal_state.window.visible = True
parent_widget = db.internal_state.window.frame
return parent_widget
# This widget is nested under some other widget
parent_widget = find_widget_among_all_windows(parent_widget_path)
if not parent_widget:
db.log_error("Cannot find the parent widget at the specified path!")
return None
return parent_widget
def find_widget_path(widget: ui.Widget):
"""Find the path to the widget. Search among all windows."""
for window in ui.Workspace.get_windows():
if isinstance(window, ui.Window):
query_result = OmniUIQuery.get_widget_path(window, widget)
if query_result is not None:
return query_result
return None
######################################################################################################
# All code in this block deal with Viewport 2.0
# TODO: Uncomment this block of code when Viewport 2.0 becomes the default Viewport
# def get_unique_frame_identifier(db):
# """Return a unique identifier for the created viewport frame"""
# unique_widget_identifier = get_unique_widget_identifier(db)
# return "omni.graph.action.ui_node." + unique_widget_identifier
#
#
# def get_default_viewport_window():
# default_viewport_name = vp.ViewportWindowExtension.WINDOW_NAME
# for window in vp.get_viewport_window_instances():
# if window.name == default_viewport_name:
# return window
# return None
#
#
# def get_parent_widget(db):
# """Given the path to the parent widget db.inputs.parentWidgetPath, find the parent widget at that path.
# If the path is empty, then the parent widget will be the viewport frame."""
# parent_widget_path = db.inputs.parentWidgetPath
#
# if not parent_widget_path:
# # This widget is a direct child of the viewport frame
# viewport_window = get_default_viewport_window()
# if not viewport_window:
# db.log_error("Cannot find the default viewport window!")
# return None
# frame_identifier = get_unique_frame_identifier(db)
# viewport_frame = viewport_window.get_frame(frame_identifier)
# return viewport_frame
#
# else:
# # This widget is nested under some other widget
# parent_widget = OmniUIQuery.find_widget(parent_widget_path)
# if not parent_widget:
# db.log_error("Cannot find the parent widget at the specified path!")
# return None
# return parent_widget
#
#
# def find_widget_path(widget: ui.Widget):
# """Given a widget in the default viewport window, find the path to the widget"""
# viewport_window = get_default_viewport_window()
# if not viewport_window:
# return None
# return OmniUIQuery.get_widget_path(viewport_window, widget)
######################################################################################################
def tear_down_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot tear down a widget that has not been created")
return False
# Since ui.Frame can only have one child, this code effectively replaces the previous child of ui.Frame
# with an empty ui.Placer, and the previous child will be automatically garbage collected.
# Due to the limitations of omni.ui, we cannot remove child widgets from the parent, so this is the best we can do.
db.internal_state.created_widget = None
with db.internal_state.created_frame:
ui.Placer()
db.internal_state.created_frame = None
db.outputs.created = og.ExecutionAttributeState.DISABLED
db.outputs.widgetPath = ""
return True
def show_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot show a widget that has not been created")
return False
db.internal_state.created_widget.visible = True
db.outputs.created = og.ExecutionAttributeState.DISABLED
# Keep db.outputs.widgetPath unchanged
return True
def hide_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot hide a widget that has not been created")
return False
db.internal_state.created_widget.visible = False
db.outputs.created = og.ExecutionAttributeState.DISABLED
# Keep db.outputs.widgetPath unchanged
return True
def enable_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot enable a widget that has not been created")
return False
db.internal_state.created_widget.enabled = True
db.outputs.created = og.ExecutionAttributeState.DISABLED
# Keep db.outputs.widgetPath unchanged
return True
def disable_widget(db: og.Database) -> bool:
if db.internal_state.created_widget is None:
db.log_error("Cannot disable a widget that has not been created")
return False
db.internal_state.created_widget.enabled = False
db.outputs.created = og.ExecutionAttributeState.DISABLED
# Keep db.outputs.widgetPath unchanged
return True
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)
class OgnUIEventNodeInternalState:
def __init__(self):
"""Instantiate the per-node state information."""
# This subscription object controls the lifetime of our callback,
# it will be cleaned up automatically when our node is destroyed
self.sub = None
# Set when the callback has triggered
self.is_set = False
# The last payload received
self.payload = None
# The event name we used to subscribe
self.sub_event_name = ""
# The node instance handle
self.node = None
def on_event(self, custom_event):
"""The event callback"""
if custom_event is None:
return
self.is_set = True
self.payload = custom_event.payload
# Tell the evaluator we need to be computed
if self.node.is_valid():
self.node.request_compute()
def first_time_subscribe(self, node: og.Node, event_name: str) -> bool:
"""Checked call to set up carb subscription
Args:
node: The node instance
event_name: The name of the carb event
Returns:
True if we subscribed, False if we are already subscribed
"""
if self.sub is not None and self.sub_event_name != event_name:
# event name changed since we last subscribed, unsubscribe
self.sub.unsubscribe()
self.sub = None
if self.sub is None:
# Add a subscription for the given event name. This is a pop subscription,
# so we expect a 1-frame lag between send and receive
reg_event_name = registered_event_name(event_name)
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self.sub = message_bus.create_subscription_to_pop_by_type(reg_event_name, self.on_event)
self.sub_event_name = event_name
self.node = node
return True
return False
def try_pop_event(self):
"""Pop the payload of the last event received, or None if there is no event to pop"""
if self.is_set:
self.is_set = False
payload = self.payload
self.payload = None
return payload
return None
def release(self):
# Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing
# after the node has been released.
if self.sub:
self.sub.unsubscribe()
self.sub = None
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadPickState.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnReadPickStateDatabase.h>
#include "PickingNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/relationship.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <omni/graph/core/PostUsdInclude.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnReadPickState
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr pickingSub;
PickingEventPayloads eventPayloads;
} m_internalState;
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
OgnReadPickState& state = OgnReadPickStateDatabase::sm_stateManagerOgnReadPickState
.getState<OgnReadPickState>(nodeObj.nodeHandle);
// Subscribe to picking events
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.pickingSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kPickingEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadPickState& state = OgnReadPickStateDatabase::sm_stateManagerOgnReadPickState
.getState<OgnReadPickState>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setPayload(e->payload);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnReadPickState& state = OgnReadPickStateDatabase::sm_stateManagerOgnReadPickState
.getState<OgnReadPickState>(nodeObj.nodeHandle);
// Unsubscribe from picking events
if (state.m_internalState.pickingSub.get())
state.m_internalState.pickingSub.detach()->unsubscribe();
}
static bool compute(OgnReadPickStateDatabase& db)
{
OgnReadPickState& state = db.internalState<OgnReadPickState>();
// Get the targeted viewport and gesture
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
char const* const gestureName = db.tokenToString(db.inputs.gesture());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
auto const* eventPayloadValuePtr = state.m_internalState.eventPayloads.getPayloadValue(viewportWindowName, gestureName);
if (eventPayloadValuePtr)
{
// Get the picked path and pos for the targeted viewport and gesture
char const* const pickedPrimPath = eventPayloadValuePtr->pickedPrimPath;
pxr::GfVec3d const& pickedWorldPos = eventPayloadValuePtr->pickedWorldPos;
// Determine if a tracked prim is picked
bool isTrackedPrimPicked;
// First determine if any prim is picked
bool const isAnyPrimPicked = pickedPrimPath && pickedPrimPath[0] != '\0';
if (isAnyPrimPicked)
{
// If any prim is picked, determine if the picked prim is tracked
if (db.inputs.usePaths())
{
// Get the list of tracked prims from the path[] input
auto& inputPaths = db.inputs.trackedPrimPaths();
// If no tracked prims are specified then we consider all prims to be tracked
// Else search the list of tracked prims for the picked prim
if (inputPaths.empty())
isTrackedPrimPicked = true;
else
isTrackedPrimPicked = std::any_of(inputPaths.begin(), inputPaths.end(),
[&db, pickedPrimPath](NameToken const& path) {
return (std::strcmp(db.tokenToString(path), pickedPrimPath) == 0);
});
}
else
{
// Get the list of tracked prims from the bundle input
pxr::SdfPathVector inputPaths;
long int stageId = db.abi_context().iContext->getStageId(db.abi_context());
pxr::UsdStageRefPtr stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
auto nodeObj = db.abi_node();
pxr::UsdPrim nodePrim = stage->GetPrimAtPath(pxr::SdfPath(nodeObj.iNode->getPrimPath(nodeObj)));
nodePrim.GetRelationship(kTrackedPrimsRelToken).GetTargets(&inputPaths);
// If no tracked prims are specified then we consider all prims to be tracked
// Else search the list of tracked prims for the picked prim
if (inputPaths.empty())
isTrackedPrimPicked = true;
else
isTrackedPrimPicked = std::any_of(inputPaths.begin(), inputPaths.end(),
[pickedPrimPath](pxr::SdfPath const& path) {
return (std::strcmp(path.GetText(), pickedPrimPath) == 0);
});
}
}
else
{
// No prim is picked at all, so a tracked prim certainly isn't picked
isTrackedPrimPicked = false;
}
// Set outputs
db.outputs.pickedPrimPath() = db.stringToToken(pickedPrimPath);
db.outputs.pickedWorldPos() = pickedWorldPos;
db.outputs.isTrackedPrimPicked() = isTrackedPrimPicked;
db.outputs.isValid() = true;
}
else
{
db.outputs.pickedPrimPath() = db.stringToToken("");
db.outputs.pickedWorldPos() = {0, 0, 0};
db.outputs.isTrackedPrimPicked() = false;
db.outputs.isValid() = false;
}
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnPlacer.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 typing import List, Optional
import carb
import omni.graph.core as og
import omni.ui as ui
from . import UINodeCommon
class OgnPlacer(UINodeCommon.OgWidgetNode):
@staticmethod
def compute(db) -> bool:
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
(position_x, position_y) = db.inputs.position
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
db.log_error("No parentWidgetPath supplied.")
return False
parent_widget = UINodeCommon.find_widget_among_all_windows(parent_widget_path)
if parent_widget is None:
db.log_error("Could not find parent widget.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
with parent_widget:
placer = ui.Placer(offset_x=position_x, offset_y=position_y)
if style:
placer.set_style(style)
OgnPlacer.register_widget(db.abi_context, widget_identifier, placer)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(placer)
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
@staticmethod
def get_property_names(placer: ui.Placer, writeable: bool) -> Optional[List[str]]:
props = super(OgnPlacer, OgnPlacer).get_property_names(placer, writeable)
if props is not None:
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to retrieve property names from non-placer object '{placer}'.")
return None
props += [
"drag_axis", # ui.Axis
"draggable", # bool
"frames_to_start_drag", # int
"offset_x", # ui.Length
"offset_y", # ui.Length
"stable_size", # bool
]
return props
@staticmethod
def get_property_value(placer: ui.Placer, property_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to get value of property {property_name} on non-placer object '{placer}'.")
return False
if property_name not in OgnPlacer.get_property_names(placer, False):
carb.log_warn(f"'{property_name}' is not a readable property of placer '{placer.identifier}'")
return False
return super(OgnPlacer, OgnPlacer).get_property_value(placer, property_name, attribute)
@staticmethod
def set_property_value(placer: ui.Placer, property_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to set value of property {property_name} on non-placer object '{placer}'.")
return False
if property_name not in OgnPlacer.get_property_names(placer, True):
carb.log_warn(f"'{property_name}' is not a writeable property of placer '{placer.identifier}'")
return False
return super(OgnPlacer, OgnPlacer).set_property_value(placer, property_name, attribute)
@staticmethod
def get_style_element_names(placer: ui.Placer, writeable: bool) -> List[str]:
element_names = super(OgnPlacer, OgnPlacer).get_style_element_names(placer, writeable)
if element_names is not None: # noqa: SIM102
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to retrieve style element names from non-placer widget '{placer}'.")
return None
# TBD
return element_names
@staticmethod
def get_style_value(placer: ui.Placer, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to get style element from non-placer object '{placer}'.")
return False
return super(OgnPlacer, OgnPlacer).get_style_value(placer, element_name, attribute)
@staticmethod
def set_style_value(placer: ui.Placer, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(placer, ui.Placer):
carb.log_warn(f"Attempt to set style element on non-placer object '{placer}'.")
return False
return super(OgnPlacer, OgnPlacer).set_style_value(placer, element_name, attribute)
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadWidgetProperty.ogn | {
"ReadWidgetProperty": {
"version": 1,
"description": ["Read the value of a widget's property (height, tooltip, etc)."],
"uiName": "Read Widget Property (BETA)",
"language": "Python",
"categories": ["graph:action", "ui"],
"scheduling": "global-write",
"inputs": {
"widgetIdentifier": {
"type": "token",
"description": "Unique identifier for the widget. This is only valid within the current graph.",
"uiName": "Widget Identifier"
},
"widgetPath": {
"type": "token",
"description": [
"Full path to the widget. If present this will be used insted of 'widgetIdentifier'.",
"Unlike 'widgetIdentifier' this is valid across all graphs."
],
"uiName": "Widget Path"
},
"propertyName": {
"type": "token",
"description": "Name of the property to read.",
"uiName": "Property Name"
}
},
"outputs": {
"value": {
"type": ["bool", "int", "double", "string"],
"description": "The value of the property.",
"uiName": "Value",
"unvalidated": true
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportScrolled.ogn | {
"OnViewportScrolled": {
"version": 1,
"description": [
"Event node which fires when a viewport scroll event occurs in the specified viewport.",
"Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."
],
"uiName": "On Viewport Scrolled (BETA)",
"categories": ["graph:action", "ui"],
"scheduling": "compute-on-request",
"inputs": {
"useNormalizedCoords": {
"type": "bool",
"description": [
"When true, the components of the 2D position output are scaled to between 0 and 1,",
"where 0 is top/left and 1 is bottom/right.",
"When false, components are in viewport render resolution pixels."
],
"uiName": "Use Normalized Coords",
"default": false,
"metadata": {
"literalOnly": "1"
}
},
"viewport": {
"type": "token",
"description": "Name of the viewport window to watch for scroll events",
"uiName": "Viewport",
"default": "Viewport",
"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": {
"scrolled": {
"type": "execution",
"description": "Enabled when a viewport scroll event occurs in the specified viewport",
"uiName": "Scrolled"
},
"scrollValue": {
"type": "float",
"description": "The number of mouse wheel clicks scrolled up if positive, or scrolled down if negative",
"uiName": "Scroll Value"
},
"position": {
"type": "double[2]",
"description": "The position at which the viewport scroll event occurred",
"uiName": "Position"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadWindowSize.ogn | {
"ReadWindowSize": {
"version": 1,
"description": "Outputs the size of a UI window.",
"uiName": "Read Window Size (BETA)",
"language": "Python",
"categories": ["ui"],
"scheduling": "global-read",
"inputs": {
"name": {
"type": "token",
"description": [
"Name of the window. If there are multiple windows with the same name",
"the first one found will be used."
],
"uiName": "Name",
"optional": true
},
"widgetPath": {
"type": "token",
"description": [
"Full path to a widget in the window. If specified then 'name' will be ignored and",
"the window containing the widget will be used."
],
"uiName": "Widget Path",
"optional": true
},
"isViewport": {
"type": "bool",
"description": "If true then only viewport windows will be considered.",
"uiName": "Is Viewport?",
"default": false,
"optional": true
}
},
"outputs": {
"height": {
"type": "float",
"description": "Height of the window in pixels.",
"uiName": "Height"
},
"width": {
"type": "float",
"description": "Width of the window in pixels.",
"uiName": "Width"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportScrollNodeCommon.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "UINodeCommon.h"
namespace omni
{
namespace graph
{
namespace ui
{
constexpr carb::events::EventType kScrollEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.scroll");
class ViewportScrollEventPayloads
{
public:
struct Key
{
char const* viewportWindowName;
bool operator<(Key const& other) const
{
return std::strcmp(viewportWindowName, other.viewportWindowName) < 0;
}
};
struct Value
{
pxr::GfVec2d positionNorm;
pxr::GfVec2d positionPixel;
float scrollValue;
bool isValid;
};
// Store an event payload as a key-value pair
void setPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {
stringMemo.lookup(idict->get<char const*>(payload, "viewport"))
};
payloadMap[key] = Value {
pxr::GfVec2d {
idict->get<double>(payload, "pos_norm_x"),
idict->get<double>(payload, "pos_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "pos_pixel_x"),
idict->get<double>(payload, "pos_pixel_y")
},
idict->get<float>(payload, "scroll"),
true
};
}
// Retrieve a payload value by key
Value const* getPayloadValue(char const* viewportWindowName)
{
auto it = payloadMap.find({viewportWindowName});
if (it != payloadMap.end() && it->second.isValid)
{
return &(it->second);
}
return nullptr;
}
// Invalidate all stored payloads
void clear()
{
for (auto& p : payloadMap) {
p.second.isValid = false;
}
}
// Check if there exists a valid payload
bool empty()
{
return std::none_of(payloadMap.begin(), payloadMap.end(),
[](auto const& p) {
return p.second.isValid;
});
}
private:
std::map<Key, Value> payloadMap;
StringMemo stringMemo;
};
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnWidgetClicked.ogn | {
"OnWidgetClicked": {
"version": 1,
"description": [
"Event node which fires when a UI widget with the specified identifier is clicked.",
"This node should be used in combination with UI creation nodes such as OgnButton."
],
"uiName": "On Widget Clicked (BETA)",
"language": "Python",
"categories": ["graph:action", "ui"],
"scheduling": "compute-on-request",
"inputs": {
"widgetIdentifier": {
"type": "token",
"description": [
"A unique identifier identifying the widget.",
"This should be specified in the UI creation node such as OgnButton."
],
"uiName": "Widget Identifier",
"metadata": {
"literalOnly": "1"
}
}
},
"outputs": {
"clicked": {
"type": "execution",
"description": "Executed when the widget is clicked",
"uiName": "Clicked"
}
},
"state": {
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnVStack.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 typing import List, Optional
import carb
import omni.graph.core as og
import omni.ui as ui
from . import UINodeCommon
class OgnVStack(UINodeCommon.OgWidgetNode):
@staticmethod
def compute(db) -> bool:
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
direction = UINodeCommon.to_ui_direction(db.inputs.direction)
if not direction:
db.log_warning("Unexpected direction input")
return False
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
db.log_error("No parentWidgetPath supplied.")
return False
parent_widget = UINodeCommon.find_widget_among_all_windows(parent_widget_path)
if parent_widget is None:
db.log_error("Could not find parent widget.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
with parent_widget:
stack = ui.Stack(direction, identifier=widget_identifier)
if style:
stack.set_style(style)
OgnVStack.register_widget(db.abi_context, widget_identifier, stack)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(stack)
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
@staticmethod
def get_property_names(stack: ui.Stack, writeable: bool) -> Optional[List[str]]:
props = super(OgnVStack, OgnVStack).get_property_names(stack, writeable)
if props is not None:
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to retrieve property names from non-stack object '{stack}'.")
return None
props += ["content_clipping", "direction", "spacing"] # bool # str # float
return props
@staticmethod
def resolve_output_property(stack: ui.Stack, property_name: str, attribute: og.Attribute) -> bool:
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to resolve property on non-stack object '{stack}'.")
return False
if property_name not in OgnVStack.get_property_names(stack, False):
carb.log_warn(f"'{property_name}' is not a readable property of stack '{stack.identifier}'")
return False
return super(OgnVStack, OgnVStack).resolve_output_property(stack, property_name, attribute)
@staticmethod
def get_property_value(stack: ui.Stack, property_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to get value of property {property_name} on non-stack object '{stack}'.")
return False
if property_name not in OgnVStack.get_property_names(stack, False):
carb.log_warn(f"'{property_name}' is not a readable property of stack '{stack.identifier}'")
return False
return super(OgnVStack, OgnVStack).get_property_value(stack, property_name, attribute)
@staticmethod
def set_property_value(stack: ui.Stack, property_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to set value of property {property_name} on non-stack object '{stack}'.")
return False
if property_name not in OgnVStack.get_property_names(stack, True):
carb.log_warn(f"'{property_name}' is not a writeable property of stack '{stack.identifier}'")
return False
return super(OgnVStack, OgnVStack).set_property_value(stack, property_name, attribute)
@staticmethod
def get_style_element_names(stack: ui.Stack, writeable: bool) -> List[str]:
element_names = super(OgnVStack, OgnVStack).get_style_element_names(stack, writeable)
if element_names is not None: # noqa: SIM102
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to retrieve style element names from non-stack widget '{stack}'.")
return None
# TBD
return element_names
@staticmethod
def get_style_value(stack: ui.Stack, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to get style element from non-stack object '{stack}'.")
return False
return super(OgnVStack, OgnVStack).get_style_value(stack, element_name, attribute)
@staticmethod
def set_style_value(stack: ui.Stack, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(stack, ui.Stack):
carb.log_warn(f"Attempt to set style element on non-stack object '{stack}'.")
return False
return super(OgnVStack, OgnVStack).set_style_value(stack, element_name, attribute)
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnButton.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 typing import List, Optional
import carb
import omni.graph.core as og
import omni.kit.app
import omni.ui as ui
from . import UINodeCommon
class OgnButton(UINodeCommon.OgWidgetNode):
@staticmethod
def compute(db) -> bool:
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
start_hidden = db.inputs.startHidden
text = db.inputs.text
(size_x, size_y) = db.inputs.size
if size_x < 0 or size_y < 0:
db.log_error("The size of the widget cannot be negative!")
return False
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
db.log_error("No parentWidgetPath supplied.")
return False
parent_widget = UINodeCommon.find_widget_among_all_windows(parent_widget_path)
if parent_widget is None:
db.log_error("Could not find parent widget.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
def on_button_clicked():
widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier)
if not widget or not widget.enabled:
return
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
event_name = "clicked_" + widget_identifier
reg_event_name = UINodeCommon.registered_event_name(event_name)
message_bus.push(reg_event_name)
# Now create the button widget and register callbacks
with parent_widget:
button = ui.Button(
text, identifier=widget_identifier, width=size_x, height=size_y, visible=not start_hidden
)
button.set_clicked_fn(on_button_clicked)
if style:
button.set_style(style)
OgnButton.register_widget(db.abi_context, widget_identifier, button)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(button)
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
@staticmethod
def get_property_names(button: ui.Button, writeable: bool) -> Optional[List[str]]:
props = super(OgnButton, OgnButton).get_property_names(button, writeable)
if props is not None:
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to retrieve property names from non-button object '{button}'.")
return None
props += [
"image_height", # ui.Length
"image_url", # str
"image_width", # ui.Length
"spacing", # float
"text", # str
]
return props
@staticmethod
def resolve_output_property(button: ui.Button, property_name: str, attribute: og.Attribute) -> bool:
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to resolve property on non-button object '{button}'.")
return False
if property_name not in OgnButton.get_property_names(button, False):
carb.log_warn(f"'{property_name}' is not a readable property of button '{button.identifier}'")
return False
return super(OgnButton, OgnButton).resolve_output_property(button, property_name, attribute)
@staticmethod
def get_property_value(button: ui.Button, property_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to get value of property {property_name} on non-button object '{button}'.")
return False
if property_name not in OgnButton.get_property_names(button, False):
carb.log_warn(f"'{property_name}' is not a readable property of button '{button.identifier}'")
return False
return super(OgnButton, OgnButton).get_property_value(button, property_name, attribute)
@staticmethod
def set_property_value(button: ui.Button, property_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to set value of property {property_name} on non-button object '{button}'.")
return False
if property_name not in OgnButton.get_property_names(button, True):
carb.log_warn(f"'{property_name}' is not a writeable property of button '{button.identifier}'")
return False
return super(OgnButton, OgnButton).set_property_value(button, property_name, attribute)
@staticmethod
def get_style_element_names(button: ui.Button, writeable: bool) -> List[str]:
element_names = super(OgnButton, OgnButton).get_style_element_names(button, writeable)
if element_names is not None: # noqa: SIM102
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to retrieve style element names from non-button widget '{button}'.")
return None
# TBD
return element_names
@staticmethod
def get_style_value(button: ui.Button, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to get style element from non-button object '{button}'.")
return False
return super(OgnButton, OgnButton).get_style_value(button, element_name, attribute)
@staticmethod
def set_style_value(button: ui.Button, element_name: str, attribute: og.RuntimeAttribute) -> bool:
if not isinstance(button, ui.Button):
carb.log_warn(f"Attempt to set style element on non-button object '{button}'.")
return False
return super(OgnButton, OgnButton).set_style_value(button, element_name, attribute)
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportHovered.ogn | {
"OnViewportHovered": {
"version": 1,
"description": [
"Event node which fires when the specified viewport is hovered over.",
"Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."
],
"uiName": "On Viewport Hovered (BETA)",
"categories": ["graph:action", "ui"],
"scheduling": "compute-on-request",
"inputs": {
"viewport": {
"type": "token",
"description": "Name of the viewport window to watch for hover events",
"uiName": "Viewport",
"default": "Viewport",
"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": {
"began": {
"type": "execution",
"description": "Enabled when the hover begins",
"uiName": "Began"
},
"ended": {
"type": "execution",
"description": "Enabled when the hover ends",
"uiName": "Ended"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSlider.ogn | {
"Slider": {
"version": 1,
"description": ["Create a slider widget on the Viewport"],
"uiName": "Slider (BETA)",
"language": "Python",
"categories": ["graph:action", "ui"],
"inputs": {
"create": {
"type": "execution",
"description": "Input execution to create and show the widget",
"uiName": "Create"
},
"tearDown": {
"type": "execution",
"description": "Input execution to tear down the widget and all its child widgets",
"uiName": "Tear Down"
},
"show": {
"type": "execution",
"description": "Input execution to show the widget and all its child widgets after they become hidden",
"uiName": "Show"
},
"hide": {
"type": "execution",
"description": "Input execution to hide the widget and all its child widgets",
"uiName": "Hide"
},
"enable": {
"type": "execution",
"description": "Enable this button after it has been disabled",
"uiName": "Enable"
},
"disable": {
"type": "execution",
"description": "Disable this button so that it cannot be pressed",
"uiName": "Disable"
},
"widgetIdentifier": {
"type": "token",
"description": [
"An optional unique identifier for the widget.",
"Can be used to refer to this widget in other places such as the OnWidgetClicked node."
],
"uiName": "Widget Identifier",
"optional": true
},
"parentWidgetPath": {
"type": "token",
"description": [
"The absolute path to the parent widget.",
"If empty, this widget will be created as a direct child of Viewport."
],
"uiName": "Parent Widget Path",
"optional": true
},
"width": {
"type": "double",
"description": "The width of the created slider",
"uiName": "Width",
"default": 100.0
},
"min": {
"type": "float",
"description": "The minimum value of the slider",
"uiName": "Min"
},
"max": {
"type": "float",
"description": "The maximum value of the slider",
"uiName": "Max"
},
"step": {
"type": "float",
"description": "The step size of the slider",
"uiName": "Step",
"default": 0.01
}
},
"outputs": {
"created": {
"type": "execution",
"description": "Executed when the widget is created",
"uiName": "Created"
},
"widgetPath": {
"type": "token",
"description": "The absolute path to the created widget",
"uiName": "Widget Path"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/CameraState.h | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <carb/Types.h>
#include <pxr/usd/usdGeom/camera.h>
namespace omni
{
namespace graph
{
namespace ui
{
class CameraState
{
PXR_NS::UsdGeomCamera m_camera;
const PXR_NS::UsdTimeCode m_timeCode;
public:
CameraState(PXR_NS::UsdGeomCamera camera, const PXR_NS::UsdTimeCode* time = nullptr);
~CameraState() = default;
void getCameraPosition(carb::Double3& position) const;
void getCameraTarget(carb::Double3& target) const;
bool setCameraPosition(const carb::Double3& position, bool rotate);
bool setCameraTarget(const carb::Double3& target, bool rotate);
};
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportPressManipulator.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.
#
__all__ = ["ViewportPressManipulatorFactory"]
from typing import Any
import carb
import omni.kit.app
import omni.kit.commands
from omni.ui import scene as sc
EVENT_NAME_BEGAN = "omni.graph.viewport.press.began"
EVENT_NAME_ENDED = "omni.graph.viewport.press.ended"
GESTURE_NAMES = ["Left Mouse Press", "Right Mouse Press", "Middle Mouse Press"]
class DoNotPrevent(sc.GestureManager):
def can_be_prevented(self, gesture):
return False
class ViewportPressGesture(sc.DragGesture):
def __init__(self, viewport_api: Any, viewport_window_name: str, mouse_button: int):
super().__init__(mouse_button=mouse_button, manager=DoNotPrevent())
self._viewport_api = viewport_api
self._viewport_window_name = viewport_window_name
self._gesture_name = GESTURE_NAMES[mouse_button]
self._event_type_began = carb.events.type_from_string(EVENT_NAME_BEGAN)
self._event_type_ended = carb.events.type_from_string(EVENT_NAME_ENDED)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self._start_pos_valid = False
def on_began(self):
mouse = self.sender.gesture_payload.mouse
resolution = self._viewport_api.resolution
# Position in normalized coords
pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0]
pos_norm = (pos_norm[0], 1.0 - pos_norm[1])
if not all(0.0 <= x <= 1.0 for x in pos_norm):
self._start_pos_valid = False
return
# Position in viewport resolution pixels
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
payload = {
"viewport": self._viewport_window_name,
"gesture": self._gesture_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
}
self._message_bus.push(self._event_type_began, payload=payload)
self._start_pos_valid = True
def on_ended(self):
if not self._start_pos_valid:
return
mouse = self.sender.gesture_payload.mouse
resolution = self._viewport_api.resolution
# Position in normalized coords
pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0]
pos_norm = (pos_norm[0], 1.0 - pos_norm[1])
pos_valid = True
if not all(0.0 <= x <= 1.0 for x in pos_norm):
pos_valid = False
pos_norm = [0.0, 0.0]
# Position in viewport resolution pixels
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
payload = {
"viewport": self._viewport_window_name,
"gesture": self._gesture_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
"pos_valid": pos_valid,
}
self._message_bus.push(self._event_type_ended, payload=payload)
self._start_pos_valid = False
# Custom manipulator containing a Screen that contains the gestures
class ViewportPressManipulator(sc.Manipulator):
def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gestures = [
ViewportPressGesture(viewport_api, viewport_window_name, 0), # left mouse press
ViewportPressGesture(viewport_api, viewport_window_name, 1), # right mouse press
ViewportPressGesture(viewport_api, viewport_window_name, 2), # middle mouse press
]
self._screen = None
self._transform = None
self.name = None
self.categories = ()
def on_build(self):
self._transform = sc.Transform()
with self._transform:
self._screen = sc.Screen(gesture=self._gestures)
def destroy(self):
self._gestures = []
self._screen = None
if self._transform:
self._transform.clear()
self._transform = None
# Factory creator
def ViewportPressManipulatorFactory(desc: dict) -> ViewportPressManipulator: # noqa: N802
manip = ViewportPressManipulator(desc.get("viewport_api"), desc.get("viewport_window_name"))
manip.categories = ()
manip.name = f"ViewportPressManipulator.{desc.get('viewport_window_name')}"
return manip
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnGetCameraTarget.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnGetCameraTargetDatabase.h>
#include "CameraState.h"
#include "NodeUtils.h"
namespace omni
{
namespace graph
{
namespace ui
{
class OgnGetCameraTarget
{
public:
static bool compute(OgnGetCameraTargetDatabase& db)
{
PXR_NS::UsdPrim prim = getPrimFromPathOrRelationship(db, OgnGetCameraTargetAttributes::inputs::prim.m_token);
if (!prim)
return false;
auto camera = PXR_NS::UsdGeomCamera(prim);
if (!camera)
return true;
CameraState cameraState(std::move(camera));
carb::Double3 target;
cameraState.getCameraTarget(target);
carb::Double3& targetAttrib = reinterpret_cast<carb::Double3&>(db.outputs.target());
targetAttrib = target;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportDragged.ogn | {
"OnViewportDragged": {
"version": 1,
"description": [
"Event node which fires when a viewport drag event occurs in the specified viewport.",
"Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."
],
"uiName": "On Viewport Dragged (BETA)",
"categories": ["graph:action", "ui"],
"scheduling": "compute-on-request",
"inputs": {
"useNormalizedCoords": {
"type": "bool",
"description": [
"When true, the components of 2D position outputs are scaled to between 0 and 1,",
"where 0 is top/left and 1 is bottom/right.",
"When false, components are in viewport render resolution pixels."
],
"uiName": "Use Normalized Coords",
"default": false,
"metadata": {
"literalOnly": "1"
}
},
"viewport": {
"type": "token",
"description": "Name of the viewport window to watch for drag events",
"uiName": "Viewport",
"default": "Viewport",
"metadata": {
"literalOnly": "1"
}
},
"gesture": {
"type": "token",
"description": "The input gesture to trigger viewport drag events",
"uiName": "Gesture",
"default": "Left Mouse Drag",
"metadata": {
"displayGroup": "parameters",
"literalOnly": "1",
"allowedTokens": {
"LeftMouseDrag": "Left Mouse Drag",
"RightMouseDrag": "Right Mouse Drag",
"MiddleMouseDrag": "Middle Mouse Drag"
}
}
},
"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": {
"began": {
"type": "execution",
"description": "Enabled when the drag begins, populating 'Initial Position' with the current mouse position",
"uiName": "Began"
},
"ended": {
"type": "execution",
"description": "Enabled when the drag ends, populating 'Final Position' with the current mouse position",
"uiName": "Ended"
},
"initialPosition": {
"type": "double[2]",
"description": "The mouse position at which the drag began (valid when either 'Began' or 'Ended' is enabled)",
"uiName": "Initial Position"
},
"finalPosition": {
"type": "double[2]",
"description": "The mouse position at which the drag ended (valid when 'Ended' is enabled)",
"uiName": "Final Position"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportClickManipulator.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.
#
__all__ = ["ViewportClickManipulatorFactory"]
from typing import Any
import carb
import omni.kit.app
import omni.kit.commands
from omni.ui import scene as sc
EVENT_NAME = "omni.graph.viewport.click"
GESTURE_NAMES = ["Left Mouse Click", "Right Mouse Click", "Middle Mouse Click"]
class DoNotPrevent(sc.GestureManager):
def can_be_prevented(self, gesture):
return False
class ViewportClickGesture(sc.ClickGesture):
def __init__(self, viewport_api: Any, viewport_window_name: str, mouse_button: int):
super().__init__(mouse_button=mouse_button, manager=DoNotPrevent())
self._viewport_api = viewport_api
self._viewport_window_name = viewport_window_name
self._gesture_name = GESTURE_NAMES[mouse_button]
self._event_type = carb.events.type_from_string(EVENT_NAME)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
def on_ended(self, *args):
if self.state == sc.GestureState.CANCELED:
return
mouse = self.sender.gesture_payload.mouse
resolution = self._viewport_api.resolution
# Position in normalized coords
pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0]
pos_norm = (pos_norm[0], 1.0 - pos_norm[1])
if not all(0.0 <= x <= 1.0 for x in pos_norm):
return
# Position in viewport resolution pixels
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
payload = {
"viewport": self._viewport_window_name,
"gesture": self._gesture_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
}
self._message_bus.push(self._event_type, payload=payload)
class ViewportClickManipulator(sc.Manipulator):
def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gestures = [
ViewportClickGesture(viewport_api, viewport_window_name, 0), # left mouse click
ViewportClickGesture(viewport_api, viewport_window_name, 1), # right mouse click
ViewportClickGesture(viewport_api, viewport_window_name, 2), # middle mouse click
]
self._screen = None
self._transform = None
self.name = None
self.categories = ()
def on_build(self):
self._transform = sc.Transform()
with self._transform:
self._screen = sc.Screen(gesture=self._gestures)
def destroy(self):
self._gestures = []
self._screen = None
if self._transform:
self._transform.clear()
self._transform = None
# Factory creator
def ViewportClickManipulatorFactory(desc: dict) -> ViewportClickManipulator: # noqa: N802
manip = ViewportClickManipulator(desc.get("viewport_api"), desc.get("viewport_window_name"))
manip.categories = ()
manip.name = f"ViewportClickManipulator.{desc.get('viewport_window_name')}"
return manip
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSetViewportMode.ogn | {
"SetViewportMode": {
"version": 1,
"description": [
"Sets the mode of a specified viewport window to 'Scripted' mode or 'Default' mode when executed.\n",
"'Scripted' mode disables default viewport interaction and enables placing UI elements over the viewport.",
"'Default' mode is the default state of the viewport, and entering it will destroy any UI elements on the viewport.\n",
"Executing with 'Enable Viewport Mouse Events' set to true in 'Scripted' mode is required to allow the specified viewport",
"to be targeted by viewport mouse event nodes, including 'On Viewport Dragged' and 'Read Viewport Drag State'.\n",
"Executing with 'Enable Picking' set to true in 'Scripted' mode is required to allow the specified viewport",
"to be targeted by the 'On Picked' and 'Read Pick State' nodes."
],
"uiName": "Set Viewport Mode (BETA)",
"language": "Python",
"categories": ["graph:action", "ui"],
"inputs": {
"execIn": {
"type": "execution",
"description": "Input execution"
},
"mode": {
"type": "int",
"description": "The mode to set the specified viewport to when this node is executed (0: 'Default', 1: 'Scripted')",
"uiName": "Mode",
"default": 0
},
"enableViewportMouseEvents": {
"type": "bool",
"description": "Enable/Disable viewport mouse events on the specified viewport when in 'Scripted' mode",
"uiName": "Enable Viewport Mouse Events",
"default": false
},
"enablePicking": {
"type": "bool",
"description": "Enable/Disable picking prims in the specified viewport when in 'Scripted' mode",
"uiName": "Enable Picking",
"default": false
},
"viewport": {
"type": "token",
"description": "Name of the viewport window to set the mode of",
"uiName": "Viewport",
"default": "Viewport"
}
},
"outputs": {
"defaultMode": {
"type": "execution",
"description": "Fires when this node is successfully executed with 'Mode' set to 'Default'",
"uiName": "Default Mode"
},
"scriptedMode": {
"type": "execution",
"description": "Fires when this node is successfully executed with 'Mode' set to 'Scripted'",
"uiName": "Scripted Mode"
},
"widgetPath": {
"type": "token",
"description": [
"When the viewport enters 'Scripted' mode, a container widget is created under which other UI may be parented.",
"This attribute provides the absolute path to that widget, which can be used as the 'parentWidgetPath'",
"input to various UI nodes, such as Button. When the viewport exits 'Scripted' mode,",
"the container widget and all the UI within it will be destroyed."
],
"uiName": "Widget Path"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportDragged.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnOnViewportDraggedDatabase.h>
#include "ViewportDragNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnOnViewportDragged
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr dragBeganSub;
carb::events::ISubscriptionPtr dragChangedSub;
carb::events::ISubscriptionPtr dragEndedSub;
ViewportDragEventPayloads eventPayloads;
ViewportDragEventStates eventStates;
} m_internalState;
static void initialize(GraphContextObj const&, NodeObj const& nodeObj)
{
OgnOnViewportDragged& state = OgnOnViewportDraggedDatabase::sm_stateManagerOgnOnViewportDragged
.getState<OgnOnViewportDragged>(nodeObj.nodeHandle);
// Subscribe to drag events
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.dragBeganSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kDragBeganEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnOnViewportDragged& state = OgnOnViewportDraggedDatabase::sm_stateManagerOgnOnViewportDragged
.getState<OgnOnViewportDragged>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setDragBeganPayload(e->payload);
if (nodeObj.iNode->isValid(nodeObj))
nodeObj.iNode->requestCompute(nodeObj);
}
}
);
state.m_internalState.dragChangedSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kDragChangedEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnOnViewportDragged& state = OgnOnViewportDraggedDatabase::sm_stateManagerOgnOnViewportDragged
.getState<OgnOnViewportDragged>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setDragChangedPayload(e->payload);
}
}
);
state.m_internalState.dragEndedSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kDragEndedEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnOnViewportDragged& state = OgnOnViewportDraggedDatabase::sm_stateManagerOgnOnViewportDragged
.getState<OgnOnViewportDragged>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setDragEndedPayload(e->payload);
if (nodeObj.iNode->isValid(nodeObj))
nodeObj.iNode->requestCompute(nodeObj);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnOnViewportDragged& state = OgnOnViewportDraggedDatabase::sm_stateManagerOgnOnViewportDragged
.getState<OgnOnViewportDragged>(nodeObj.nodeHandle);
// Unsubscribe from drag events
if (state.m_internalState.dragBeganSub.get())
state.m_internalState.dragBeganSub.detach()->unsubscribe();
if (state.m_internalState.dragChangedSub.get())
state.m_internalState.dragChangedSub.detach()->unsubscribe();
if (state.m_internalState.dragEndedSub.get())
state.m_internalState.dragEndedSub.detach()->unsubscribe();
}
static bool compute(OgnOnViewportDraggedDatabase& db)
{
if (checkNodeDisabledForOnlyPlay(db))
return true;
OgnOnViewportDragged& state = db.internalState<OgnOnViewportDragged>();
if (state.m_internalState.eventPayloads.empty())
return true;
// Get the targeted viewport and gesture
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
char const* const gestureName = db.tokenToString(db.inputs.gesture());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
// Process event payloads and update event state
bool dragBegan = false;
for (auto const& dragBeganPayload : state.m_internalState.eventPayloads.dragBeganPayloads())
{
if (!dragBeganPayload.second.isValid)
continue;
auto& eventStateValue = state.m_internalState.eventStates[dragBeganPayload.first];
eventStateValue.isDragInProgress = true;
eventStateValue.initialPositionNorm = dragBeganPayload.second.initialPositionNorm;
eventStateValue.initialPositionPixel = dragBeganPayload.second.initialPositionPixel;
eventStateValue.currentPositionNorm = dragBeganPayload.second.currentPositionNorm;
eventStateValue.currentPositionPixel = dragBeganPayload.second.currentPositionPixel;
if (std::strcmp(viewportWindowName, dragBeganPayload.first.viewportWindowName) == 0
&& std::strcmp(gestureName, dragBeganPayload.first.gestureName) == 0)
{
dragBegan = true;
}
}
for (auto const& dragChangedPayload : state.m_internalState.eventPayloads.dragChangedPayloads())
{
if (!dragChangedPayload.second.isValid)
continue;
auto& eventStateValue = state.m_internalState.eventStates[dragChangedPayload.first];
if (eventStateValue.isDragInProgress)
{
eventStateValue.currentPositionNorm = dragChangedPayload.second.currentPositionNorm;
eventStateValue.currentPositionPixel = dragChangedPayload.second.currentPositionPixel;
}
}
bool dragEnded = false;
for (auto const& dragEndedPayload : state.m_internalState.eventPayloads.dragEndedPayloads())
{
if (!dragEndedPayload.second.isValid)
continue;
auto& eventStateValue = state.m_internalState.eventStates[dragEndedPayload.first];
if (eventStateValue.isDragInProgress)
{
eventStateValue.isDragInProgress = false;
if (std::strcmp(viewportWindowName, dragEndedPayload.first.viewportWindowName) == 0
&& std::strcmp(gestureName, dragEndedPayload.first.gestureName) == 0)
{
dragEnded = true;
}
}
}
state.m_internalState.eventPayloads.clear();
// Get event state and set outputs
auto it = state.m_internalState.eventStates.find({viewportWindowName, gestureName});
if (it != state.m_internalState.eventStates.end())
{
if (dragEnded)
{
db.outputs.began() = kExecutionAttributeStateDisabled;
db.outputs.ended() = kExecutionAttributeStateEnabled;
db.outputs.initialPosition() = db.inputs.useNormalizedCoords() ? it->second.initialPositionNorm : it->second.initialPositionPixel;
db.outputs.finalPosition() = db.inputs.useNormalizedCoords() ? it->second.currentPositionNorm : it->second.currentPositionPixel;
}
else if (dragBegan)
{
db.outputs.began() = kExecutionAttributeStateEnabled;
db.outputs.ended() = kExecutionAttributeStateDisabled;
db.outputs.initialPosition() = db.inputs.useNormalizedCoords() ? it->second.initialPositionNorm : it->second.initialPositionPixel;
db.outputs.finalPosition() = {0.0, 0.0};
}
else
{
db.outputs.began() = kExecutionAttributeStateDisabled;
db.outputs.ended() = kExecutionAttributeStateDisabled;
}
}
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadPickState.ogn | {
"ReadPickState": {
"version": 1,
"description": [
"Read the state of the last picking event from the specified viewport.",
"Note that picking events must be enabled on the specified viewport using a SetViewportMode node."
],
"uiName": "Read Pick State (BETA)",
"categories": ["ui"],
"inputs": {
"trackedPrimPaths": {
"type": "token[]",
"description": [
"Optionally specify a set of prims (by paths) to track whether or not they got picked",
"(only affects the value of 'Is Tracked Prim Picked')"
],
"uiName": "Tracked Prim Paths",
"optional": true
},
"usePaths": {
"type": "bool",
"default": false,
"description": "When true, 'Tracked Prim Paths' is used, otherwise 'Tracked Prims' is used",
"uiName": "Use Paths"
},
"trackedPrims": {
"type": "bundle",
"description": [
"Optionally specify a set of prims to track whether or not they got picked",
"(only affects the value of 'Is Tracked Prim Picked')"
],
"uiName": "Tracked Prims",
"optional": true
},
"viewport": {
"type": "token",
"description": "Name of the viewport window to watch for picking events",
"uiName": "Viewport",
"default": "Viewport"
},
"gesture": {
"type": "token",
"description": "The input gesture to trigger a picking event",
"uiName": "Gesture",
"default": "Left Mouse Click",
"metadata": {
"displayGroup": "parameters",
"allowedTokens": {
"LeftMouseClick": "Left Mouse Click",
"RightMouseClick": "Right Mouse Click",
"MiddleMouseClick": "Middle Mouse Click",
"LeftMousePress": "Left Mouse Press",
"RightMousePress": "Right Mouse Press",
"MiddleMousePress": "Middle Mouse Press"
}
}
}
},
"outputs": {
"pickedPrimPath": {
"type": "token",
"description": "The path of the prim picked in the last picking event, or an empty string if nothing got picked",
"uiName": "Picked Prim Path"
},
"pickedWorldPos": {
"type": "pointd[3]",
"description": [
"The XYZ-coordinates of the point in world space at which the prim got picked,",
"or (0,0,0) if nothing got picked"
],
"uiName": "Picked World Position"
},
"isTrackedPrimPicked": {
"type": "bool",
"description": [
"True if a tracked prim got picked in the last picking event,",
"or if any prim got picked if no tracked prims are specified"
],
"uiName": "Is Tracked Prim Picked"
},
"isValid": {
"type": "bool",
"description": "True if a valid event state was detected and the outputs of this node are valid, and false otherwise",
"uiName": "Is Valid"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnWriteWidgetStyle.ogn | {
"WriteWidgetStyle": {
"version": 1,
"description": [
"Sets a widget's style properties.",
"This node should be used in combination with UI creation nodes such as Button."
],
"uiName": "Write Widget Style (BETA)",
"language": "Python",
"categories": ["graph:action", "ui"],
"scheduling": "global-read",
"inputs": {
"write": {
"type": "execution",
"description": "Input execution"
},
"widgetIdentifier": {
"type": "token",
"description": [
"A unique identifier identifying the widget. This is only valid within the current graph.",
"This should be specified in the UI creation node such as OgnButton."
],
"uiName": "Widget Identifier"
},
"widgetPath": {
"type": "token",
"description": [
"Full path to the widget. If present this will be used insted of 'widgetIdentifier'.",
"Unlike 'widgetIdentifier' this is valid across all graphs."
],
"uiName": "Widget Path"
},
"style": {
"type": "string",
"description": [
"The style to set the widget to."
]
}
},
"outputs": {
"written": {
"type": "execution",
"description": "Output execution"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportHoverManipulator.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.
#
__all__ = ["ViewportHoverManipulatorFactory"]
from typing import Any
import carb
import omni.kit.app
import omni.kit.commands
from omni.ui import scene as sc
EVENT_NAME_BEGAN = "omni.graph.viewport.hover.began"
EVENT_NAME_CHANGED = "omni.graph.viewport.hover.changed"
EVENT_NAME_ENDED = "omni.graph.viewport.hover.ended"
class DoNotPrevent(sc.GestureManager):
def can_be_prevented(self, gesture):
return False
class ViewportHoverGesture(sc.HoverGesture):
def __init__(self, viewport_api: Any, viewport_window_name: str):
super().__init__(manager=DoNotPrevent())
self._viewport_api = viewport_api
self._viewport_window_name = viewport_window_name
self._event_type_began = carb.events.type_from_string(EVENT_NAME_BEGAN)
self._event_type_changed = carb.events.type_from_string(EVENT_NAME_CHANGED)
self._event_type_ended = carb.events.type_from_string(EVENT_NAME_ENDED)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self._viewport_hovered = False
def on_began(self):
self._viewport_hovered = False
def on_changed(self):
mouse = self.sender.gesture_payload.mouse
pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0]
pos_norm = (pos_norm[0], 1.0 - pos_norm[1])
viewport_hovered = all(0.0 <= x <= 1.0 for x in pos_norm)
if not self._viewport_hovered and viewport_hovered:
# hover began
resolution = self._viewport_api.resolution
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
payload = {
"viewport": self._viewport_window_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
}
self._message_bus.push(self._event_type_began, payload=payload)
elif self._viewport_hovered and viewport_hovered:
# hover changed
resolution = self._viewport_api.resolution
pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1])
mouse_moved = self.sender.gesture_payload.mouse_moved
vel_norm = self._viewport_api.map_ndc_to_texture(mouse_moved)[0]
origin_norm = self._viewport_api.map_ndc_to_texture((0, 0))[0]
vel_norm = (vel_norm[0] - origin_norm[0], origin_norm[1] - vel_norm[1])
vel_pixel = (vel_norm[0] * resolution[0], vel_norm[1] * resolution[1])
payload = {
"viewport": self._viewport_window_name,
"pos_norm_x": pos_norm[0],
"pos_norm_y": pos_norm[1],
"pos_pixel_x": pos_pixel[0],
"pos_pixel_y": pos_pixel[1],
"vel_norm_x": vel_norm[0],
"vel_norm_y": vel_norm[1],
"vel_pixel_x": vel_pixel[0],
"vel_pixel_y": vel_pixel[1],
}
self._message_bus.push(self._event_type_changed, payload=payload)
elif self._viewport_hovered and not viewport_hovered:
# hover ended
payload = {
"viewport": self._viewport_window_name,
}
self._message_bus.push(self._event_type_ended, payload=payload)
self._viewport_hovered = viewport_hovered
def on_ended(self):
if self._viewport_hovered:
# hover ended
payload = {
"viewport": self._viewport_window_name,
}
self._message_bus.push(self._event_type_ended, payload=payload)
self._viewport_hovered = False
# Custom manipulator containing a Screen that contains the gestures
class ViewportHoverManipulator(sc.Manipulator):
def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gestures = [ViewportHoverGesture(viewport_api, viewport_window_name)]
self._screen = None
self._transform = None
self.name = None
self.categories = ()
def on_build(self):
self._transform = sc.Transform()
with self._transform:
self._screen = sc.Screen(gesture=self._gestures)
def destroy(self):
self._gestures = []
self._screen = None
if self._transform:
self._transform.clear()
self._transform = None
# Factory creator
def ViewportHoverManipulatorFactory(desc: dict) -> ViewportHoverManipulator: # noqa: N802
manip = ViewportHoverManipulator(desc.get("viewport_api"), desc.get("viewport_window_name"))
manip.categories = ()
manip.name = f"ViewportHoverManipulator.{desc.get('viewport_window_name')}"
return manip
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadViewportDragState.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnReadViewportDragStateDatabase.h>
#include "ViewportDragNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnReadViewportDragState
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr dragBeganSub;
carb::events::ISubscriptionPtr dragChangedSub;
carb::events::ISubscriptionPtr dragEndedSub;
carb::events::ISubscriptionPtr updateSub;
ViewportDragEventPayloads eventPayloads;
ViewportDragEventStates eventStates;
} m_internalState;
// Process event payloads and update event states every frame
static void updateEventStates(ViewportDragEventStates& eventStates, ViewportDragEventPayloads& eventPayloads)
{
for (auto& eventState : eventStates)
{
eventState.second.velocityNorm = {0.0, 0.0};
eventState.second.velocityPixel = {0.0, 0.0};
}
for (auto const& dragBeganPayload : eventPayloads.dragBeganPayloads())
{
if (!dragBeganPayload.second.isValid)
continue;
auto& eventStateValue = eventStates[dragBeganPayload.first];
eventStateValue.isDragInProgress = true;
eventStateValue.initialPositionNorm = dragBeganPayload.second.initialPositionNorm;
eventStateValue.initialPositionPixel = dragBeganPayload.second.initialPositionPixel;
eventStateValue.currentPositionNorm = dragBeganPayload.second.currentPositionNorm;
eventStateValue.currentPositionPixel = dragBeganPayload.second.currentPositionPixel;
eventStateValue.velocityNorm = dragBeganPayload.second.velocityNorm;
eventStateValue.velocityPixel = dragBeganPayload.second.velocityPixel;
}
for (auto const& dragChangedPayload : eventPayloads.dragChangedPayloads())
{
if (!dragChangedPayload.second.isValid)
continue;
auto& eventStateValue = eventStates[dragChangedPayload.first];
if (eventStateValue.isDragInProgress)
{
eventStateValue.currentPositionNorm = dragChangedPayload.second.currentPositionNorm;
eventStateValue.currentPositionPixel = dragChangedPayload.second.currentPositionPixel;
eventStateValue.velocityNorm = dragChangedPayload.second.velocityNorm;
eventStateValue.velocityPixel = dragChangedPayload.second.velocityPixel;
}
}
for (auto const& dragEndedPayload : eventPayloads.dragEndedPayloads())
{
if (!dragEndedPayload.second.isValid)
continue;
auto& eventStateValue = eventStates[dragEndedPayload.first];
if (eventStateValue.isDragInProgress)
{
eventStateValue.isDragInProgress = false;
eventStateValue.velocityNorm = {0.0, 0.0};
eventStateValue.velocityPixel = {0.0, 0.0};
}
}
eventPayloads.clear();
}
static void initialize(GraphContextObj const&, NodeObj const& nodeObj)
{
OgnReadViewportDragState& state = OgnReadViewportDragStateDatabase::sm_stateManagerOgnReadViewportDragState
.getState<OgnReadViewportDragState>(nodeObj.nodeHandle);
// Subscribe to drag events and update tick
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.dragBeganSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kDragBeganEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportDragState& state = OgnReadViewportDragStateDatabase::sm_stateManagerOgnReadViewportDragState
.getState<OgnReadViewportDragState>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setDragBeganPayload(e->payload);
}
}
);
state.m_internalState.dragChangedSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kDragChangedEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportDragState& state = OgnReadViewportDragStateDatabase::sm_stateManagerOgnReadViewportDragState
.getState<OgnReadViewportDragState>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setDragChangedPayload(e->payload);
}
}
);
state.m_internalState.dragEndedSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kDragEndedEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportDragState& state = OgnReadViewportDragStateDatabase::sm_stateManagerOgnReadViewportDragState
.getState<OgnReadViewportDragState>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setDragEndedPayload(e->payload);
}
}
);
state.m_internalState.updateSub = carb::events::createSubscriptionToPush(
app->getUpdateEventStream(),
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportDragState& state = OgnReadViewportDragStateDatabase::sm_stateManagerOgnReadViewportDragState
.getState<OgnReadViewportDragState>(nodeObj.nodeHandle);
updateEventStates(state.m_internalState.eventStates, state.m_internalState.eventPayloads);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnReadViewportDragState& state = OgnReadViewportDragStateDatabase::sm_stateManagerOgnReadViewportDragState
.getState<OgnReadViewportDragState>(nodeObj.nodeHandle);
// Unsubscribe from drag events and update tick
if (state.m_internalState.dragBeganSub.get())
state.m_internalState.dragBeganSub.detach()->unsubscribe();
if (state.m_internalState.dragChangedSub.get())
state.m_internalState.dragChangedSub.detach()->unsubscribe();
if (state.m_internalState.dragEndedSub.get())
state.m_internalState.dragEndedSub.detach()->unsubscribe();
if (state.m_internalState.updateSub.get())
state.m_internalState.updateSub.detach()->unsubscribe();
}
static bool compute(OgnReadViewportDragStateDatabase& db)
{
OgnReadViewportDragState& state = db.internalState<OgnReadViewportDragState>();
// Get the targeted viewport and gesture
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
char const* const gestureName = db.tokenToString(db.inputs.gesture());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
// Output drag state
auto it = state.m_internalState.eventStates.find({viewportWindowName, gestureName});
if (it != state.m_internalState.eventStates.end())
{
if (db.inputs.useNormalizedCoords())
{
db.outputs.initialPosition() = it->second.initialPositionNorm;
db.outputs.currentPosition() = it->second.currentPositionNorm;
db.outputs.velocity() = it->second.velocityNorm;
}
else
{
db.outputs.initialPosition() = it->second.initialPositionPixel;
db.outputs.currentPosition() = it->second.currentPositionPixel;
db.outputs.velocity() = it->second.velocityPixel;
}
db.outputs.isDragInProgress() = it->second.isDragInProgress;
db.outputs.isValid() = true;
}
else
{
db.outputs.initialPosition() = {0.0, 0.0};
db.outputs.currentPosition() = {0.0, 0.0};
db.outputs.velocity() = {0.0, 0.0};
db.outputs.isDragInProgress() = false;
db.outputs.isValid() = false;
}
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadWindowSize.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from . import UINodeCommon
class OgnReadWindowSize:
@staticmethod
def compute(db) -> bool:
db.outputs.height = 0.0
db.outputs.width = 0.0
if db.inputs.isViewport:
try:
from omni.kit.viewport.window import get_viewport_window_instances
vp_wins = [win for win in get_viewport_window_instances(None) if isinstance(win, ui.Window)]
except ImportError:
db.log_error("No non-legacy viewports found.")
return False
widget_path = db.inputs.widgetPath
if not widget_path:
window_name = db.inputs.name
if not window_name:
db.log_warning("No window name or widgetPath provided.")
return True
if db.inputs.isViewport:
for window in vp_wins:
if window.title == window_name:
db.outputs.height = window.height
db.outputs.width = window.width
return True
db.log_error(f"No viewport named '{window_name}' found.")
return False
for window in ui.Workspace.get_windows():
if isinstance(window, ui.Window) and window.title == window_name:
db.outputs.height = window.height
db.outputs.width = window.width
return True
db.log_error(f"No window named '{window_name}' found.")
return False
window = UINodeCommon.get_widget_window(widget_path)
if not window:
db.log_error(f"No widget found at path '{widget_path}'.")
return False
if db.inputs.isViewport and window not in vp_wins:
db.log_error(f"Widget '{widget_path} is not in a viewport window.")
return False
db.outputs.height = window.height
db.outputs.width = window.width
return True
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportDragNodeCommon.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "UINodeCommon.h"
namespace omni
{
namespace graph
{
namespace ui
{
constexpr carb::events::EventType kDragBeganEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.drag.began");
constexpr carb::events::EventType kDragChangedEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.drag.changed");
constexpr carb::events::EventType kDragEndedEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.drag.ended");
class ViewportDragEventPayloads
{
public:
struct Key
{
char const* viewportWindowName;
char const* gestureName;
bool operator<(Key const& other) const
{
int const ret = std::strcmp(viewportWindowName, other.viewportWindowName);
if (ret < 0)
return true;
else if (ret <= 0)
return std::strcmp(gestureName, other.gestureName) < 0;
return false;
}
};
struct DragBeganValue
{
pxr::GfVec2d initialPositionNorm;
pxr::GfVec2d initialPositionPixel;
pxr::GfVec2d currentPositionNorm;
pxr::GfVec2d currentPositionPixel;
pxr::GfVec2d velocityNorm;
pxr::GfVec2d velocityPixel;
bool isValid;
};
struct DragChangedValue
{
pxr::GfVec2d currentPositionNorm;
pxr::GfVec2d currentPositionPixel;
pxr::GfVec2d velocityNorm;
pxr::GfVec2d velocityPixel;
bool isValid;
};
struct DragEndedValue
{
bool isValid;
};
// Store a drag began event payload
void setDragBeganPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {
stringMemo.lookup(idict->get<char const*>(payload, "viewport")),
stringMemo.lookup(idict->get<char const*>(payload, "gesture"))
};
dragBeganPayloadMap[key] = DragBeganValue {
pxr::GfVec2d {
idict->get<double>(payload, "start_pos_norm_x"),
idict->get<double>(payload, "start_pos_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "start_pos_pixel_x"),
idict->get<double>(payload, "start_pos_pixel_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "pos_norm_x"),
idict->get<double>(payload, "pos_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "pos_pixel_x"),
idict->get<double>(payload, "pos_pixel_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "vel_norm_x"),
idict->get<double>(payload, "vel_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "vel_pixel_x"),
idict->get<double>(payload, "vel_pixel_y")
},
true
};
}
// Store a drag changed event payload
void setDragChangedPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {
stringMemo.lookup(idict->get<char const*>(payload, "viewport")),
stringMemo.lookup(idict->get<char const*>(payload, "gesture"))
};
dragChangedPayloadMap[key] = DragChangedValue {
pxr::GfVec2d {
idict->get<double>(payload, "pos_norm_x"),
idict->get<double>(payload, "pos_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "pos_pixel_x"),
idict->get<double>(payload, "pos_pixel_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "vel_norm_x"),
idict->get<double>(payload, "vel_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "vel_pixel_x"),
idict->get<double>(payload, "vel_pixel_y")
},
true
};
}
// Store a drag ended event payload
void setDragEndedPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {
stringMemo.lookup(idict->get<char const*>(payload, "viewport")),
stringMemo.lookup(idict->get<char const*>(payload, "gesture"))
};
dragEndedPayloadMap[key] = DragEndedValue {true};
}
// Invalidate all stored payloads
void clear()
{
for (auto& p : dragBeganPayloadMap)
{
p.second.isValid = false;
}
for (auto& p : dragChangedPayloadMap)
{
p.second.isValid = false;
}
for (auto& p : dragEndedPayloadMap)
{
p.second.isValid = false;
}
}
bool empty()
{
if (std::any_of(dragBeganPayloadMap.begin(), dragBeganPayloadMap.end(),
[](auto const& p) {
return p.second.isValid;
}))
{
return false;
}
if (std::any_of(dragChangedPayloadMap.begin(), dragChangedPayloadMap.end(),
[](auto const& p) {
return p.second.isValid;
}))
{
return false;
}
if (std::any_of(dragEndedPayloadMap.begin(), dragEndedPayloadMap.end(),
[](auto const& p) {
return p.second.isValid;
}))
{
return false;
}
return true;
}
std::map<Key, DragBeganValue> const& dragBeganPayloads()
{
return dragBeganPayloadMap;
}
std::map<Key, DragChangedValue> const& dragChangedPayloads()
{
return dragChangedPayloadMap;
}
std::map<Key, DragEndedValue> const& dragEndedPayloads()
{
return dragEndedPayloadMap;
}
private:
std::map<Key, DragBeganValue> dragBeganPayloadMap;
std::map<Key, DragChangedValue> dragChangedPayloadMap;
std::map<Key, DragEndedValue> dragEndedPayloadMap;
StringMemo stringMemo;
};
using ViewportDragEventStateKey = ViewportDragEventPayloads::Key;
struct ViewportDragEventStateValue
{
bool isDragInProgress = false;
pxr::GfVec2d initialPositionNorm = {0.0, 0.0};
pxr::GfVec2d initialPositionPixel = {0.0, 0.0};
pxr::GfVec2d currentPositionNorm = {0.0, 0.0};
pxr::GfVec2d currentPositionPixel = {0.0, 0.0};
pxr::GfVec2d velocityNorm = {0.0, 0.0};
pxr::GfVec2d velocityPixel = {0.0, 0.0};
};
using ViewportDragEventStates = std::map<ViewportDragEventStateKey, ViewportDragEventStateValue>;
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnPrintText.py | """
This is the implementation of the OGN node defined in OgnPrintText.ogn
"""
import time
import carb
import omni.graph.core as og
from omni.kit.viewport.utility import get_viewport_from_window_name, post_viewport_message
class OgnOnCustomEventInternalState:
"""Convenience class for maintaining per-node state information"""
def __init__(self):
self.display_time: float = 0
class OgnPrintText:
"""
Prints text to the log and optionally the viewport
"""
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnOnCustomEventInternalState()
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
def ok():
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
return True
try:
toast_min_period_s = 5.0
to_screen = db.inputs.toScreen
log_level = db.inputs.logLevel.lower()
text = db.inputs.text
if not text:
return ok()
if log_level:
if log_level not in ("error", "warning", "warn", "info"):
db.log_error("Log Level must be one of error, warning or info")
return False
else:
log_level = "info"
if to_screen:
toast_time = db.internal_state.display_time
viewport_name = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport_name)
if viewport_api is None:
# Preserve legacy behavior of erroring when a name was provided
if viewport_name:
db.log_error(f"Could not get viewport window {viewport_name}")
return False
return ok()
now_s = time.time()
toast_age = now_s - toast_time
if toast_age > toast_min_period_s:
toast_time = 0
if toast_time == 0:
post_viewport_message(viewport_api, text)
db.state.displayTime = now_s
else:
# FIXME: Toast also prints to log so we only do one or the other
if log_level == "info":
carb.log_info(text)
elif log_level.startswith("warn"):
carb.log_warn(text)
else:
carb.log_error(text)
return ok()
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportHoverNodeCommon.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "UINodeCommon.h"
namespace omni
{
namespace graph
{
namespace ui
{
constexpr carb::events::EventType kHoverBeganEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.hover.began");
constexpr carb::events::EventType kHoverChangedEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.hover.changed");
constexpr carb::events::EventType kHoverEndedEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.hover.ended");
class ViewportHoverEventPayloads
{
public:
struct Key
{
char const* viewportWindowName;
bool operator<(Key const& other) const
{
return std::strcmp(viewportWindowName, other.viewportWindowName) < 0;
}
};
struct HoverBeganValue
{
pxr::GfVec2d positionNorm;
pxr::GfVec2d positionPixel;
bool isValid;
};
struct HoverChangedValue
{
pxr::GfVec2d positionNorm;
pxr::GfVec2d positionPixel;
pxr::GfVec2d velocityNorm;
pxr::GfVec2d velocityPixel;
bool isValid;
};
struct HoverEndedValue
{
bool isValid;
};
// Store a hover began event payload
void setHoverBeganPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {stringMemo.lookup(idict->get<char const*>(payload, "viewport"))};
hoverBeganPayloadMap[key] = HoverBeganValue {
pxr::GfVec2d {
idict->get<double>(payload, "pos_norm_x"),
idict->get<double>(payload, "pos_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "pos_pixel_x"),
idict->get<double>(payload, "pos_pixel_y")
},
true
};
}
// Store a hover changed event payload
void setHoverChangedPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {stringMemo.lookup(idict->get<char const*>(payload, "viewport"))};
hoverChangedPayloadMap[key] = HoverChangedValue {
pxr::GfVec2d {
idict->get<double>(payload, "pos_norm_x"),
idict->get<double>(payload, "pos_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "pos_pixel_x"),
idict->get<double>(payload, "pos_pixel_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "vel_norm_x"),
idict->get<double>(payload, "vel_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "vel_pixel_x"),
idict->get<double>(payload, "vel_pixel_y")
},
true
};
}
// Store a hover ended event payload
void setHoverEndedPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {stringMemo.lookup(idict->get<char const*>(payload, "viewport"))};
hoverEndedPayloadMap[key] = HoverEndedValue {true};
}
// Invalidate all stored payloads
void clear()
{
for (auto& p : hoverBeganPayloadMap)
{
p.second.isValid = false;
}
for (auto& p : hoverChangedPayloadMap)
{
p.second.isValid = false;
}
for (auto& p : hoverEndedPayloadMap)
{
p.second.isValid = false;
}
}
bool empty()
{
if (std::any_of(hoverBeganPayloadMap.begin(), hoverBeganPayloadMap.end(),
[](auto const& p) {
return p.second.isValid;
}))
{
return false;
}
if (std::any_of(hoverChangedPayloadMap.begin(), hoverChangedPayloadMap.end(),
[](auto const& p) {
return p.second.isValid;
}))
{
return false;
}
if (std::any_of(hoverEndedPayloadMap.begin(), hoverEndedPayloadMap.end(),
[](auto const& p) {
return p.second.isValid;
}))
{
return false;
}
return true;
}
std::map<Key, HoverBeganValue> const& hoverBeganPayloads()
{
return hoverBeganPayloadMap;
}
std::map<Key, HoverChangedValue> const& hoverChangedPayloads()
{
return hoverChangedPayloadMap;
}
std::map<Key, HoverEndedValue> const& hoverEndedPayloads()
{
return hoverEndedPayloadMap;
}
private:
std::map<Key, HoverBeganValue> hoverBeganPayloadMap;
std::map<Key, HoverChangedValue> hoverChangedPayloadMap;
std::map<Key, HoverEndedValue> hoverEndedPayloadMap;
StringMemo stringMemo;
};
using ViewportHoverEventStateKey = ViewportHoverEventPayloads::Key;
struct ViewportHoverEventStateValue
{
bool isHovered = false;
pxr::GfVec2d positionNorm = {0.0, 0.0};
pxr::GfVec2d positionPixel = {0.0, 0.0};
pxr::GfVec2d velocityNorm = {0.0, 0.0};
pxr::GfVec2d velocityPixel = {0.0, 0.0};
};
using ViewportHoverEventStates = std::map<ViewportHoverEventStateKey, ViewportHoverEventStateValue>;
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadViewportClickState.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnReadViewportClickStateDatabase.h>
#include "ViewportClickNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnReadViewportClickState
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr clickSub;
ViewportClickEventPayloads eventPayloads;
} m_internalState;
static void initialize(GraphContextObj const& context, NodeObj const& nodeObj)
{
OgnReadViewportClickState& state = OgnReadViewportClickStateDatabase::sm_stateManagerOgnReadViewportClickState
.getState<OgnReadViewportClickState>(nodeObj.nodeHandle);
// Subscribe to click events
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.clickSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kClickEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportClickState& state = OgnReadViewportClickStateDatabase::sm_stateManagerOgnReadViewportClickState
.getState<OgnReadViewportClickState>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setPayload(e->payload);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnReadViewportClickState& state = OgnReadViewportClickStateDatabase::sm_stateManagerOgnReadViewportClickState
.getState<OgnReadViewportClickState>(nodeObj.nodeHandle);
// Unsubscribe from click events
if (state.m_internalState.clickSub.get())
state.m_internalState.clickSub.detach()->unsubscribe();
}
static bool compute(OgnReadViewportClickStateDatabase& db)
{
OgnReadViewportClickState& state = db.internalState<OgnReadViewportClickState>();
// Get the targeted viewport and gesture
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
char const* const gestureName = db.tokenToString(db.inputs.gesture());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
auto const* eventPayloadValuePtr = state.m_internalState.eventPayloads.getPayloadValue(viewportWindowName, gestureName);
if (eventPayloadValuePtr)
{
db.outputs.position() = db.inputs.useNormalizedCoords() ? eventPayloadValuePtr->positionNorm : eventPayloadValuePtr->positionPixel;
db.outputs.isValid() = true;
}
else
{
db.outputs.position() = {0.0, 0.0};
db.outputs.isValid() = false;
}
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSetCameraTarget.cpp | // 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.
//
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include <OgnSetCameraTargetDatabase.h>
#include "CameraState.h"
#include "NodeUtils.h"
#include <pxr/base/gf/vec3d.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnSetCameraTarget
{
public:
static bool compute(OgnSetCameraTargetDatabase& db)
{
PXR_NS::UsdPrim prim = getPrimFromPathOrRelationship(db, OgnSetCameraTargetAttributes::inputs::prim.m_token);
if (!prim)
return false;
auto target = db.inputs.target();
auto rotate = db.inputs.rotate();
auto camera = PXR_NS::UsdGeomCamera(prim);
if (!camera)
return false;
CameraState cameraState(std::move(camera));
bool ok = cameraState.setCameraTarget({ target[0], target[1], target[2] }, rotate);
if (!ok)
{
db.logError("Could not set target for camera %s", prim.GetPath().GetText());
}
db.outputs.execOut() = kExecutionAttributeStateEnabled;
return true;
}
};
REGISTER_OGN_NODE()
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnPlacer.ogn | {
"Placer": {
"version": 1,
"description": [
"Contruct a Placer widget.",
"The Placer takes a single child and places it at a given position within it."
],
"uiName": "Placer (BETA)",
"language": "Python",
"categories": ["graph:action", "ui"],
"inputs": {
"create": {
"type": "execution",
"description": "Input execution to create and show the widget",
"uiName": "Create"
},
"widgetIdentifier": {
"type": "token",
"description": [
"An optional unique identifier for the widget.",
"Can be used to refer to this widget in other places such as the OnWidgetClicked node."
],
"uiName": "Widget Identifier",
"optional": true
},
"parentWidgetPath": {
"type": "token",
"description": "The absolute path to the parent widget.",
"uiName": "Parent Widget Path"
},
"position": {
"type": "double[2]",
"description": "Where to position the child widget within the Placer.",
"uiName": "Position"
},
"style": {
"type": "string",
"description": [
"Style to be applied to the Placer and its child. This can later be changed with the",
"WriteWidgetStyle node."
],
"optional": true
}
},
"outputs": {
"created": {
"type": "execution",
"description": "Executed when the widget is created",
"uiName": "Created"
},
"widgetPath": {
"type": "token",
"description": "The absolute path to the created Placer widget",
"uiName": "Widget Path"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadViewportHoverState.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnReadViewportHoverStateDatabase.h>
#include "ViewportHoverNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnReadViewportHoverState
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr hoverBeganSub;
carb::events::ISubscriptionPtr hoverChangedSub;
carb::events::ISubscriptionPtr hoverEndedSub;
carb::events::ISubscriptionPtr updateSub;
ViewportHoverEventPayloads eventPayloads;
ViewportHoverEventStates eventStates;
} m_internalState;
// Process event payloads and update event states every frame
static void updateEventStates(ViewportHoverEventStates& eventStates, ViewportHoverEventPayloads& eventPayloads)
{
for (auto& eventState : eventStates)
{
eventState.second.velocityNorm = {0.0, 0.0};
eventState.second.velocityPixel = {0.0, 0.0};
}
for (auto const& hoverBeganPayload : eventPayloads.hoverBeganPayloads())
{
if (!hoverBeganPayload.second.isValid)
continue;
auto& eventStateValue = eventStates[hoverBeganPayload.first];
eventStateValue.isHovered = true;
eventStateValue.positionNorm = hoverBeganPayload.second.positionNorm;
eventStateValue.positionPixel = hoverBeganPayload.second.positionPixel;
eventStateValue.velocityNorm = {0.0, 0.0};
eventStateValue.velocityPixel = {0.0, 0.0};
}
for (auto const& hoverChangedPayload : eventPayloads.hoverChangedPayloads())
{
if (!hoverChangedPayload.second.isValid)
continue;
auto& eventStateValue = eventStates[hoverChangedPayload.first];
if (eventStateValue.isHovered)
{
eventStateValue.positionNorm = hoverChangedPayload.second.positionNorm;
eventStateValue.positionPixel = hoverChangedPayload.second.positionPixel;
eventStateValue.velocityNorm = hoverChangedPayload.second.velocityNorm;
eventStateValue.velocityPixel = hoverChangedPayload.second.velocityPixel;
}
}
for (auto const& hoverEndedPayload : eventPayloads.hoverEndedPayloads())
{
if (!hoverEndedPayload.second.isValid)
continue;
auto& eventStateValue = eventStates[hoverEndedPayload.first];
if (eventStateValue.isHovered)
{
eventStateValue.isHovered = false;
eventStateValue.positionNorm = {0.0, 0.0};
eventStateValue.positionPixel = {0.0, 0.0};
eventStateValue.velocityNorm = {0.0, 0.0};
eventStateValue.velocityPixel = {0.0, 0.0};
}
}
eventPayloads.clear();
}
static void initialize(GraphContextObj const&, NodeObj const& nodeObj)
{
OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sm_stateManagerOgnReadViewportHoverState
.getState<OgnReadViewportHoverState>(nodeObj.nodeHandle);
// Subscribe to hover events and update tick
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.hoverBeganSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kHoverBeganEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sm_stateManagerOgnReadViewportHoverState
.getState<OgnReadViewportHoverState>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setHoverBeganPayload(e->payload);
}
}
);
state.m_internalState.hoverChangedSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kHoverChangedEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sm_stateManagerOgnReadViewportHoverState
.getState<OgnReadViewportHoverState>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setHoverChangedPayload(e->payload);
}
}
);
state.m_internalState.hoverEndedSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kHoverEndedEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sm_stateManagerOgnReadViewportHoverState
.getState<OgnReadViewportHoverState>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setHoverEndedPayload(e->payload);
}
}
);
state.m_internalState.updateSub = carb::events::createSubscriptionToPush(
app->getUpdateEventStream(),
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sm_stateManagerOgnReadViewportHoverState
.getState<OgnReadViewportHoverState>(nodeObj.nodeHandle);
updateEventStates(state.m_internalState.eventStates, state.m_internalState.eventPayloads);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sm_stateManagerOgnReadViewportHoverState
.getState<OgnReadViewportHoverState>(nodeObj.nodeHandle);
// Unsubscribe from hover events and update tick
if (state.m_internalState.hoverBeganSub.get())
state.m_internalState.hoverBeganSub.detach()->unsubscribe();
if (state.m_internalState.hoverChangedSub.get())
state.m_internalState.hoverChangedSub.detach()->unsubscribe();
if (state.m_internalState.hoverEndedSub.get())
state.m_internalState.hoverEndedSub.detach()->unsubscribe();
if (state.m_internalState.updateSub.get())
state.m_internalState.updateSub.detach()->unsubscribe();
}
static bool compute(OgnReadViewportHoverStateDatabase& db)
{
OgnReadViewportHoverState& state = db.internalState<OgnReadViewportHoverState>();
// Get the targeted viewport
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
// Output hover state
auto it = state.m_internalState.eventStates.find({viewportWindowName});
if (it != state.m_internalState.eventStates.end())
{
if (db.inputs.useNormalizedCoords())
{
db.outputs.position() = it->second.positionNorm;
db.outputs.velocity() = it->second.velocityNorm;
}
else
{
db.outputs.position() = it->second.positionPixel;
db.outputs.velocity() = it->second.velocityPixel;
}
db.outputs.isHovered() = it->second.isHovered;
db.outputs.isValid() = true;
}
else
{
db.outputs.position() = {0.0, 0.0};
db.outputs.velocity() = {0.0, 0.0};
db.outputs.isHovered() = false;
db.outputs.isValid() = false;
}
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnPicked.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnOnPickedDatabase.h>
#include "PickingNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/relationship.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <omni/graph/core/PostUsdInclude.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnOnPicked
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr pickingSub;
PickingEventPayloads eventPayloads;
} m_internalState;
static void initialize(GraphContextObj const&, NodeObj const& nodeObj)
{
OgnOnPicked& state = OgnOnPickedDatabase::sm_stateManagerOgnOnPicked.getState<OgnOnPicked>(nodeObj.nodeHandle);
// Subscribe to picking events
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.pickingSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kPickingEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnOnPicked& state = OgnOnPickedDatabase::sm_stateManagerOgnOnPicked.getState<OgnOnPicked>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setPayload(e->payload);
if (nodeObj.iNode->isValid(nodeObj))
nodeObj.iNode->requestCompute(nodeObj);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnOnPicked& state = OgnOnPickedDatabase::sm_stateManagerOgnOnPicked.getState<OgnOnPicked>(nodeObj.nodeHandle);
// Unsubscribe from picking events
if (state.m_internalState.pickingSub.get())
state.m_internalState.pickingSub.detach()->unsubscribe();
}
static bool compute(OgnOnPickedDatabase& db)
{
if (checkNodeDisabledForOnlyPlay(db))
return true;
OgnOnPicked& state = db.internalState<OgnOnPicked>();
if (state.m_internalState.eventPayloads.empty())
return true;
// Get the targeted viewport and gesture
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
char const* const gestureName = db.tokenToString(db.inputs.gesture());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
auto const* eventPayloadValuePtr = state.m_internalState.eventPayloads.getPayloadValue(viewportWindowName, gestureName);
if (eventPayloadValuePtr)
{
// Get the picked path and pos for the targeted viewport and gesture
char const* const pickedPrimPath = eventPayloadValuePtr->pickedPrimPath;
pxr::GfVec3d const& pickedWorldPos = eventPayloadValuePtr->pickedWorldPos;
// Determine if a tracked prim is picked
bool isTrackedPrimPicked;
pxr::SdfPathVector inputPaths;
// First determine if any prim is picked
bool const isAnyPrimPicked = pickedPrimPath && pickedPrimPath[0] != '\0';
if (isAnyPrimPicked)
{
// If any prim is picked, determine if the picked prim is tracked
// Get the list of tracked prims from the bundle input
long int stageId = db.abi_context().iContext->getStageId(db.abi_context());
pxr::UsdStageRefPtr stage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId));
auto nodeObj = db.abi_node();
pxr::UsdPrim nodePrim = stage->GetPrimAtPath(pxr::SdfPath(nodeObj.iNode->getPrimPath(nodeObj)));
nodePrim.GetRelationship(kTrackedPrimsRelToken).GetTargets(&inputPaths);
// If no tracked prims are specified then we consider all prims to be tracked
// Else search the list of tracked prims for the picked prim
if (inputPaths.empty())
isTrackedPrimPicked = true;
else
isTrackedPrimPicked = std::any_of(inputPaths.begin(), inputPaths.end(),
[pickedPrimPath](pxr::SdfPath const& path) {
return (std::strcmp(path.GetText(), pickedPrimPath) == 0);
});
}
else
{
// No prim is picked at all, so a tracked prim certainly isn't picked
isTrackedPrimPicked = false;
}
// Set outputs
db.outputs.pickedPrimPath() = db.stringToToken(pickedPrimPath);
db.outputs.pickedWorldPos() = pickedWorldPos;
db.outputs.isTrackedPrimPicked() = isTrackedPrimPicked;
auto& outputPaths = db.outputs.trackedPrimPaths();
outputPaths.resize(inputPaths.size());
std::transform(inputPaths.begin(), inputPaths.end(), outputPaths.begin(),
[&db](pxr::SdfPath const& path) {
return db.stringToToken(path.GetText());
});
if (isTrackedPrimPicked)
{
db.outputs.picked() = kExecutionAttributeStateEnabled;
db.outputs.missed() = kExecutionAttributeStateDisabled;
}
else
{
db.outputs.picked() = kExecutionAttributeStateDisabled;
db.outputs.missed() = kExecutionAttributeStateEnabled;
}
}
state.m_internalState.eventPayloads.clear();
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/PickingNodeCommon.h | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "UINodeCommon.h"
namespace omni
{
namespace graph
{
namespace ui
{
constexpr carb::events::EventType kPickingEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.picking");
pxr::TfToken const kTrackedPrimsRelToken {"inputs:trackedPrims"};
class PickingEventPayloads
{
public:
struct Key
{
char const* viewportWindowName;
char const* gestureName;
bool operator<(Key const& other) const
{
int const ret = std::strcmp(viewportWindowName, other.viewportWindowName);
if (ret < 0)
return true;
else if (ret <= 0)
return std::strcmp(gestureName, other.gestureName) < 0;
return false;
}
};
struct Value
{
char const* pickedPrimPath;
pxr::GfVec3d pickedWorldPos;
bool isValid;
};
// Store an event payload as a key-value pair
void setPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {
stringMemo.lookup(idict->get<char const*>(payload, "viewport")),
stringMemo.lookup(idict->get<char const*>(payload, "gesture"))
};
payloadMap[key] = Value {
stringMemo.lookup(idict->get<char const*>(payload, "path")),
pxr::GfVec3d {
idict->get<double>(payload, "pos_x"),
idict->get<double>(payload, "pos_y"),
idict->get<double>(payload, "pos_z")
},
true
};
}
// Retrieve a payload value by key
Value const* getPayloadValue(char const* viewportWindowName, char const* gestureName)
{
auto it = payloadMap.find({viewportWindowName, gestureName});
if (it != payloadMap.end() && it->second.isValid)
{
return &(it->second);
}
return nullptr;
}
// Invalidate all stored payloads
void clear()
{
for (auto& p : payloadMap) {
p.second.isValid = false;
}
}
// Check if there exists a valid payload
bool empty()
{
return std::none_of(payloadMap.begin(), payloadMap.end(),
[](auto const& p) {
return p.second.isValid;
});
}
private:
std::map<Key, Value> payloadMap;
StringMemo stringMemo;
};
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportClicked.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnOnViewportClickedDatabase.h>
#include "ViewportClickNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnOnViewportClicked
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr clickSub;
ViewportClickEventPayloads eventPayloads;
} m_internalState;
static void initialize(GraphContextObj const&, NodeObj const& nodeObj)
{
OgnOnViewportClicked& state = OgnOnViewportClickedDatabase::sm_stateManagerOgnOnViewportClicked.getState<OgnOnViewportClicked>(nodeObj.nodeHandle);
// Subscribe to click events
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.clickSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kClickEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnOnViewportClicked& state = OgnOnViewportClickedDatabase::sm_stateManagerOgnOnViewportClicked.getState<OgnOnViewportClicked>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setPayload(e->payload);
if (nodeObj.iNode->isValid(nodeObj))
nodeObj.iNode->requestCompute(nodeObj);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnOnViewportClicked& state = OgnOnViewportClickedDatabase::sm_stateManagerOgnOnViewportClicked.getState<OgnOnViewportClicked>(nodeObj.nodeHandle);
// Unsubscribe from click events
if (state.m_internalState.clickSub.get())
state.m_internalState.clickSub.detach()->unsubscribe();
}
static bool compute(OgnOnViewportClickedDatabase& db)
{
if (checkNodeDisabledForOnlyPlay(db))
return true;
OgnOnViewportClicked& state = db.internalState<OgnOnViewportClicked>();
if (state.m_internalState.eventPayloads.empty())
return true;
// Get the targeted viewport and gesture
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
char const* const gestureName = db.tokenToString(db.inputs.gesture());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
auto const* eventPayloadValuePtr = state.m_internalState.eventPayloads.getPayloadValue(viewportWindowName, gestureName);
if (eventPayloadValuePtr)
{
db.outputs.position() = db.inputs.useNormalizedCoords() ? eventPayloadValuePtr->positionNorm : eventPayloadValuePtr->positionPixel;
db.outputs.clicked() = kExecutionAttributeStateEnabled;
}
state.m_internalState.eventPayloads.clear();
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSpacer.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.graph.core as og
import omni.ui as ui
from . import UINodeCommon
class OgnSpacer(UINodeCommon.OgWidgetNode):
@staticmethod
def compute(db) -> bool:
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
db.log_error("No parentWidgetPath supplied.")
return False
parent_widget = UINodeCommon.find_widget_among_all_windows(parent_widget_path)
if parent_widget is None:
db.log_error("Could not find parent widget.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
# Now create the spacer widget and register it.
with parent_widget:
spacer = ui.Spacer(identifier=widget_identifier, width=db.inputs.width, height=db.inputs.height)
if style:
spacer.set_style(style)
OgnSpacer.register_widget(db.abi_context, widget_identifier, spacer)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(spacer)
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
# The spacer has no properties or styles of its own: height and width are base Widget properties.
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadMouseState.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnReadMouseStateDatabase.h>
#include <carb/input/IInput.h>
#include <carb/input/InputTypes.h>
#include <omni/kit/IAppWindow.h>
#include <omni/ui/Workspace.h>
using namespace carb::input;
namespace omni {
namespace graph {
namespace ui {
// We do not read the specific input for scrolls and movements for four directions
// We only read the coordinates instead, normalized one or absolute one.
constexpr size_t s_numNames = size_t(carb::input::MouseInput::eCount) - 8 + 2;
static std::array<NameToken, s_numNames> s_mouseInputTokens;
class OgnReadMouseState
{
public:
static bool compute(OgnReadMouseStateDatabase& db)
{
NameToken const& mouseIn = db.inputs.mouseElement();
// First time look up all the token string values
static bool callOnce = ([&db] {
s_mouseInputTokens = {
db.tokens.LeftButton,
db.tokens.RightButton,
db.tokens.MiddleButton,
db.tokens.ForwardButton,
db.tokens.BackButton,
db.tokens.MouseCoordsNormalized,
db.tokens.MouseCoordsPixel
};
} (), true);
omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow();
if (!appWindow)
{
return false;
}
Mouse* mouse = appWindow->getMouse();
if (!mouse)
{
CARB_LOG_ERROR_ONCE("No Mouse!");
return false;
}
IInput* input = carb::getCachedInterface<IInput>();
if (!input)
{
CARB_LOG_ERROR_ONCE("No Input!");
return false;
}
bool isPressed = false;
// Get the index of the token of the mouse input of interest
auto iter = std::find(s_mouseInputTokens.begin(), s_mouseInputTokens.end(), mouseIn);
if (iter == s_mouseInputTokens.end())
return true;
size_t token_index = iter - s_mouseInputTokens.begin();
if (token_index < 5) // Mouse Input is related to a button
{
MouseInput button = MouseInput(token_index);
isPressed = (carb::input::kButtonFlagStateDown & input->getMouseButtonFlags(mouse, button));
db.outputs.isPressed() = isPressed;
}
else // Mouse Input is position
{
carb::Float2 coords = input->getMouseCoordsPixel(mouse);
bool foundWindow{ false };
NameToken windowToken = carb::flatcache::kUninitializedToken;
float windowWidth = static_cast<float>(appWindow->getWidth());
float windowHeight = static_cast<float>(appWindow->getHeight());
if (db.inputs.useRelativeCoords())
{
// Find the workspace window the mouse pointer is over, and convert the coords to window-relative
for (auto const& window : omni::ui::Workspace::getWindows())
{
if ((window->isDocked() && (! window->isSelectedInDock()) || (! window->isVisible())))
continue;
std::string const& windowTitle = window->getTitle();
if (windowTitle == "DockSpace")
continue;
float dpiScale = omni::ui::Workspace::getDpiScale();
float left = window->getPositionX() * dpiScale;
float top = window->getPositionY() * dpiScale;
float curWindowWidth = window->getWidth() * dpiScale;
float curWindowHeight = window->getHeight() * dpiScale;
if (coords.x >= left && coords.y >= top && coords.x <= left + curWindowWidth && coords.y <= top + curWindowHeight)
{
foundWindow = true;
coords.x -= left;
coords.y -= top;
windowToken = db.stringToToken(windowTitle.c_str());
windowWidth = curWindowWidth;
windowHeight = curWindowHeight;
break;
}
}
}
else
{
foundWindow = true;
}
float* data = db.outputs.coords().data();
if (foundWindow)
{
if (*iter == db.tokens.MouseCoordsNormalized)
{
coords.x /= windowWidth;
coords.y /= windowHeight;
}
data[0] = coords.x;
data[1] = coords.y;
}
else
{
data[0] = 0.f;
data[1] = 0.f;
}
if (windowToken == carb::flatcache::kUninitializedToken)
windowToken = db.stringToToken("");
db.outputs.window() = windowToken;
}
return true;
}
};
REGISTER_OGN_NODE()
} // namespace ui
} // namespace graph
} // namespace omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportClicked.ogn | {
"OnViewportClicked": {
"version": 1,
"description": [
"Event node which fires when a viewport click event occurs in the specified viewport.",
"Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."
],
"uiName": "On Viewport Clicked (BETA)",
"categories": ["graph:action", "ui"],
"scheduling": "compute-on-request",
"inputs": {
"useNormalizedCoords": {
"type": "bool",
"description": [
"When true, the components of the 2D position output are scaled to between 0 and 1,",
"where 0 is top/left and 1 is bottom/right.",
"When false, components are in viewport render resolution pixels."
],
"uiName": "Use Normalized Coords",
"default": false,
"metadata": {
"literalOnly": "1"
}
},
"viewport": {
"type": "token",
"description": "Name of the viewport window to watch for click events",
"uiName": "Viewport",
"default": "Viewport",
"metadata": {
"literalOnly": "1"
}
},
"gesture": {
"type": "token",
"description": "The input gesture to trigger viewport click events",
"uiName": "Gesture",
"default": "Left Mouse Click",
"metadata": {
"displayGroup": "parameters",
"literalOnly": "1",
"allowedTokens": {
"LeftMouseClick": "Left Mouse Click",
"RightMouseClick": "Right Mouse Click",
"MiddleMouseClick": "Middle Mouse Click"
}
}
},
"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": {
"clicked": {
"type": "execution",
"description": "Enabled when the specified input gesture triggers a viewport click event in the specified viewport",
"uiName": "Clicked"
},
"position": {
"type": "double[2]",
"description": "The position at which the viewport click event occurred",
"uiName": "Position"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnDrawDebugCurve.ogn | {
"DrawDebugCurve": {
"version": 1,
"categories": "debug",
"description": [
"Given a set of curve points, draw a curve in the viewport"],
"language": "Python",
"uiName": "Draw Debug Curve",
"exclude": ["tests"],
"inputs": {
"execIn": {
"type": "execution",
"description": "Execution input",
"uiName": "In"
},
"curvepoints": {
"type": "double[3][]",
"description": "The curve to be drawn",
"uiName": "Curve Points"
},
"color": {
"type": "colorf[3]",
"description": "The color of the curve",
"uiName": "Color"
},
"closed": {
"type": "bool",
"description": "When true, connect the last point to the first",
"uiName": "Closed"
}
},
"outputs": {
"execOut": {
"type": "execution",
"description": "Execution Output",
"uiName": "Out"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSetActiveViewportCamera.ogn | {
"SetActiveViewportCamera": {
"version": 1,
"description": "Sets Viewport's actively bound camera to given camera at give path",
"language": "Python",
"uiName": "Set Active Camera",
"exclude": ["tests"],
"categories": ["sceneGraph:camera"],
"inputs": {
"primPath": {
"type": "token",
"description": "Path of the camera to bind",
"uiName": "Camera Path"
},
"viewport": {
"type": "token",
"description": "Name of the viewport, or empty for the default viewport",
"uiName": "Viewport"
},
"execIn": {
"type": "execution",
"description": "Execution input",
"uiName": "In"
}
},
"outputs": {
"execOut": {
"type": "execution",
"description": "Execution Output",
"uiName": "Out"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnGetActiveViewportCamera.ogn | {
"GetActiveViewportCamera": {
"version": 1,
"description": "Gets the path of the camera bound to a viewport",
"language": "Python",
"uiName": "Get Active Camera",
"exclude": ["tests"],
"categories": ["sceneGraph:camera"],
"inputs": {
"viewport": {
"type": "token",
"description": "Name of the viewport, or empty for the default viewport",
"uiName": "Viewport"
}
},
"outputs": {
"camera": {
"type": "token",
"description": "Path of the active camera",
"uiName": "Camera"
}
},
"tests": [
{"outputs:camera": "/OmniverseKit_Persp"}
]
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadWidgetProperty.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 . import UINodeCommon
class OgnReadWidgetProperty:
@staticmethod
def compute(db) -> bool:
widget_path = db.inputs.widgetPath
if not widget_path:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
db.log_warning("No widgetIdentifier or widgetPath provided.")
return False
widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier)
if not widget:
db.log_warning(f"No widget with identifier '{widget_identifier}' found in this graph.")
return False
else:
widget = UINodeCommon.find_widget_among_all_windows(widget_path)
if not widget:
db.log_warning(f"No widget found at path '{widget_path}'.")
return False
# For error messages only.
widget_identifier = widget_path
property_name = db.inputs.propertyName
if not property_name:
db.log_warning("No property provided.")
return False
if not hasattr(widget, property_name):
db.log_error(f"Widget '{widget_identifier}' has no property '{property_name}'.")
return False
widget_summary = f"widget '{widget_identifier}' ({type(widget)})"
callbacks = UINodeCommon.get_widget_callbacks(widget)
if not callbacks:
db.log_error(f"{widget_summary} is not supported by the ReadWidgetProperty node.")
return False
if not hasattr(callbacks, "get_property_names") or not callable(callbacks.get_property_names):
db.log_error(f"No 'get_property_names' callback found for {widget_summary}")
return False
readable_props = callbacks.get_property_names(widget, False)
if not readable_props or property_name not in readable_props:
db.log_error(f"'{property_name}' is not a readable property of {widget_summary}")
return False
if not hasattr(callbacks, "resolve_output_property") or not callable(callbacks.resolve_output_property):
db.log_error(f"No 'resolve_output_property' callback found for {widget_summary}")
return False
if not callbacks.resolve_output_property(widget, property_name, db.node.get_attribute("outputs:value")):
db.log_error(f"Could resolve outputs from '{property_name}' for {widget_summary}")
return False
if not hasattr(callbacks, "get_property_value") or not callable(callbacks.get_property_value):
db.log_error(f"No 'get_property_value' callback found for {widget_summary}")
return False
if not callbacks.get_property_value(widget, property_name, db.outputs.value):
db.log_error(f"Could not get value of '{property_name}' on {widget_summary}")
return False
return True
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportScrolled.cpp | // Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnOnViewportScrolledDatabase.h>
#include "ViewportScrollNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
namespace omni
{
namespace graph
{
namespace ui
{
class OgnOnViewportScrolled
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr scrollSub;
ViewportScrollEventPayloads eventPayloads;
} m_internalState;
static void initialize(GraphContextObj const&, NodeObj const& nodeObj)
{
OgnOnViewportScrolled& state = OgnOnViewportScrolledDatabase::sm_stateManagerOgnOnViewportScrolled.getState<OgnOnViewportScrolled>(nodeObj.nodeHandle);
// Subscribe to scroll events
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.scrollSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kScrollEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnOnViewportScrolled& state = OgnOnViewportScrolledDatabase::sm_stateManagerOgnOnViewportScrolled.getState<OgnOnViewportScrolled>(nodeObj.nodeHandle);
state.m_internalState.eventPayloads.setPayload(e->payload);
if (nodeObj.iNode->isValid(nodeObj))
nodeObj.iNode->requestCompute(nodeObj);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnOnViewportScrolled& state = OgnOnViewportScrolledDatabase::sm_stateManagerOgnOnViewportScrolled.getState<OgnOnViewportScrolled>(nodeObj.nodeHandle);
// Unsubscribe from scroll events
if (state.m_internalState.scrollSub.get())
state.m_internalState.scrollSub.detach()->unsubscribe();
}
static bool compute(OgnOnViewportScrolledDatabase& db)
{
if (checkNodeDisabledForOnlyPlay(db))
return true;
OgnOnViewportScrolled& state = db.internalState<OgnOnViewportScrolled>();
if (state.m_internalState.eventPayloads.empty())
return true;
// Get the targeted viewport
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
auto const* eventPayloadValuePtr = state.m_internalState.eventPayloads.getPayloadValue(viewportWindowName);
if (eventPayloadValuePtr)
{
db.outputs.scrollValue() = eventPayloadValuePtr->scrollValue;
db.outputs.position() = db.inputs.useNormalizedCoords() ? eventPayloadValuePtr->positionNorm : eventPayloadValuePtr->positionPixel;
db.outputs.scrolled() = kExecutionAttributeStateEnabled;
}
state.m_internalState.eventPayloads.clear();
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSpacer.ogn | {
"Spacer": {
"version": 1,
"description": ["A widget that leaves empty space."],
"uiName": "Spacer (BETA)",
"language": "Python",
"categories": ["graph:action", "ui"],
"inputs": {
"create": {
"type": "execution",
"description": "Input execution to create and show the widget",
"uiName": "Create"
},
"height": {
"type": "int",
"description": "The amount of vertical space to leave, in pixels.",
"uiName": "Height",
"default": 0,
"optional": true
},
"width": {
"type": "int",
"description": "The amount of horizontal space to leave, in pixels.",
"uiName": "Width",
"default": 0,
"optional": true
},
"parentWidgetPath": {
"type": "token",
"description": "The absolute path to the parent widget.",
"uiName": "Parent Widget Path"
},
"widgetIdentifier": {
"type": "token",
"description": [
"An optional unique identifier for the widget.",
"Can be used to refer to this widget in other places such as the OnWidgetClicked node."
],
"uiName": "Widget Identifier",
"optional": true
},
"style": {
"type": "string",
"description":
"Style to be applied to the spacer. This can later be changed with the WriteWidgetStyle node.",
"optional": true
}
},
"outputs": {
"created": {
"type": "execution",
"description": "Executed when the widget is created",
"uiName": "Created"
},
"widgetPath": {
"type": "token",
"description": "The absolute path to the created widget",
"uiName": "Widget Path"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnGetCameraPosition.ogn | {
"GetCameraPosition": {
"version": 1,
"description": "Gets a viewport camera position",
"uiName": "Get Camera Position",
"exclude": ["tests"],
"categories": ["sceneGraph:camera"],
"inputs": {
"usePath": {
"type": "bool",
"default": true,
"description": "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute"
},
"prim": {
"type": "bundle",
"description": "The camera prim, when 'usePath' is false",
"optional": true
},
"primPath": {
"type": "token",
"description": "Path of the camera, used when 'usePath' is true",
"uiName": "Camera Path"
}
},
"outputs": {
"position": {
"type": "pointd[3]",
"description": "The position of the camera in world space",
"uiName": "Position"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadViewportHoverState.ogn | {
"ReadViewportHoverState": {
"version": 1,
"description": [
"Read the state of the last viewport hover event from the specified viewport.",
"Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."
],
"uiName": "Read Viewport Hover State (BETA)",
"categories": ["ui"],
"inputs": {
"useNormalizedCoords": {
"type": "bool",
"description": [
"When true, the components of 2D position and velocity outputs are scaled to between 0 and 1,",
"where 0 is top/left and 1 is bottom/right.",
"When false, components are in viewport render resolution pixels."
],
"uiName": "Use Normalized Coords",
"default": false
},
"viewport": {
"type": "token",
"description": "Name of the viewport window to watch for hover events",
"uiName": "Viewport",
"default": "Viewport"
}
},
"outputs": {
"position": {
"type": "double[2]",
"description": "The current mouse position if the specified viewport is currently hovered, otherwise (0,0)",
"uiName": "Position"
},
"velocity": {
"type": "double[2]",
"description": [
"A vector representing the change in position of the mouse since the previous frame",
"if the specified viewport is currently hovered, otherwise (0,0)"
],
"uiName": "Velocity"
},
"isHovered": {
"type": "bool",
"description": "True if the specified viewport is currently hovered",
"uiName": "Is Hovered"
},
"isValid": {
"type": "bool",
"description": "True if a valid event state was detected and the outputs of this node are valid, and false otherwise",
"uiName": "Is Valid"
}
}
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSetActiveViewportCamera.py | """
This is the implementation of the OGN node defined in OgnSetActiveViewportCamera.ogn
"""
import omni.graph.core as og
from omni.kit.viewport.utility import get_viewport_from_window_name
from pxr import Sdf, UsdGeom
class OgnSetActiveViewportCamera:
"""
Sets a viewport's actively bound camera to a free camera
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
db.outputs.execOut = og.ExecutionAttributeState.DISABLED
try:
new_camera_path = db.inputs.primPath
if not Sdf.Path.IsValidPathString(new_camera_path):
return True
viewport_name = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport_name)
if not viewport_api:
return True
stage = viewport_api.stage
new_camera_prim = stage.GetPrimAtPath(new_camera_path) if stage else False
if not new_camera_prim:
return True
if not new_camera_prim.IsA(UsdGeom.Camera):
return True
new_camera_path = Sdf.Path(new_camera_path)
if viewport_api.camera_path != new_camera_path:
viewport_api.camera_path = new_camera_path
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
return True
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnWriteWidgetProperty.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.graph.core as og
from . import UINodeCommon
class OgnWriteWidgetProperty:
@staticmethod
def compute(db) -> bool:
if db.inputs.write != og.ExecutionAttributeState.DISABLED:
widget_path = db.inputs.widgetPath
if not widget_path:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
db.log_warning("No widgetIdentifier or widgetPath provided.")
return False
widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier)
if not widget:
db.log_warning(f"No widget with identifier '{widget_identifier}' found in this graph.")
return False
else:
widget = UINodeCommon.find_widget_among_all_windows(widget_path)
if not widget:
db.log_warning(f"No widget found at path '{widget_path}'.")
return False
# For error messages only.
widget_identifier = widget_path
property_name = db.inputs.propertyName
if not property_name:
db.log_error("No property provided.")
return False
if not hasattr(widget, property_name):
db.log_error(f"Widget '{widget_identifier}' has no property '{property_name}'.")
return False
widget_summary = f"widget '{widget_identifier}' ({type(widget)})"
callbacks = UINodeCommon.get_widget_callbacks(widget)
if not callbacks:
db.log_error(f"{widget_summary} is not supported by the WriteWidgetProperty node.")
return False
if not hasattr(callbacks, "get_property_names") or not callable(callbacks.get_property_names):
db.log_error(f"No 'get_property_names' callback found for {widget_summary}")
return False
writeable_props = callbacks.get_property_names(widget, True)
if not writeable_props or property_name not in writeable_props:
db.log_error(f"'{property_name}' is not a writeable property of {widget_summary}")
return False
if not hasattr(callbacks, "set_property_value") or not callable(callbacks.set_property_value):
db.log_error(f"No 'set_property_value' callback found for {widget_summary}")
return False
if not callbacks.set_property_value(widget, property_name, db.inputs.value):
db.log_error(f"Could not set value of '{property_name}' on {widget_summary}")
return False
db.outputs.written = og.ExecutionAttributeState.ENABLED
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnOnWidgetClicked.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.ui.ogn.OgnOnWidgetClickedDatabase import OgnOnWidgetClickedDatabase
test_file_name = "OgnOnWidgetClickedTemplate.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_ui_OnWidgetClicked")
database = OgnOnWidgetClickedDatabase(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:widgetIdentifier"))
attribute = test_node.get_attribute("inputs:widgetIdentifier")
db_value = database.inputs.widgetIdentifier
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:clicked"))
attribute = test_node.get_attribute("outputs:clicked")
db_value = database.outputs.clicked
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnOnViewportHovered.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.ui.ogn.OgnOnViewportHoveredDatabase import OgnOnViewportHoveredDatabase
test_file_name = "OgnOnViewportHoveredTemplate.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_ui_OnViewportHovered")
database = OgnOnViewportHoveredDatabase(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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:began"))
attribute = test_node.get_attribute("outputs:began")
db_value = database.outputs.began
self.assertTrue(test_node.get_attribute_exists("outputs:ended"))
attribute = test_node.get_attribute("outputs:ended")
db_value = database.outputs.ended
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnReadViewportHoverState.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.ui.ogn.OgnReadViewportHoverStateDatabase import OgnReadViewportHoverStateDatabase
test_file_name = "OgnReadViewportHoverStateTemplate.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_ui_ReadViewportHoverState")
database = OgnReadViewportHoverStateDatabase(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:useNormalizedCoords"))
attribute = test_node.get_attribute("inputs:useNormalizedCoords")
db_value = database.inputs.useNormalizedCoords
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:isHovered"))
attribute = test_node.get_attribute("outputs:isHovered")
db_value = database.outputs.isHovered
self.assertTrue(test_node.get_attribute_exists("outputs:isValid"))
attribute = test_node.get_attribute("outputs:isValid")
db_value = database.outputs.isValid
self.assertTrue(test_node.get_attribute_exists("outputs:position"))
attribute = test_node.get_attribute("outputs:position")
db_value = database.outputs.position
self.assertTrue(test_node.get_attribute_exists("outputs:velocity"))
attribute = test_node.get_attribute("outputs:velocity")
db_value = database.outputs.velocity
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnSetViewportMode.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.ui.ogn.OgnSetViewportModeDatabase import OgnSetViewportModeDatabase
test_file_name = "OgnSetViewportModeTemplate.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_ui_SetViewportMode")
database = OgnSetViewportModeDatabase(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:enablePicking"))
attribute = test_node.get_attribute("inputs:enablePicking")
db_value = database.inputs.enablePicking
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:enableViewportMouseEvents"))
attribute = test_node.get_attribute("inputs:enableViewportMouseEvents")
db_value = database.inputs.enableViewportMouseEvents
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:mode"))
attribute = test_node.get_attribute("inputs:mode")
db_value = database.inputs.mode
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:defaultMode"))
attribute = test_node.get_attribute("outputs:defaultMode")
db_value = database.outputs.defaultMode
self.assertTrue(test_node.get_attribute_exists("outputs:scriptedMode"))
attribute = test_node.get_attribute("outputs:scriptedMode")
db_value = database.outputs.scriptedMode
self.assertTrue(test_node.get_attribute_exists("outputs:widgetPath"))
attribute = test_node.get_attribute("outputs:widgetPath")
db_value = database.outputs.widgetPath
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnReadWidgetProperty.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.ui.ogn.OgnReadWidgetPropertyDatabase import OgnReadWidgetPropertyDatabase
test_file_name = "OgnReadWidgetPropertyTemplate.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_ui_ReadWidgetProperty")
database = OgnReadWidgetPropertyDatabase(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:propertyName"))
attribute = test_node.get_attribute("inputs:propertyName")
db_value = database.inputs.propertyName
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:widgetIdentifier"))
attribute = test_node.get_attribute("inputs:widgetIdentifier")
db_value = database.inputs.widgetIdentifier
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:widgetPath"))
attribute = test_node.get_attribute("inputs:widgetPath")
db_value = database.inputs.widgetPath
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.ui/omni/graph/ui/ogn/tests/TestOgnOnViewportPressed.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.ui.ogn.OgnOnViewportPressedDatabase import OgnOnViewportPressedDatabase
test_file_name = "OgnOnViewportPressedTemplate.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_ui_OnViewportPressed")
database = OgnOnViewportPressedDatabase(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:gesture"))
attribute = test_node.get_attribute("inputs:gesture")
db_value = database.inputs.gesture
expected_value = "Left Mouse Press"
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:useNormalizedCoords"))
attribute = test_node.get_attribute("inputs:useNormalizedCoords")
db_value = database.inputs.useNormalizedCoords
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:isReleasePositionValid"))
attribute = test_node.get_attribute("outputs:isReleasePositionValid")
db_value = database.outputs.isReleasePositionValid
self.assertTrue(test_node.get_attribute_exists("outputs:pressPosition"))
attribute = test_node.get_attribute("outputs:pressPosition")
db_value = database.outputs.pressPosition
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:releasePosition"))
attribute = test_node.get_attribute("outputs:releasePosition")
db_value = database.outputs.releasePosition
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.ui/omni/graph/ui/ogn/tests/TestOgnPlacer.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.ui.ogn.OgnPlacerDatabase import OgnPlacerDatabase
test_file_name = "OgnPlacerTemplate.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_ui_Placer")
database = OgnPlacerDatabase(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:create"))
attribute = test_node.get_attribute("inputs:create")
db_value = database.inputs.create
self.assertTrue(test_node.get_attribute_exists("inputs:parentWidgetPath"))
attribute = test_node.get_attribute("inputs:parentWidgetPath")
db_value = database.inputs.parentWidgetPath
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:position"))
attribute = test_node.get_attribute("inputs:position")
db_value = database.inputs.position
expected_value = [0.0, 0.0]
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:created"))
attribute = test_node.get_attribute("outputs:created")
db_value = database.outputs.created
self.assertTrue(test_node.get_attribute_exists("outputs:widgetPath"))
attribute = test_node.get_attribute("outputs:widgetPath")
db_value = database.outputs.widgetPath
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnReadViewportPressState.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.ui.ogn.OgnReadViewportPressStateDatabase import OgnReadViewportPressStateDatabase
test_file_name = "OgnReadViewportPressStateTemplate.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_ui_ReadViewportPressState")
database = OgnReadViewportPressStateDatabase(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:gesture"))
attribute = test_node.get_attribute("inputs:gesture")
db_value = database.inputs.gesture
expected_value = "Left Mouse Press"
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:useNormalizedCoords"))
attribute = test_node.get_attribute("inputs:useNormalizedCoords")
db_value = database.inputs.useNormalizedCoords
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:isReleasePositionValid"))
attribute = test_node.get_attribute("outputs:isReleasePositionValid")
db_value = database.outputs.isReleasePositionValid
self.assertTrue(test_node.get_attribute_exists("outputs:isValid"))
attribute = test_node.get_attribute("outputs:isValid")
db_value = database.outputs.isValid
self.assertTrue(test_node.get_attribute_exists("outputs:pressPosition"))
attribute = test_node.get_attribute("outputs:pressPosition")
db_value = database.outputs.pressPosition
self.assertTrue(test_node.get_attribute_exists("outputs:releasePosition"))
attribute = test_node.get_attribute("outputs:releasePosition")
db_value = database.outputs.releasePosition
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnReadViewportClickState.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.ui.ogn.OgnReadViewportClickStateDatabase import OgnReadViewportClickStateDatabase
test_file_name = "OgnReadViewportClickStateTemplate.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_ui_ReadViewportClickState")
database = OgnReadViewportClickStateDatabase(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:gesture"))
attribute = test_node.get_attribute("inputs:gesture")
db_value = database.inputs.gesture
expected_value = "Left Mouse Click"
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:useNormalizedCoords"))
attribute = test_node.get_attribute("inputs:useNormalizedCoords")
db_value = database.inputs.useNormalizedCoords
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:isValid"))
attribute = test_node.get_attribute("outputs:isValid")
db_value = database.outputs.isValid
self.assertTrue(test_node.get_attribute_exists("outputs:position"))
attribute = test_node.get_attribute("outputs:position")
db_value = database.outputs.position
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnSpacer.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.ui.ogn.OgnSpacerDatabase import OgnSpacerDatabase
test_file_name = "OgnSpacerTemplate.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_ui_Spacer")
database = OgnSpacerDatabase(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:create"))
attribute = test_node.get_attribute("inputs:create")
db_value = database.inputs.create
self.assertTrue(test_node.get_attribute_exists("inputs:parentWidgetPath"))
attribute = test_node.get_attribute("inputs:parentWidgetPath")
db_value = database.inputs.parentWidgetPath
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:created"))
attribute = test_node.get_attribute("outputs:created")
db_value = database.outputs.created
self.assertTrue(test_node.get_attribute_exists("outputs:widgetPath"))
attribute = test_node.get_attribute("outputs:widgetPath")
db_value = database.outputs.widgetPath
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnComboBox.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.ui.ogn.OgnComboBoxDatabase import OgnComboBoxDatabase
test_file_name = "OgnComboBoxTemplate.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_ui_ComboBox")
database = OgnComboBoxDatabase(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:create"))
attribute = test_node.get_attribute("inputs:create")
db_value = database.inputs.create
self.assertTrue(test_node.get_attribute_exists("inputs:disable"))
attribute = test_node.get_attribute("inputs:disable")
db_value = database.inputs.disable
self.assertTrue(test_node.get_attribute_exists("inputs:enable"))
attribute = test_node.get_attribute("inputs:enable")
db_value = database.inputs.enable
self.assertTrue(test_node.get_attribute_exists("inputs:hide"))
attribute = test_node.get_attribute("inputs:hide")
db_value = database.inputs.hide
self.assertTrue(test_node.get_attribute_exists("inputs:itemList"))
attribute = test_node.get_attribute("inputs:itemList")
db_value = database.inputs.itemList
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:show"))
attribute = test_node.get_attribute("inputs:show")
db_value = database.inputs.show
self.assertTrue(test_node.get_attribute_exists("inputs:tearDown"))
attribute = test_node.get_attribute("inputs:tearDown")
db_value = database.inputs.tearDown
self.assertTrue(test_node.get_attribute_exists("inputs:width"))
attribute = test_node.get_attribute("inputs:width")
db_value = database.inputs.width
expected_value = 100.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:created"))
attribute = test_node.get_attribute("outputs:created")
db_value = database.outputs.created
self.assertTrue(test_node.get_attribute_exists("outputs:widgetPath"))
attribute = test_node.get_attribute("outputs:widgetPath")
db_value = database.outputs.widgetPath
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnReadMouseState.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.ui.ogn.OgnReadMouseStateDatabase import OgnReadMouseStateDatabase
test_file_name = "OgnReadMouseStateTemplate.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_ui_ReadMouseState")
database = OgnReadMouseStateDatabase(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:useRelativeCoords"))
attribute = test_node.get_attribute("inputs:useRelativeCoords")
db_value = database.inputs.useRelativeCoords
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:coords"))
attribute = test_node.get_attribute("outputs:coords")
db_value = database.outputs.coords
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:window"))
attribute = test_node.get_attribute("outputs:window")
db_value = database.outputs.window
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnOnViewportDragged.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.ui.ogn.OgnOnViewportDraggedDatabase import OgnOnViewportDraggedDatabase
test_file_name = "OgnOnViewportDraggedTemplate.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_ui_OnViewportDragged")
database = OgnOnViewportDraggedDatabase(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:gesture"))
attribute = test_node.get_attribute("inputs:gesture")
db_value = database.inputs.gesture
expected_value = "Left Mouse Drag"
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:useNormalizedCoords"))
attribute = test_node.get_attribute("inputs:useNormalizedCoords")
db_value = database.inputs.useNormalizedCoords
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:began"))
attribute = test_node.get_attribute("outputs:began")
db_value = database.outputs.began
self.assertTrue(test_node.get_attribute_exists("outputs:ended"))
attribute = test_node.get_attribute("outputs:ended")
db_value = database.outputs.ended
self.assertTrue(test_node.get_attribute_exists("outputs:finalPosition"))
attribute = test_node.get_attribute("outputs:finalPosition")
db_value = database.outputs.finalPosition
self.assertTrue(test_node.get_attribute_exists("outputs:initialPosition"))
attribute = test_node.get_attribute("outputs:initialPosition")
db_value = database.outputs.initialPosition
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnWriteWidgetStyle.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.ui.ogn.OgnWriteWidgetStyleDatabase import OgnWriteWidgetStyleDatabase
test_file_name = "OgnWriteWidgetStyleTemplate.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_ui_WriteWidgetStyle")
database = OgnWriteWidgetStyleDatabase(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:style"))
attribute = test_node.get_attribute("inputs:style")
db_value = database.inputs.style
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:widgetIdentifier"))
attribute = test_node.get_attribute("inputs:widgetIdentifier")
db_value = database.inputs.widgetIdentifier
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:widgetPath"))
attribute = test_node.get_attribute("inputs:widgetPath")
db_value = database.inputs.widgetPath
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:write"))
attribute = test_node.get_attribute("inputs:write")
db_value = database.inputs.write
self.assertTrue(test_node.get_attribute_exists("outputs:written"))
attribute = test_node.get_attribute("outputs:written")
db_value = database.outputs.written
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/__init__.py | """====== GENERATED BY omni.graph.tools - DO NOT EDIT ======"""
import omni.graph.tools as ogt
ogt.import_tests_in_directory(__file__, __name__)
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnReadPickState.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.ui.ogn.OgnReadPickStateDatabase import OgnReadPickStateDatabase
test_file_name = "OgnReadPickStateTemplate.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_ui_ReadPickState")
database = OgnReadPickStateDatabase(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:gesture"))
attribute = test_node.get_attribute("inputs:gesture")
db_value = database.inputs.gesture
expected_value = "Left Mouse Click"
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:usePaths"))
attribute = test_node.get_attribute("inputs:usePaths")
db_value = database.inputs.usePaths
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:isTrackedPrimPicked"))
attribute = test_node.get_attribute("outputs:isTrackedPrimPicked")
db_value = database.outputs.isTrackedPrimPicked
self.assertTrue(test_node.get_attribute_exists("outputs:isValid"))
attribute = test_node.get_attribute("outputs:isValid")
db_value = database.outputs.isValid
self.assertTrue(test_node.get_attribute_exists("outputs:pickedPrimPath"))
attribute = test_node.get_attribute("outputs:pickedPrimPath")
db_value = database.outputs.pickedPrimPath
self.assertTrue(test_node.get_attribute_exists("outputs:pickedWorldPos"))
attribute = test_node.get_attribute("outputs:pickedWorldPos")
db_value = database.outputs.pickedWorldPos
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnOnNewFrame.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.ui.ogn.OgnOnNewFrameDatabase import OgnOnNewFrameDatabase
test_file_name = "OgnOnNewFrameTemplate.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_ui_OnNewFrame")
database = OgnOnNewFrameDatabase(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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
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
self.assertTrue(test_node.get_attribute_exists("outputs:frameNumber"))
attribute = test_node.get_attribute("outputs:frameNumber")
db_value = database.outputs.frameNumber
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnReadViewportScrollState.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.ui.ogn.OgnReadViewportScrollStateDatabase import OgnReadViewportScrollStateDatabase
test_file_name = "OgnReadViewportScrollStateTemplate.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_ui_ReadViewportScrollState")
database = OgnReadViewportScrollStateDatabase(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:useNormalizedCoords"))
attribute = test_node.get_attribute("inputs:useNormalizedCoords")
db_value = database.inputs.useNormalizedCoords
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:isValid"))
attribute = test_node.get_attribute("outputs:isValid")
db_value = database.outputs.isValid
self.assertTrue(test_node.get_attribute_exists("outputs:position"))
attribute = test_node.get_attribute("outputs:position")
db_value = database.outputs.position
self.assertTrue(test_node.get_attribute_exists("outputs:scrollValue"))
attribute = test_node.get_attribute("outputs:scrollValue")
db_value = database.outputs.scrollValue
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnOnWidgetValueChanged.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.ui.ogn.OgnOnWidgetValueChangedDatabase import OgnOnWidgetValueChangedDatabase
test_file_name = "OgnOnWidgetValueChangedTemplate.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_ui_OnWidgetValueChanged")
database = OgnOnWidgetValueChangedDatabase(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:widgetIdentifier"))
attribute = test_node.get_attribute("inputs:widgetIdentifier")
db_value = database.inputs.widgetIdentifier
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:valueChanged"))
attribute = test_node.get_attribute("outputs:valueChanged")
db_value = database.outputs.valueChanged
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnReadWindowSize.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.ui.ogn.OgnReadWindowSizeDatabase import OgnReadWindowSizeDatabase
test_file_name = "OgnReadWindowSizeTemplate.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_ui_ReadWindowSize")
database = OgnReadWindowSizeDatabase(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:height"))
attribute = test_node.get_attribute("outputs:height")
db_value = database.outputs.height
self.assertTrue(test_node.get_attribute_exists("outputs:width"))
attribute = test_node.get_attribute("outputs:width")
db_value = database.outputs.width
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnVStack.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.ui.ogn.OgnVStackDatabase import OgnVStackDatabase
test_file_name = "OgnVStackTemplate.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_ui_VStack")
database = OgnVStackDatabase(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:create"))
attribute = test_node.get_attribute("inputs:create")
db_value = database.inputs.create
self.assertTrue(test_node.get_attribute_exists("inputs:direction"))
attribute = test_node.get_attribute("inputs:direction")
db_value = database.inputs.direction
expected_value = "TOP_TO_BOTTOM"
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:parentWidgetPath"))
attribute = test_node.get_attribute("inputs:parentWidgetPath")
db_value = database.inputs.parentWidgetPath
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:created"))
attribute = test_node.get_attribute("outputs:created")
db_value = database.outputs.created
self.assertTrue(test_node.get_attribute_exists("outputs:widgetPath"))
attribute = test_node.get_attribute("outputs:widgetPath")
db_value = database.outputs.widgetPath
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnReadViewportDragState.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.ui.ogn.OgnReadViewportDragStateDatabase import OgnReadViewportDragStateDatabase
test_file_name = "OgnReadViewportDragStateTemplate.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_ui_ReadViewportDragState")
database = OgnReadViewportDragStateDatabase(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:gesture"))
attribute = test_node.get_attribute("inputs:gesture")
db_value = database.inputs.gesture
expected_value = "Left Mouse Drag"
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:useNormalizedCoords"))
attribute = test_node.get_attribute("inputs:useNormalizedCoords")
db_value = database.inputs.useNormalizedCoords
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:currentPosition"))
attribute = test_node.get_attribute("outputs:currentPosition")
db_value = database.outputs.currentPosition
self.assertTrue(test_node.get_attribute_exists("outputs:initialPosition"))
attribute = test_node.get_attribute("outputs:initialPosition")
db_value = database.outputs.initialPosition
self.assertTrue(test_node.get_attribute_exists("outputs:isDragInProgress"))
attribute = test_node.get_attribute("outputs:isDragInProgress")
db_value = database.outputs.isDragInProgress
self.assertTrue(test_node.get_attribute_exists("outputs:isValid"))
attribute = test_node.get_attribute("outputs:isValid")
db_value = database.outputs.isValid
self.assertTrue(test_node.get_attribute_exists("outputs:velocity"))
attribute = test_node.get_attribute("outputs:velocity")
db_value = database.outputs.velocity
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnWriteWidgetProperty.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.ui.ogn.OgnWriteWidgetPropertyDatabase import OgnWriteWidgetPropertyDatabase
test_file_name = "OgnWriteWidgetPropertyTemplate.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_ui_WriteWidgetProperty")
database = OgnWriteWidgetPropertyDatabase(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:propertyName"))
attribute = test_node.get_attribute("inputs:propertyName")
db_value = database.inputs.propertyName
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:widgetIdentifier"))
attribute = test_node.get_attribute("inputs:widgetIdentifier")
db_value = database.inputs.widgetIdentifier
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:widgetPath"))
attribute = test_node.get_attribute("inputs:widgetPath")
db_value = database.inputs.widgetPath
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:write"))
attribute = test_node.get_attribute("inputs:write")
db_value = database.inputs.write
self.assertTrue(test_node.get_attribute_exists("outputs:written"))
attribute = test_node.get_attribute("outputs:written")
db_value = database.outputs.written
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnOnPicked.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.ui.ogn.OgnOnPickedDatabase import OgnOnPickedDatabase
test_file_name = "OgnOnPickedTemplate.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_ui_OnPicked")
database = OgnOnPickedDatabase(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:gesture"))
attribute = test_node.get_attribute("inputs:gesture")
db_value = database.inputs.gesture
expected_value = "Left Mouse Click"
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:isTrackedPrimPicked"))
attribute = test_node.get_attribute("outputs:isTrackedPrimPicked")
db_value = database.outputs.isTrackedPrimPicked
self.assertTrue(test_node.get_attribute_exists("outputs:missed"))
attribute = test_node.get_attribute("outputs:missed")
db_value = database.outputs.missed
self.assertTrue(test_node.get_attribute_exists("outputs:picked"))
attribute = test_node.get_attribute("outputs:picked")
db_value = database.outputs.picked
self.assertTrue(test_node.get_attribute_exists("outputs:pickedPrimPath"))
attribute = test_node.get_attribute("outputs:pickedPrimPath")
db_value = database.outputs.pickedPrimPath
self.assertTrue(test_node.get_attribute_exists("outputs:pickedWorldPos"))
attribute = test_node.get_attribute("outputs:pickedWorldPos")
db_value = database.outputs.pickedWorldPos
self.assertTrue(test_node.get_attribute_exists("outputs:trackedPrimPaths"))
attribute = test_node.get_attribute("outputs:trackedPrimPaths")
db_value = database.outputs.trackedPrimPaths
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnOnViewportScrolled.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.ui.ogn.OgnOnViewportScrolledDatabase import OgnOnViewportScrolledDatabase
test_file_name = "OgnOnViewportScrolledTemplate.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_ui_OnViewportScrolled")
database = OgnOnViewportScrolledDatabase(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:useNormalizedCoords"))
attribute = test_node.get_attribute("inputs:useNormalizedCoords")
db_value = database.inputs.useNormalizedCoords
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:position"))
attribute = test_node.get_attribute("outputs:position")
db_value = database.outputs.position
self.assertTrue(test_node.get_attribute_exists("outputs:scrollValue"))
attribute = test_node.get_attribute("outputs:scrollValue")
db_value = database.outputs.scrollValue
self.assertTrue(test_node.get_attribute_exists("outputs:scrolled"))
attribute = test_node.get_attribute("outputs:scrolled")
db_value = database.outputs.scrolled
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnButton.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.ui.ogn.OgnButtonDatabase import OgnButtonDatabase
test_file_name = "OgnButtonTemplate.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_ui_Button")
database = OgnButtonDatabase(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:create"))
attribute = test_node.get_attribute("inputs:create")
db_value = database.inputs.create
self.assertTrue(test_node.get_attribute_exists("inputs:parentWidgetPath"))
attribute = test_node.get_attribute("inputs:parentWidgetPath")
db_value = database.inputs.parentWidgetPath
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:size"))
attribute = test_node.get_attribute("inputs:size")
db_value = database.inputs.size
expected_value = [0.0, 0.0]
actual_value = og.Controller.get(attribute)
ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True))
ogts.verify_values(expected_value, db_value, _attr_error(attribute, False))
self.assertTrue(test_node.get_attribute_exists("outputs:created"))
attribute = test_node.get_attribute("outputs:created")
db_value = database.outputs.created
self.assertTrue(test_node.get_attribute_exists("outputs:widgetPath"))
attribute = test_node.get_attribute("outputs:widgetPath")
db_value = database.outputs.widgetPath
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnOnViewportClicked.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.ui.ogn.OgnOnViewportClickedDatabase import OgnOnViewportClickedDatabase
test_file_name = "OgnOnViewportClickedTemplate.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_ui_OnViewportClicked")
database = OgnOnViewportClickedDatabase(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:gesture"))
attribute = test_node.get_attribute("inputs:gesture")
db_value = database.inputs.gesture
expected_value = "Left Mouse Click"
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:useNormalizedCoords"))
attribute = test_node.get_attribute("inputs:useNormalizedCoords")
db_value = database.inputs.useNormalizedCoords
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:viewport"))
attribute = test_node.get_attribute("inputs:viewport")
db_value = database.inputs.viewport
expected_value = "Viewport"
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:clicked"))
attribute = test_node.get_attribute("outputs:clicked")
db_value = database.outputs.clicked
self.assertTrue(test_node.get_attribute_exists("outputs:position"))
attribute = test_node.get_attribute("outputs:position")
db_value = database.outputs.position
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/TestOgnSlider.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.ui.ogn.OgnSliderDatabase import OgnSliderDatabase
test_file_name = "OgnSliderTemplate.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_ui_Slider")
database = OgnSliderDatabase(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:create"))
attribute = test_node.get_attribute("inputs:create")
db_value = database.inputs.create
self.assertTrue(test_node.get_attribute_exists("inputs:disable"))
attribute = test_node.get_attribute("inputs:disable")
db_value = database.inputs.disable
self.assertTrue(test_node.get_attribute_exists("inputs:enable"))
attribute = test_node.get_attribute("inputs:enable")
db_value = database.inputs.enable
self.assertTrue(test_node.get_attribute_exists("inputs:hide"))
attribute = test_node.get_attribute("inputs:hide")
db_value = database.inputs.hide
self.assertTrue(test_node.get_attribute_exists("inputs:max"))
attribute = test_node.get_attribute("inputs:max")
db_value = database.inputs.max
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:min"))
attribute = test_node.get_attribute("inputs:min")
db_value = database.inputs.min
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:show"))
attribute = test_node.get_attribute("inputs:show")
db_value = database.inputs.show
self.assertTrue(test_node.get_attribute_exists("inputs:step"))
attribute = test_node.get_attribute("inputs:step")
db_value = database.inputs.step
expected_value = 0.01
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:tearDown"))
attribute = test_node.get_attribute("inputs:tearDown")
db_value = database.inputs.tearDown
self.assertTrue(test_node.get_attribute_exists("inputs:width"))
attribute = test_node.get_attribute("inputs:width")
db_value = database.inputs.width
expected_value = 100.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:created"))
attribute = test_node.get_attribute("outputs:created")
db_value = database.outputs.created
self.assertTrue(test_node.get_attribute_exists("outputs:widgetPath"))
attribute = test_node.get_attribute("outputs:widgetPath")
db_value = database.outputs.widgetPath
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnVStackTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnVStack.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_ui_VStack" (
docs="""Contruct a Stack on the Viewport. All child widgets of Stack will be placed in a row, column or layer based on the direction input."""
)
{
token node:type = "omni.graph.ui.VStack"
int node:typeVersion = 1
# 5 attributes
custom uint inputs:create (
docs="""Input execution to create and show the widget"""
)
custom token inputs:direction = "TOP_TO_BOTTOM" (
docs="""The direction the widgets will be stacked."""
)
custom token inputs:parentWidgetPath = "" (
docs="""The absolute path to the parent widget."""
)
custom string inputs:style (
docs="""Style to be applied to the stack and its children. This can later be changed with the
WriteWidgetStyle node."""
)
custom token inputs:widgetIdentifier (
docs="""An optional unique identifier for the widget.
Can be used to refer to this widget in other places such as the OnWidgetClicked node."""
)
# 2 attributes
custom uint outputs:created (
docs="""Executed when the widget is created"""
)
custom token outputs:widgetPath (
docs="""The absolute path to the created widget"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnOnViewportHoveredTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnViewportHovered.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_ui_OnViewportHovered" (
docs="""Event node which fires when the specified viewport is hovered over. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."""
)
{
token node:type = "omni.graph.ui.OnViewportHovered"
int node:typeVersion = 1
# 2 attributes
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played"""
)
custom token inputs:viewport = "Viewport" (
docs="""Name of the viewport window to watch for hover events"""
)
# 2 attributes
custom uint outputs:began (
docs="""Enabled when the hover begins"""
)
custom uint outputs:ended (
docs="""Enabled when the hover ends"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnReadPickStateTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnReadPickState.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_ui_ReadPickState" (
docs="""Read the state of the last picking event from the specified viewport. Note that picking events must be enabled on the specified viewport using a SetViewportMode node."""
)
{
token node:type = "omni.graph.ui.ReadPickState"
int node:typeVersion = 1
# 5 attributes
custom token inputs:gesture = "Left Mouse Click" (
docs="""The input gesture to trigger a picking event"""
)
custom token[] inputs:trackedPrimPaths (
docs="""Optionally specify a set of prims (by paths) to track whether or not they got picked
(only affects the value of 'Is Tracked Prim Picked')"""
)
custom rel inputs:trackedPrims (
docs="""Optionally specify a set of prims to track whether or not they got picked
(only affects the value of 'Is Tracked Prim Picked')"""
)
custom bool inputs:usePaths = false (
docs="""When true, 'Tracked Prim Paths' is used, otherwise 'Tracked Prims' is used"""
)
custom token inputs:viewport = "Viewport" (
docs="""Name of the viewport window to watch for picking events"""
)
# 4 attributes
custom bool outputs:isTrackedPrimPicked (
docs="""True if a tracked prim got picked in the last picking event,
or if any prim got picked if no tracked prims are specified"""
)
custom bool outputs:isValid (
docs="""True if a valid event state was detected and the outputs of this node are valid, and false otherwise"""
)
custom token outputs:pickedPrimPath (
docs="""The path of the prim picked in the last picking event, or an empty string if nothing got picked"""
)
custom point3d outputs:pickedWorldPos (
docs="""The XYZ-coordinates of the point in world space at which the prim got picked,
or (0,0,0) if nothing got picked"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnSpacerTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnSpacer.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_ui_Spacer" (
docs="""A widget that leaves empty space."""
)
{
token node:type = "omni.graph.ui.Spacer"
int node:typeVersion = 1
# 6 attributes
custom uint inputs:create (
docs="""Input execution to create and show the widget"""
)
custom int inputs:height = 0 (
docs="""The amount of vertical space to leave, in pixels."""
)
custom token inputs:parentWidgetPath = "" (
docs="""The absolute path to the parent widget."""
)
custom string inputs:style (
docs="""Style to be applied to the spacer. This can later be changed with the WriteWidgetStyle node."""
)
custom token inputs:widgetIdentifier (
docs="""An optional unique identifier for the widget.
Can be used to refer to this widget in other places such as the OnWidgetClicked node."""
)
custom int inputs:width = 0 (
docs="""The amount of horizontal space to leave, in pixels."""
)
# 2 attributes
custom uint outputs:created (
docs="""Executed when the widget is created"""
)
custom token outputs:widgetPath (
docs="""The absolute path to the created widget"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnGetCameraTargetTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnGetCameraTarget.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_ui_GetCameraTarget" (
docs="""Gets a viewport camera's target point."""
)
{
token node:type = "omni.graph.ui.GetCameraTarget"
int node:typeVersion = 1
# 3 attributes
custom rel inputs:prim (
docs="""The camera prim, when 'usePath' is false"""
)
custom token inputs:primPath = "" (
docs="""Path of the camera, used when 'usePath' is true"""
)
custom bool inputs:usePath = true (
docs="""When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute"""
)
# 1 attribute
custom point3d outputs:target (
docs="""The target point"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnOnViewportPressedTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnViewportPressed.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_ui_OnViewportPressed" (
docs="""Event node which fires when the specified viewport is pressed, and when that press is released. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."""
)
{
token node:type = "omni.graph.ui.OnViewportPressed"
int node:typeVersion = 1
# 4 attributes
custom token inputs:gesture = "Left Mouse Press" (
docs="""The input gesture to trigger viewport press events"""
)
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played"""
)
custom bool inputs:useNormalizedCoords = false (
docs="""When true, the components of 2D position outputs are scaled to between 0 and 1,
where 0 is top/left and 1 is bottom/right.
When false, components are in viewport render resolution pixels."""
)
custom token inputs:viewport = "Viewport" (
docs="""Name of the viewport window to watch for press events"""
)
# 5 attributes
custom bool outputs:isReleasePositionValid (
docs="""True if the press was released inside of the viewport, and false otherwise"""
)
custom double2 outputs:pressPosition (
docs="""The position at which the viewport was pressed (valid when either 'Pressed' or 'Released' is enabled)"""
)
custom uint outputs:pressed (
docs="""Enabled when the specified viewport is pressed, populating 'Press Position' with the current mouse position"""
)
custom double2 outputs:releasePosition (
docs="""The position at which the press was released, or (0,0) if the press was released outside of the viewport
or the viewport is currently pressed (valid when 'Ended' is enabled and 'Is Release Position Valid' is true)"""
)
custom uint outputs:released (
docs="""Enabled when the press is released, populating 'Release Position' with the current mouse position
and setting 'Is Release Position Valid' to true if the press is released inside of the viewport.
If the press is released outside of the viewport, 'Is Release Position Valid' is set to false
and 'Release Position' is set to (0,0)."""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnDrawDebugCurveTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnDrawDebugCurve.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_ui_DrawDebugCurve" (
docs="""Given a set of curve points, draw a curve in the viewport"""
)
{
token node:type = "omni.graph.ui.DrawDebugCurve"
int node:typeVersion = 1
# 4 attributes
custom bool inputs:closed = false (
docs="""When true, connect the last point to the first"""
)
custom color3f inputs:color = (0.0, 0.0, 0.0) (
docs="""The color of the curve"""
)
custom double3[] inputs:curvepoints = [] (
docs="""The curve to be drawn"""
)
custom uint inputs:execIn (
docs="""Execution input"""
)
# 1 attribute
custom uint outputs:execOut (
docs="""Execution Output"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnOnPickedTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnPicked.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_ui_OnPicked" (
docs="""Event node which fires when a picking event occurs in the specified viewport. Note that picking events must be enabled on the specified viewport using a SetViewportMode node."""
)
{
token node:type = "omni.graph.ui.OnPicked"
int node:typeVersion = 1
# 4 attributes
custom token inputs:gesture = "Left Mouse Click" (
docs="""The input gesture to trigger a picking event"""
)
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played."""
)
custom rel inputs:trackedPrims (
docs="""Optionally specify a set of tracked prims that will cause 'Picked' to fire when picked"""
)
custom token inputs:viewport = "Viewport" (
docs="""Name of the viewport window to watch for picking events"""
)
# 6 attributes
custom bool outputs:isTrackedPrimPicked (
docs="""True if a tracked prim got picked, or if any prim got picked if no tracked prims are specified
(will always be true when 'Picked' fires, and false when 'Missed' fires)"""
)
custom uint outputs:missed (
docs="""Enabled when an attempted picking did not pick a tracked prim,
or when nothing gets picked if no tracked prims are specified"""
)
custom uint outputs:picked (
docs="""Enabled when a tracked prim is picked,
or when any prim is picked if no tracked prims are specified"""
)
custom token outputs:pickedPrimPath (
docs="""The path of the picked prim, or an empty string if nothing got picked"""
)
custom point3d outputs:pickedWorldPos (
docs="""The XYZ-coordinates of the point in world space at which the prim got picked,
or (0,0,0) if nothing got picked"""
)
custom token[] outputs:trackedPrimPaths (
docs="""A list of the paths of the prims specified in 'Tracked Prims'"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnButtonTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnButton.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_ui_Button" (
docs="""Create a button widget on the Viewport"""
)
{
token node:type = "omni.graph.ui.Button"
int node:typeVersion = 1
# 7 attributes
custom uint inputs:create (
docs="""Input execution to create and show the widget"""
)
custom token inputs:parentWidgetPath = "" (
docs="""The absolute path to the parent widget."""
)
custom double2 inputs:size = (0.0, 0.0) (
docs="""The width and height of the created widget.
Value of 0 means the created widget will be just large enough to fit everything."""
)
custom bool inputs:startHidden = false (
docs="""Determines whether the button will initially be visible (False) or not (True)."""
)
custom string inputs:style (
docs="""Style to be applied to the button. This can later be changed with the WriteWidgetStyle node."""
)
custom string inputs:text (
docs="""The text that is displayed on the button"""
)
custom token inputs:widgetIdentifier (
docs="""An optional unique identifier for the widget.
Can be used to refer to this widget in other places such as the OnWidgetClicked node."""
)
# 2 attributes
custom uint outputs:created (
docs="""Executed when the widget is created"""
)
custom token outputs:widgetPath (
docs="""The absolute path to the created widget"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnComboBoxTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnComboBox.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_ui_ComboBox" (
docs="""Create a combo box widget on the Viewport"""
)
{
token node:type = "omni.graph.ui.ComboBox"
int node:typeVersion = 1
# 10 attributes
custom uint inputs:create (
docs="""Input execution to create and show the widget"""
)
custom uint inputs:disable (
docs="""Disable this button so that it cannot be pressed"""
)
custom uint inputs:enable (
docs="""Enable this button after it has been disabled"""
)
custom uint inputs:hide (
docs="""Input execution to hide the widget and all its child widgets"""
)
custom token[] inputs:itemList = [] (
docs="""A list of items that appears in the drop-down list"""
)
custom token inputs:parentWidgetPath (
docs="""The absolute path to the parent widget.
If empty, this widget will be created as a direct child of Viewport."""
)
custom uint inputs:show (
docs="""Input execution to show the widget and all its child widgets after they become hidden"""
)
custom uint inputs:tearDown (
docs="""Input execution to tear down the widget and all its child widgets"""
)
custom token inputs:widgetIdentifier (
docs="""An optional unique identifier for the widget.
Can be used to refer to this widget in other places such as the OnWidgetClicked node."""
)
custom double inputs:width = 100.0 (
docs="""The width of the created combo box"""
)
# 2 attributes
custom uint outputs:created (
docs="""Executed when the widget is created"""
)
custom token outputs:widgetPath (
docs="""The absolute path to the created widget"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnPlacerTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnPlacer.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_ui_Placer" (
docs="""Contruct a Placer widget. The Placer takes a single child and places it at a given position within it."""
)
{
token node:type = "omni.graph.ui.Placer"
int node:typeVersion = 1
# 5 attributes
custom uint inputs:create (
docs="""Input execution to create and show the widget"""
)
custom token inputs:parentWidgetPath = "" (
docs="""The absolute path to the parent widget."""
)
custom double2 inputs:position = (0.0, 0.0) (
docs="""Where to position the child widget within the Placer."""
)
custom string inputs:style (
docs="""Style to be applied to the Placer and its child. This can later be changed with the
WriteWidgetStyle node."""
)
custom token inputs:widgetIdentifier (
docs="""An optional unique identifier for the widget.
Can be used to refer to this widget in other places such as the OnWidgetClicked node."""
)
# 2 attributes
custom uint outputs:created (
docs="""Executed when the widget is created"""
)
custom token outputs:widgetPath (
docs="""The absolute path to the created Placer widget"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnReadMouseStateTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnReadMouseState.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_ui_ReadMouseState" (
docs="""Reads the current state of the mouse. You can choose which mouse element this node is associated with. When mouse element is chosen to be a button, only outputs:isPressed is meaningful. When coordinates are chosen, only outputs:coords and outputs:window are meaningful.
Pixel coordinates are the position of the mouse cursor in screen pixel units with (0,0) top left. Normalized coordinates are values between 0-1 where 0 is top/left and 1 is bottom/right. By default, coordinates are relative to the application window, but if 'Use Relative Coords' is set to true, then coordinates are relative to the workspace window containing the mouse pointer."""
)
{
token node:type = "omni.graph.ui.ReadMouseState"
int node:typeVersion = 1
# 2 attributes
custom token inputs:mouseElement = "Left Button" (
docs="""The mouse input to check the state of"""
)
custom bool inputs:useRelativeCoords = false (
docs="""When true, the output 'coords' is made relative to the workspace window containing the
mouse pointer instead of the entire application window"""
)
# 3 attributes
custom float2 outputs:coords (
docs="""The coordinates of the mouse. If the mouse element selected is a button, this will output a zero vector."""
)
custom bool outputs:isPressed (
docs="""True if the button is currently pressed, false otherwise. If the mouse element selected
is a coordinate, this will output false."""
)
custom token outputs:window (
docs="""The name of the workspace window containing the mouse pointer if 'Use Relative Coords' is true
and the mouse element selected is a coordinate"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnOnNewFrameTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnNewFrame.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_ui_OnNewFrame" (
docs="""Triggers when there is a new frame available for the given viewport. Note that the graph will run asynchronously to the new frame event"""
)
{
token node:type = "omni.graph.ui.OnNewFrame"
int node:typeVersion = 1
# 1 attribute
custom token inputs:viewport = "" (
docs="""Name of the viewport, or empty for the default viewport"""
)
# 2 attributes
custom uint outputs:execOut (
docs="""Output Execution"""
)
custom int outputs:frameNumber (
docs="""The number of the frame which is available"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnSetCameraPositionTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnSetCameraPosition.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_ui_SetCameraPosition" (
docs="""Sets the camera's position"""
)
{
token node:type = "omni.graph.ui.SetCameraPosition"
int node:typeVersion = 1
# 6 attributes
custom uint inputs:execIn (
docs="""Execution input"""
)
custom point3d inputs:position = (0.0, 0.0, 0.0) (
docs="""The new position"""
)
custom rel inputs:prim (
docs="""The camera prim, when 'usePath' is false"""
)
custom token inputs:primPath = "" (
docs="""Path of the camera, used when 'usePath' is true"""
)
custom bool inputs:rotate = true (
docs="""True to keep position but change orientation and radius (camera moves to new
position while still looking at the same target).
False to keep orientation and radius but change position (camera moves to look at new target)."""
)
custom bool inputs:usePath = true (
docs="""When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute"""
)
# 1 attribute
custom uint outputs:execOut (
docs="""Execution Output"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnGetActiveViewportCameraTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnGetActiveViewportCamera.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_ui_GetActiveViewportCamera" (
docs="""Gets the path of the camera bound to a viewport"""
)
{
token node:type = "omni.graph.ui.GetActiveViewportCamera"
int node:typeVersion = 1
# 1 attribute
custom token inputs:viewport = "" (
docs="""Name of the viewport, or empty for the default viewport"""
)
# 1 attribute
custom token outputs:camera (
docs="""Path of the active camera"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnWriteWidgetPropertyTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnWriteWidgetProperty.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_ui_WriteWidgetProperty" (
docs="""Set the value of a widget's property (height, tooltip, etc)."""
)
{
token node:type = "omni.graph.ui.WriteWidgetProperty"
int node:typeVersion = 1
# 5 attributes
custom token inputs:propertyName = "" (
docs="""Name of the property to write to."""
)
custom token inputs:value = "any" (
docs="""The value to write to the property."""
)
custom token inputs:widgetIdentifier = "" (
docs="""Unique identifier for the widget. This is only valid within the current graph."""
)
custom token inputs:widgetPath = "" (
docs="""Full path to the widget. If present this will be used insted of 'widgetIdentifier'.
Unlike 'widgetIdentifier' this is valid across all graphs."""
)
custom uint inputs:write (
docs="""Input execution to write the value to the widget's property."""
)
# 1 attribute
custom uint outputs:written (
docs="""Executed when the value has been successfully written."""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnReadWidgetPropertyTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnReadWidgetProperty.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_ui_ReadWidgetProperty" (
docs="""Read the value of a widget's property (height, tooltip, etc)."""
)
{
token node:type = "omni.graph.ui.ReadWidgetProperty"
int node:typeVersion = 1
# 3 attributes
custom token inputs:propertyName = "" (
docs="""Name of the property to read."""
)
custom token inputs:widgetIdentifier = "" (
docs="""Unique identifier for the widget. This is only valid within the current graph."""
)
custom token inputs:widgetPath = "" (
docs="""Full path to the widget. If present this will be used insted of 'widgetIdentifier'.
Unlike 'widgetIdentifier' this is valid across all graphs."""
)
# 1 attribute
custom token outputs:value (
docs="""The value of the property."""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnReadViewportHoverStateTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnReadViewportHoverState.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_ui_ReadViewportHoverState" (
docs="""Read the state of the last viewport hover event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."""
)
{
token node:type = "omni.graph.ui.ReadViewportHoverState"
int node:typeVersion = 1
# 2 attributes
custom bool inputs:useNormalizedCoords = false (
docs="""When true, the components of 2D position and velocity outputs are scaled to between 0 and 1,
where 0 is top/left and 1 is bottom/right.
When false, components are in viewport render resolution pixels."""
)
custom token inputs:viewport = "Viewport" (
docs="""Name of the viewport window to watch for hover events"""
)
# 4 attributes
custom bool outputs:isHovered (
docs="""True if the specified viewport is currently hovered"""
)
custom bool outputs:isValid (
docs="""True if a valid event state was detected and the outputs of this node are valid, and false otherwise"""
)
custom double2 outputs:position (
docs="""The current mouse position if the specified viewport is currently hovered, otherwise (0,0)"""
)
custom double2 outputs:velocity (
docs="""A vector representing the change in position of the mouse since the previous frame
if the specified viewport is currently hovered, otherwise (0,0)"""
)
}
}
|
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/tests/usd/OgnOnViewportScrolledTemplate.usda | #usda 1.0
(
doc ="""Generated from node description file OgnOnViewportScrolled.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_ui_OnViewportScrolled" (
docs="""Event node which fires when a viewport scroll event occurs in the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node."""
)
{
token node:type = "omni.graph.ui.OnViewportScrolled"
int node:typeVersion = 1
# 3 attributes
custom bool inputs:onlyPlayback = true (
docs="""When true, the node is only computed while Stage is being played"""
)
custom bool inputs:useNormalizedCoords = false (
docs="""When true, the components of the 2D position output are scaled to between 0 and 1,
where 0 is top/left and 1 is bottom/right.
When false, components are in viewport render resolution pixels."""
)
custom token inputs:viewport = "Viewport" (
docs="""Name of the viewport window to watch for scroll events"""
)
# 3 attributes
custom double2 outputs:position (
docs="""The position at which the viewport scroll event occurred"""
)
custom float outputs:scrollValue (
docs="""The number of mouse wheel clicks scrolled up if positive, or scrolled down if negative"""
)
custom uint outputs:scrolled (
docs="""Enabled when a viewport scroll event occurs in the specified viewport"""
)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.