file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.graph.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
| 685 | Python | 26.439999 | 84 | 0.649635 |
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
| 34,697 | Python | 37.81208 | 119 | 0.619304 |
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
| 6,644 | C++ | 38.790419 | 130 | 0.59106 |
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)
| 5,201 | Python | 41.991735 | 111 | 0.637954 |
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;
};
}
}
}
| 2,541 | C | 24.168317 | 109 | 0.595041 |
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)
| 5,677 | Python | 43.708661 | 109 | 0.649815 |
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)
| 6,675 | Python | 44.108108 | 111 | 0.630861 |
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);
};
}
}
}
| 1,100 | C | 25.214285 | 89 | 0.748182 |
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
| 4,852 | Python | 35.488722 | 96 | 0.630256 |
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()
}
}
}
| 1,312 | C++ | 22.872727 | 117 | 0.702744 |
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
| 3,531 | Python | 35.412371 | 96 | 0.650241 |
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
| 8,721 | C++ | 39.567442 | 146 | 0.618163 |
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
| 5,243 | Python | 37.277372 | 96 | 0.613008 |
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
| 9,187 | C++ | 39.475771 | 131 | 0.61968 |
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
| 2,426 | Python | 35.772727 | 108 | 0.597279 |
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>;
}
}
}
| 7,061 | C | 29.439655 | 120 | 0.578672 |
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
| 2,702 | Python | 30.8 | 90 | 0.534789 |
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>;
}
}
}
| 5,625 | C | 28 | 122 | 0.600356 |
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
| 3,426 | C++ | 33.616161 | 143 | 0.660829 |
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()
}
}
}
| 1,513 | C++ | 23.419354 | 117 | 0.678784 |
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
| 8,672 | C++ | 38.60274 | 134 | 0.607588 |
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
| 6,317 | C++ | 37.290909 | 135 | 0.614691 |
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;
};
}
}
}
| 2,811 | C | 25.280374 | 102 | 0.599787 |
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
| 3,520 | C++ | 33.861386 | 171 | 0.665341 |
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.
| 2,116 | Python | 37.490908 | 112 | 0.657845 |
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
| 5,438 | C++ | 32.782608 | 134 | 0.544318 |
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
| 3,351 | Python | 45.555555 | 112 | 0.653536 |
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
| 3,516 | C++ | 34.17 | 175 | 0.666667 |
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
| 1,488 | Python | 32.088888 | 86 | 0.623656 |
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
| 3,323 | Python | 46.485714 | 107 | 0.621426 |
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
| 1,859 | Python | 46.692306 | 92 | 0.683701 |
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
| 2,472 | Python | 47.490195 | 95 | 0.683657 |
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
| 2,909 | Python | 48.322033 | 105 | 0.69199 |
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
| 3,783 | Python | 49.453333 | 92 | 0.690722 |
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))
| 2,577 | Python | 49.549019 | 97 | 0.686069 |
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
| 4,040 | Python | 50.151898 | 95 | 0.695297 |
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
| 2,625 | Python | 46.745454 | 92 | 0.678095 |
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
| 3,620 | Python | 49.999999 | 105 | 0.69779 |
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
| 2,981 | Python | 49.542372 | 105 | 0.690372 |
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
| 2,183 | Python | 45.468084 | 92 | 0.678424 |
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
| 3,479 | Python | 45.399999 | 92 | 0.676631 |
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
| 2,683 | Python | 47.799999 | 92 | 0.686918 |
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
| 3,796 | Python | 49.626666 | 95 | 0.690727 |
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
| 2,903 | Python | 48.220338 | 93 | 0.682053 |
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__)
| 145 | Python | 35.499991 | 63 | 0.634483 |
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
| 3,344 | Python | 48.925372 | 92 | 0.689892 |
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
| 2,005 | Python | 45.651162 | 92 | 0.678304 |
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
| 2,734 | Python | 48.727272 | 107 | 0.693124 |
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
| 1,899 | Python | 47.717947 | 101 | 0.690363 |
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
| 1,570 | Python | 43.885713 | 92 | 0.677707 |
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
| 2,633 | Python | 46.890908 | 92 | 0.679833 |
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
| 3,599 | Python | 49.704225 | 103 | 0.696027 |
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
| 2,939 | Python | 48.830508 | 99 | 0.685948 |
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
| 3,717 | Python | 48.573333 | 92 | 0.690342 |
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
| 3,160 | Python | 49.174602 | 97 | 0.691139 |
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
| 2,613 | Python | 46.527272 | 92 | 0.676617 |
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
| 3,404 | Python | 49.820895 | 95 | 0.688602 |
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
| 4,299 | Python | 46.252747 | 92 | 0.674343 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/metaclass.py | """
Management for a singleton metaclass
"""
import inspect
import pprint
from gc import get_referrers
import omni.graph.tools as ogt
# Unique constant that goes in the module's dictionary so that it can be filtered out
__SINGLETON_MODULE = True
class Singleton(type):
"""
Helper for defining a singleton class in Python. You define it by starting
your class as follows:
from Singleton import Singleton
class MyClass(metaclass=Singleton):
# rest of implementation
Then you can do things like this:
a = MyClass()
a.var = 12
b = MyClass()
assert b.var == 12
assert a == b
"""
_instances = {}
def __call__(cls, *args, **kwargs):
"""Construct the unique instance of the class if necessary, otherwise return the existing one"""
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
@staticmethod
def forget(instanced_cls):
"""Removes the singleton class from the list of allocated singletons"""
try:
# Caller will usually be the class's destroy() function, invoker has a reference to the object
# on which the destroy function is being called (which it will presumably remove after calling)
(caller, invoker) = inspect.stack()[1:3] # noqa: PLW0632
referrers = []
# Filter our the class's reference to itself as that is about to be destroyed
for referrer in get_referrers(instanced_cls._instances[instanced_cls]): # noqa: PLW0212
try:
if referrer.f_back not in (caller.frame, invoker.frame):
referrers.append(referrer.f_back)
except AttributeError:
if isinstance(referrer, dict):
if instanced_cls in referrer:
continue
if "__SINGLETON_MODULE" in referrer:
continue
referrers.append(referrer)
if referrers:
referrers = pprint.PrettyPrinter(indent=4).pformat(referrers)
ogt.dbg_gc(f"Singleton {instanced_cls.__name__} has dangling references {referrers}")
else:
ogt.dbg_gc(f"Singleton {instanced_cls.__name__} cleanly forgotten")
del instanced_cls._instances[instanced_cls] # noqa: PLW0212
except (AttributeError, KeyError) as error:
ogt.dbg_gc(f"Failed trying to destroy singleton type {instanced_cls} - {error}")
| 2,631 | Python | 37.705882 | 107 | 0.595971 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/stage_picker_dialog.py | import weakref
from functools import partial
from typing import Callable
import omni.ui as ui
from omni.kit.property.usd.relationship import SelectionWatch
from omni.kit.widget.stage import StageWidget
from pxr import Sdf, Usd
class StagePickerDialog:
def __init__(
self,
stage,
on_select_fn: Callable[[Usd.Prim], None],
title=None,
select_button_text=None,
filter_type_list=None,
filter_lambda=None,
):
self._weak_stage = weakref.ref(stage)
self._on_select_fn = on_select_fn
if filter_type_list is None:
self._filter_type_list = []
else:
self._filter_type_list = filter_type_list
self._filter_lambda = filter_lambda
self._selected_paths = []
def on_window_visibility_changed(visible):
if not visible:
self._stage_widget.open_stage(None)
else:
# Only attach the stage when picker is open. Otherwise the Tf notice listener in StageWidget kills perf
self._stage_widget.open_stage(self._weak_stage())
self._window = ui.Window(
title if title else "Select Prim",
width=600,
height=400,
visible=False,
flags=0,
visibility_changed_fn=on_window_visibility_changed,
)
with self._window.frame:
with ui.VStack():
with ui.Frame():
self._stage_widget = StageWidget(None, columns_enabled=["Type"])
self._selection_watch = SelectionWatch(
stage=stage,
on_selection_changed_fn=self._on_selection_changed,
filter_type_list=filter_type_list,
filter_lambda=filter_lambda,
)
self._stage_widget.set_selection_watch(self._selection_watch)
def on_select(weak_self):
weak_self = weak_self()
if not weak_self:
return
selected_prim = None
if len(weak_self._selected_paths) > 0: # noqa: PLW0212
selected_prim = stage.GetPrimAtPath(Sdf.Path(weak_self._selected_paths[0])) # noqa: PLW0212
if weak_self._on_select_fn: # noqa: PLW0212
weak_self._on_select_fn(selected_prim) # noqa: PLW0212
weak_self._window.visible = False # noqa: PLW0212
with ui.VStack(height=0, style={"Button.Label:disabled": {"color": 0xFF606060}}):
self._label = ui.Label("Selected Path(s):\n\tNone")
self._button = ui.Button(
select_button_text if select_button_text else "Select",
height=10,
clicked_fn=partial(on_select, weak_self=weakref.ref(self)),
enabled=False,
)
def clean(self):
self._window.set_visibility_changed_fn(None)
self._window.destroy()
self._window = None
self._selection_watch = None
self._stage_widget.open_stage(None)
self._stage_widget.destroy()
self._stage_widget = None
self._filter_type_list = None
self._filter_lambda = None
self._selected_paths = None
self._on_select_fn = None
self._weak_stage = None
self._label.destroy()
self._label = None
self._button.destroy()
self._button = None
def show(self):
self._selection_watch.reset(1)
self._window.visible = True
if self._filter_lambda is not None:
self._stage_widget._filter_by_lambda({"relpicker_filter": self._filter_lambda}, True) # noqa: PLW0212
if self._filter_type_list:
self._stage_widget._filter_by_type(self._filter_type_list, True) # noqa: PLW0212
self._stage_widget.update_filter_menu_state(self._filter_type_list)
def hide(self):
self._window.visible = False
def _on_selection_changed(self, paths):
self._selected_paths = paths
if self._button:
self._button.enabled = len(self._selected_paths) > 0
if self._label:
text = "\n\t".join(self._selected_paths)
label_text = "Selected Path"
label_text += f":\n\t{text if text else 'None'}"
self._label.text = label_text
| 4,519 | Python | 36.355372 | 119 | 0.545917 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_attribute_base.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 json
import weakref
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import carb
import carb.settings
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
import omni.kit
from omni.kit.property.usd.control_state_manager import ControlStateManager
from omni.kit.property.usd.placeholder_attribute import PlaceholderAttribute
from pxr import Sdf, Usd
def get_ui_style():
return carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
def get_model_cls(cls, args, key="model_cls"):
if args:
return args.get(key, cls)
return cls
AUTO_REFRESH_PERIOD = 0.33 # How frequently to poll for held node compute for refresh
BIG_ARRAY_MIN = 17 # The minimum number of elements to be considered a big-array
PLAY_COMPUTEGRAPH_SETTING = "/app/player/playComputegraph"
# =============================================================================
class PlaceholderOmniGraphAttribute:
"""Standin when a held Node does not have the given Attribute"""
def __init__(self, name: str, node: str):
self._name = name
self._node = node
HELD_ATTRIB = Union[og.Attribute, PlaceholderOmniGraphAttribute]
# =============================================================================
class OmniGraphBase:
"""Mixin base for OmniGraph attribute models"""
# Static refresh callback - shared among all instances
_update_sub = None
_update_counter: float = 0
_instances = weakref.WeakSet() # Set of all OmniGraphBase instances, for update polling
_compute_counts: Dict[str, int] = {} # Keep track of last compute count for each node by path.
# FIXME: Would be nicer to have an Attribute.get_change_num() to know if it
# has actually changed, rather than just if the node computed.
@staticmethod
def _on_update(event):
"""Called by kit update event - refreshes OG-based attribute models at a fixed interval."""
# FIXME: In an action graph is probably more efficient to listen for a compute event instead of polling.
# likewise in a push graph we should just refresh every N frames.
OmniGraphBase._update_counter += event.payload["dt"] # noqa: PLR1702
if OmniGraphBase._update_counter > AUTO_REFRESH_PERIOD: # noqa: PLR1702
OmniGraphBase._update_counter = 0
# If we find one of our nodes has computed since the last check we want to dirty all output and connected
# inputs attribute bases
dirty_nodes: Set[int] = set()
dirty_bases: Set[OmniGraphBase] = set()
for base in OmniGraphBase._instances:
for attrib in base._get_og_attributes(): # noqa: PLW0212
if isinstance(attrib, og.Attribute):
port_type = attrib.get_port_type()
if (port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) and (
attrib.get_upstream_connection_count() == 0
):
# Special case - unconnected inputs don't ever have to be polled because they only
# change when set externally
continue
# Check if this attribute's node was computed since last update. If so mark it as dirty so
# that we don't have to do the check again in this pass.
node = attrib.get_node()
node_hash = hash(node)
want_dirty = node_hash in dirty_nodes
if not want_dirty:
node_path = node.get_prim_path()
cc = node.get_compute_count()
cached_cc = OmniGraphBase._compute_counts.get(node_path, -1)
if cached_cc != cc:
OmniGraphBase._compute_counts[node_path] = cc
dirty_nodes.add(node_hash)
want_dirty = True
if want_dirty and (base not in dirty_bases):
dirty_bases.add(base)
for base in dirty_bases:
base._set_dirty() # noqa: PLW0212
def __init__(
self,
stage: Usd.Stage,
object_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict = None,
change_on_edit_end=False,
**kwargs,
):
self._control_state_mgr = ControlStateManager.get_instance()
self._stage = stage
self._object_paths = object_paths
self._object_paths_set = set(object_paths)
self._metadata = metadata if metadata is not None else {}
self._change_on_edit_end = change_on_edit_end
self._dirty = True
self._value = None # The value to be displayed on widget
self._has_default_value = False
self._default_value = None
self._real_values = [] # The actual values in usd, might be different from self._value if ambiguous.
self._real_type: og.Type = None
self._connections = []
self._is_big_array = False
self._prev_value = None
self._prev_real_values = []
self._editing = 0
self._ignore_notice = False
self._ambiguous = False
self._comp_ambiguous = []
self._might_be_time_varying = False # Inaccurate named. It really means if timesamples > 0
self._soft_range_min = None
self._soft_range_max = None
# get soft_range userdata settings
# FIXME: We need an OG equivalent
# attributes = self._get_attributes()
# if attributes:
# attribute = attributes[-1]
# if isinstance(attribute, Usd.Attribute):
# soft_range = attribute.GetCustomDataByKey("omni:kit:property:usd:soft_range_ui")
# if soft_range:
# self._soft_range_min = soft_range[0]
# self._soft_range_max = soft_range[1]
# Hard range for the value. For vector type, range value is a float/int that compares against each component
self._min = kwargs.get("min", None)
self._max = kwargs.get("max", None)
# Override with node-specified
# FIXME: minimum/maximum metadata isn't processed
# for attrib in self._get_og_attributes():
# if isinstance(attrib, og.Attribute):
# self._max = attrib.get_metadata(ogn.MetaDataKeys.MAXIMUM)
# self._min = attrib.get_metadata(ogn.MetaDataKeys.MINIMUM)
# break
# Invalid range
if self._min is not None and self._max is not None and self._min >= self._max:
self._min = self._max = None
# The state of the icon on the right side of the line with widgets
self._control_state = 0
# Callback when the control state is changing. We use it to redraw UI
self._on_control_state_changed_fn = None
# Callback when the value is reset. We use it to redraw UI
self._on_set_default_fn = None
# True if the attribute has the default value and the current value is not default
self._different_from_default: bool = False
# Per component different from default
self._comp_different_from_default: List[bool] = []
# We want to keep updating when OG is evaluating
self._last_compute_count = 0
settings = carb.settings.get_settings()
if settings.get(PLAY_COMPUTEGRAPH_SETTING):
OmniGraphBase._instances.add(self)
if len(OmniGraphBase._instances) == 1 and (OmniGraphBase._update_sub is None):
OmniGraphBase._update_sub = (
omni.kit.app.get_app()
.get_update_event_stream()
.create_subscription_to_pop(OmniGraphBase._on_update, name="OG prop-panel ui update")
)
@property
def control_state(self):
"""Returns the current control state, it's the icon on the right side of the line with widgets"""
return self._control_state
@property
def stage(self):
return self._stage
def update_control_state(self):
control_state, force_refresh = self._control_state_mgr.update_control_state(self)
# Redraw control state icon when the control state is changed
if self._control_state != control_state or force_refresh:
self._control_state = control_state
if self._on_control_state_changed_fn:
self._on_control_state_changed_fn()
def set_on_control_state_changed_fn(self, fn):
"""Callback that is called when control state is changed"""
self._on_control_state_changed_fn = fn
def set_on_set_default_fn(self, fn):
"""Callback that is called when value is reset"""
self._on_set_default_fn = fn
def clean(self):
self._stage = None
OmniGraphBase._instances.discard(self)
if not OmniGraphBase._instances:
OmniGraphBase._update_sub = None # unsubscribe from app update stream
OmniGraphBase._compute_counts.clear()
@carb.profiler.profile
def _get_default_value(self, attrib: HELD_ATTRIB) -> Tuple[bool, Any]:
if isinstance(attrib, og.Attribute):
default_str = attrib.get_metadata(ogn.MetadataKeys.DEFAULT)
og_tp = attrib.get_resolved_type()
if default_str is not None:
py_val = json.loads(default_str)
val = og.python_value_as_usd(og_tp, py_val)
return True, val
# If we still don't find default value, use type's default value
val_base = 0
if og_tp.array_depth > 0:
# Special case string, path vs uchar[]
if (og_tp.base_type == og.BaseDataType.UCHAR) and (
og_tp.role in [og.AttributeRole.TEXT, og.AttributeRole.PATH]
):
val_base = ""
else:
return True, []
elif og_tp.base_type == og.BaseDataType.BOOL:
val_base = False
elif og_tp.base_type == og.BaseDataType.TOKEN:
val_base = ""
py_val = val_base
if og_tp.tuple_count > 1:
if og_tp.role in [og.AttributeRole.FRAME, og.AttributeRole.MATRIX, og.AttributeRole.TRANSFORM]:
dim = 2 if og_tp.tuple_count == 4 else 3 if og_tp.tuple_count == 9 else 4
py_val = [[1 if i == j else 0 for j in range(dim)] for i in range(dim)]
else:
py_val = [val_base] * og_tp.tuple_count
val = og.python_value_as_usd(og_tp, py_val)
return True, val
return False, None
def is_different_from_default(self):
"""Returns True if the attribute has the default value and the current value is not default"""
self._update_value()
# soft_range has been overridden
if self._soft_range_min is not None and self._soft_range_max is not None:
return True
return self._different_from_default
def might_be_time_varying(self):
self._update_value()
return self._might_be_time_varying
def is_ambiguous(self):
self._update_value()
return self._ambiguous
def is_comp_ambiguous(self, index: int):
self._update_value()
comp_len = len(self._comp_ambiguous)
if comp_len == 0 or index < 0:
return self.is_ambiguous()
if index < comp_len:
return self._comp_ambiguous[index]
return False
def get_value_by_comp(self, comp: int):
self._update_value()
if comp == -1:
return self._value
return self._get_value_by_comp(self._value, comp)
def _save_real_values_as_prev(self):
# It's like copy.deepcopy but not all USD types support pickling (e.g. Gf.Quat*)
self._prev_real_values = [type(value)(value) for value in self._real_values]
def _get_value_by_comp(self, value, comp: int):
if value.__class__.__module__ == "pxr.Gf":
if value.__class__.__name__.startswith("Quat"):
if comp == 0:
return value.real
return value.imaginary[comp - 1]
if value.__class__.__name__.startswith("Matrix"):
dimension = len(value)
row = comp // dimension
col = comp % dimension # noqa: S001
return value[row, col]
if value.__class__.__name__.startswith("Vec"):
return value[comp]
else:
return value[comp]
return None
def _update_value_by_comp(self, value, comp: int):
if self._value.__class__.__module__ == "pxr.Gf":
if self._value.__class__.__name__.startswith("Quat"):
if comp == 0:
value.real = self._value.real
else:
imaginary = self._value.imaginary
imaginary[comp - 1] = self._value.imaginary[comp - 1]
value.SetImaginary(imaginary)
elif self._value.__class__.__name__.startswith("Matrix"):
dimension = len(self._value)
row = comp // dimension
col = comp % dimension # noqa: S001
value[row, col] = self._value[row, col]
elif self._value.__class__.__name__.startswith("Vec"):
value[comp] = self._value[comp]
else:
value[comp] = self._value[comp]
return value
def _compare_value_by_comp(self, val1, val2, comp: int):
return self._get_value_by_comp(val1, comp) == self._get_value_by_comp(val2, comp)
def _get_comp_num(self):
"""Returns the number of components in the value type"""
if self._real_type:
# For OG scalers have tuple_count == 1, but here we expect 0
return self._real_type.tuple_count if self._real_type.tuple_count > 1 else 0
return 0
def _on_dirty(self):
pass
def _set_dirty(self):
if self._editing > 0:
return
self._dirty = True
self._on_dirty()
def _get_type_name(self, obj: Usd.Object):
if hasattr(obj, "GetTypeName"):
return obj.GetTypeName()
if hasattr(obj, "typeName"):
return obj.typeName
return None
def _is_array_type(self, obj: HELD_ATTRIB):
if isinstance(obj, og.Attribute):
attr_type = obj.get_resolved_type()
is_array_type = attr_type.array_depth > 0 and attr_type.role not in [
og.AttributeRole.TEXT,
og.AttributeRole.PATH,
]
return is_array_type
return False
def _get_resolved_attribute_path(self, attribute: og.Attribute) -> str:
"""Return the path to the given attribute, considering resolved extended attributes"""
return f"{attribute.get_node().get_prim_path()}.{og.Attribute.resolved_prefix}{attribute.get_name()}"
def get_attribute_paths(self) -> List[Sdf.Path]:
return self._object_paths
def get_property_paths(self) -> List[Sdf.Path]:
return self.get_attribute_paths()
def get_connections(self):
return self._connections
def set_default(self, comp=-1):
"""Set the og.Attribute default value if it exists in metadata"""
# FIXME
# self.set_soft_range_userdata(None, None)
if self.is_different_from_default() is False or self._has_default_value is False:
if self._soft_range_min is not None and self._soft_range_max is not None:
if self._on_set_default_fn:
self._on_set_default_fn()
self.update_control_state()
return
with omni.kit.undo.group():
for attribute in self._get_og_attributes():
if isinstance(attribute, og.Attribute):
current_value = self._read_value(attribute)
if comp >= 0:
default_value = current_value
default_value[comp] = self._default_value[comp]
else:
default_value = self._default_value
self._change_property(attribute, default_value, current_value)
# We just set all the properties to the same value, it's no longer ambiguous
self._ambiguous = False
self._comp_ambiguous.clear()
self._different_from_default = False
self._comp_different_from_default.clear()
if self._on_set_default_fn:
self._on_set_default_fn()
def set_value(self, value, comp=-1):
if self._min is not None:
if hasattr(value, "__len__"):
for i in range(len(value)): # noqa: PLC0200
if value[i] < self._min:
value[i] = self._min
else:
if value < self._min:
value = self._min
if self._max is not None:
if hasattr(value, "__len__"):
for i in range(len(value)): # noqa: PLC0200
if value[i] > self._max:
value[i] = self._max
else:
if value > self._max:
value = self._max
if not self._ambiguous and not any(self._comp_ambiguous) and (value == self._value):
return False
if self.is_locked():
carb.log_warn("Setting locked attribute is not supported yet")
self._update_value(True) # reset value
return False
if self._might_be_time_varying:
carb.log_warn("Setting time varying attribute is not supported yet")
self._update_value(True) # reset value
return False
self._value = value
attributes = self._get_og_attributes()
if len(attributes) == 0:
return False
# FIXME: Here we normally harden placeholders into real attributes. For OG we don't do that.
# This is because all OG attributes are 'real', IE there are no attributes inherited from a 'type' that
# are un-instantiated. However there could be real (dynamic) USD attributes for which there are no
# OG attributes. In that case we want to allow editing of those values...
# self._create_placeholder_attributes(attributes)
if self._editing:
for i, attribute in enumerate(attributes):
set_value = False
self._ignore_notice = True
if comp == -1:
self._real_values[i] = self._value
if not self._change_on_edit_end:
set_value = True
else:
# Only update a single component of the value (for vector type)
value = self._real_values[i]
self._real_values[i] = self._update_value_by_comp(value, comp)
if not self._change_on_edit_end:
set_value = True
if set_value:
# Directly set the value on the attribute, not through a command.
# FIXME: Due to the TfNotice issue - we use USD API here.
is_extended_attr = (
attribute.get_extended_type() != og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR
)
usd_attr = self._stage.GetAttributeAtPath(attribute.get_path())
if is_extended_attr:
# But the resolved attrib is not in USD, so we need to set the value using OG, but then
# trigger a tfnotice so that the system will know that the attrib has changed
og.Controller.set(attribute, value)
# The USD attrib is actually a token, so the hack here is to change the token value
# so that the node will get the onValueChanged callback. FIXME: Obviously not ideal
# to be tokenizing the value
usd_attr.Set(str(value))
else:
usd_attr.Set(self._value)
self._ignore_notice = False
else:
with omni.kit.undo.group():
for i, attribute in enumerate(attributes):
self._ignore_notice = True
# begin_edit is not called for certain widget (like Checkbox), issue the command directly
if comp == -1:
self._change_property(attribute, self._value, None)
else:
# Only update a single component of the value (for vector type)
value = self._real_values[i]
self._real_values[i] = self._update_value_by_comp(value, comp)
self._change_property(attribute, value, None)
self._ignore_notice = False
if comp == -1:
# We just set all the properties to the same value, it's no longer ambiguous
self._ambiguous = False
self._comp_ambiguous.clear()
else:
self._comp_ambiguous[comp] = False
self._ambiguous = any(self._comp_ambiguous)
if self._has_default_value:
self._comp_different_from_default = [False] * self._get_comp_num()
if comp == -1:
self._different_from_default = value != self._default_value
if self._different_from_default:
for comp_non_default in range(len(self._comp_different_from_default)): # noqa: PLC0200
self._comp_different_from_default[comp_non_default] = not self._compare_value_by_comp(
value, self._default_value, comp_non_default
)
else:
self._comp_different_from_default[comp] = not self._compare_value_by_comp(
value, self._default_value, comp
)
self._different_from_default = any(self._comp_different_from_default)
else:
self._different_from_default = False
self._comp_different_from_default.clear()
self.update_control_state()
return True
def _is_prev_same(self):
return self._prev_real_values == self._real_values
def begin_edit(self):
self._editing = self._editing + 1
self._prev_value = self._value
self._save_real_values_as_prev()
def end_edit(self):
self._editing = self._editing - 1
if self._is_prev_same():
return
attributes = self._get_og_attributes()
omni.kit.undo.begin_group()
self._ignore_notice = True
for i, attribute in enumerate(attributes):
self._change_property(attribute, self._real_values[i], self._prev_real_values[i])
self._ignore_notice = False
omni.kit.undo.end_group()
# Set flags. It calls _on_control_state_changed_fn when the user finished editing
self._update_value(True)
def _change_property(self, attribute: og.Attribute, new_value, old_value):
"""Change the given attribute via a command"""
path = Sdf.Path(attribute.get_path())
# Set the value on the attribute, called to "commit" the value
# FIXME: Due to the TfNotice issue - we use USD API here.
is_extended_attr = attribute.get_extended_type() != og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR
if is_extended_attr:
# But the resolved attrib is not in USD, so we need to set the value using OG, but then
# trigger a tfnotice so that the system will know that the attrib has changed
og.Controller.set(attribute, new_value)
# The USD attrib is actually a token, so the hack here is to change the token value
# so that the node will get the onValueChanged callback. FIXME: Obviously not ideal
# to be tokenizing the value + Undo doesn't work
omni.kit.commands.execute("ChangeProperty", prop_path=path, value=str(new_value), prev=str(old_value))
else:
# FIXME: The UI widgets seem to rely on USD notices (eg color control), so we must set values through
# USD until we can refactor things to not require the notices.
omni.kit.commands.execute("ChangeProperty", prop_path=path, value=new_value, prev=old_value)
def get_value(self):
self._update_value()
return self._value
def get_current_time_code(self):
# FIXME: Why are we being asked this
return Usd.TimeCode.Default()
def _update_value(self, force=False):
"""Pull the current value of the attributes into this object"""
return self._update_value_objects(force, self._get_og_attributes())
def _update_value_objects(self, force: bool, objects: List[HELD_ATTRIB]):
if (self._dirty or force) and self._stage: # noqa: PLR1702
carb.profiler.begin(1, "OmniGraphBase._update_value_objects")
self._might_be_time_varying = False
self._value = None
self._has_default_value = False
self._default_value = None
self._real_values.clear()
self._real_type = None
self._connections.clear()
self._ambiguous = False
self._comp_ambiguous.clear()
self._different_from_default = False
self._comp_different_from_default.clear()
for index, attr_object in enumerate(objects):
value, tp = self._read_value_and_type(attr_object)
self._real_values.append(value)
self._real_type = tp
#
if isinstance(attr_object, og.Attribute):
# FIXME: Can OG attributes be 'time varying'?
# self._might_be_time_varying = self._might_be_time_varying or attr_object.GetNumTimeSamples() > 0
self._connections.append(
[
Sdf.Path(conn.get_node().get_prim_path()).AppendProperty(conn.get_name())
for conn in attr_object.get_upstream_connections()
]
)
# only need to check the first prim. All other prims attributes are ostensibly the same
if index == 0:
self._value = value
if (
(self._value is not None)
and self._is_array_type(attr_object)
and len(self._value) >= BIG_ARRAY_MIN
):
self._is_big_array = True
comp_num = self._get_comp_num()
self._comp_ambiguous = [False] * comp_num
self._comp_different_from_default = [False] * comp_num
# Loads the default value
self._has_default_value, self._default_value = self._get_default_value(attr_object)
elif self._value != value:
self._value = value
self._ambiguous = True
comp_num = len(self._comp_ambiguous)
if comp_num > 0:
for i in range(comp_num):
if not self._comp_ambiguous[i]:
self._comp_ambiguous[i] = not self._compare_value_by_comp(
value, self._real_values[0], i
)
if self._has_default_value:
comp_num = len(self._comp_different_from_default)
if comp_num > 0 and (not self._is_array_type(attr_object)):
for i in range(comp_num):
if not self._comp_different_from_default[i]:
self._comp_different_from_default[i] = not self._compare_value_by_comp(
value, self._default_value, i
)
self._different_from_default |= any(self._comp_different_from_default)
elif not self._is_array_type(attr_object) or value or self._default_value:
# empty arrays may compare unequal
self._different_from_default |= value != self._default_value
self._dirty = False
self.update_control_state()
carb.profiler.end(1)
return True
return False
def _get_attributes(self):
"""
Gets the list of managed USD Attributes
NOTE: Only returns attributes for which there are corresponding OG Attributes
"""
attributes = []
if not self._stage:
return attributes
for path in self._object_paths:
prim = self._stage.GetPrimAtPath(path.GetPrimPath())
if prim:
attr = prim.GetAttribute(path.name)
if attr:
# Hidden attributes don't get placeholders
if not attr.IsHidden():
try:
_ = og.Controller.attribute(path.pathString)
except og.OmniGraphError:
# No corresponding OG Attribute
pass
else:
attributes.append(attr)
else:
attr = PlaceholderAttribute(name=path.name, prim=prim, metadata=self._metadata)
attributes.append(attr)
return attributes
def _get_og_attributes(self) -> List[HELD_ATTRIB]:
"""Returns the held attributes object wrappers"""
attributes = []
for path in self._object_paths:
attrib = None
try:
attrib = og.Controller.attribute(path.pathString)
attributes.append(attrib)
except og.OmniGraphError:
# Invalid attribute for whatever reason, put in a placeholder
pass
if not attrib:
attributes.append(PlaceholderOmniGraphAttribute(path.name, path.GetPrimPath().pathString))
return attributes
@carb.profiler.profile
def _read_value_and_type(self, attr_object: HELD_ATTRIB) -> Tuple[Any, Optional[og.Type]]:
"""Reads the value and type of the given object
Args:
attr_object The object to be read
Returns:
The value
The og.Type if the value is read from OG
"""
val = None
if not isinstance(attr_object, PlaceholderOmniGraphAttribute):
# The ui expects USD attr_objects, so we must convert data
# here.
# FIXME: Could optimize by wrapping numpy in compatible shim classes
#
try:
if attr_object.is_valid():
og_val = og.Controller(attr_object).get()
og_tp = attr_object.get_resolved_type()
# Truncate big arrays to limit copying between numpy/USD types
val = og.attribute_value_as_usd(og_tp, og_val, BIG_ARRAY_MIN)
return (val, og_tp)
except og.OmniGraphError:
carb.log_warn(f"Failed to read {attr_object.get_path()}")
return (val, None)
def _read_value(self, attr_object: HELD_ATTRIB):
"""Returns the current USD value of the given attribute object"""
val, _ = self._read_value_and_type(attr_object)
return val
def set_locked(self, locked):
pass
def is_locked(self):
return False
def has_connections(self):
return self._connections[-1]
| 32,585 | Python | 42.390146 | 118 | 0.555777 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/style.py | """Contains common information for styling of the OGN node editor and ancillary windows"""
import os
from pathlib import Path
from typing import Dict
from omni import ui
# These values are not affected by style parameters. Using **kwargs keeps them consistent.
VSTACK_ARGS = {"height": 0, "spacing": 8, "margin_height": 4}
HSTACK_PROPERTIES = {"spacing": 10}
# Style names that can be used for the overrides
STYLE_GHOST = "Ghost Prompt"
KIT_GREEN = 0xFF8A8777
LABEL_WIDTH = 120
# Styling information for tooltips
TOOLTIP_STYLE = {
"background_color": 0xFFD1F7FF,
"color": 0xFF333333,
"margin_width": 3,
"margin_height": 2,
"border_width": 3,
"border_color": 0xFF000000,
}
# Styling for integer input boxes
INT_STYLE = {"Tooltip": TOOLTIP_STYLE}
# Styling for the main menubar
MENU_STYLE = {
"Tooltip": TOOLTIP_STYLE,
"background_color": 0xFF555555,
"background_selected_color": 0xFF999999,
"color": 0xFFFFFFFF,
"border_radius": 4,
"padding": 8,
}
# Styling for the metadata subsection
METADATA_STYLE = {
"Tooltip": TOOLTIP_STYLE,
"border_color": 0xFF555555,
"background_color": 0xFF000000,
"border_width": 1,
"margin": 0,
"TreeView": {"font_size": 12, "color": 0xFFAAAAAA, "background_color": 0xFF23211F, "secondary_color": 0xFF23211F},
"TreeView::header": {
"font_size": 12,
"color": 0xFFAAAAAA,
"background_color": 0xFF00FFFF,
"secondary_color": 0xFF23211F,
},
}
# Styling for string input boxes
STRING_STYLE = {"Tooltip": TOOLTIP_STYLE}
# Styling information for vertical stacks.
VSTACK_STYLE = {"Tooltip": TOOLTIP_STYLE}
# ======================================================================
# General styling for the window as a whole (dark mode)
WINDOW_STYLE = {
"Window": {"background_color": 0xFF444444},
"Button": {"background_color": 0xFF292929, "margin": 3, "padding": 3, "border_radius": 2},
"Button.Label": {"color": 0xFFCCCCCC},
"Button:hovered": {"background_color": 0xFF9E9E9E},
"Button:pressed": {"background_color": 0xC22A8778},
"VStack::main_v_stack": {"secondary_color": 0x0, "margin_width": 10, "margin_height": 0},
"VStack::frame_v_stack": {"margin_width": 15},
"Rectangle::frame_background": {"background_color": 0xFF343432, "border_radius": 5},
"Field::models": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 4.0},
"Frame": {"background_color": 0xFFAAAAAA},
"Label::transform": {"font_size": 14, "color": 0xFF8A8777},
"Circle::transform": {"background_color": 0x558A8777},
"Field::transform": {
"background_color": 0xFF23211F,
"border_radius": 3,
"corner_flag": ui.CornerFlag.RIGHT,
"font_size": 14,
},
"Slider::transform": {
"background_color": 0xFF23211F,
"border_radius": 3,
"draw_mode": ui.SliderDrawMode.DRAG,
"corner_flag": ui.CornerFlag.RIGHT,
"font_size": 14,
},
"Label::transform_label": {"font_size": 14, "color": 0xFFDDDDDD},
"Label": {"font_size": 14, "color": 0xFF8A8777},
"Label::label": {"font_size": 14, "color": 0xFF8A8777},
"Label::title": {"font_size": 14, "color": 0xFFAAAAAA},
"Triangle::title": {"background_color": 0xFFAAAAAA},
"ComboBox::path": {"font_size": 12, "secondary_color": 0xFF23211F, "color": 0xFFAAAAAA},
"ComboBox::choices": {
"font_size": 12,
"color": 0xFFAAAAAA,
"background_color": 0xFF23211F,
"secondary_color": 0xFF23211F,
},
"ComboBox:hovered:choices": {"background_color": 0xFF33312F, "secondary_color": 0xFF33312F},
"Slider::value_less": {
"font_size": 14,
"color": 0x0,
"border_radius": 5,
"background_color": 0xFF23211F,
"secondary_color": KIT_GREEN,
"border_color": 0xFFAAFFFF,
"border_width": 0,
},
"Slider::value": {
"font_size": 14,
"color": 0xFFAAAAAA,
"border_radius": 5,
"background_color": 0xFF23211F,
"secondary_color": KIT_GREEN,
},
"Rectangle::add": {"background_color": 0xFF23211F},
"Rectangle:hovered:add": {"background_color": 0xFF73414F},
"CheckBox::greenCheck": {"font_size": 12, "background_color": KIT_GREEN, "color": 0xFF23211F},
"CheckBox::whiteCheck": {"font_size": 12, "background_color": 0xFFDDDDDD, "color": 0xFF23211F},
"Slider::colorField": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFF8A8777},
# Frame
"CollapsableFrame::standard_collapsable": {
"background_color": 0xFF343432,
"secondary_color": 0xFF343432,
"font_size": 16,
"border_radius": 2.0,
"border_color": 0x0,
"border_width": 0,
},
"CollapsableFrame:hovered:standard_collapsable": {"secondary_color": 0xFFFBF1E5},
"CollapsableFrame:pressed:standard_collapsable": {"secondary_color": 0xFFF7E4CC},
}
# ======================================================================
# Styling for all of the collapsable frames
COLLAPSABLE_FRAME_STYLE = {
"CollapsableFrame::standard_collapsable": {
"background_color": 0xFF343432,
"secondary_color": 0xFF343432,
"color": 0xFFAAAAAA,
"border_radius": 4.0,
"border_color": 0x0,
"border_width": 0,
"font_size": 14,
"padding": 0,
"margin_height": 5,
"margin_width": 5,
},
"HStack::header": {"margin": 5},
"CollapsableFrame:hovered": {"secondary_color": 0xFF3A3A3A},
"CollapsableFrame:pressed": {"secondary_color": 0xFF343432},
}
# ==============================================================================================================
class Icons:
"""A utility that uses the current style to look up the path to icons"""
def __init__(self):
import carb.settings
icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons")
self.__style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
# Read all the svg files in the directory
self.__icons = {icon.stem: icon for icon in icon_path.joinpath(self.__style).glob("*.svg")}
def get(self, prim_type, default=None):
"""Checks the icon cache and returns the icon if exists, None if not"""
found = self.__icons.get(prim_type)
if not found and default:
found = self.__icons.get(default)
return str(found) if found else None
# ======================================================================
def get_window_style() -> Dict:
"""Returns a dictionary holding the style information for the OGN editor window"""
import carb.settings
style_name = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
icons = Icons()
if style_name == "NvidiaLight":
style = {
"AddElement.Image": {"image_url": icons.get("Plus"), "color": 0xFF535354},
"Button": {"background_color": 0xFF296929, "margin": 3, "padding": 3, "border_radius": 4},
"Button.Label": {"color": 0xFFCCCCCC},
"Button:hovered": {"background_color": 0xFF9E9E9E},
"Button:pressed": {"background_color": 0xC22A8778},
"DangerButton": {"background_color": 0xFF292989, "margin": 3, "padding": 3, "border_radius": 4},
"DisabledButton": {"background_color": 0x33296929, "margin": 3, "padding": 3, "border_radius": 4},
"DisabledButton.Label": {"color": 0x33666666},
"Code": {"color": 0xFFACACAC, "margin_width": 4, "font_size": 14, "background_color": 0xFF535354},
"Info": {"color": 0xFF000000, "margin_width": 4, "background_color": 0xFF53E3E3},
"FolderImage.Image": {"image_url": icons.get("folder"), "color": 0xFF535354},
"LabelOverlay": {"background_color": 0xFF535354},
"Rectangle::frame_background": {"background_color": 0xFFC4C4C2, "border_radius": 5},
"RemoveElement.Image": {"image_url": icons.get("trash"), "color": 0xFF535354},
"ScrollingFrame": {"secondary_color": 0xFF444444},
STYLE_GHOST: {"color": 0xFF4C4C4C},
"Tooltip": {
"background_color": 0xFFD1F7FF,
"color": 0xFF333333,
"margin_width": 3,
"margin_height": 2,
"border_width": 3,
"border_color": 0xFF000000,
},
"TreeView": {
"background_color": 0xFFE0E0E0,
"background_selected_color": 0x109D905C,
"secondary_color": 0xFFACACAC,
},
"TreeView.ScrollingFrame": {"background_color": 0xFFE0E0E0},
"TreeView.Header": {"color": 0xFFCCCCCC},
"TreeView.Header::background": {
"background_color": 0xFF535354,
"border_color": 0xFF707070,
"border_width": 0.5,
},
"TreeView.Item": {"color": 0xFF535354, "font_size": 16},
"TreeView.Item:selected": {"color": 0xFF2A2825},
"TreeView:selected": {"background_color": 0x409D905C},
}
else:
style = {
"AddElement.Image": {"image_url": icons.get("Plus"), "color": 0xFF8A8777},
"Button": {"background_color": 0xFF296929, "margin": 3, "padding": 3, "border_radius": 4},
"Button.Label": {"color": 0xFFCCCCCC},
"Button:hovered": {"background_color": 0xFF9E9E9E},
"Button:pressed": {"background_color": 0xC22A8778},
"DangerButton": {"background_color": 0xFF292989, "margin": 3, "padding": 3, "border_radius": 4},
"DisabledButton": {"background_color": 0x33296929, "margin": 3, "padding": 3, "border_radius": 4},
"DisabledButton.Label": {"color": 0x33666666},
"Code": {"color": 0xFF808080, "margin_width": 4, "font_size": 14, "background_color": 0xFF8A8777},
"Info": {"color": 0xFFFFFFFF, "margin_width": 4, "background_color": 0xFF232323},
"FolderImage.Image": {"image_url": icons.get("folder"), "color": 0xFF8A8777},
"RemoveElement.Image": {"image_url": icons.get("trash"), "color": 0xFF8A8777},
STYLE_GHOST: {"color": 0xFF4C4C4C, "margin_width": 4},
"Tooltip": {
"background_color": 0xFFD1F7FF,
"color": 0xFF333333,
"margin_width": 3,
"margin_height": 2,
"border_width": 3,
"border_color": 0xFF000000,
},
"TreeView": {
"background_color": 0xFF23211F,
"background_selected_color": 0x664F4D43,
"secondary_color": 0xFF403B3B,
},
"TreeView.ScrollingFrame": {"background_color": 0xFF23211F},
"TreeView.Header": {"background_color": 0xFF343432, "color": 0xFFCCCCCC, "font_size": 13.0},
"TreeView.Image:disabled": {"color": 0x60FFFFFF},
"TreeView.Item": {"color": 0xFF8A8777},
"TreeView.Item:disabled": {"color": 0x608A8777},
"TreeView.Item:selected": {"color": 0xFF23211F},
"TreeView:selected": {"background_color": 0xFF8A8777},
}
# Add the style elements common to both light and dark
shared_style = {
"ScrollingFrame": {"margin_height": 10},
"Frame::attribute_value_frame": {"margin_height": 5, "margin_width": 5},
"Label::frame_label": {"margin_width": 5},
"CheckBox": {"font_size": 12},
"CollapsableFrame": {
"background_color": 0xFF343432,
"secondary_color": 0xFF343432,
"color": 0xFFAAAAAA,
"border_radius": 4.0,
"border_color": 0x0,
"border_width": 0,
"font_size": 16,
"padding": 0,
"margin_width": 5,
},
"CollapsableFrame:hovered": {"secondary_color": 0xFF3A3A3A},
"CollapsableFrame:pressed": {"secondary_color": 0xFF343432},
# "HStack": {"height": 0, "spacing": 5, "margin_width": 10},
# "HStack::header": {"margin": 5},
# "Label": {"word_wrap": True},
"VStack": {"margin_height": 5},
}
# Add some color to hovered widgets for debugging
if os.getenv("OGN_DEBUG_EDITOR"):
shared_style[":hovered"] = {"debug_color": 0x22FFDDDD}
style.update(shared_style)
return style
# ======================================================================
# Constants for the layout of the window
WIDGET_WIDTH = 200 # Standard widget width
LINE_HEIGHT = 16 # Height of a single input line
NAME_VALUE_WIDTH = 150 # Width of the node property name column
BUTTON_WIDTH = 120 # Standard button width
# ======================================================================
def name_value_label(property_name: str, tooltip: str = ""):
"""Emit a UI label for the node property names; allows a common fixed width for the column"""
return ui.Label(property_name, width=NAME_VALUE_WIDTH, alignment=ui.Alignment.RIGHT_TOP, tooltip=tooltip)
# ======================================================================
def name_value_hstack():
"""Emit an HStack widget suitable for the property/value pairs for node properties"""
return ui.HStack(**HSTACK_PROPERTIES)
# ======================================================================
def icon_directory() -> Path:
"""Returns a string containing the path to the icon directory for the current style"""
import carb.settings
style_name = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
return Path(__file__).joinpath("icons").joinpath(style_name)
| 13,778 | Python | 41.925234 | 118 | 0.573378 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_prim_node_templates.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from functools import partial
from typing import List
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel
from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH
from pxr import Sdf, Usd
# Common functionality for get/set prim attribute templates
ATTRIB_LABEL_STYLE = {"alignment": ui.Alignment.RIGHT_TOP}
def get_use_path(stage: Usd.Stage, node_prim_path: Sdf.Path) -> bool:
# Gets the value of the usePath input attribute
prim = stage.GetPrimAtPath(node_prim_path)
if prim:
return prim.GetAttribute("inputs:usePath").Get()
return False
def is_usable(type_name: Sdf.ValueTypeName) -> bool:
# Returns True if the given type can be used by OG
return og.AttributeType.type_from_sdf_type_name(str(type_name)).base_type != og.BaseDataType.UNKNOWN
def get_filtered_attributes(prim: Usd.Prim) -> List[str]:
# Return attributes that should be selectable for the given prim
# FIXME: Ideally we only want to show attributes that are useful and can actually be sensibly set. We
# will want to add customize logic here to handle pseudo-attributes that can only be manipulated using
# USD function sets.
return [p.GetName() for p in prim.GetAttributes() if not p.IsHidden() and is_usable(p.GetTypeName())]
class TargetPrimAttributeNameModel(TfTokenAttributeModel):
"""Model for selecting the target attribute for the write/read operation. We modify the list to show attributes
which are available on the target prim.
"""
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, item, label):
"""
Args:
item: the attribute name token to be shown
label: the label to show in the drop-down
"""
super().__init__()
self.token = item
self.model = ui.SimpleStringModel(label)
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
node_prim_path: Sdf.Path,
):
"""
Args:
stage: The current stage
attribute_paths: The list of full attribute paths
self_refresh: ignored
metadata: pass-through metadata for model
node_prim_path: The path of the compute node
"""
self._stage = stage
self._node_prim_path = node_prim_path
self._target_prim = None
self._max_attrib_name_length = 0
super().__init__(stage, attribute_paths, self_refresh, metadata)
def _get_allowed_tokens(self, _):
# Override of TfTokenAttributeModel to specialize what tokens are to be shown
return self._get_target_attribs_of_interest()
def _update_value(self, force=False):
# Override of TfTokenAttributeModel to refresh the allowed token cache
self._update_allowed_token()
super()._update_value(force)
def _item_factory(self, item):
# Construct the item for the model
label = item
# FIXME: trying to right-justify type in drop down doesn't work because
# font is not fixed widget
# if item and self._target_prim:
# prop = self._target_prim.GetProperty(item)
# if prop:
# spacing = 2 + (self._max_attrib_name_length - len(item))
# label = f"{item} {' '*spacing} {str(prop.GetTypeName())})"
return TargetPrimAttributeNameModel.AllowedTokenItem(item, label)
def _update_allowed_token(self):
# Override of TfTokenAttributeModel to specialize the model items
super()._update_allowed_token(token_item=self._item_factory)
def _get_target_attribs_of_interest(self) -> List[str]:
# Returns the attributes we want to let the user select from
prim = self._stage.GetPrimAtPath(self._node_prim_path)
attribs = []
target = None
if prim:
if not get_use_path(self._stage, self._node_prim_path):
rel = prim.GetRelationship("inputs:prim")
if rel.IsValid():
targets = rel.GetTargets()
if targets:
target = self._stage.GetPrimAtPath(targets[0])
else:
prim_path = prim.GetAttribute("inputs:primPath").Get()
if prim_path:
target = self._stage.GetPrimAtPath(prim_path)
if target:
attribs = get_filtered_attributes(target)
self._target_prim = target
self._max_attrib_name_length = max(len(s) for s in attribs) if attribs else 0
name_attr = prim.GetAttribute("inputs:name")
if len(attribs) > 0:
current_value = name_attr.Get()
if (current_value is not None) and (current_value != "") and (current_value not in attribs):
attribs.append(current_value)
attribs.insert(0, "")
else:
name_attr.Set("")
return attribs
class PrimAttributeCustomLayoutBase:
"""Base class for Read/WritePrimAttribute"""
# Set by the derived class to customize the layout
_value_is_output = True
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.attribs = []
self.target_attrib_name_model = None
self.prim_path_model = None
self.prim_rel_widget = None
self.use_path_model = None
self._inputs_prim_watcher = None
self._inputs_usepath_watcher = None
def _name_attrib_build_fn(self, ui_prop: UsdPropertyUiEntry, *args):
# Build the Attribute Name widget
stage = self.compute_node_widget.stage
node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212
if get_use_path(stage, node_prim_path):
# Build the simple token input for data-driven attribute name
ui_prop.override_display_name("Attribute Name")
self.target_attrib_name_model = UsdPropertiesWidgetBuilder._tftoken_builder( # noqa: PLW0212
stage,
ui_prop.prop_name,
ui_prop.property_type,
ui_prop.metadata,
[node_prim_path],
{"enabled": True, "style": ATTRIB_LABEL_STYLE},
{"enabled": True},
)
return
with ui.HStack(spacing=HORIZONTAL_SPACING):
ui.Label("Attribute Name", name="label", style=ATTRIB_LABEL_STYLE, width=LABEL_WIDTH)
ui.Spacer(width=HORIZONTAL_SPACING)
with ui.ZStack():
attr_path = node_prim_path.AppendProperty("inputs:name")
# Build the token-selection widget when prim is known
self.target_attrib_name_model = TargetPrimAttributeNameModel(
stage, [attr_path], False, {}, node_prim_path
)
ui.ComboBox(self.target_attrib_name_model)
def _prim_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *args):
# Build the token input prim path widget
stage = self.compute_node_widget.stage
node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212
use_path = get_use_path(stage, node_prim_path)
ui_prop.override_display_name("Prim Path")
self.prim_path_model = UsdPropertiesWidgetBuilder._tftoken_builder( # noqa: PLW0212
stage,
ui_prop.prop_name,
ui_prop.property_type,
ui_prop.metadata,
[node_prim_path],
{"enabled": use_path, "style": ATTRIB_LABEL_STYLE},
{"enabled": use_path},
)
self.prim_path_model.add_value_changed_fn(self._on_target_prim_path_changed)
def _prim_rel_build_fn(self, ui_prop: UsdPropertyUiEntry, *args):
# Build the relationship input prim widget
stage = self.compute_node_widget.stage
node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212
use_path = get_use_path(stage, node_prim_path)
ui_prop.override_display_name("Prim")
self.prim_rel_widget = UsdPropertiesWidgetBuilder._relationship_builder( # noqa: PLW0212
stage,
ui_prop.prop_name,
ui_prop.metadata,
[node_prim_path],
{"enabled": not use_path, "style": ATTRIB_LABEL_STYLE},
{
"enabled": not use_path,
"on_remove_target": self._on_target_prim_rel_changed,
"target_picker_on_add_targets": self._on_target_prim_rel_changed,
"targets_limit": 1,
},
)
def _use_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *args):
# Build the boolean toggle for inputs:usePath
stage = self.compute_node_widget.stage
node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212
ui_prop.override_display_name("Use Path")
self.use_path_model = UsdPropertiesWidgetBuilder._bool_builder( # noqa: PLW0212
stage,
ui_prop.prop_name,
ui_prop.property_type,
ui_prop.metadata,
[node_prim_path],
{"style": ATTRIB_LABEL_STYLE},
)
self.use_path_model.add_value_changed_fn(self._on_usepath_changed)
def _on_target_prim_rel_changed(self, *args):
# When the inputs:prim relationship changes
# Dirty the attribute name list model because the prim may have changed
self.target_attrib_name_model._set_dirty() # noqa: PLW0212
self.prim_rel_widget._set_dirty() # noqa: PLW0212
def _on_target_prim_path_changed(self, *args):
# When the inputs:primPath token changes
# Dirty the attribute name list model because the prim may have changed
self.target_attrib_name_model._set_dirty() # noqa: PLW0212
def _on_usepath_changed(self, _):
# When the usePath toggle changes
self.prim_rel_widget._set_dirty() # noqa: PLW0212
self.prim_path_model._set_dirty() # noqa: PLW0212
# FIXME: Not sure why _set_dirty doesn't trigger UI change, have to rebuild
self.compute_node_widget.request_rebuild()
def apply(self, props):
# Called by compute_node_widget to apply UI when selection changes
def find_prop(name):
try:
return next((p for p in props if p.prop_name == name))
except StopIteration:
return None
def build_fn_for_value(prop: UsdPropertyUiEntry):
def build_fn(*args):
# The resolved attribute is procedural and does not inherit the meta-data of the extended attribute
# so we need to manually set the display name
prop.override_display_name("Value")
self.compute_node_widget.build_property_item(
self.compute_node_widget.stage, prop, self.compute_node_widget._payload # noqa: PLW0212
)
return build_fn
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
prop = find_prop("inputs:prim")
CustomLayoutProperty(None, None, build_fn=partial(self._prim_rel_build_fn, prop))
prop = find_prop("inputs:name")
CustomLayoutProperty(None, None, build_fn=partial(self._name_attrib_build_fn, prop))
prop = find_prop("inputs:usePath")
CustomLayoutProperty(None, None, build_fn=partial(self._use_path_build_fn, prop))
prop = find_prop("inputs:primPath")
CustomLayoutProperty(None, None, build_fn=partial(self._prim_path_build_fn, prop))
# Build the input/output value widget using the compute_node_widget logic so that
# we get the automatic handling of extended attribute
if not self._value_is_output:
prop = find_prop("inputs:value")
CustomLayoutProperty(None, None, build_fn=build_fn_for_value(prop))
if self._value_is_output:
with CustomLayoutGroup("Outputs"):
prop = find_prop("outputs:value")
CustomLayoutProperty(None, None, build_fn=build_fn_for_value(prop))
return frame.apply(props)
| 13,207 | Python | 42.590759 | 115 | 0.6174 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/extension.py | """
Standard file used to manage extension load and unload
"""
from pathlib import Path
import carb
import omni.ext
import omni.kit
from omni.kit.window.extensions import ExtsWindowExtension
from .compute_node_widget import ComputeNodeWidget # noqa: PLE0402
from .menu import Menu # noqa: PLE0402
from .metaclass import Singleton # noqa: PLE0402
from .omnigraph_in_extension_window import OmniGraphPage, clear_omnigraph_caches, has_omnigraph_nodes
from .properties_widget import OmniGraphProperties # noqa: PLE0402
# ==============================================================================================================
class _PublicExtension(omni.ext.IExt):
"""Standard extension support class, necessary for extension management"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__menu = None
self.__widget = None
self._properties = None
self._hook = None
def register_stage_icon(self):
"""Register the icon used in the stage widget for OmniGraph Prims"""
try:
import omni.kit.widget.stage # noqa: PLW0621
except ImportError:
# No stage widget, no need to register icons
return
stage_icons = omni.kit.widget.stage.StageIcons()
current_path = Path(__file__).parent
icon_path = current_path.parent.parent.parent.parent.joinpath("icons")
style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
icon_path = icon_path.joinpath(style)
for file_name, prim_type in [("OmniGraph.svg", "OmniGraph"), ("OmniGraph.svg", "ComputeGraph")]:
file_path = icon_path.joinpath(file_name)
stage_icons.set(prim_type, file_path)
def on_startup(self):
"""Callback executed when the extension is starting up. Create the menu that houses the UI functionality"""
self.__menu = Menu()
self.__widget = ComputeNodeWidget()
self._properties = OmniGraphProperties()
manager = omni.kit.app.get_app().get_extension_manager()
self._hook = manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self.register_stage_icon(),
ext_name="omni.kit.widget.stage",
hook_name="omni.graph.ui",
)
ComputeNodeWidget.get_instance().add_template_path(__file__)
ExtsWindowExtension.add_tab_to_info_widget(OmniGraphPage)
ExtsWindowExtension.add_searchable_keyword(
"@omnigraph",
"Uses OmniGraph",
has_omnigraph_nodes,
clear_omnigraph_caches,
)
def on_shutdown(self):
"""Callback executed when the extension is being shut down. The menu will clean up the dangling editors"""
ExtsWindowExtension.remove_searchable_keyword("@omnigraph")
ExtsWindowExtension.remove_tab_from_info_widget(OmniGraphPage)
self.__menu.on_shutdown()
self.__menu = None
# Must do this here to avoid the dangling reference
Singleton.forget(Menu)
self.__widget.on_shutdown()
self.__widget = None
self._properties.on_shutdown()
self._properties = None
| 3,231 | Python | 37.939759 | 115 | 0.629526 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/compute_node_widget.py | import asyncio
import importlib.util
import pathlib
import weakref
from contextlib import suppress
from typing import List
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
import omni.kit.window.property as p
import omni.ui as ui
import omni.usd
from omni.kit.property.usd.custom_layout_helper import CustomLayoutGroup, CustomLayoutProperty
from omni.kit.property.usd.usd_attribute_widget import UsdAttributeUiEntry, UsdPropertiesWidget, UsdPropertyUiEntry
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH
from pxr import Sdf, Usd
from .omnigraph_attribute_builder import OmniGraphPropertiesWidgetBuilder # noqa: PLE0402
from .omnigraph_attribute_builder import find_first_node_with_attrib # noqa: PLE0402
_compute_node_widget_instance = None
class ComputeNodeWidget(UsdPropertiesWidget):
"""Creates and registers a widget in the Property Window to display Compute Node contents"""
# self.bundles : dict[bundle_name : str, tuple[omni::graph::core::Py_Bundle, list[attrib_name : str]]]
BUNDLE_INDEX = 0
ATTRIB_LIST_INDEX = 1
def __init__(self, title="OmniGraph Node", collapsed=False):
super().__init__(title=title, collapsed=collapsed)
self.context_menu = ui.Menu("ContextMenu")
self.bundle_update_sub = None
self.bundles = {}
self.graph_context: og.GraphContext = None
self.graph: og.Graph = None
self.node: og.Node = None
self.selection = omni.usd.get_context().get_selection()
self.stage: Usd.Stage = None
self.stage_update_sub = None
self.template = None
self.template_paths = []
self.time = 0
self.window = None
self.window_width_change = False
self.window_width_change_fn_set = False
self.node_type_name = None
self.node_event_sub = None
self._payload = None
w = p.get_window()
w.register_widget("prim", "compute_node", self)
global _compute_node_widget_instance
_compute_node_widget_instance = weakref.ref(self)
OmniGraphPropertiesWidgetBuilder.startup()
@staticmethod
def get_instance():
return _compute_node_widget_instance()
def on_shutdown(self):
w = p.get_window()
w.unregister_widget("prim", "compute_node")
def reset(self):
super().reset()
window = ui.Workspace.get_window("Property")
if self.window != window:
self.window_width_change_fn_set = False
self.window = window
self.window_width_change = False
def __on_node_event(self, event):
# Called when one of the node event happens
self.request_rebuild()
def on_new_payload(self, payload: List[Sdf.Path]) -> bool:
"""
See PropertyWidget.on_new_payload
"""
if self.bundle_update_sub:
self.bundle_update_sub = None
if self.stage_update_sub:
self.stage_update_sub = None
if len(payload) == 0:
return False
self.stage = omni.usd.get_context().get_stage()
self.node = None
for path in reversed(payload):
node = og.get_node_by_path(path.pathString)
if (
node
and node.is_valid()
and self.stage.GetPrimAtPath(node.get_prim_path()).GetTypeName() in ("ComputeNode", "OmniGraphNode")
):
self.node = node
self.graph = self.node.get_graph()
self.node_event_sub = node.get_event_stream().create_subscription_to_pop(
self.__on_node_event, name=f"{path.pathString} Event"
)
break
if self.node is None:
return False
self.node_type_name = self.node.get_type_name()
self._payload = payload
self.graph_context = self.graph.get_default_graph_context() if self.graph.is_valid() else None
self.bundles = {}
return True
def get_additional_kwargs(self, ui_attr: UsdAttributeUiEntry):
additional_label_kwargs = {"alignment": ui.Alignment.RIGHT}
additional_widget_kwargs = {"no_mixed": True}
return additional_label_kwargs, additional_widget_kwargs
def get_widget_prim(self):
return self.stage.GetPrimAtPath(self._payload[-1])
def add_template_path(self, file_path):
"""Makes a path from the file_path parameter and adds it to templates paths.
So if there is a same kind of structure:
/templates
template_<ModuleName>.<NameOfComputeNodeType>.py
<my_extension>.py
then template path can be added by this line in the <my_extension>.py:
omni.graph.ui.ComputeNodeWidget.get_instance().add_template_path(__file__)
example of template filename:
template_omni.particle.system.core.Emitter.py
"""
template_path = pathlib.Path(file_path).parent.joinpath(pathlib.Path("templates"))
if template_path not in self.template_paths:
self.template_paths.append(template_path)
def get_template_path(self, template_name):
for path in self.template_paths:
path = path / template_name
if path.is_file():
return path
return None
def load_template(self, props):
if not self.node_type_name:
return None
if self.node_type_name.startswith("omni.graph.ui."):
template_name = f"template_{self.node_type_name[14:]}.py"
else:
template_name = f"template_{self.node_type_name}.py"
path = self.get_template_path(template_name)
if path is None:
return None
spec = importlib.util.spec_from_file_location(template_name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
self.template = module.CustomLayout(self)
if not self.template.enable:
return None
return self.template.apply(props)
async def __delayed_build_layout(self):
await omni.kit.app.get_app().next_update_async()
self.window.frame.rebuild()
def rebuild_window(self):
asyncio.ensure_future(self.__delayed_build_layout())
def _customize_props_layout(self, props):
for prop in props:
if self.node.get_attribute_exists(prop.prop_name):
node_attr = self.node.get_attribute(prop.prop_name)
description = node_attr.get_metadata(ogn.MetadataKeys.DESCRIPTION)
if description:
prop.metadata[Sdf.PropertySpec.DocumentationKey] = description
for key in ogn.MetadataKeys.key_names():
prop.add_custom_metadata(key, node_attr.get_metadata(key))
template = self.load_template(props)
if template is not None:
return template
parameter_attrs = []
relationship_attrs = []
hidden_props = []
for prop in props:
prop_name = prop.prop_name
if prop.property_type == Usd.Relationship:
prop.override_display_group("Relationships")
relationship_attrs.append(prop)
continue
if not self.node.get_attribute_exists(prop.prop_name):
hidden_props.append(prop)
continue
is_parameter = False
attribute = self.node.get_attribute(prop.prop_name)
if attribute.get_metadata("displayGroup") == "parameters":
prop.override_display_group("Parameters")
parameter_attrs.append(prop)
is_parameter = True
if attribute.get_metadata(ogn.MetadataKeys.HIDDEN) is not None:
hidden_props.append(prop)
continue
if attribute.get_resolved_type().role == og.AttributeRole.EXECUTION:
hidden_props.append(prop)
continue
if attribute.get_metadata(ogn.MetadataKeys.OBJECT_ID) is not None:
hidden_props.append(prop)
continue
if prop_name.startswith("inputs:"):
prop_name = prop_name.replace("inputs:", "")
prop.override_display_name(prop_name)
if not is_parameter:
prop.override_display_group("Inputs")
continue
elif prop_name.startswith("outputs:"):
prop_name = prop_name.replace("outputs:", "")
prop.override_display_name(prop_name)
if not is_parameter:
prop.override_display_group("Outputs")
continue
elif prop_name.startswith("state:"):
prop_name = prop_name.replace("state:", "")
prop.override_display_name(prop_name)
if not is_parameter:
prop.override_display_group("State")
continue
# Hide everything else
if not is_parameter:
hidden_props.append(prop)
filtered_props = props.copy()
for hidden_prop in hidden_props:
filtered_props.remove(hidden_prop)
self.apply_ogn_metadata_display_names(filtered_props)
reordered_attrs = filtered_props
self.move_elements_to_beginning(relationship_attrs, reordered_attrs)
self.move_elements_to_beginning(parameter_attrs, reordered_attrs)
return reordered_attrs
def width_changed_subscribe(self):
self.window = ui.Workspace.get_window("Property")
self.window_width_change = True
if not self.window_width_change_fn_set:
self.window.set_width_changed_fn(self.width_changed)
self.window_width_change_fn_set = True
def list_diff(self, list_a, list_b):
return [i for i in list_a + list_b if i not in list_a or i not in list_b]
def apply_ogn_metadata_display_names(self, attrs):
for attr in attrs:
if not self.node.get_attribute_exists(attr.attr_name):
continue
node_attr = self.node.get_attribute(attr.attr_name)
if node_attr is None:
continue
ogn_display_name = node_attr.get_metadata(ogn.MetadataKeys.UI_NAME)
if ogn_display_name is not None:
attr.override_display_name(ogn_display_name)
def move_elements_to_beginning(self, elements_list, target_list):
elements_list.reverse()
for element in elements_list:
target_list.remove(element)
for element in elements_list:
target_list.insert(0, element)
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
"""Override of base - intercepts all attribute widget building"""
with ui.HStack():
# override prim paths to build if UsdPropertyUiEntry specifies one
if ui_prop.prim_paths:
prim_paths = ui_prop.prim_paths
# Use supplied build_fn or our customized builder
build_fn = ui_prop.build_fn if ui_prop.build_fn else OmniGraphPropertiesWidgetBuilder.build
additional_label_kwargs, additional_widget_kwargs = self.get_additional_kwargs(ui_prop)
# Handle extended attributes
if ui_prop.property_type is Usd.Attribute:
attr_name = ui_prop.attr_name
# Find a selected node that actually has this attribute in order to interrogate it
node_with_attr = find_first_node_with_attrib(prim_paths, attr_name)
if node_with_attr:
ogn_attr = node_with_attr.get_attribute(attr_name)
is_extended_attribute = ogn_attr.get_extended_type() in (
og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY,
og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION,
)
if is_extended_attribute:
resolved_type = ogn_attr.get_resolved_type()
if resolved_type.base_type == og.BaseDataType.UNKNOWN:
# This is an unresolved attribute
extended_type = (
"any"
if ogn_attr.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY
else "union"
)
ui_prop.metadata[
OmniGraphPropertiesWidgetBuilder.OVERRIDE_TYPENAME_KEY
] = f"unresolved {extended_type}"
ui_prop.metadata[Sdf.PrimSpec.TypeNameKey] = "unknown"
else:
# Resolved attribute - swap in the resolved type to the ui_prop
sdf_type = og.AttributeType.sdf_type_name_from_type(resolved_type)
ui_prop.metadata[Sdf.PrimSpec.TypeNameKey] = sdf_type
models = build_fn(
stage,
ui_prop.prop_name,
ui_prop.metadata,
ui_prop.property_type,
prim_paths,
additional_label_kwargs,
additional_widget_kwargs,
)
if models:
if not isinstance(models, list):
models = [models]
for model in models:
for prim_path in prim_paths:
self._models[prim_path.AppendProperty(ui_prop.prop_name)].append(model)
def get_bundles(self):
if self.graph_context is None:
return
inputs_particles_rel = self.stage.GetRelationshipAtPath(self._payload[-1].pathString + ".inputs:particles")
if inputs_particles_rel.IsValid():
input_prims = inputs_particles_rel.GetTargets()
for input_prim in input_prims:
self.bundles[input_prim.GetParentPath().name + ".inputs:particles"] = (
self.graph_context.get_bundle(input_prim.pathString),
[],
)
self.bundles["outputs:particles"] = (
self.graph_context.get_bundle(self._payload[-1].pathString + "/outputs_particles"),
[],
)
def bundle_elements_layout_fn(self, **kwargs):
with ui.HStack(spacing=HORIZONTAL_SPACING):
ui.Label(kwargs["name"], name="label", style={"alignment": ui.Alignment.RIGHT_TOP}, width=LABEL_WIDTH)
ui.Spacer(width=HORIZONTAL_SPACING)
model = ui.StringField(name="models_readonly", read_only=True, enabled=False).model
self.bundles[kwargs["bundle_name"]][self.ATTRIB_LIST_INDEX].append(model)
def display_bundles_content(self):
self.get_bundles()
self.bundle_update_sub = (
omni.kit.app.get_app()
.get_update_event_stream()
.create_subscription_to_pop(self.on_bundles_update, name="bundles ui update")
)
self.stage_update_sub = (
omni.usd.get_context()
.get_stage_event_stream()
.create_subscription_to_pop(self.on_stage_update, name="bundles ui stage update")
)
for bundle_name, bundle_value in self.bundles.items():
names, _ = bundle_value[self.BUNDLE_INDEX].get_attribute_names_and_types()
data_count = bundle_value[self.BUNDLE_INDEX].get_attribute_data_count()
if data_count == 0:
continue
with CustomLayoutGroup(bundle_name, collapsed=True):
for i in range(0, data_count):
attr_name = names[i]
def fn(*args, n=attr_name, b=bundle_name):
self.bundle_elements_layout_fn(name=n, bundle_name=b)
CustomLayoutProperty(None, None, build_fn=fn)
def set_bundle_models_values(self):
if self.graph_context is None:
return
for _bundle_name, bundle_value in self.bundles.items():
if not bundle_value[1]:
continue
_, types = bundle_value[self.BUNDLE_INDEX].get_attribute_names_and_types()
data = bundle_value[self.BUNDLE_INDEX].get_attribute_data()
for i, d in enumerate(data):
with suppress(Exception):
attr_type_name = types[i].get_type_name()
elem_count = self.graph_context.get_elem_count(d)
bundle_value[self.ATTRIB_LIST_INDEX][i].set_value(
attr_type_name + " " + str(elem_count) + " elements"
)
bundle_value[self.ATTRIB_LIST_INDEX][i]._value_changed() # noqa: PLW0212
def on_bundles_update(self, event):
self.time += event.payload["dt"]
if self.time > 0.25:
self.set_bundle_models_values()
self.time = 0
def on_stage_update(self, event):
if event.type == int(omni.usd.StageEventType.CLOSING) and self.bundle_update_sub:
self.bundle_update_sub = None # unsubscribe from app update stream
| 17,299 | Python | 39.705882 | 116 | 0.584253 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_settings_editor.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.settings
import omni.graph.core as og
import omni.ui as ui
from omni.kit.widget.settings.deprecated import SettingType
from omni.kit.window.preferences import PERSISTENT_SETTINGS_PREFIX, PreferenceBuilder
SETTING_PAGE_NAME = "Visual Scripting"
class OmniGraphSettingsEditor(PreferenceBuilder):
def __init__(self):
super().__init__(SETTING_PAGE_NAME)
self._settings = carb.settings.get_settings()
def destroy(self):
self._settings = None
def build(self):
"""Updates"""
with ui.VStack(height=0):
with self.add_frame("Update Settings"):
with ui.VStack():
self.create_setting_widget(
"Update to USD",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/updateToUsd",
SettingType.BOOL,
tooltip="When this setting is enabled, copies all OmniGraph node attribute values to USD"
" every tick",
)
self.create_setting_widget(
"Update mesh points to Hydra",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/updateMeshPointsToHydra",
SettingType.BOOL,
tooltip="When this setting is enabled, mesh points will be not be written back to USD",
)
self.create_setting_widget(
"Use Realm scheduler",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/realmEnabled",
SettingType.BOOL,
tooltip="When this setting is enabled, use the Realm scheduler instead of the static scheduler"
" with Push evaluator",
)
self.create_setting_widget(
"Default graph evaluator",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/defaultEvaluator",
SettingType.STRING,
tooltip="The evaluator to use for new Graphs when not specified",
)
self.create_setting_widget(
"Use legacy simulation pipeline",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/useLegacySimulationPipeline",
SettingType.BOOL,
tooltip="(deprecated) - When this setting is enabled , all graphs are run from the simulation"
" pipeline stage",
)
self.create_setting_widget(
"Disable automatic population of prim nodes",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/disablePrimNodes",
SettingType.BOOL,
tooltip="(deprecated) - When this setting is disabled, prim nodes are populated into Fabric"
" for support of direct prim-to-node connections",
)
self.create_setting_widget(
"Create OmniGraph prims using the schema",
og.USE_SCHEMA_PRIMS_SETTING,
SettingType.BOOL,
tooltip="When this setting is enabled, creates OmniGraph and OmniGraph node prims using the"
" schema. Disable the three settings below and enable the one above before enabling"
" this.",
)
self.create_setting_widget(
"Allow global implicit graph",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/allowGlobalImplicitGraph",
SettingType.BOOL,
tooltip="(deprecated) - When this setting is enabled, allows the global implicit graph"
" to exist",
)
self.create_setting_widget(
"Enable direct connection to prim nodes",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/enableLegacyPrimConnections",
SettingType.BOOL,
tooltip="(deprecated) - When this setting is enabled, direct connections from OG nodes"
" to Prim nodes are allowed",
)
self.create_setting_widget(
"Enable deprecated OmniGraph prim drop menu",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/createPrimNodes",
SettingType.BOOL,
tooltip="(deprecated) - When this setting is enabled, adds a menu item on the"
" Drop-menu for Prim nodes and allows creation of the omni.graph.core.Prim node type",
)
self.create_setting_widget(
"Enable deprecated Node.pathChanged callback",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/enablePathChangedCallback",
SettingType.BOOL,
tooltip="(deprecated) - When this setting is enabled the callback is enabled"
" which will affect performance.",
)
self.create_setting_widget(
"Escalate all deprecation warnings to be errors",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/deprecationsAreErrors",
SettingType.BOOL,
tooltip="When this setting is enabled any deprecation warnings that a code path"
" encounters are escalated to log errors in C++ or raise exceptions in Python. This"
" provides a preview of what needs to be fixed when hard deprecation of a code path happens.",
)
self.create_setting_widget(
"Enable deprecated USD access in pre-render graphs",
f"{PERSISTENT_SETTINGS_PREFIX}/omnigraph/enableUSDInPreRender",
SettingType.BOOL,
tooltip="(deprecated) - When this setting is enabled, nodes that read USD data may"
" safely be used in a pre-render graph.",
)
| 6,777 | Python | 54.557377 | 119 | 0.539029 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/utils.py | """
* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
"""
from pathlib import Path
from typing import Union
import carb
import omni.graph.core as og
import omni.kit.notification_manager as nm
import omni.ui as ui
from pxr import Sdf
# ======================================================================
def get_icons_dir() -> str:
"""Returns the location of the directory containing the icons used by these windows"""
return Path(__file__).parent.parent.parent.parent.parent.joinpath("icons")
# ======================================================================
class DestructibleButton(ui.Button):
"""Class that enhances the standard button with a destroy method that removes callbacks"""
def destroy(self):
"""Called when the button is being destroyed"""
self.set_clicked_fn(None)
# ======================================================================
class DestructibleImage(ui.Image):
"""Class that enhances the standard image with a destroy method that removes callbacks"""
def destroy(self):
"""Called when the image is being destroyed"""
self.set_mouse_pressed_fn(None)
INSTANCE_NODES_WHITELIST = {
# Safe to use despite state information in the node
"omni.graph.action.OnTick",
"omni.graph.core.ReadVariable",
"omni.graph.core.WriteVariable",
"omni.graph.instancing.ReadGraphVariable",
"omni.graph.instancing.WriteGraphVariable",
"omni.graph.nodes.FindPrims",
"omni.graph.nodes.ReadPrimAttribute",
"omni.graph.nodes.WritePrimAttribute",
"omni.graph.nodes.ReadPrimBundle",
"omni.graph.ui.OnNewFrame",
"omni.graph.ui.PrintText",
# The following temporal nodes are ignored because there is no way to
# set them up with instances at the moment. Any uses of them use explicit paths,
# not the graph target node
"omni.graph.nodes.MoveToTarget",
"omni.graph.nodes.MoveToTransform",
"omni.graph.nodes.RotateToOrientation",
"omni.graph.nodes.RotateToTarget",
"omni.graph.nodes.ScaleToSize",
"omni.graph.nodes.TranslateToLocation",
"omni.graph.nodes.TranslateToTarget",
# visualization nodes are safe - internal state is for caching
"omni.graph.visualization.nodes.DrawLine",
"omni.graph.visualization.nodes.DrawLabel",
"omni.graph.visualization.nodes.DrawScreenSpaceText",
}
def validate_graph_for_instancing(graph_path: Union[str, Sdf.Path]):
"""Validate the node types used in a graph are okay to be used with instancing,
and post a warning if they are not"""
graph = og.get_graph_by_path(str(graph_path))
if not graph:
return
problematic_nodes = set()
nodes = graph.get_nodes()
for node in nodes:
node_type = node.get_node_type()
if node_type and node_type.has_state() and node_type.get_node_type() not in INSTANCE_NODES_WHITELIST:
problematic_nodes.add(node_type.get_node_type())
if len(problematic_nodes) == 0:
return
newline = "\n"
node_list = newline.join(sorted(problematic_nodes))
warning_string = (
f"The OmniGraph at path {graph_path} contains nodes that may not execute as"
f" expected with multiple instances{newline}{node_list}"
)
nm.post_notification(warning_string, status=nm.NotificationStatus.WARNING)
carb.log_warn(warning_string)
class Prompt:
def __init__(
self,
title,
text,
ok_button_text="OK",
cancel_button_text=None,
middle_button_text=None,
ok_button_fn=None,
cancel_button_fn=None,
middle_button_fn=None,
modal=False,
):
self._title = title
self._text = text
self._cancel_button_text = cancel_button_text
self._cancel_button_fn = cancel_button_fn
self._ok_button_fn = ok_button_fn
self._ok_button_text = ok_button_text
self._middle_button_text = middle_button_text
self._middle_button_fn = middle_button_fn
self._modal = modal
self._build_ui()
def __del__(self):
self._cancel_button_fn = None
self._ok_button_fn = None
def __enter__(self):
self._window.show()
return self
def __exit__(self, exit_type, value, trace):
self._window.hide()
def show(self):
self._window.visible = True
def hide(self):
self._window.visible = False
def is_visible(self):
return self._window.visible
def set_text(self, text):
self._text_label.text = text
def set_confirm_fn(self, on_ok_button_clicked):
self._ok_button_fn = on_ok_button_clicked
def set_cancel_fn(self, on_cancel_button_clicked):
self._cancel_button_fn = on_cancel_button_clicked
def set_middle_button_fn(self, on_middle_button_clicked):
self._middle_button_fn = on_middle_button_clicked
def _on_ok_button_fn(self):
self.hide()
if self._ok_button_fn:
self._ok_button_fn()
def _on_cancel_button_fn(self):
self.hide()
if self._cancel_button_fn:
self._cancel_button_fn()
def _on_middle_button_fn(self):
self.hide()
if self._middle_button_fn:
self._middle_button_fn()
def _build_ui(self):
self._window = ui.Window(self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
)
if self._modal:
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
self._text_label = ui.Label(self._text, word_wrap=True, width=self._window.width - 80, height=0)
ui.Spacer()
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(height=0)
if self._ok_button_text:
ok_button = ui.Button(self._ok_button_text, width=60, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
if self._middle_button_text:
middle_button = ui.Button(self._middle_button_text, width=60, height=0)
middle_button.set_clicked_fn(self._on_middle_button_fn)
if self._cancel_button_text:
cancel_button = ui.Button(self._cancel_button_text, width=60, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
| 7,319 | Python | 34.362319 | 116 | 0.610739 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_in_extension_window.py | """Support for adding OmniGraph information to the Kit extensions window"""
import json
from functools import lru_cache
from pathlib import Path
from typing import Any, Dict, List
import omni.kit.app
import omni.ui as ui
from omni.kit.window.extensions.common import ExtensionCommonInfo
# ==============================================================================================================
class OmniGraphTab:
def build(self, ext_info):
try:
ext_name = ext_info["package"]["name"]
except KeyError:
ext_name = "omni.graph"
with ui.VStack(height=0):
found_nodes = False
node_data = _get_omnigraph_info(ext_info.get("path"))
if node_data:
node_name_map = {
node_name: node_name.replace(f"{ext_name}.", "") for node_name in node_data["nodes"].keys()
}
for node_name in sorted(node_data["nodes"].keys(), key=lambda name: node_name_map[name]):
node_info = node_data["nodes"][node_name]
found_nodes = True
try:
description = node_info["description"]
except KeyError:
description = "No description provided"
with ui.CollapsableFrame(node_name_map[node_name], collapsed=True, tooltip=description):
with ui.VStack():
for property_key, property_value in node_info.items():
if property_key == "extension":
continue
with ui.HStack():
ui.Spacer(width=20)
ui.Label(
f"{property_key.capitalize()}: ",
width=0,
style={"color": 0xFF8A8777},
alignment=ui.Alignment.LEFT_TOP,
)
ui.Spacer(width=5)
ui.Label(str(property_value), word_wrap=True)
if not found_nodes:
ui.Label(
"No OmniGraph nodes are present in this extension",
style_type_name_override="ExtensionDescription.Title",
)
def destroy(self):
pass
# ==============================================================================================================
class OmniGraphPage:
"""Wrapper for an OmniGraph tab inside the extension window"""
def __init__(self):
self.tab = OmniGraphTab()
def build_tab(self, ext_info, is_local: bool):
self.tab.build(ext_info)
def destroy(self):
self.tab.destroy()
@staticmethod
def get_tab_name():
return "OMNIGRAPH"
# ==============================================================================================================
@lru_cache()
def _get_omnigraph_info(ext_path) -> Dict[str, Any]:
"""Returns the OmniGraph data associated with the extension as a dictionary of path:NodeJsonData
The NodeJsonData will be empty if there is no OmniGraph data for the given extension
"""
node_data = {}
path = Path(ext_path) / "ogn" / "nodes.json"
if path.is_file():
with open(path, "r", encoding="utf-8") as json_fd:
node_data = json.load(json_fd)
return node_data
# ==============================================================================================================
@lru_cache()
def _get_omnigraph_user_exts() -> List[Dict[str, Any]]:
"""Returns the list of all visible extensions that are known to contain OmniGraph nodes.
This can be expensive so the results are cached and it is not called until the user explicitly asks for it.
TODO: This current method of discovery does not work for extensions that are not installed as there is no
information in the .toml file to identify that they have nodes. Once that information is added then it can be
checked instead of looking at the extensions on disk as that will be much faster for this quick check.
"""
found_exts = set()
ext_manager = omni.kit.app.get_app().get_extension_manager()
for ext_info in ext_manager.get_extensions():
ext_omnigraph_info = _get_omnigraph_info(ext_info.get("path"))
if ext_omnigraph_info:
found_exts.add(ext_info["name"])
return found_exts
# ==============================================================================================================
def clear_omnigraph_caches():
"""Clear the cached OmniGraph info for extensions. Use only when extensions are modified as this could be
costly to call repeatedly as it will force reload of OmniGraph node description files
"""
_get_omnigraph_info.cache_clear()
_get_omnigraph_user_exts.cache_clear()
# ==============================================================================================================
def has_omnigraph_nodes(extension_info: ExtensionCommonInfo) -> bool:
"""Check to see if the extension info item refers to an extension that contains OmniGraph nodes."""
return extension_info.fullname in _get_omnigraph_user_exts()
| 5,376 | Python | 43.438016 | 113 | 0.503534 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/menu.py | """
Support for the menu containing the OmniGraph UI operations.
"""
import asyncio
from functools import partial
from typing import List, TypeVar
import carb
import carb.settings
import omni.graph.core as og
import omni.graph.tools as ogt
import omni.kit.ui
import omni.usd
from omni import ui
from omni.kit.app import get_app_interface
from omni.kit.menu.utils import MenuItemDescription
from omni.kit.window.preferences import register_page, unregister_page
from pxr import Sdf
from .metaclass import Singleton # noqa: PLE0402
from .omnigraph_node_description_editor.main_editor import MENU_PATH as MENU_OGN_EDITOR # noqa: PLE0402
from .omnigraph_node_description_editor.main_editor import Editor
from .omnigraph_settings_editor import OmniGraphSettingsEditor # noqa: PLE0402
from .omnigraph_toolkit import MENU_PATH as MENU_TOOLKIT # noqa: PLE0402
from .omnigraph_toolkit import Toolkit
# Settings
# For now we always have an implicit global graph which encompasses the stage. Once that is deprecated we can
# disable the workaround code by setting this to False
USE_IMPLICIT_GLOBAL_GRAPH = True
# ======================================================================
# Menu item names
MENU_RELOAD_FROM_STAGE = "deprecated"
# ======================================================================
# ==============================================================================================================
# Lookup table for operations triggered by the menu items.
# They are called with (KEY, ENABLE) values, where KEY is the key in this dictionary and ENABLE is a boolean
# where the menu item is triggered when True and "untriggered" when False (i.e. window is opened or closed)
MENU_WINDOWS = {
MENU_OGN_EDITOR: Editor,
}
TOOLKIT_WINDOW = Toolkit
WindowClassType = TypeVar("WindowClassType", OmniGraphSettingsEditor, Editor, Toolkit)
VISUAL_SCRIPTING_MENU_INDEX_OFFSET = 20
MENU_GRAPH = "menu_graph.svg"
original_svg_color = carb.settings.get_settings().get("/exts/omni.kit.menu.create/original_svg_color")
# ======================================================================
class Menu(metaclass=Singleton):
"""Manage the menu containing OmniGraph operations
Internal Attributes:
__menu_items: List of menu trigger subscriptions
__toolkit_menu_item: Trigger subscription for the optional toolkit menu item
__windows: Dictionary of menu_item/editor_object for editors the menu can open
__extension_change_subscription: Subscription to extension changes
"""
def __init__(self):
"""Initialize the menu by finding the current context and selection information"""
self.__menu_items = []
self.__edit_menu_items = []
self.__create_menu_items = []
self.__create_graph_menu_tuples = [] # noqa: PLW0238
self.__context_menus = [] # noqa: PLW0238
self.__preferences_page = None
self.__extension_change_subscription = None
self.__toolkit_menu_item = None
self.__windows = {}
self.on_startup()
# --------------------------------------------------------------------------------------------------------------
def set_window_state(self, menu: str, value: bool):
"""Trigger the visibility state of the given window object.
Note: This is not called when the window is manually closed
Args:
menu: Name of the menu to which the window class is attached
value: True means show the window, else hide and destroy
Note:
It is assumed that the window_class can be destroyed, has is_visible() and is a singleton
"""
if value:
self.__windows[menu].show_window()
else:
self.__windows[menu].hide_window()
def __deferred_set_window_state(self, menu: str, value: bool):
# We can't modify UI elements safely from callbacks, so defer that work
async def __func():
await omni.kit.app.get_app().next_update_async()
self.set_window_state(menu, value)
asyncio.ensure_future(__func())
# --------------------------------------------------------------------------------------------------------------
@property
def menu_items(self) -> List[ui.MenuItem]:
"""Returns a list of the menu items owned by this menu class"""
return self.__menu_items + self.__edit_menu_items
# --------------------------------------------------------------------------------------------------------------
def __on_extension_change(self):
"""Callback executed when extensions change state"""
# Only enable the toolkit debugging window if the inspection extension was enabled since
# it supplies the features
inspection_enabled = get_app_interface().get_extension_manager().is_extension_enabled("omni.inspect")
menu = omni.kit.ui.get_editor_menu()
if inspection_enabled:
if self.__toolkit_menu_item is None:
self.__windows[MENU_TOOLKIT] = TOOLKIT_WINDOW()
# Toolkit goes to bottom. There are two graph editors and one node description editor
self.__toolkit_menu_item = menu.add_item(
MENU_TOOLKIT,
self.__deferred_set_window_state,
priority=4 + VISUAL_SCRIPTING_MENU_INDEX_OFFSET,
toggle=True,
value=False,
)
else:
ogt.destroy_property(self, "__toolkit_menu_item")
# --------------------------------------------------------------------------------------------------------------
# Used to be OnClick function for reload from stage menu item
# The item is no longer available to external customers but we can keep it alive internally
def _on_menu_click(self, menu_item, value):
if menu_item == MENU_RELOAD_FROM_STAGE:
usd_context = omni.usd.get_context()
selection = usd_context.get_selection()
selected_prim_paths = selection.get_selected_prim_paths()
found_selected_graph = False
if selected_prim_paths:
all_graphs = og.get_all_graphs()
for selected_path in selected_prim_paths:
for graph in all_graphs:
if graph.get_path_to_graph() == selected_path:
found_selected_graph = True
carb.log_info(f"reloading graph: '{selected_path}'")
graph.reload_from_stage()
if not found_selected_graph:
current_graph = og.get_current_graph()
current_graph_path = current_graph.get_path_to_graph()
carb.log_info(f"reloading graph: '{current_graph_path}'")
current_graph.reload_from_stage()
@classmethod
def add_create_menu_type(cls, menu_title: str, evaluator_type: str, prefix: str, glyph_file: str, open_editor_fn):
if cls not in cls._instances: # noqa: PLE1101
return
instance = cls._instances[cls] # noqa: PLE1101
instance.__create_graph_menu_tuples.append( # noqa: PLW0212,PLW0238
(menu_title, evaluator_type, prefix, glyph_file, open_editor_fn)
)
# A wrapper to the create_graph function. Create the graph first and then open that graph
def onclick_fn(evaluator_type: str, name_prefix: str, open_editor_fn, menu_arg=None, value=None):
node = instance.create_graph(evaluator_type, name_prefix)
if open_editor_fn:
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(node.get_wrapped_graph().get_path_to_graph())
open_editor_fn([prim])
def build_context_menu(objects):
with omni.ui.Menu(f' {omni.kit.ui.get_custom_glyph_code("${glyphs}/" + MENU_GRAPH)} Visual Scripting'):
for (
title,
evaluator_type,
prefix,
glyph_file,
_open_editor_fn,
) in instance.__create_graph_menu_tuples: # noqa: PLW0212,E501
omni.ui.MenuItem(
f' {omni.kit.ui.get_custom_glyph_code("${glyphs}/" + f"{glyph_file}")} {title}',
triggered_fn=partial(onclick_fn, evaluator_type, prefix, _open_editor_fn, objects),
)
# First time to add items to create menu, need to create the Visual Scripting submenu
if not instance.__context_menus: # noqa: PLW0212
menu_dict = {
"name": "Omnigraph Context Create Menu",
"glyph": MENU_GRAPH,
"populate_fn": build_context_menu,
}
instance.__context_menus.append( # noqa: PLW0212
omni.kit.context_menu.add_menu(menu_dict, "CREATE", "omni.kit.widget.stage")
)
instance.__context_menus.append( # noqa: PLW0212
omni.kit.context_menu.add_menu(menu_dict, "CREATE", "omni.kit.window.viewport")
)
if not instance.__create_menu_items: # noqa: PLW0212
instance.__create_menu_items.append( # noqa: PLW0212
MenuItemDescription(
name="Visual Scripting",
glyph=MENU_GRAPH,
appear_after=["Xform"],
sub_menu=[
MenuItemDescription(
name=title,
glyph=glyph_file,
onclick_fn=partial(onclick_fn, evaluator_type, prefix, _open_editor_fn),
original_svg_color=original_svg_color,
)
for (
title,
evaluator_type,
prefix,
glyph_file,
_open_editor_fn,
) in instance.__create_graph_menu_tuples # noqa: PLW0212
],
original_svg_color=original_svg_color,
)
)
omni.kit.menu.utils.add_menu_items(instance.__create_menu_items, "Create", -9) # noqa: PLW0212
else:
instance.__create_menu_items[0].sub_menu.append( # noqa: PLW0212
MenuItemDescription(
name=menu_title,
glyph=glyph_file,
onclick_fn=partial(onclick_fn, evaluator_type, prefix, open_editor_fn),
original_svg_color=original_svg_color,
)
)
omni.kit.menu.utils.rebuild_menus()
@classmethod
def remove_create_menu_type(cls, menu_title: str):
if cls not in cls._instances: # noqa: PLE1101
return
instance = cls._instances[cls] # noqa: PLE1101
instance.__create_graph_menu_tuples = [ # noqa: PLW0212,PLW0238
item for item in instance.__create_graph_menu_tuples if item[0] != menu_title # noqa: PLW0212
]
if not instance.__create_menu_items: # noqa: PLW0212
return
if len(instance.__create_graph_menu_tuples) == 0: # noqa: PLW0212
omni.kit.menu.utils.remove_menu_items(instance.__create_menu_items, "Create") # noqa: PLW0212
ogt.destroy_property(instance, "__context_menus")
ogt.destroy_property(instance, "__create_menu_items")
else:
instance.__create_menu_items[0].sub_menu = [ # noqa: PLW0212
item for item in instance.__create_menu_items[0].sub_menu if item.name != menu_title # noqa: PLW0212
]
omni.kit.menu.utils.rebuild_menus()
# --------------------------------------------------------------------------------------------------------------
def on_startup(self):
"""Called when the menu is invoked - build all of the menu entries"""
self._settings = carb.settings.get_settings()
editor_menu = omni.kit.ui.get_editor_menu()
# In a testing environment there may not be an editor, but that's okay
if editor_menu is None:
return
# Add settings page to preference
self.__preferences_page = OmniGraphSettingsEditor()
register_page(self.__preferences_page)
for index, (menu_path, menu_window) in enumerate(MENU_WINDOWS.items()):
self.__windows[menu_path] = menu_window()
self.__menu_items.append(
editor_menu.add_item(
menu_path,
self.__deferred_set_window_state,
priority=index + 1 + VISUAL_SCRIPTING_MENU_INDEX_OFFSET,
toggle=True,
value=False,
)
)
# Set up a subscription to monitor for events that may change whether the toolkit is visible or not
change_stream = get_app_interface().get_extension_manager().get_change_event_stream()
self.__extension_change_subscription = change_stream.create_subscription_to_pop(
lambda _: self.__on_extension_change(), name="OmniGraph Menu Extension Changes"
)
assert self.__extension_change_subscription
# Ensure the initial state is correct
self.__on_extension_change()
# --------------------------------------------------------------------------------------------------------------
def on_shutdown(self):
"""Remove all of the menu objects when the menu is closed"""
self.__extension_change_subscription = None
if self.__preferences_page:
unregister_page(self.__preferences_page)
self.__preferences_page = None
# Remove all of the menu items from the main menu. Most important when removing callbacks
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
for menu in self.__windows:
editor_menu.remove_item(menu)
if self.__toolkit_menu_item is not None:
editor_menu.remove_item(MENU_TOOLKIT)
omni.kit.menu.utils.remove_menu_items(self.__create_menu_items, "Create")
ogt.destroy_property(self, "__create_menu_items")
ogt.destroy_property(self, "__extension_change_subscription")
ogt.destroy_property(self, "__toolkit_menu_item")
ogt.destroy_property(self, "__menu_items")
ogt.destroy_property(self, "__edit_menu_items")
ogt.destroy_property(self, "__context_menus")
ogt.destroy_property(self, "__create_graph_menu_tuples")
ogt.destroy_property(self, "__windows")
# Note that Singleton.forget(Menu) has to be called in the main shutdown since it has a Menu reference
# --------------------------------------------------------------------------------------------------------------
def create_graph(self, evaluator_type: str, name_prefix: str, menu_arg=None, value=None) -> og.Node:
"""Create a new GlobalGraph below the default prim
Note: USE_IMPLICIT_GLOBAL_GRAPH forces creation of subgraphs only
Args:
evaluator_type: the evaluator type to use for the new graph
name_prefix: the desired name of the GlobalGraph node. Will be made unique
menu_arg: menu info
value: menu value
Returns:
wrapper_node: the node that wraps the new graph
"""
# FIXME: How to specify USD backing?
usd_backing = True
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
graph_path = Sdf.Path(name_prefix).MakeAbsolutePath(Sdf.Path.absoluteRootPath)
graph_path = omni.usd.get_stage_next_free_path(stage, graph_path, True)
container_graphs = og.get_global_container_graphs()
# FIXME: Just use the first one? We may want a clearer API here.
container_graph = container_graphs[0]
with omni.kit.undo.group():
_, wrapper_node = og.cmds.CreateGraphAsNode(
graph=container_graph,
node_name=Sdf.Path(graph_path).name,
graph_path=graph_path,
evaluator_name=evaluator_type,
is_global_graph=True,
backed_by_usd=usd_backing,
fc_backing_type=og.GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED,
pipeline_stage=og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION,
)
return wrapper_node
def add_create_menu_type(menu_title: str, evaluator_type: str, prefix: str, glyph_file: str, open_editor_fn):
"""Add a new graph type menu item under Create/Visual Scripting menu which creates a new graph and open the graph.
This will create the Visual Scripting menu if menu_title is the first one added
Args:
menu_title: the display name of this menu item
evaluator_type: the evaluator type to use for the new graph
prefix: the desired name of the GlobalGraph node. Will be made unique
glyph_file: the file name of the svg icon to be displayed. This file must be in the resources package
open_editor_fn: the function to open the corresponding graph editor and open the created graph.
This is invoked after create_graph
"""
Menu.add_create_menu_type(menu_title, evaluator_type, prefix, glyph_file, open_editor_fn)
def remove_create_menu_type(menu_title: str):
"""
Remove the menu item named menu_title from Create/Visual Scripting menu.
This will remove the entire Visual Scripting menu if menu_title is the last one under it.
Args:
menu_title: the display name of this menu item
"""
Menu.remove_create_menu_type(menu_title)
| 17,858 | Python | 45.266839 | 118 | 0.567589 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/properties_widget.py | import asyncio
import types
from functools import partial
from pathlib import Path
from typing import List
import carb
import omni.graph.core as og
import omni.kit.ui
import omni.ui as ui
import omni.usd
from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload
from omni.kit.property.usd.usd_attribute_model import FloatModel, IntModel
from omni.kit.property.usd.usd_model_base import UsdBase
from omni.kit.property.usd.usd_property_widget import (
UsdPropertiesWidget,
UsdPropertiesWidgetBuilder,
UsdPropertyUiEntry,
)
from omni.kit.property.usd.widgets import ICON_PATH
from omni.kit.window.property.templates import HORIZONTAL_SPACING
from pxr import Gf, OmniGraphSchema, Sdf, Tf, Usd
from .stage_picker_dialog import StagePickerDialog # noqa: PLE0402
from .token_array_edit_widget import build_token_array_prop # noqa: PLE0402
from .utils import Prompt # noqa: PLE0402
from .utils import validate_graph_for_instancing # noqa: PLE0402
REMOVE_BUTTON_STYLE = style = {"image_url": str(Path(ICON_PATH).joinpath("remove.svg")), "margin": 0, "padding": 0}
AUTO_REFRESH_PERIOD = 0.33 # How frequently to poll for variable refreshes
GRAPH_VARIABLE_ATTR_PREFIX = "graph:variable:"
OMNIGRAPHS_REL_ATTR = "omniGraphs"
COMPUTEGRAPH_TYPE_NAME = (
"OmniGraph" if carb.settings.get_settings().get(og.USE_SCHEMA_PRIMS_SETTING) else "ComputeGraph"
)
# Keys for metadata dictionary that the vector variable runtime model will lookup
VARIABLE_ATTR = "variable_attr"
VARIABLE_GRAPH_PATH = "variable_graph_path"
VARIABLE_INSTANCE_PATH = "variable_instance_path"
# Used to determine if we need a single channel model builder or not
VECTOR_TYPES = {
UsdPropertiesWidgetBuilder.tf_gf_vec2i,
UsdPropertiesWidgetBuilder.tf_gf_vec2h,
UsdPropertiesWidgetBuilder.tf_gf_vec2f,
UsdPropertiesWidgetBuilder.tf_gf_vec2d,
UsdPropertiesWidgetBuilder.tf_gf_vec3i,
UsdPropertiesWidgetBuilder.tf_gf_vec3h,
UsdPropertiesWidgetBuilder.tf_gf_vec3f,
UsdPropertiesWidgetBuilder.tf_gf_vec3d,
UsdPropertiesWidgetBuilder.tf_gf_vec4i,
UsdPropertiesWidgetBuilder.tf_gf_vec4h,
UsdPropertiesWidgetBuilder.tf_gf_vec4f,
UsdPropertiesWidgetBuilder.tf_gf_vec4d,
}
class OmniGraphProperties:
def __init__(self):
self._api_widget = None
self._variables_widget = None
self.on_startup()
def on_startup(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
self._api_widget = OmniGraphAPIPropertiesWidget("Visual Scripting")
w.register_widget("prim", "omni_graph_api", self._api_widget)
self._variables_widget = OmniGraphVariablesPropertiesWidget("Variables")
w.register_widget("prim", "omni_graph_variables", self._variables_widget)
def on_shutdown(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
if self._api_widget is not None:
w.unregister_widget("prim", "omni_graph_api")
self._api_widget.destroy()
self._api_widget = None
if self._variables_widget is not None:
w.unregister_widget("prim", "omni_graph_variables")
self._variables_widget.destroy()
self._variables_widget = None
# ----------------------------------------------------------------------------------------
def is_different_from_default_override(self) -> bool:
"""Override for USDBase.is_different_from_default"""
# Values that are backed by real attributes _always_ override the default value.
# Values that are backed by placeholders never override the default value.
attributes = self._get_attributes() # noqa: PLW0212
return any(isinstance(attribute, Usd.Attribute) for attribute in attributes)
class OmniGraphAPIPropertiesWidget(UsdPropertiesWidget):
"""Widget for graph instances"""
def __init__(self, title: str):
super().__init__(title, collapsed=False)
self._title = title
from omni.kit.property.usd import PrimPathWidget
self._add_button_menus = []
self._add_button_menus.append(
PrimPathWidget.add_button_menu_entry(
"Visual Scripting",
show_fn=self._button_show,
onclick_fn=self._button_onclick,
)
)
self._omnigraph_vars = []
self._omnigraph_vars_props = []
self._graph_targets = set()
self._stage_picker = None
self._stage_picker_selected_graph = None
self._pending_rebuild_task = None
def destroy(self):
from omni.kit.property.usd import PrimPathWidget
for menu in self._add_button_menus:
PrimPathWidget.remove_button_menu_entry(menu)
self._add_button_menus = []
def _button_show(self, objects: dict):
if "prim_list" not in objects or "stage" not in objects:
return False
stage = objects["stage"]
if not stage:
return False
prim_list = objects["prim_list"]
if len(prim_list) < 1:
return False
for item in prim_list:
if isinstance(item, Sdf.Path):
prim = stage.GetPrimAtPath(item)
elif isinstance(item, Usd.Prim):
prim = item
type_name = prim.GetTypeName()
if "Graph" in type_name or prim.HasAPI(OmniGraphSchema.OmniGraphAPI):
return False
return True
def _on_stage_picker_select_graph(self, selected_prim):
for path in self._apply_prim_paths:
if not omni.usd.get_context().get_stage().GetPrimAtPath(path).HasAPI(OmniGraphSchema.OmniGraphAPI):
validate_graph_for_instancing(selected_prim.GetPath())
omni.kit.commands.execute(
"ApplyOmniGraphAPICommand", paths=self._apply_prim_paths, graph_path=selected_prim.GetPath()
)
self._refresh_window()
return True
def __item_added(self, items):
"""Callback when the target picker adds a graph target"""
for (_, path) in items:
validate_graph_for_instancing(path)
def _button_onclick(self, payload: PrimSelectionPayload):
if payload is None:
return Sdf.Path.emptyPath
if self._stage_picker:
self._stage_picker.clean()
self._stage_picker = StagePickerDialog(
omni.usd.get_context().get_stage(),
lambda p: self._on_stage_picker_select_graph(p), # noqa: PLW0108
"Select Graph",
"Select",
[],
lambda p: self._filter_target_lambda(p), # noqa: PLW0108
)
self._stage_picker.show()
self._apply_prim_paths = payload.get_paths() # noqa: PLW0201
return self._apply_prim_paths
def on_new_payload(self, payload):
self._omnigraph_vars.clear()
self._omnigraph_vars_props.clear()
self._graph_targets.clear()
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
for prim_path in payload: # noqa: PLR1702
prim = self._get_prim(prim_path)
if not prim:
return False
attrs = prim.GetProperties()
for attr in attrs:
attr_name_str = attr.GetName()
if attr_name_str == OMNIGRAPHS_REL_ATTR:
targets = attr.GetTargets()
for target in targets:
self._graph_targets.add(target)
target_prim = self._get_prim(target)
target_attrs = target_prim.GetAttributes()
for target_attr in target_attrs:
target_attr_name = target_attr.GetName()
if target_attr_name.startswith(GRAPH_VARIABLE_ATTR_PREFIX):
self._omnigraph_vars.append(target_attr_name)
self._omnigraph_vars_props.append(target_attr)
return True
return False
return False
def _filter_props_to_build(self, props):
return [
prop
for prop in props
if prop.GetName().startswith(OMNIGRAPHS_REL_ATTR)
or (prop.GetName().startswith(GRAPH_VARIABLE_ATTR_PREFIX) and prop.GetName() in self._omnigraph_vars)
]
def _filter_target_lambda(self, target_prim):
return target_prim.GetTypeName() == COMPUTEGRAPH_TYPE_NAME
def get_additional_kwargs(self, ui_attr):
random_prim = Usd.Prim()
if self._payload:
prim_paths = self._payload.get_paths()
for prim_path in prim_paths:
prim = self._get_prim(prim_path)
if not prim:
continue
if not random_prim:
random_prim = prim
elif random_prim.GetTypeName() != prim.GetTypeName():
break
if ui_attr.prop_name == OMNIGRAPHS_REL_ATTR:
return None, {
"target_picker_filter_lambda": self._filter_target_lambda,
"target_picker_on_add_targets": self.__item_added,
}
return None, None
def _get_default_value(self, attr_name):
"""Retreives the default value from the backing attribute"""
for graph_prop in self._omnigraph_vars_props:
prop_name = graph_prop.GetName()
if prop_name == attr_name:
if graph_prop.HasValue():
return graph_prop.Get()
return graph_prop.GetTypeName().defaultValue
return None
def _customize_props_layout(self, attrs):
variable_group = "Variables"
instance_props = set()
for attr in attrs:
if attr.attr_name == OMNIGRAPHS_REL_ATTR:
attr.override_display_group("Graphs")
if attr.attr_name in self._omnigraph_vars:
instance_props.add(attr.attr_name)
var_offset = attr.attr_name.rindex(":") + 1
display_group = variable_group
display_name = attr.attr_name[var_offset:]
attr.override_display_name(display_name)
attr.override_display_group(display_group)
attr.add_custom_metadata("default", self._get_default_value(attr.attr_name))
# append the graph properties that don't appear in the list
for graph_prop in self._omnigraph_vars_props:
prop_name = graph_prop.GetName()
if prop_name in instance_props:
continue
value = graph_prop.GetTypeName().defaultValue
if graph_prop.HasValue():
value = graph_prop.Get()
ui_prop = UsdPropertyUiEntry(
prop_name,
variable_group,
{Sdf.PrimSpec.TypeNameKey: str(graph_prop.GetTypeName()), "customData": {"default": value}},
Usd.Attribute,
)
var_offset = prop_name.rindex(":") + 1
ui_prop.override_display_name(prop_name[var_offset:])
attrs.append(ui_prop)
# sort by name to keep the ordering consistent as placeholders are
# modified and become actual properies
def sort_key(elem):
return elem.attr_name
attrs.sort(key=sort_key)
def build_header(*args):
with ui.HStack(spacing=HORIZONTAL_SPACING):
ui.Label("Initial", alignment=ui.Alignment.RIGHT)
ui.Label("Runtime", alignment=ui.Alignment.RIGHT)
header_prop = UsdPropertyUiEntry("header", variable_group, {}, Usd.Property, build_fn=build_header)
attrs.insert(0, header_prop)
return attrs
def _is_placeholder_property(self, ui_prop: UsdPropertyUiEntry) -> bool:
"""Returns false if this property represents a graph target property that has not
been overwritten
"""
if not ui_prop.attr_name.startswith(GRAPH_VARIABLE_ATTR_PREFIX):
return False
if self._payload:
prim_paths = self._payload.get_paths()
for prim_path in prim_paths:
prim = self._get_prim(prim_path)
if prim and prim.HasAttribute(ui_prop.attr_name):
return True
return False
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
metadata = ui_prop.metadata
type_name = metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")
sdf_type_name = Sdf.ValueTypeNames.Find(type_name)
if sdf_type_name.type == Sdf.ValueTypeNames.TokenArray.type:
ui_prop.build_fn = build_token_array_prop
elif ui_prop.attr_name.startswith(GRAPH_VARIABLE_ATTR_PREFIX):
ui_prop.build_fn = build_variable_prop
# override the build function to make modifications to the model
build_fn = ui_prop.build_fn if ui_prop.build_fn else UsdPropertiesWidgetBuilder.build
ui_prop.build_fn = partial(self.__build_fn_intercept, build_fn)
return super().build_property_item(stage, ui_prop, prim_paths)
def build_impl(self):
if self._collapsable:
self._collapsable_frame = ui.CollapsableFrame( # noqa: PLW0201
self._title, build_header_fn=self._build_custom_frame_header, collapsed=self._collapsed
)
def on_collapsed_changed(collapsed):
self._collapsed = collapsed # noqa: PLW0201
self._collapsable_frame.set_collapsed_changed_fn(on_collapsed_changed) # noqa: PLW0201
else:
self._collapsable_frame = ui.Frame(height=10, style={"Frame": {"padding": 5}}) # noqa: PLW0201
self._collapsable_frame.set_build_fn(self._build_frame)
def _on_remove_with_prompt(self):
def on_remove_omnigraph_api():
selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
omni.kit.commands.execute("RemoveOmniGraphAPICommand", paths=selected_paths)
prompt = Prompt(
"Remove Visual Scripting?",
"Are you sure you want to remove the 'Visual Scripting' component?",
"Yes",
"No",
ok_button_fn=on_remove_omnigraph_api,
modal=True,
)
prompt.show()
def _build_custom_frame_header(self, collapsed, text):
if collapsed:
alignment = ui.Alignment.RIGHT_CENTER
width = 5
height = 7
else:
alignment = ui.Alignment.CENTER_BOTTOM
width = 7
height = 5
with ui.HStack(spacing=8):
with ui.VStack(width=0):
ui.Spacer()
ui.Triangle(
style_type_name_override="CollapsableFrame.Header", width=width, height=height, alignment=alignment
)
ui.Spacer()
ui.Label(text, style_type_name_override="CollapsableFrame.Header")
with ui.HStack(width=0):
ui.Spacer(width=8)
with ui.VStack(width=0):
ui.Spacer(height=5)
ui.Button(style=REMOVE_BUTTON_STYLE, height=16, width=16).set_mouse_pressed_fn(
lambda *_: self._on_remove_with_prompt()
)
ui.Spacer(width=5)
def _on_usd_changed(self, notice, stage):
"""Overrides the base case USD listener to request a rebuild if the graph target attributes change"""
targets = notice.GetChangedInfoOnlyPaths()
if any(p.GetPrimPath() in self._graph_targets for p in targets):
self._refresh_window()
else:
super()._on_usd_changed(notice, stage)
def _delay_refresh_window(self):
self._pending_rebuild_task = asyncio.ensure_future(self._refresh_window())
def _refresh_window(self):
"""Refreshes the entire property window"""
selection = omni.usd.get_context().get_selection()
selected_paths = selection.get_selected_prim_paths()
window = omni.kit.window.property.get_window()._window # noqa: PLW0212
selection.clear_selected_prim_paths()
window.frame.rebuild()
selection.set_selected_prim_paths(selected_paths, True)
window.frame.rebuild()
def __on_set_default_callback(self, paths: List[Sdf.Path], attr_name: str):
"""
Callback triggered when a model is set to the default value. Instead of reverting
to a default value, this will remove the property instead
"""
stage = omni.usd.get_context().get_stage()
for p in paths:
prop_path = p.AppendProperty(attr_name)
if stage.GetAttributeAtPath(prop_path).IsValid():
omni.kit.commands.execute("RemoveProperty", prop_path=prop_path)
def __build_fn_intercept(
self,
src_build_fn,
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
"""Build function that leverages an existing build function and sets the model default value callback"""
models = src_build_fn(
stage, attr_name, metadata, property_type, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
# Set a callback when the default is set so that it will do the same operation as remove
# Replace the is_different_from_default method to change the behaviour of the reset to default widget
if models:
if issubclass(type(models), UsdBase):
models.set_on_set_default_fn(partial(self.__on_set_default_callback, prim_paths, attr_name))
models.is_different_from_default = types.MethodType(is_different_from_default_override, models)
elif hasattr(models, "__iter__"):
for model in models:
if issubclass(type(model), UsdBase):
model.set_on_set_default_fn(partial(self.__on_set_default_callback, prim_paths, attr_name))
model.is_different_from_default = types.MethodType(is_different_from_default_override, model)
return models
class OmniGraphVariablesPropertiesWidget(UsdPropertiesWidget):
"""Widget for the graph"""
def __init__(self, title: str):
super().__init__(title, collapsed=False)
self._title = title
def destroy(self):
pass
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
for prim_path in payload:
prim = self._get_prim(prim_path)
if not prim:
return False
is_graph_type = prim.GetTypeName() == COMPUTEGRAPH_TYPE_NAME
attrs = prim.GetProperties()
for attr in attrs:
attr_name_str = attr.GetName()
if is_graph_type and attr_name_str.startswith(GRAPH_VARIABLE_ATTR_PREFIX):
return True
return False
return False
def _filter_props_to_build(self, props):
return [prop for prop in props if prop.GetName().startswith(GRAPH_VARIABLE_ATTR_PREFIX)]
def _filter_target_lambda(self, target_prim):
return target_prim.GetTypeName() == COMPUTEGRAPH_TYPE_NAME
def get_additional_kwargs(self, ui_attr):
random_prim = Usd.Prim()
if self._payload:
prim_paths = self._payload.get_paths()
for prim_path in prim_paths:
prim = self._get_prim(prim_path)
if not prim:
continue
if not random_prim:
random_prim = prim
elif random_prim.GetTypeName() != prim.GetTypeName():
break
return None, None
def _customize_props_layout(self, attrs):
for attr in attrs:
if attr.attr_name.startswith(GRAPH_VARIABLE_ATTR_PREFIX):
var_offset = attr.attr_name.rindex(":") + 1
display_name = attr.attr_name[var_offset:]
attr.override_display_name(display_name)
with ui.HStack(spacing=HORIZONTAL_SPACING):
ui.Label("Initial", alignment=ui.Alignment.RIGHT)
ui.Label("Runtime", alignment=ui.Alignment.RIGHT)
return attrs
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
metadata = ui_prop.metadata
type_name = metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")
sdf_type_name = Sdf.ValueTypeNames.Find(type_name)
if sdf_type_name.type == Sdf.ValueTypeNames.TokenArray.type:
ui_prop.build_fn = build_token_array_prop
else:
ui_prop.build_fn = build_variable_prop
super().build_property_item(stage, ui_prop, prim_paths)
class OmniGraphVariableBase:
"""Mixin base for OmnGraph variable runtime models"""
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
change_on_edit_end=False,
**kwargs,
):
self._soft_range_min = None
self._soft_range_max = None
self._variable = None
self._value = None
self._context = None
self._event_sub = None
self._dirty = True
graph_path = kwargs.get(VARIABLE_GRAPH_PATH, None)
self._graph_path = graph_path.pathString
attr = kwargs.get(VARIABLE_ATTR, None)
self._variable_name = attr.GetBaseName()
self._instance = kwargs.get(VARIABLE_INSTANCE_PATH, None)
self._update_counter: float = 0
self._update_sub = (
omni.kit.app.get_app()
.get_update_event_stream()
.create_subscription_to_pop(self._on_update, name="OmniGraph Variable Runtime Properties")
)
def _on_update(self, event):
# Ideally, we would have fabric level notifications when a variable has been changed. But for now, just poll at
# a fixed interval since variables can be set at any time, not just when a node computes
self._update_counter += event.payload["dt"]
if self._update_counter > AUTO_REFRESH_PERIOD:
self._update_counter = 0
self._on_dirty()
def clean(self):
self._update_sub = None # unsubscribe from app update stream
def get_value(self):
return self._value
def set_value(self, value):
self._value = value
def _update_value(self, force=False):
if self._dirty or force:
if self._variable is None:
graph = og.get_graph_by_path(self._graph_path)
if graph is not None:
self._context = graph.get_default_graph_context()
self._variable = graph.find_variable(self._variable_name)
if self._variable is not None:
self.set_value(
self._variable.get(self._context)
if self._instance is None
else self._variable.get(self._context, self._instance.pathString)
)
self._dirty = False
def _on_dirty(self):
pass
def _set_dirty(self):
self._dirty = True
self._on_dirty()
class OmniGraphVariableRuntimeModel(ui.AbstractValueModel, OmniGraphVariableBase):
"""Model for variable values at runtime"""
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
change_on_edit_end=False,
**kwargs,
):
OmniGraphVariableBase.__init__(
self, stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs
)
ui.AbstractValueModel.__init__(self)
def clean(self):
OmniGraphVariableBase.clean(self)
def get_value(self):
return self._value
def set_value(self, value):
self._value = value
def get_value_as_float(self) -> float:
self._update_value()
return float(self._value) if self._variable is not None else 0.0
def get_value_as_bool(self) -> bool:
self._update_value()
return bool(self._value) if self._variable is not None else False
def get_value_as_int(self) -> int:
self._update_value()
return int(self._value) if self._variable is not None else 0
def get_value_as_string(self) -> str:
self._update_value()
return str(self._value) if self._variable is not None else ""
def _on_dirty(self):
self._value_changed() # tell widget that model value has changed
class OmniGraphVectorVariableRuntimeModel(ui.AbstractItemModel, OmniGraphVariableBase):
"""Model for vector variable values at runtime"""
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
comp_count: int,
tf_type: Tf.Type,
self_refresh: bool,
metadata: dict,
**kwargs,
):
OmniGraphVariableBase.__init__(self, stage, attribute_paths, self_refresh, metadata, False, **kwargs)
ui.AbstractItemModel.__init__(self)
self._comp_count = comp_count
self._data_type_name = "Vec" + str(self._comp_count) + tf_type.typeName[-1]
self._data_type = getattr(Gf, self._data_type_name)
class UsdVectorItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
if self._data_type_name.endswith("i"):
self._items = [UsdVectorItem(IntModel(self)) for i in range(self._comp_count)]
else:
self._items = [UsdVectorItem(FloatModel(self)) for i in range(self._comp_count)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
OmniGraphVariableBase.clean(self)
def _construct_vector_from_item(self):
if self._data_type_name.endswith("i"):
data = [item.model.get_value_as_int() for item in self._items]
else:
data = [item.model.get_value_as_float() for item in self._items]
return self._data_type(data)
def _on_value_changed(self, item):
"""Called when the submodel is changed"""
if self._edit_mode_counter > 0:
vector = self._construct_vector_from_item()
index = self._items.index(item)
if vector and self.set_value(vector, index):
# Read the new value back in case hard range clamped it
item.model.set_value(self._value[index])
self._item_changed(item)
else:
# If failed to update value in model, revert the value in submodel
item.model.set_value(self._value[index])
def _update_value(self, force=False):
if OmniGraphVariableBase._update_value(self, force):
if self._value is None:
for i in range(len(self._items)): # noqa: PLC0200
self._items[i].model.set_value(0.0)
return
for i in range(len(self._items)): # noqa: PLC0200
self._items[i].model.set_value(self._value[i])
def set_value(self, value, comp=-1):
pass
def _on_dirty(self):
self._item_changed(None)
def get_item_children(self, item):
"""Reimplemented from the base class"""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
self._edit_mode_counter -= 1
class OmniGraphSingleChannelVariableRuntimeModel(OmniGraphVariableRuntimeModel):
"""Model for per-channel vector variable values at runtime"""
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
channel_index: int,
self_refresh: bool,
metadata: dict,
change_on_edit_end=False,
**kwargs,
):
self._channel_index = channel_index
self._soft_range_min = None
self._soft_range_max = None
super().__init__(stage, attribute_paths, self_refresh, metadata, False, **kwargs)
def set_value(self, value, comp=-1):
if comp == -1:
super().set_value(value)
elif hasattr(self._value, "__len__"):
self._value[comp] = value
def get_value_as_string(self, **kwargs) -> str:
self._update_value()
if self._value is None:
return ""
return str(self._value[self._channel_index])
def get_value_as_float(self) -> float:
self._update_value()
if self._value is None:
return 0.0
if hasattr(self._value, "__len__"):
return float(self._value[self._channel_index])
return float(self._value)
def get_value_as_bool(self) -> bool:
self._update_value()
if self._value is None:
return False
if hasattr(self._value, "__len__"):
return bool(self._value[self._channel_index])
return bool(self._value)
def get_value_as_int(self) -> int:
self._update_value()
if self._value is None:
return 0
if hasattr(self._value, "__len__"):
return int(self._value[self._channel_index])
return int(self._value)
def build_variable_prop(
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
"""Variable widget that displays both initial (USD) and runtime (Fabric) values. This customized widget will be used
for both the graph and graph instance on a prim. Make sure we return the models, since the UsdPropertiesWidget will
listen for usd notices and update its models accordingly"""
# For instanced graph, prim_path is the prim that the instance is on. For non-instanced graphs, prim is the graph
# path. See which one we have
prims = [stage.GetPrimAtPath(path) for path in prim_paths]
attrs = [prim.GetAttribute(attr_name) for prim in prims]
models = []
for idx, attr in enumerate(attrs):
# if prim is an instance, need to get the graph path from the relationship and verify that a variable with
# the given name is on the graph. Also handle the case where multiple graphs have the same variable (this is
# not well supported at the moment, but the intention is for it to work)
graphs = []
instances = []
if prims[idx].IsA(OmniGraphSchema.OmniGraph):
graphs.append(attr.GetPrimPath())
instances.append(None)
else:
for g in prims[idx].GetProperty(OMNIGRAPHS_REL_ATTR).GetTargets():
graph = og.get_graph_by_path(g.pathString)
if graph.find_variable(attr.GetBaseName()):
graphs.append(g)
instances.append(attr.GetPrimPath())
# TODO: if the graph is instanced, and the evaluation mode is automatic or instanced, then the runtime value
# on the graph itself won't update. Only the value on the instance will. So grey out the runtime column
for graph, instance in zip(graphs, instances):
with ui.HStack(spacing=HORIZONTAL_SPACING):
# Build the initial value widget that reads from USD
model = UsdPropertiesWidgetBuilder.build(
stage,
attr_name,
metadata,
property_type,
prim_paths,
additional_label_kwargs,
additional_widget_kwargs,
)
if isinstance(model, list):
models = models + model
else:
models.append(model)
# Build runtime value widget which reads from fabric
widget_kwargs = {"no_control_state": True}
model_kwargs = {VARIABLE_ATTR: attr, VARIABLE_GRAPH_PATH: graph, VARIABLE_INSTANCE_PATH: instance}
type_key = metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")
type_name = Sdf.ValueTypeNames.Find(type_key)
if type_name.type in VECTOR_TYPES: # type_name.type is the tf_type
widget_kwargs["model_cls"] = OmniGraphVectorVariableRuntimeModel
widget_kwargs["single_channel_model_cls"] = OmniGraphSingleChannelVariableRuntimeModel
else:
widget_kwargs["model_cls"] = OmniGraphVariableRuntimeModel
widget_kwargs["model_kwargs"] = model_kwargs
model = UsdPropertiesWidgetBuilder.build(
stage, attr_name, metadata, property_type, prim_paths, {"visible": False}, widget_kwargs
)
if isinstance(model, list):
models = models + model
else:
models.append(model)
return models
| 34,283 | Python | 37.959091 | 120 | 0.595806 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_attribute_models.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 copy
from typing import List
import omni.ui as ui
from omni.kit.property.usd.usd_attribute_model import FloatModel, IntModel
from pxr import Gf, Sdf, Tf, Usd
from .omnigraph_attribute_base import OmniGraphBase # noqa: PLE0402
# =============================================================================
class OmniGraphAttributeModel(ui.AbstractValueModel, OmniGraphBase):
"""The value model that is reimplemented in Python to watch an OmniGraph attribute path"""
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
change_on_edit_end=False,
**kwargs,
):
OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs)
ui.AbstractValueModel.__init__(self)
def clean(self):
OmniGraphBase.clean(self)
def begin_edit(self):
OmniGraphBase.begin_edit(self)
ui.AbstractValueModel.begin_edit(self)
def end_edit(self):
OmniGraphBase.end_edit(self)
ui.AbstractValueModel.end_edit(self)
def get_value_as_string(self, elide_big_array=True) -> str:
self._update_value()
if self._value is None:
return ""
if self._is_big_array and elide_big_array:
return "[...]"
return str(self._value)
def get_value_as_float(self) -> float:
self._update_value()
if self._value is None:
return 0.0
if hasattr(self._value, "__len__"):
return float(self._value[self._channel_index])
return float(self._value)
def get_value_as_bool(self) -> bool:
self._update_value()
if self._value is None:
return False
if hasattr(self._value, "__len__"):
return bool(self._value[self._channel_index])
return bool(self._value)
def get_value_as_int(self) -> int:
self._update_value()
if self._value is None:
return 0
if hasattr(self._value, "__len__"):
return int(self._value[self._channel_index])
return int(self._value)
def set_value(self, value): # noqa: PLW0221 FIXME: reconcile with base class calls
if OmniGraphBase.set_value(self, value):
self._value_changed()
def _on_dirty(self):
self._value_changed() # AbstractValueModel
# =============================================================================
# OmniGraph Attribute Models need to use OmniGraphBase for their super class state rather than UsdBase
# -----------------------------------------------------------------------------
class OmniGraphTfTokenAttributeModel(ui.AbstractItemModel, OmniGraphBase):
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, item):
super().__init__()
self.token = item
self.model = ui.SimpleStringModel(item)
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict):
OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._allowed_tokens = []
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._updating_value = False
self._has_index = False
self._update_value()
self._has_index = True
def clean(self):
OmniGraphBase.clean(self)
def get_item_children(self, item):
self._update_value()
return self._allowed_tokens
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
OmniGraphBase.begin_edit(self)
def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
OmniGraphBase.end_edit(self)
def _current_index_changed(self, model):
if not self._has_index:
return
# if we're updating from USD notice change to UI, don't call set_value
if self._updating_value:
return
index = model.as_int
if self.set_value(self._allowed_tokens[index].token):
self._item_changed(None)
def _get_allowed_tokens(self, attr):
return attr.GetMetadata("allowedTokens")
def _update_allowed_token(self, token_item=AllowedTokenItem):
self._allowed_tokens = []
# For multi prim editing, the allowedTokens should all be the same
attributes = self._get_attributes()
attr = attributes[0] if len(attributes) > 0 else None
if attr:
for t in self._get_allowed_tokens(attr):
self._allowed_tokens.append(token_item(t))
def _update_value(self, force=False):
was_updating_value = self._updating_value
self._updating_value = True
if OmniGraphBase._update_value(self, force):
# TODO don't have to do this every time. Just needed when "allowedTokens" actually changed
self._update_allowed_token()
index = -1
for i in range(0, len(self._allowed_tokens)): # noqa: PLC0200
if self._allowed_tokens[i].token == self._value:
index = i
if index not in (-1, self._current_index.as_int):
self._current_index.set_value(index)
self._item_changed(None)
self._updating_value = was_updating_value
def _on_dirty(self):
self._item_changed(None)
def get_value_as_token(self):
index = self._current_index.as_int
return self._allowed_tokens[index].token
def is_allowed_token(self, token):
return token in [allowed.token for allowed in self._allowed_tokens]
# -----------------------------------------------------------------------------
class OmniGraphGfVecAttributeModel(ui.AbstractItemModel, OmniGraphBase):
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
comp_count: int,
tf_type: Tf.Type,
self_refresh: bool,
metadata: dict,
**kwargs,
):
OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata, **kwargs)
ui.AbstractItemModel.__init__(self)
self._comp_count = comp_count
self._data_type_name = "Vec" + str(self._comp_count) + tf_type.typeName[-1]
self._data_type = getattr(Gf, self._data_type_name)
class UsdVectorItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
if self._data_type_name.endswith("i"):
self._items = [UsdVectorItem(IntModel(self)) for i in range(self._comp_count)]
else:
self._items = [UsdVectorItem(FloatModel(self)) for i in range(self._comp_count)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
OmniGraphBase.clean(self)
def _construct_vector_from_item(self):
if self._data_type_name.endswith("i"):
data = [item.model.get_value_as_int() for item in self._items]
else:
data = [item.model.get_value_as_float() for item in self._items]
return self._data_type(data)
def _on_value_changed(self, item):
"""Called when the submodel is changed"""
if self._edit_mode_counter > 0:
vector = self._construct_vector_from_item()
index = self._items.index(item)
if vector and self.set_value(vector, index):
# Read the new value back in case hard range clamped it
item.model.set_value(self._value[index])
self._item_changed(item)
else:
# If failed to update value in model, revert the value in submodel
item.model.set_value(self._value[index])
def _update_value(self, force=False):
if OmniGraphBase._update_value(self, force):
if self._value is None:
for i in range(len(self._items)): # noqa: PLC0200
self._items[i].model.set_value(0.0)
return
for i in range(len(self._items)): # noqa: PLC0200
self._items[i].model.set_value(self._value[i])
def _on_dirty(self):
self._item_changed(None)
def get_item_children(self, item):
"""Reimplemented from the base class"""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
OmniGraphBase.begin_edit(self)
def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
OmniGraphBase.end_edit(self)
self._edit_mode_counter -= 1
# -----------------------------------------------------------------------------
class OmniGraphGfVecAttributeSingleChannelModel(OmniGraphAttributeModel):
"""Specialize version of GfVecAttributeSingleChannelModel"""
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
channel_index: int,
self_refresh: bool,
metadata: dict,
change_on_edit_end=False,
**kwargs,
):
self._channel_index = channel_index
super().__init__(stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs)
def get_value_as_string(self, **kwargs) -> str: # noqa: PLW0221 FIXME: reconcile with base class calls
self._update_value()
if self._value is None:
return ""
return str(self._value[self._channel_index])
def get_value_as_float(self) -> float:
self._update_value()
if self._value is None:
return 0.0
if hasattr(self._value, "__len__"):
return float(self._value[self._channel_index])
return float(self._value)
def get_value_as_bool(self) -> bool:
self._update_value()
if self._value is None:
return False
if hasattr(self._value, "__len__"):
return bool(self._value[self._channel_index])
return bool(self._value)
def get_value_as_int(self) -> int:
self._update_value()
if self._value is None:
return 0
if hasattr(self._value, "__len__"):
return int(self._value[self._channel_index])
return int(self._value)
def set_value(self, value):
if self._real_type is None:
# FIXME: This Attribute does not have a corresponding OG attribute
return
vec_value = copy.copy(self._value)
vec_value[self._channel_index] = value
# Skip over our base class impl, because that is specialized for scaler
if OmniGraphBase.set_value(self, vec_value, self._channel_index):
self._value_changed()
def is_different_from_default(self):
"""Override to only check channel"""
if super().is_different_from_default():
return self._comp_different_from_default[self._channel_index]
return False
# -----------------------------------------------------------------------------
class OmniGraphGfQuatAttributeModel(ui.AbstractItemModel, OmniGraphBase):
def __init__(
self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], tf_type: Tf.Type, self_refresh: bool, metadata: dict
):
OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
data_type_name = "Quat" + tf_type.typeName[-1]
self._data_type = getattr(Gf, data_type_name)
class UsdQuatItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create four models per component
self._items = [UsdQuatItem(FloatModel(self)) for i in range(4)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
OmniGraphBase.clean(self)
def _on_value_changed(self, item):
"""Called when the submodel is chaged"""
if self._edit_mode_counter > 0:
quat = self._construct_quat_from_item()
if quat and self.set_value(quat, self._items.index(item)):
self._item_changed(item)
def _update_value(self, force=False):
if OmniGraphBase._update_value(self, force):
for i in range(len(self._items)): # noqa: PLC0200
if i == 0:
self._items[i].model.set_value(self._value.real)
else:
self._items[i].model.set_value(self._value.imaginary[i - 1])
def _on_dirty(self):
self._item_changed(None)
def get_item_children(self, item):
"""Reimplemented from the base class"""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
OmniGraphBase.begin_edit(self)
def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
OmniGraphBase.end_edit(self)
self._edit_mode_counter -= 1
def _construct_quat_from_item(self):
data = [item.model.get_value_as_float() for item in self._items]
return self._data_type(data[0], data[1], data[2], data[3])
# -----------------------------------------------------------------------------
class OmniGraphGfMatrixAttributeModel(ui.AbstractItemModel, OmniGraphBase):
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
comp_count: int,
tf_type: Tf.Type,
self_refresh: bool,
metadata: dict,
):
OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._comp_count = comp_count
data_type_name = "Matrix" + str(self._comp_count) + tf_type.typeName[-1]
self._data_type = getattr(Gf, data_type_name)
class UsdMatrixItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
self._items = [UsdMatrixItem(FloatModel(self)) for i in range(self._comp_count * self._comp_count)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
OmniGraphBase.clean(self)
def _on_value_changed(self, item):
"""Called when the submodel is chaged"""
if self._edit_mode_counter > 0:
matrix = self._construct_matrix_from_item()
if matrix and self.set_value(matrix, self._items.index(item)):
self._item_changed(item)
def _update_value(self, force=False):
if OmniGraphBase._update_value(self, force):
for i in range(len(self._items)): # noqa: PLC0200
self._items[i].model.set_value(self._value[i // self._comp_count][i % self._comp_count]) # noqa: S001
def _on_dirty(self):
self._item_changed(None)
# it's still better to call _value_changed for all child items
for child in self._items:
child.model._value_changed() # noqa: PLW0212
def get_item_children(self, item):
"""Reimplemented from the base class."""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class."""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
OmniGraphBase.begin_edit(self)
def end_edit(self, item): # noqa: PLW0221 FIXME: reconcile with base class calls
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
OmniGraphBase.end_edit(self)
self._edit_mode_counter -= 1
def _construct_matrix_from_item(self):
data = [item.model.get_value_as_float() for item in self._items]
matrix = []
for i in range(self._comp_count):
matrix_row = []
for j in range(self._comp_count):
matrix_row.append(data[i * self._comp_count + j])
matrix.append(matrix_row)
return self._data_type(matrix)
# -----------------------------------------------------------------------------
class OmniGraphSdfTimeCodeModel(OmniGraphAttributeModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._prev_real_values = None
def _save_real_values_as_prev(self):
# SdfTimeCode cannot be inited from another SdfTimeCode, only from float (double in C++)..
self._prev_real_values = [Sdf.TimeCode(float(value)) for value in self._real_values]
| 19,393 | Python | 34.134058 | 118 | 0.582633 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/graph_variable_custom_layout.py | from functools import partial
from typing import List
import omni.graph.core as og
import omni.ui as ui
from carb import settings
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel
from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH
from pxr import Sdf, Usd
ATTRIB_LABEL_STYLE = {"alignment": ui.Alignment.RIGHT_TOP}
GRAPH_VARIABLE_PREFIX = "graph:variable:"
COMPUTEGRAPH_TYPE_NAME = "OmniGraph" if settings.get_settings().get(og.USE_SCHEMA_PRIMS_SETTING) else "ComputeGraph"
def is_usable(type_name: Sdf.ValueTypeName) -> bool:
# returns if the given type can be used by OG
return og.AttributeType.type_from_sdf_type_name(str(type_name)).base_type != og.BaseDataType.UNKNOWN
def get_filtered_variables(prim: Usd.Prim) -> List[str]:
# return only the USD attributes that start with the graph variable attribute prefix
return [
attr.GetName()[len(GRAPH_VARIABLE_PREFIX) :]
for attr in prim.GetAttributes()
if not attr.IsHidden() and is_usable(attr.GetTypeName()) and attr.GetName().startswith(GRAPH_VARIABLE_PREFIX)
]
class VariableNameModel(TfTokenAttributeModel):
"""Model for selecting the target attribute for the write/read operation. We modify the list to show attributes
which are available on the target prim.
"""
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, item, label):
"""
Args:
item: the attribute name token to be shown
label: the label to show in the drop-down
"""
super().__init__()
self.token = item
self.model = ui.SimpleStringModel(label)
def __init__(
self,
stage: Usd.Stage,
variable_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
node_prim_path: Sdf.Path,
):
"""
Args:
stage: The current stage
variable_paths: The list of full variable paths
self_refresh: ignored
metadata: pass-through metadata for model
node_prim_path: The path of the compute node
"""
self._stage = stage
self._node_prim_path = node_prim_path
self._target_graph = None
self._target_prim = None
super().__init__(stage, variable_paths, self_refresh, metadata)
def _get_allowed_tokens(self, _):
# override of TfTokenAttributeModel to specialize what tokens to be shown
return self._get_variables_of_interest()
def _update_value(self, force=False):
# override of TfTokenAttributeModel to refresh the allowed token cache
self._update_allowed_token()
super()._update_value(force)
def _item_factory(self, item):
# construct the item for the model
label = item
return VariableNameModel.AllowedTokenItem(item, label)
def _update_allowed_token(self):
# override of TfTokenAttributeModel to specialize the model items
super()._update_allowed_token(token_item=self._item_factory)
def _get_variables_of_interest(self) -> List[str]:
# returns the attributes we want to let the user select from
prim = self._stage.GetPrimAtPath(self._node_prim_path)
variables = []
target = None
rel = prim.GetRelationship("inputs:graph")
if rel.IsValid():
targets = rel.GetTargets()
if targets:
target = self._stage.GetPrimAtPath(targets[0])
if target:
variables = get_filtered_variables(target)
self._target_prim = target # noqa: PLW0212
var_name_attr = prim.GetAttribute("inputs:variableName")
if len(variables) > 0:
current_value = var_name_attr.Get()
if (current_value is not None) and (current_value != "") and (current_value not in variables):
variables.append(current_value)
variables.insert(0, "")
else:
var_name_attr.Set("")
return variables
class GraphVariableCustomLayout:
_value_is_output = True
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.graph_rel_widget = None
self.variables = []
self.variable_name_model = None
def _variable_name_build_fn(self, *args):
# build the variableName widget
stage = self.compute_node_widget.stage
node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212
with ui.HStack(spacing=HORIZONTAL_SPACING):
ui.Label("Variable Name", name="label", style=ATTRIB_LABEL_STYLE, width=LABEL_WIDTH)
ui.Spacer(width=HORIZONTAL_SPACING)
with ui.ZStack():
attr_path = node_prim_path.AppendProperty("inputs:variableName")
self.variable_name_model = VariableNameModel(stage, [attr_path], False, {}, node_prim_path)
ui.ComboBox(self.variable_name_model)
def _filter_target_lambda(self, target_prim):
return target_prim.GetTypeName() == COMPUTEGRAPH_TYPE_NAME
def _graph_rel_build_fn(self, ui_prop: UsdPropertyUiEntry, *args):
# build the graph relationship widget
stage = self.compute_node_widget.stage
node_prim_path = self.compute_node_widget._payload[-1] # noqa: PLW0212
ui_prop.override_display_name("Graph")
self.graph_rel_widget = UsdPropertiesWidgetBuilder._relationship_builder( # noqa: PLW0212
stage,
ui_prop.prop_name,
ui_prop.metadata,
[node_prim_path],
{"enabled": True, "style": ATTRIB_LABEL_STYLE},
{
"enabled": True,
"on_remove_target": self._on_graph_rel_changed,
"target_picker_on_add_targets": self._on_graph_rel_changed,
"targets_limit": 1,
"target_picker_filter_lambda": self._filter_target_lambda,
},
)
def _on_graph_rel_changed(self, *args):
# when the inputs:graph changes, we dirty the variableName list model because the graph may have changed
self.variable_name_model._set_dirty() # noqa: PLW0212
self.graph_rel_widget._set_dirty() # noqa: PLW0212
def apply(self, props):
# called by compute_node_widget to apply UI when selection changes
def find_prop(name):
try:
return next((p for p in props if p.prop_name == name))
except StopIteration:
return None
def value_build_fn(prop: UsdPropertyUiEntry):
def build_fn(*args):
# the resolved attribute is procedural and does not inherit the meta-data of the extended attribute
# so we need to manually set the display name
prop.override_display_name("Value")
self.compute_node_widget.build_property_item(
self.compute_node_widget.stage, prop, self.compute_node_widget._payload # noqa: PLW0212
)
return build_fn
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
prop = find_prop("inputs:graph")
if prop is not None:
CustomLayoutProperty(None, None, build_fn=partial(self._graph_rel_build_fn, prop))
CustomLayoutProperty(None, None, build_fn=self._variable_name_build_fn)
prop = find_prop("inputs:value")
if prop is not None:
CustomLayoutProperty(None, None, build_fn=value_build_fn(prop))
prop = find_prop("outputs:value")
if prop is not None:
with CustomLayoutGroup("Outputs"):
CustomLayoutProperty(None, None, build_fn=value_build_fn(prop))
return frame.apply(props)
| 8,280 | Python | 40.613065 | 117 | 0.62186 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_attribute_builder.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 omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH
from pxr import Sdf, Tf, Usd
from .omnigraph_attribute_base import get_model_cls # noqa: PLE0402
from .omnigraph_attribute_models import OmniGraphAttributeModel # noqa: PLE0402
from .omnigraph_attribute_models import OmniGraphGfVecAttributeModel # noqa: PLE0402
from .omnigraph_attribute_models import OmniGraphGfVecAttributeSingleChannelModel # noqa: PLE0402
from .omnigraph_attribute_models import OmniGraphSdfTimeCodeModel # noqa: PLE0402
from .omnigraph_attribute_models import OmniGraphTfTokenAttributeModel # noqa: PLE0402
# =============================================================================
def find_first_node_with_attrib(prim_paths: List[Sdf.Path], attr_name: str) -> Optional[og.Node]:
"""Returns the first node in the paths that has the given attrib name"""
node_with_attr = None
for prim_path in prim_paths:
node = og.get_node_by_path(prim_path.pathString)
if node and node.get_attribute_exists(attr_name):
node_with_attr = node
break
return node_with_attr
# =============================================================================
class OmniGraphPropertiesWidgetBuilder(UsdPropertiesWidgetBuilder):
"""OmniGraph specialization of USD widget factory based on OG API instead of USD"""
OVERRIDE_TYPENAME_KEY = "OGTypeName"
UNRESOLVED_TYPENAME = "OGUnresolvedType"
tf_gf_matrix2d = Sdf.ValueTypeNames.Matrix2d
tf_gf_matrix3d = Sdf.ValueTypeNames.Matrix3d
tf_gf_matrix4d = Sdf.ValueTypeNames.Matrix4d
@classmethod
def init_builder_table(cls):
# Make our own list of builder functions because we need `cls` to be us for the
# classmethod callstack
cls.widget_builder_table = {
cls.tf_half: cls._floating_point_builder,
cls.tf_float: cls._floating_point_builder,
cls.tf_double: cls._floating_point_builder,
cls.tf_uchar: cls._integer_builder,
cls.tf_uint: cls._integer_builder,
cls.tf_int: cls._integer_builder,
cls.tf_int64: cls._integer_builder,
cls.tf_uint64: cls._integer_builder,
cls.tf_bool: cls._bool_builder,
cls.tf_string: cls._string_builder,
cls.tf_gf_vec2i: cls._vec2_per_channel_builder,
cls.tf_gf_vec2h: cls._vec2_per_channel_builder,
cls.tf_gf_vec2f: cls._vec2_per_channel_builder,
cls.tf_gf_vec2d: cls._vec2_per_channel_builder,
cls.tf_gf_vec3i: cls._vec3_per_channel_builder,
cls.tf_gf_vec3h: cls._vec3_per_channel_builder,
cls.tf_gf_vec3f: cls._vec3_per_channel_builder,
cls.tf_gf_vec3d: cls._vec3_per_channel_builder,
cls.tf_gf_vec4i: cls._vec4_per_channel_builder,
cls.tf_gf_vec4h: cls._vec4_per_channel_builder,
cls.tf_gf_vec4f: cls._vec4_per_channel_builder,
cls.tf_gf_vec4d: cls._vec4_per_channel_builder,
# FIXME: nicer matrix handling
cls.tf_gf_matrix2d: cls._floating_point_builder,
cls.tf_gf_matrix3d: cls._floating_point_builder,
cls.tf_gf_matrix4d: cls._floating_point_builder,
cls.tf_tf_token: cls._tftoken_builder,
cls.tf_sdf_asset_path: cls._sdf_asset_path_builder,
cls.tf_sdf_time_code: cls._time_code_builder,
Tf.Type.Unknown: cls._unresolved_builder,
}
vec_model_dict = {
"model_cls": OmniGraphGfVecAttributeModel,
"single_channel_model_cls": OmniGraphGfVecAttributeSingleChannelModel,
}
cls.default_model_table = {
# _floating_point_builder
cls.tf_half: OmniGraphAttributeModel,
cls.tf_float: OmniGraphAttributeModel,
cls.tf_double: OmniGraphAttributeModel,
# _integer_builder
cls.tf_uchar: OmniGraphAttributeModel,
cls.tf_uint: OmniGraphAttributeModel,
cls.tf_int: OmniGraphAttributeModel,
cls.tf_int64: OmniGraphAttributeModel,
cls.tf_uint64: OmniGraphAttributeModel,
# _bool_builder
cls.tf_bool: OmniGraphAttributeModel,
# _string_builder
cls.tf_string: OmniGraphAttributeModel,
# _vec2_per_channel_builder
cls.tf_gf_vec2i: vec_model_dict,
cls.tf_gf_vec2h: vec_model_dict,
cls.tf_gf_vec2f: vec_model_dict,
cls.tf_gf_vec2d: vec_model_dict,
# _vec3_per_channel_builder
cls.tf_gf_vec3i: vec_model_dict,
cls.tf_gf_vec3h: vec_model_dict,
cls.tf_gf_vec3f: vec_model_dict,
cls.tf_gf_vec3d: vec_model_dict,
# _vec4_per_channel_builder
cls.tf_gf_vec4i: vec_model_dict,
cls.tf_gf_vec4h: vec_model_dict,
cls.tf_gf_vec4f: vec_model_dict,
cls.tf_gf_vec4d: vec_model_dict,
# FIXME: matrix models
cls.tf_gf_matrix2d: OmniGraphAttributeModel,
cls.tf_gf_matrix3d: OmniGraphAttributeModel,
cls.tf_gf_matrix4d: OmniGraphAttributeModel,
cls.tf_tf_token: {
"model_cls": OmniGraphTfTokenAttributeModel,
"no_allowed_tokens_model_cls": OmniGraphAttributeModel,
},
cls.tf_sdf_time_code: OmniGraphSdfTimeCodeModel,
# FIXME: Not converted yet
# cls.tf_sdf_asset_path: cls._sdf_asset_path_builder,
}
@classmethod
def startup(cls):
cls.init_builder_table()
@classmethod
def _generate_tooltip_string(cls, attr_name, metadata):
"""Override tooltip to specialize extended types"""
doc_string = metadata.get(Sdf.PropertySpec.DocumentationKey)
type_name = metadata.get(OmniGraphPropertiesWidgetBuilder.OVERRIDE_TYPENAME_KEY, cls._get_type_name(metadata))
tooltip = f"{attr_name} ({type_name})" if not doc_string else f"{attr_name} ({type_name})\n\t\t{doc_string}"
return tooltip
@classmethod
def build(
cls,
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
if property_type == Usd.Attribute:
type_name = cls._get_type_name(metadata)
tf_type = type_name.type
# Lookup the build func
build_func = cls.widget_builder_table.get(tf_type, cls._fallback_builder)
# Check for override the default attribute model(s)
default_model = cls.default_model_table.get(tf_type, None)
if isinstance(default_model, dict):
additional_widget_kwargs.update(default_model)
elif default_model:
additional_widget_kwargs["model_cls"] = default_model
# Output attributes should be read-only
node_with_attr = find_first_node_with_attrib(prim_paths, attr_name)
if node_with_attr:
ogn_attr = node_with_attr.get_attribute(attr_name)
if ogn_attr.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT:
additional_widget_kwargs["enabled"] = False
return build_func(
stage, attr_name, type_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
if property_type == Usd.Relationship:
return cls._relationship_builder(
stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
return None
# -------------------------------------------------------------------------
# Builder function overrides
@classmethod
def _unresolved_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
label_txt = attr_name
node_with_attr = find_first_node_with_attrib(prim_paths, attr_name)
if node_with_attr:
ogn_attr = node_with_attr.get_attribute(attr_name)
extended_type = (
"any" if ogn_attr.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY else "union"
)
label_txt = f"<unresolved {extended_type}>"
display_name = metadata.get(Sdf.PropertySpec.DisplayNameKey, attr_name)
ui.Label(display_name, name="label", style={"alignment": ui.Alignment.RIGHT_CENTER}, width=LABEL_WIDTH)
ui.Spacer(width=16)
ui.Label(label_txt, name="label", style={"alignment": ui.Alignment.LEFT_CENTER, "color": 0xFF809095})
ui.Spacer(width=HORIZONTAL_SPACING)
ui.Spacer(width=12)
return []
@classmethod
def _fallback_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_cls = get_model_cls(OmniGraphAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata)
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
kwargs = {
"name": "models_readonly",
"model": model,
"enabled": False,
"tooltip": model.get_value_as_string(),
}
if additional_widget_kwargs:
kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.StringField(**kwargs)
value_widget.identifier = f"fallback_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
cls._create_control_state(value_widget=value_widget, mixed_overlay=mixed_overlay, **kwargs, label=label)
return model
| 10,772 | Python | 42.092 | 118 | 0.612978 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/token_array_edit_widget.py | import weakref
from functools import partial
from typing import List
import omni.ui as ui
from omni.kit.property.usd.usd_attribute_model import UsdAttributeModel
from pxr import Sdf, Vt
class TokenArrayEditWidget:
def __init__(self, stage, attr_name, prim_paths, metadata):
self._model = UsdAttributeModel(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata)
self._token_array_attrs = [stage.GetPrimAtPath(path).GetAttribute(attr_name) for path in prim_paths]
self._frame = ui.Frame()
self._frame.set_build_fn(self._build)
def clean(self):
self._model.clean()
self._frame = None
def _build(self):
shared_tokens = None
for attr in self._token_array_attrs:
if attr.HasValue():
tokens = list(attr.Get())
else:
tokens = []
if shared_tokens is None:
shared_tokens = tokens
elif shared_tokens != tokens:
shared_tokens = None
break
with ui.VStack(spacing=2):
if shared_tokens is not None:
for i, token in enumerate(shared_tokens):
with ui.HStack(spacing=2):
token_model = ui.StringField(name="models").model
token_model.set_value(token)
def on_edit_element(value_model, weak_self, index):
weak_self = weak_self()
if weak_self:
token_array = list(weak_self._token_array_attrs[0].Get()) # noqa: PLW0212
token_array[index] = value_model.as_string
weak_self._model.set_value(Vt.TokenArray(token_array)) # noqa: PLW0212
token_model.add_end_edit_fn(partial(on_edit_element, weak_self=weakref.ref(self), index=i))
def on_remove_element(weak_self, index):
weak_self = weak_self()
if weak_self:
token_array = list(weak_self._token_array_attrs[0].Get()) # noqa: PLW0212
token_array.pop(index)
weak_self._model.set_value(Vt.TokenArray(token_array)) # noqa: PLW0212
ui.Button(
"-",
width=ui.Pixel(14),
clicked_fn=partial(on_remove_element, weak_self=weakref.ref(self), index=i),
)
def on_add_element(weak_self):
weak_self = weak_self()
if weak_self:
token_array_attr = weak_self._token_array_attrs[0] # noqa: PLW0212
if token_array_attr.HasValue():
token_array = list(token_array_attr.Get())
else:
token_array = []
token_array.append("")
weak_self._model.set_value(Vt.TokenArray(token_array)) # noqa: PLW0212
ui.Button(
"Add Element", width=ui.Pixel(30), clicked_fn=partial(on_add_element, weak_self=weakref.ref(self))
)
else:
ui.StringField(name="models", read_only=True).model.set_value("Mixed")
def _set_dirty(self):
self._frame.rebuild()
def build_token_array_prop(
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=4):
label_kwargs = {"name": "label", "width": 160, "height": 18}
ui.Label(attr_name, **label_kwargs)
ui.Spacer(width=5)
return TokenArrayEditWidget(stage, attr_name, prim_paths, metadata)
| 3,956 | Python | 37.048077 | 120 | 0.512133 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_window.py | """Manager for the OmniGraph Toolkit window"""
from contextlib import suppress
import omni.graph.tools as ogt
import omni.kit.ui as kit_ui
import omni.ui as ui
from ..metaclass import Singleton # noqa: PLE0402
from ..style import VSTACK_ARGS # noqa: PLE0402
from ..style import get_window_style # noqa: PLE0402
from .toolkit_frame_inspection import ToolkitFrameInspection
from .toolkit_frame_memory import ToolkitFrameMemory
from .toolkit_frame_output import ToolkitFrameOutput
from .toolkit_frame_scene import ToolkitFrameScene
MENU_PATH = "Window/Visual Scripting/Toolkit"
# ======================================================================
class Toolkit(metaclass=Singleton):
"""Class containing all of the functionality for the OmniGraph Toolkit Window"""
@staticmethod
def get_name():
"""Returns the name of this window extension"""
return "OmniGraph Toolkit"
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def get_description():
"""Returns a description of this window extension"""
return "Collection of utilities and inspectors to help in working with OmniGraph"
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def get_menu_path():
"""Returns the menu path where this window can be accessed"""
return MENU_PATH
# --------------------------------------------------------------------------------------------------------------
def __init__(self):
"""Set up the window elements - use show() for displaying the window"""
# The window object
self.__window = ui.Window(
self.get_name(),
width=800,
height=500,
menu_path=self.get_menu_path(),
visible=False,
visibility_changed_fn=self._visibility_changed_fn,
)
self.__window.frame.set_style(get_window_style())
self.__window.frame.set_build_fn(self.__rebuild_window_frame)
self.__window.frame.rebuild()
# Manager for the debug output frame of the toolkit
self.__frame_output = ToolkitFrameOutput()
# Manager for the inspection frame of the toolkit
self.__frame_inspection = ToolkitFrameInspection(self.__frame_output.set_debug_output)
# Manager for the memory usage frame of the toolkit
self.__frame_memory = ToolkitFrameMemory()
# Manager for the scene manipulation frame of the toolkit
self.__frame_scene = ToolkitFrameScene(self.__frame_output.set_debug_output)
# --------------------------------------------------------------------------------------------------------------
def destroy(self):
"""Destroy the singleton editor, if it exists"""
with suppress(AttributeError):
self.__window.visible = False
with suppress(AttributeError):
self.__window.frame.set_build_fn(None)
# Ordering is important for ensuring owners destroy references last.
ogt.destroy_property(self, "__frame_inspection")
ogt.destroy_property(self, "__frame_output")
ogt.destroy_property(self, "__frame_memory")
ogt.destroy_property(self, "__frame_scene")
ogt.destroy_property(self, "__window")
self.__window = None
Singleton.forget(Toolkit)
# --------------------------------------------------------------------------------------------------------------
def show_window(self):
"""Display the window"""
self.__window.visible = True
def hide_window(self):
self.__window.visible = False
def _visibility_changed_fn(self, visible):
editor_menu = kit_ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(MENU_PATH, visible)
# --------------------------------------------------------------------------------------------------------------
def is_visible(self):
"""Returns the visibility state of our window"""
return self.__window and self.__window.visible
# --------------------------------------------------------------------------------------------------------------
def __rebuild_window_frame(self):
"""Construct the widgets within the window"""
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
name="main_frame",
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
):
with ui.VStack(**VSTACK_ARGS, name="main_vertical_stack"):
self.__frame_memory.build()
self.__frame_inspection.build()
self.__frame_scene.build()
self.__frame_output.build()
| 4,849 | Python | 41.920354 | 116 | 0.528563 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/__init__.py | """Interface for the OmniGraph toolkit window"""
from .toolkit_window import MENU_PATH, Toolkit
| 96 | Python | 31.333323 | 48 | 0.78125 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_frame_output.py | """Handler for the debug output frame of the OmniGraph toolkit"""
import asyncio
import sys
from contextlib import suppress
from typing import Optional
import carb
import omni.graph.core as og
import omni.graph.tools as ogt
import omni.ui as ui
from ..style import VSTACK_ARGS # noqa: PLE0402
from ..utils import DestructibleButton # noqa: PLE0402
# ======================================================================
class ToolkitFrameOutput:
"""Class containing all of the functionality for the debug output frame in the OmniGraph Toolkit Window
Public Functions:
build() : Construct the frame
set_debug_output(output, tooltip): Define the text contents of the frame
Layout of the class constants is stacked:
Constants
Initialize/Destroy
Public Functions
Build Functions
Callback Functions
"""
# ----------------------------------------------------------------------
# Frame information
ID = "FrameOutput"
TITLE = "Debug Output"
# ----------------------------------------------------------------------
# Maximum number of lines to show in the debug preview pane (limited to avoid overflow crash)
DEBUG_PREVIEW_LINE_LIMIT = 10000
# ----------------------------------------------------------------------
# IDs for widgets
ID_DEBUG_LABEL = "DebugOutputLabel"
ID_DEBUG_CONTENTS = "DebugOutput"
ID_TEXT_CLIPPED = "Clipped"
# ----------------------------------------------------------------------
# Tooltip for the frame
TOOLTIP = "View the output from the debugging functions"
# --------------------------------------------------------------------------------------------------------------
def __init__(self):
"""Set up the frame elements - use build() for constructing the frame"""
# Dictionary of widgets in the window
self.__widgets = {}
# Output text from various functions to show in an auxiliary frame
self.__debug_output = "No output available yet"
self.__debug_tooltip = self.TOOLTIP
# Task for the delayed fade out of the clipboard message
self.__delayed_fade_task = None
# --------------------------------------------------------------------------------------------------------------
def destroy(self):
"""Destroy the debug output frame"""
with suppress(AttributeError, KeyError):
self.__widgets[self.ID].set_build_fn(None)
with suppress(AttributeError):
self.__delayed_fade_task.cancel()
# Ordering is important for ensuring owners destroy references last.
ogt.destroy_property(self, "__widgets")
# ----------------------------------------------------------------------
def build(self):
"""Construct the collapsable frame containing the debug output contents"""
self.__widgets[self.ID] = ui.CollapsableFrame(title=self.TITLE, collapsed=False)
self.__widgets[self.ID].set_build_fn(self.__rebuild_output_display_frame)
# ----------------------------------------------------------------------
def set_debug_output(self, new_output: str, new_tooltip: Optional[str]):
"""Manually set new output data and update it"""
self.__debug_output = new_output
self.__debug_tooltip = new_tooltip if new_tooltip else self.TOOLTIP
self.__on_debug_output_changed()
sys.stdout.write(self.__debug_output)
# ----------------------------------------------------------------------
def __rebuild_output_display_frame(self):
"""Construct and populate the display area for output from the serialization functions"""
with self.__widgets[self.ID]:
with ui.VStack(**VSTACK_ARGS):
self.__widgets[self.ID_DEBUG_LABEL] = ui.Label(
"Available in the Python variable omni.graph.core.DEBUG_DATA - (RMB to copy contents to clipboard)",
style_type_name_override="Info",
)
with ui.ZStack():
self.__widgets[self.ID_DEBUG_CONTENTS] = ui.Label(
self.ID_DEBUG_CONTENTS, style_type_name_override="Code"
)
self.__widgets[self.ID_TEXT_CLIPPED] = DestructibleButton(
" ",
height=ui.Percent(100),
width=ui.Percent(100),
alignment=ui.Alignment.CENTER_TOP,
style={"background_color": 0x00000000, "color": 0xFF00FFFF},
mouse_pressed_fn=self.__on_copy_debug_output_to_clipboard,
)
self.__on_debug_output_changed()
# --------------------------------------------------------------------------------------------------------------
def __fade_clip_message(self):
"""Enable the clipboard message, then set a timer to remove it after 3 seconds."""
async def __delayed_fade(self):
await asyncio.sleep(1.0)
color = 0xFF00FFFF
for _ in range(31):
color -= 0x08000000
self.__widgets[self.ID_TEXT_CLIPPED].set_style({"background_color": 0x00000000, "color": color})
await asyncio.sleep(0.02)
with suppress(KeyError):
self.__widgets[self.ID_TEXT_CLIPPED].set_style({"background_color": 0x00000000, "color": 0xFF00FFFF})
self.__widgets[self.ID_TEXT_CLIPPED].text = " "
with suppress(Exception):
self.__delayed_fade_task.cancel()
carb.log_info("Copied debug output to the clipboard")
self.__widgets[self.ID_TEXT_CLIPPED].text = "Debug Output Clipped"
self.__delayed_fade_task = asyncio.ensure_future(__delayed_fade(self))
# ----------------------------------------------------------------------
def __on_debug_output_changed(self):
"""Callback executed whenever any data affecting the debug output has changed"""
def find_max_line_end(full_string: str):
index = -1
for _ in range(self.DEBUG_PREVIEW_LINE_LIMIT + 1):
index = full_string.find("\n", index + 1)
if index < 0:
break
return index
with suppress(KeyError):
if self.__debug_output and self.__debug_output.count("\n") > self.DEBUG_PREVIEW_LINE_LIMIT:
last_line_ends = find_max_line_end(self.__debug_output)
if last_line_ends > 0:
self.__widgets[self.ID_DEBUG_CONTENTS].text = self.__debug_output[: last_line_ends + 1] + "...\n"
else:
self.__widgets[self.ID_DEBUG_CONTENTS].text = self.__debug_output
og.DEBUG_DATA = self.__debug_output
self.__widgets[self.ID_DEBUG_LABEL].set_tooltip(self.__debug_tooltip)
# ----------------------------------------------------------------------
def __on_copy_debug_output_to_clipboard(self, x, y, button, modifier):
"""Callback executed when right-clicking on the output location"""
if button != 1:
return
try:
import pyperclip
pyperclip.copy(self.__debug_output)
self.__fade_clip_message()
except ImportError:
carb.log_warn("Could not import pyperclip.")
| 7,387 | Python | 43.239521 | 120 | 0.512387 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_frame_inspection.py | """Handler for the inspection frame of the OmniGraph toolkit"""
from contextlib import suppress
from typing import Callable
import omni.graph.tools as ogt
import omni.ui as ui
from ..style import VSTACK_ARGS
from .widgets.categories import ToolkitWidgetCategories
from .widgets.extension_dependencies import ToolkitWidgetExtensionDependencies
from .widgets.extension_timing import ToolkitWidgetExtensionTiming
from .widgets.fabric_contents import ToolkitWidgetFabricContents
from .widgets.graph_registry import ToolkitWidgetGraphRegistry
from .widgets.graph_structure import ToolkitWidgetGraphStructure
# ======================================================================
class ToolkitFrameInspection:
"""Class containing all of the functionality for the inspection frame of the OmniGraph Toolkit Window"""
# ----------------------------------------------------------------------
# Frame information
ID = "FrameInspection"
TITLE = "OmniGraph Object Inspection"
# ----------------------------------------------------------------------
# IDs for widgets
ID_INSPECTION_LABEL = "Inspection"
# --------------------------------------------------------------------------------------------------------------
def __init__(self, set_output_callback: Callable):
"""Set up the frame elements - use build() for constructing the frame"""
# Dictionary of widgets in the window
self.__widgets = {}
# Dictionary of widget classes in the window
self.__widget_classes = []
# Callback to use for reporting new output
self.__set_output = set_output_callback
# --------------------------------------------------------------------------------------------------------------
def destroy(self):
"""Destroy the frame"""
with suppress(AttributeError, KeyError):
self.__widgets[self.ID].set_build_fn(None)
# Ordering is important for ensuring owners destroy references last.
ogt.destroy_property(self, "__widgets")
ogt.destroy_property(self, "__widget_classes")
# __widget_models are destroyed when __widgets are destroyed
# ----------------------------------------------------------------------
def build(self):
"""Construct the collapsable frame containing the inspection operations"""
self.__widgets[self.ID] = ui.CollapsableFrame(title=self.TITLE, collapsed=False)
self.__widgets[self.ID].set_build_fn(self.__rebuild_inspection_frame)
# ----------------------------------------------------------------------
def __rebuild_inspection_frame(self):
"""Construct the widgets for running inspection operations"""
self.__widget_classes.append(ToolkitWidgetFabricContents(self.__set_output))
self.__widget_classes.append(ToolkitWidgetGraphStructure(self.__set_output))
self.__widget_classes.append(ToolkitWidgetGraphRegistry(self.__set_output))
self.__widget_classes.append(ToolkitWidgetCategories(self.__set_output))
self.__widget_classes.append(ToolkitWidgetExtensionDependencies(self.__set_output))
self.__widget_classes.append(ToolkitWidgetExtensionTiming(self.__set_output))
with self.__widgets[self.ID]:
self.__widgets[self.ID_INSPECTION_LABEL] = ui.Label("", style_type_name_override="Code")
with ui.VStack(**VSTACK_ARGS, name="main_vertical_stack"):
for widget in self.__widget_classes:
with ui.HStack(width=0, spacing=10):
widget.build()
| 3,583 | Python | 48.09589 | 116 | 0.581915 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_utils.py | """An assortment of utilities shared by various pieces of the toolkit"""
import os
import omni.ui as ui
from ..utils import DestructibleImage, get_icons_dir
__all__ = ["help_button"]
# ----------------------------------------------------------------------
def help_button(callback) -> ui.Image:
"""Build the standard help button with a defined callback when the mouse button is pressed"""
with ui.HStack(spacing=10):
button = DestructibleImage(
os.path.join(get_icons_dir(), "help.svg"),
width=20,
height=20,
mouse_pressed_fn=callback,
tooltip="Show the help information for the inspector on the object",
)
return button
| 714 | Python | 30.086955 | 97 | 0.578431 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_frame_scene.py | """Handler for the scene manipulation frame of the OmniGraph toolkit"""
from contextlib import suppress
from typing import Callable
import omni.graph.core as og
import omni.graph.tools as ogt
import omni.ui as ui
from ..style import VSTACK_ARGS
from .widgets.extensions_all import ToolkitWidgetExtensionsAll
from .widgets.extensions_missing import ToolkitWidgetExtensionsMissing
from .widgets.extensions_used import ToolkitWidgetExtensionsUsed
from .widgets.ogn_from_node import ToolkitWidgetOgnFromNode
# ======================================================================
class ToolkitFrameScene:
"""Class containing all of the functionality for the scene manipulation frame of the OmniGraph Toolkit Window
Public Functions:
build() : Construct the frame
"""
# ----------------------------------------------------------------------
# Frame information
ID = "FrameScene"
TITLE = "OmniGraph Scene Manipulation"
# ----------------------------------------------------------------------
# Layout constants specific to this frame
FLAG_COLUMN_WIDTH = 80
# ----------------------------------------------------------------------
# Labels for widgets
LABEL_SCENE = "Scene"
# --------------------------------------------------------------------------------------------------------------
def __init__(self, set_output_callback: Callable):
"""Set up the frame elements - use build() for constructing the frame"""
# Dictionary of widgets in the window
self.__widgets = {}
# Dictionary of widget managers in the window
self.__widget_managers = []
# Callback to use for reporting new output
self.__set_output = set_output_callback
# Manager for the per-extension information
self.__extension_information = og.ExtensionInformation()
# --------------------------------------------------------------------------------------------------------------
def destroy(self):
"""Destroy the frame"""
with suppress(AttributeError, KeyError):
self.__widgets[self.ID].set_build_fn(None)
# Ordering is important for ensuring owners destroy references last.
ogt.destroy_property(self, "__widgets")
ogt.destroy_property(self, "__widget_managers")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Construct the collapsable frame containing the inspection operations"""
self.__widgets[self.ID] = ui.CollapsableFrame(title=self.TITLE, collapsed=False)
self.__widgets[self.ID].set_build_fn(self.__rebuild_scene_frame)
# ----------------------------------------------------------------------
def __rebuild_scene_frame(self):
"""Construct the widgets for running inspection operations"""
self.__widget_managers.append(ToolkitWidgetExtensionsUsed(self.__set_output, self.__extension_information))
self.__widget_managers.append(ToolkitWidgetExtensionsMissing(self.__set_output, self.__extension_information))
self.__widget_managers.append(ToolkitWidgetExtensionsAll(self.__set_output, self.__extension_information))
self.__widget_managers.append(ToolkitWidgetOgnFromNode(self.__set_output))
with self.__widgets[self.ID]:
self.__widgets[self.LABEL_SCENE] = ui.Label("", style_type_name_override="Code")
with ui.VStack(**VSTACK_ARGS, name="main_vertical_stack"):
with ui.HStack(width=0, spacing=10):
for widget in self.__widget_managers:
widget.build()
| 3,696 | Python | 44.641975 | 118 | 0.559253 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/toolkit_frame_memory.py | """Handler for the memory usage frame of the OmniGraph toolkit"""
import omni.graph.core as og
import omni.graph.tools as ogt
import omni.ui as ui
from ..style import BUTTON_WIDTH # noqa: PLE0402
from ..style import name_value_hstack # noqa: PLE0402
from ..style import name_value_label # noqa: PLE0402
from ..utils import DestructibleButton # noqa: PLE0402
# ======================================================================
class ToolkitFrameMemory:
"""Class containing all of the functionality for the memory usage frame in the OmniGraph Toolkit Window
Public Functions:
build() : Construct the frame
Layout of the class constants is stacked:
Constants
Initialize/Destroy
Public Functions
Build Functions
Callback Functions
"""
# ----------------------------------------------------------------------
# Frame information
ID = "FrameMemory"
TITLE = "Memory Usage"
# ----------------------------------------------------------------------
# IDs for widgets
ID_BTN_UPDATE_MEMORY = "UpdateMemoryUsed"
ID_MEMORY_USED = "MemoryUsed"
# ----------------------------------------------------------------------
# Tooltips for the editable widgets
TOOLTIPS = {
ID_MEMORY_USED: "How much memory is currently being used by OmniGraph?",
ID_BTN_UPDATE_MEMORY: "Update the memory usage for the current OmniGraph",
}
# --------------------------------------------------------------------------------------------------------------
def __init__(self):
"""Set up the frame elements - use build() for constructing the frame"""
# Dictionary of widgets in the window
self.__widgets = {}
# Dictionary of data models belonging to widgets in the window
self.__widget_models = {}
# --------------------------------------------------------------------------------------------------------------
def destroy(self):
"""Destroy the memory usage frame"""
# Ordering is important for ensuring owners destroy references last.
ogt.destroy_property(self, "__widgets")
# __widget_models are destroyed when __widgets are destroyed
# ----------------------------------------------------------------------
def build(self):
"""Construct the widgets used in the memory usage section"""
with name_value_hstack():
name_value_label("Memory Used By Graph:")
model = ui.SimpleIntModel(0)
self.__widgets[self.ID_MEMORY_USED] = ui.IntField(
model=model,
width=100,
name=self.ID_MEMORY_USED,
tooltip=self.TOOLTIPS[self.ID_MEMORY_USED],
alignment=ui.Alignment.LEFT_CENTER,
)
self.__widget_models[self.ID_MEMORY_USED] = model
self.__widgets[self.ID_BTN_UPDATE_MEMORY] = DestructibleButton(
"Update Memory Used",
name=self.ID_BTN_UPDATE_MEMORY,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIPS[self.ID_BTN_UPDATE_MEMORY],
clicked_fn=self.__on_update_memory_used_button,
)
# --------------------------------------------------------------------------------------------------------------
def __on_update_memory_used_button(self):
"""Callback executed when the Update Memory Used button is clicked"""
ctx = og.get_compute_graph_contexts()[0]
self.__widget_models[self.ID_MEMORY_USED].set_value(og.OmniGraphInspector().memory_use(ctx))
| 3,608 | Python | 40.965116 | 116 | 0.502494 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extension_timing.py | """Support for the toolkit widget that shows OmniGraph-related timing for all extensions.
The output is a dictionary of extension timing information with a legend:
.. code-block:: json
{
"Extension Processing Timing": {
"legend": {
"Key": "Extension ID",
"Value": [
"Registration Of Python Nodes",
"Deregistration Of Python Nodes"
]
},
"timing": {
"omni.graph.examples.python": [
12345,
12367
]
}
}
}
"""
import json
from contextlib import suppress
from typing import Callable
import omni.graph.core as og
import omni.graph.tools as ogt
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
__all__ = ["ToolkitWidgetExtensionTiming"]
# ==============================================================================================================
class ToolkitWidgetExtensionTiming:
ID = "DumpExtensionTiming"
LABEL = "Extension Processing Timing"
TOOLTIP = "Dump information on timing of per-extension operations initiated by OmniGraph"
RESULTS_TOOLTIP = "Timing information of per-extension operations initiated by OmniGraph - see 'legend' for details"
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable):
self.__button = None
self.__set_output = set_output_callback
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the extension information"""
self.__button = DestructibleButton(
self.LABEL,
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
# --------------------------------------------------------------------------------------------------------------
def __on_click(self):
"""Callback executed when the Extensions All button is clicked"""
try:
ext_info = og._PublicExtension # noqa: PLW0212
ext_ids = set(ext_info.REGISTRATION_TIMING.keys()).union(set(ext_info.DEREGISTRATION_TIMING.keys()))
extension_timing_information = {}
for ext_id in ext_ids:
registration_timing = None
deregistration_timing = None
with suppress(KeyError):
registration_timing = ext_info.REGISTRATION_TIMING[ext_id] / 1000000.0
with suppress(KeyError):
deregistration_timing = ext_info.DEREGISTRATION_TIMING[ext_id] / 1000000.0
extension_timing_information[ext_id] = [registration_timing, deregistration_timing]
text = json.dumps(
{
self.LABEL: {
"legend": {
"Key": "Extension ID",
"Value": ["Registration Of Python Nodes (ms)", "Deregistration Of Python Nodes (ms)"],
},
"timing": extension_timing_information,
}
},
indent=4,
)
except Exception as error: # noqa: PLW0703
text = str(error)
self.__set_output(text, self.RESULTS_TOOLTIP)
| 3,804 | Python | 37.434343 | 120 | 0.492639 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/ogn_from_node.py | """Support for the widget that dumps the categories OmniGraph knows about."""
import json
from typing import Callable
import carb
import omni.graph.core as og
import omni.graph.tools as ogt
import omni.usd
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
__all__ = ["ToolkitWidgetOgnFromNode"]
# ==============================================================================================================
class ToolkitWidgetOgnFromNode:
ID = "OgnFromNode"
LABEL = "Generate .ogn From Selected Node"
TOOLTIP = "Generate a .ogn definition that matches the contents of the selected node (one node only)"
RESULTS_TOOLTIP = ".ogn file that describes the selected node"
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable):
self.__button = None
self.__set_output = set_output_callback
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the list of nodes and their extensions from the scene"""
self.__button = DestructibleButton(
self.LABEL,
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
# --------------------------------------------------------------------------------------------------------------
def __on_click(self):
"""Callback executed when the OGN From Node button is clicked"""
try:
selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
if not selected_paths:
text = "Select a node to generate the .ogn file for it"
else:
omnigraph_nodes = []
prims = []
graph = og.get_current_graph()
for path in selected_paths:
node = graph.get_node(path)
if node.is_valid():
omnigraph_nodes.append(node)
else:
prims.append(omni.usd.get_context().get_stage().GetPrimAtPath(path))
if not omnigraph_nodes:
# TODO: Most of the .ogn information could be generated from a plain prim as well
text = "Select an OmniGraph node to generate the .ogn file for it"
else:
if len(omnigraph_nodes) > 1:
carb.log_warn(f"More than one node selected. Only generating the first one - {selected_paths}")
generated_ogn = og.generate_ogn_from_node(omnigraph_nodes[0])
text = json.dumps(generated_ogn, indent=4)
except Exception as error: # noqa: PLW0703
text = str(error)
self.__set_output(text, self.RESULTS_TOOLTIP)
| 3,243 | Python | 42.837837 | 119 | 0.50848 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extensions_all.py | """Support for the widget that dumps the categories OmniGraph knows about."""
import json
from typing import Callable
import omni.graph.core as og
import omni.graph.tools as ogt
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
__all__ = ["ToolkitWidgetExtensionsAll"]
# ==============================================================================================================
class ToolkitWidgetExtensionsAll:
ID = "ExtensionsAll"
LABEL = "Nodes In All Extensions"
TOOLTIP = "List all known extensions containing OmniGraph nodes and the nodes they contain"
RESULTS_TOOLTIP = "All known extensions containing OmniGraph nodes and the nodes they contain"
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable, extension_information: og.ExtensionInformation):
self.__button = None
self.__extension_information = extension_information
self.__set_output = set_output_callback
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__extension_information")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the list of nodes and their extensions from the scene"""
self.__button = DestructibleButton(
self.LABEL,
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
# --------------------------------------------------------------------------------------------------------------
def __on_click(self):
"""Callback executed when the Extensions All button is clicked"""
try:
enabled_extensions, disabled_extensions = self.__extension_information.get_node_types_by_extension()
text = json.dumps({"enabled": enabled_extensions, "disabled": disabled_extensions}, indent=4)
except Exception as error: # noqa: PLW0703
text = str(error)
self.__set_output(text, self.RESULTS_TOOLTIP)
| 2,426 | Python | 43.127272 | 119 | 0.54493 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extensions_missing.py | """Support for the widget that dumps the categories OmniGraph knows about."""
from typing import Callable
import omni.graph.core as og
import omni.graph.tools as ogt
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
__all__ = ["ToolkitWidgetExtensionsMissing"]
# ==============================================================================================================
class ToolkitWidgetExtensionsMissing:
ID = "ExtensionsMissing"
LABEL = "Node Extensions Missing"
TOOLTIP = "List any extensions required by OmniGraph nodes in the scene that are not currently enabled"
RESULTS_TOOLTIP = "Extensions required by OmniGraph nodes in the scene that are not currently enabled"
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable, extension_information: og.ExtensionInformation):
self.__button = None
self.__extension_information = extension_information
self.__set_output = set_output_callback
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__extension_information")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the list of nodes and their extensions from the scene"""
self.__button = DestructibleButton(
self.LABEL,
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
# --------------------------------------------------------------------------------------------------------------
def __on_click(self):
"""Callback executed when the Extensions Missing button is clicked"""
try:
_, disabled_node_types = self.__extension_information.get_nodes_by_extension()
try:
text = str(disabled_node_types)
except KeyError:
text = "[]"
except Exception as error: # noqa: PLW0703
text = str(error)
self.__set_output(text, self.RESULTS_TOOLTIP)
| 2,444 | Python | 41.894736 | 119 | 0.530687 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/graph_registry.py | """Support for the widget that dumps the categories OmniGraph knows about."""
from typing import Callable
import omni.graph.core as og
import omni.graph.tools as ogt
import omni.ui as ui
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
from ..toolkit_utils import help_button
from .flag_manager import FlagManager
__all__ = ["ToolkitWidgetGraphRegistry"]
# ==============================================================================================================
class ToolkitWidgetGraphRegistry:
ID = "DumpGraphRegistry"
TOOLTIP = "Dump the contents of the current OmniGraph registry to the console"
FLAGS = {
"jsonFlagAttributes": ("attributes", "Show the attributes on registered node types", False),
"jsonFlagDetails": ("nodeTypes", "Show the details of the registered node types", False),
}
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable):
self.__button = None
self.__flag_managers = {}
self.__help_button = None
self.__set_output = set_output_callback
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__flag_managers")
ogt.destroy_property(self, "__help_button")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the graph registry"""
self.__button = DestructibleButton(
"Dump Registry",
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True))
assert self.__help_button
for checkbox_id, (flag, tooltip, default_value) in self.FLAGS.items():
self.__flag_managers[checkbox_id] = FlagManager(checkbox_id, flag, tooltip, default_value)
with ui.HStack(spacing=5):
self.__flag_managers[checkbox_id].checkbox()
# --------------------------------------------------------------------------------------------------------------
def __on_click(self, force_help: bool = False):
"""Callback executed when the Dump Registry button is clicked"""
if force_help:
flags = ["help"]
else:
flags = [flag_manager.name for flag_manager in self.__flag_managers.values() if flag_manager.is_set]
tooltip = f"OmniGraph registry contents, filtered with flags {flags}"
text = og.OmniGraphInspector().as_json(og.GraphRegistry(), flags=flags)
self.__set_output(text, tooltip)
| 3,007 | Python | 41.366197 | 116 | 0.545727 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/flag_manager.py | """Helper to manage a checkbox flag from a list that are attached to various widgets"""
import omni.graph.tools as ogt
import omni.ui as ui
# ==============================================================================================================
class FlagManager:
"""Base class to manage values and checkboxes for flags attached to inspection widgets"""
FLAG_COLUMN_WIDTH = 80
"""Constant width used for flag checkboxes"""
def __init__(self, flag_id: str, flag_name: str, flag_tooltip: str, flag_default: bool):
self.__id = flag_id
self.__name = flag_name
self.__tooltip = flag_tooltip
self.__value = flag_default
self.__default_value = flag_default
self.__checkbox = None
self.__checkbox_model = None
# --------------------------------------------------------------------------------------------------------------
def destroy(self):
ogt.destroy_property(self, "__id")
ogt.destroy_property(self, "__name")
ogt.destroy_property(self, "__tooltip")
ogt.destroy_property(self, "__default_value")
ogt.destroy_property(self, "__value")
ogt.destroy_property(self, "__checkbox_model")
ogt.destroy_property(self, "__checkbox")
# --------------------------------------------------------------------------------------------------------------
@property
def default_value(self) -> str:
"""Returns the default value of this flag as it will be used by the inspector"""
return self.__default_value
# --------------------------------------------------------------------------------------------------------------
@property
def name(self) -> str:
"""Returns the name of this flag as it will be used by the inspector"""
return self.__name
# --------------------------------------------------------------------------------------------------------------
@property
def tooltip(self) -> str:
"""Returns the tooltip of this flag as it will be used by the inspector"""
return self.__tooltip
# --------------------------------------------------------------------------------------------------------------
@property
def is_set(self) -> bool:
"""Returns True if the flag is currently set to True"""
return self.__value
# --------------------------------------------------------------------------------------------------------------
def __on_flag_set(self, mouse_x: int, mouse_y: int, mouse_button: int, value: str):
"""Callback executed when there is a request to change status of one of the inspection flags"""
if mouse_button == 0:
new_flag_value = not self.__checkbox.model.as_bool
self.__value = new_flag_value
# --------------------------------------------------------------------------------------------------------------
def checkbox(self):
"""Define the checkbox that manages this flag's value"""
self.__checkbox_model = ui.SimpleIntModel(self.__value)
self.__checkbox = ui.CheckBox(
model=self.__checkbox_model,
alignment=ui.Alignment.RIGHT_BOTTOM,
mouse_released_fn=self.__on_flag_set,
name=self.__id,
width=0,
tooltip=self.__tooltip,
style_type_name_override="WhiteCheck",
)
ui.Label(self.__name, alignment=ui.Alignment.LEFT_TOP, width=self.FLAG_COLUMN_WIDTH, tooltip=self.__tooltip)
| 3,513 | Python | 44.636363 | 116 | 0.45232 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/graph_structure.py | """Support for the widget that dumps the categories OmniGraph knows about."""
import json
from typing import Callable
import omni.graph.core as og
import omni.graph.tools as ogt
import omni.ui as ui
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
from ..toolkit_utils import help_button
from .flag_manager import FlagManager
__all__ = ["ToolkitWidgetGraphStructure"]
# ==============================================================================================================
class ToolkitWidgetGraphStructure:
ID = "DumpGraphStructure"
TOOLTIP = "Dump the contents of all OmniGraphs to the console"
FLAGS = {
"jsonFlagAttributes": ("attributes", "Show the attributes on nodes in the graph", False),
"jsonFlagConnections": ("connections", "Show the connections between nodes in the graph", False),
"jsonFlagEvaluation": ("evaluation", "Show the details of the graph evaluator", False),
}
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable):
self.__button = None
self.__flag_managers = {}
self.__help_button = None
self.__set_output = set_output_callback
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__flag_managers")
ogt.destroy_property(self, "__help_button")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the node type categories"""
self.__button = DestructibleButton(
"Dump Graph",
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True))
assert self.__help_button
for checkbox_id, (flag, tooltip, default_value) in self.FLAGS.items():
self.__flag_managers[checkbox_id] = FlagManager(checkbox_id, flag, tooltip, default_value)
with ui.HStack(spacing=5):
self.__flag_managers[checkbox_id].checkbox()
# --------------------------------------------------------------------------------------------------------------
def __on_click(self, force_help: bool = False):
"""Callback executed when the Dump Graph button is clicked"""
if force_help:
flags = ["help"]
else:
flags = [flag_manager.name for flag_manager in self.__flag_managers.values() if flag_manager.is_set]
tooltip = f"OmniGraph contents, filtered with flags {flags}"
graph_info = {}
json_string = "Could not create output"
for graph in og.get_all_graphs():
try:
json_string = og.OmniGraphInspector().as_json(graph, flags=flags)
graph_info[graph.get_path_to_graph()] = json.loads(json_string)
except json.JSONDecodeError as error:
self.__set_output(f"Error decoding json for graph {graph.get_path_to_graph()}: {error}\n{json_string}")
return
text = json.dumps(graph_info, indent=4)
self.__set_output(text, tooltip)
| 3,552 | Python | 42.329268 | 119 | 0.549268 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extension_dependencies.py | """Support for the toolkit widget that shows OmniGraph downstream dependencies.
The output is in a hierarchy showing the dependencies of the various omni.graph extensions. Since these have their
own internal dependencies you can find all OmniGraph dependencies just by looking at the list for omni.graph.core
"""
import asyncio
import json
from contextlib import suppress
from pathlib import Path
from typing import Callable, Dict, List, Tuple
import carb
import omni.graph.tools as ogt
import omni.kit
import omni.ui as ui
from omni.kit.window.extensions.common import build_ext_info
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
from ..toolkit_utils import help_button
from .flag_manager import FlagManager
__all__ = ["ToolkitWidgetExtensionDependencies"]
# ==============================================================================================================
class ToolkitWidgetExtensionDependencies:
ID = "DumpExtensionDependencies"
LABEL = "Extensions"
TOOLTIP = "Dump information on extension dependencies on OmniGraph"
FLAGS = {
"flagAll": ("all", "Include dependencies on all omni.graph extensions, not just omni.graph.core", False),
"flagVerbose": ("verbose", "Include the list of nodes that are defined inside dependent extensions", False),
}
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable):
self.__button = None
self.__ext_information = {}
self.__flag_managers = {}
self.__help_button = None
self.__set_output = set_output_callback
self.__dependents_calculated = False
self.__dependents_expansions_calculated = False
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__ext_information")
ogt.destroy_property(self, "__flag_managers")
ogt.destroy_property(self, "__help_button")
ogt.destroy_property(self, "__set_output")
ogt.destroy_property(self, "__dependents_calculated")
ogt.destroy_property(self, "__dependents_expansions_calculated")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the extension information"""
self.__button = DestructibleButton(
self.LABEL,
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True))
assert self.__help_button
for checkbox_id, (flag, tooltip, default_value) in self.FLAGS.items():
self.__flag_managers[checkbox_id] = FlagManager(checkbox_id, flag, tooltip, default_value)
with ui.HStack(spacing=5):
self.__flag_managers[checkbox_id].checkbox()
# --------------------------------------------------------------------------------------------------------------
def __populate_extension_information(self):
"""Use the extension manager to find out all of the details for known extensions.
Populates self.__ext_information as a dictionary where:
KEY: Name of the extension (with version information stripped)
VALUE: Tuple(ExtensionCommonInfo, Extension Dictionary)
"""
if self.__ext_information:
return
manager = omni.kit.app.get_app().get_extension_manager()
carb.log_info("Syncing extension registry. May take a minute...")
asyncio.ensure_future(omni.kit.app.get_app().next_update_async())
manager.sync_registry() # Make sure all extensions are available
known_extensions = manager.fetch_extension_summaries()
# Use the utility to convert all of the extension information into a more processing friendly format.
# The latest version is used, although if we wanted to be thorough there would be entries for every version
# since they could potentially have different dependencies.
for extension in known_extensions:
latest_version = extension["latest_version"]
ext_id = latest_version["id"]
ext_name = latest_version["name"]
package_id = latest_version["package_id"]
self.__ext_information[ext_name] = build_ext_info(ext_id, package_id)
# --------------------------------------------------------------------------------------------------------------
def __expand_downstream_extension_dependencies(self, ext_name: str):
"""Expand the upstream dependencies of the given extension
Args:
ext_name: Name of the extension being expanded
"""
(_, ext_info) = self.__ext_information[ext_name]
if ext_info.get("full_dependents", None) is not None:
return ext_info["full_dependents"]
ext_info["full_dependents"] = set()
for ext_downstream in ext_info.get("dependents", []):
ext_info["full_dependents"].add(ext_downstream)
ext_info["full_dependents"].update(self.__expand_downstream_extension_dependencies(ext_downstream))
return ext_info["full_dependents"]
# --------------------------------------------------------------------------------------------------------------
def __expand_downstream_dependencies(self):
"""Take the existing one-step dependencies and expand them into lists of everything upstream of an extension"""
# Only do this once
if self.__dependents_expansions_calculated:
return
self.__dependents_expansions_calculated = True
for ext_name in self.__ext_information:
self.__expand_downstream_extension_dependencies(ext_name)
# --------------------------------------------------------------------------------------------------------------
def __create_downstream_dependencies(self):
"""Take the existing set of downstream dependencies on every extension and compute the equivalent upstream
dependencies, adding them to the extension information
"""
# Only do this once
if self.__dependents_calculated:
return
self.__dependents_calculated = True
for ext_name, (_, ext_info) in self.__ext_information.items():
dependencies = ext_info.get("dependencies", {})
for ext_dependency in dependencies:
with suppress(KeyError):
(_, dependencies_info) = self.__ext_information[ext_dependency]
dependencies_info["dependents"] = dependencies_info.get("dependents", []) + [ext_name]
# --------------------------------------------------------------------------------------------------------------
def __get_dependent_output(self, ext_name: str) -> Dict[str, List[str]]:
"""Returns a dictionary of repo_name:extensions_in_repo that are dependents of the 'ext_name' extension"""
(_, ext_info) = self.__ext_information[ext_name]
dependencies_by_repo = {}
for dependent in ext_info.get("full_dependents", []):
with suppress(KeyError):
repo = self.__ext_information[dependent][0].repository
if not repo and self.__ext_information[dependent][0].is_kit_file:
repo = "https://gitlab-master.nvidia.com/omniverse/kit"
dependencies_by_repo[repo] = dependencies_by_repo.get(repo, set())
dependencies_by_repo[repo].add(dependent)
return {repo: list(repo_dependencies) for repo, repo_dependencies in dependencies_by_repo.items()}
# --------------------------------------------------------------------------------------------------------------
def __add_nodes_to_extensions(
self, output: Dict[str, List[str]]
) -> Tuple[Dict[str, Dict[str, List[str]]], Dict[str, List[str]]]:
"""Take the dictionary of extension_repo:extension_names[] and add per-extension node information to return
(extension_repo:{extension_name:nodes_in_extension},extension_repo:{extension_name[apps_using_extension]})
"""
# If showing the nodes then transform the list of extension names to a dictionary of extension:node_list
extensions_with_nodes = {}
apps_with_nodes = {}
for repo, repo_dependencies in output.items():
extensions_with_nodes[repo] = {}
for ext_name in repo_dependencies:
try:
extensions_with_nodes[repo][ext_name] = []
ogn_node_file = Path(self.__ext_information[ext_name][0].path) / "ogn" / "nodes.json"
if ogn_node_file.is_file():
with open(ogn_node_file, "r", encoding="utf-8") as nodes_fd:
json_nodes = json.load(nodes_fd)["nodes"]
extensions_with_nodes[repo][ext_name] = list(json_nodes.keys())
else:
raise AttributeError
except (AttributeError, KeyError, json.decoder.JSONDecodeError):
if str(self.__ext_information[ext_name][0].path).endswith(".kit"):
apps_with_nodes[repo] = apps_with_nodes.get(repo, []) + [ext_name]
elif self.__ext_information[ext_name][0].is_local:
extensions_with_nodes[repo][ext_name] = []
else:
extensions_with_nodes[repo][ext_name] = "--- Install Extension To Get Node List ---"
return extensions_with_nodes, apps_with_nodes
# --------------------------------------------------------------------------------------------------------------
def __on_click(self, force_help: bool = False):
"""Callback executed when the Dump Graph button is clicked"""
if force_help:
flags = ["help"]
text = (
"Dump the dependencies of other extensions on the OmniGraph extensions.\n"
"The following flags are accepted:\n"
)
for flag_manager in self.__flag_managers.values():
text += f" {flag_manager.name} ({flag_manager.default_value}): {flag_manager.tooltip}\n"
self.__set_output(text, "Help Information")
return
flags = [flag_manager.name for flag_manager in self.__flag_managers.values() if flag_manager.is_set]
tooltip = f"OmniGraph extension dependencies, filtered with flags {flags}"
# Clean out the information so that the extensions can be reread each time. There is no callback when extensions
# are installed or updated so this is the only way to ensure correct information.
self.__ext_information = {}
self.__dependents_calculated = False
self.__dependents_expansions_calculated = False
# Get all of the extension information for analysis
self.__populate_extension_information()
# If the "all" flag is set then scan the extensions to get the ones starting with omni.graph
# Doing this instead of using a hardcoded list future-proofs us.
omnigraph_extensions = ["omni.graph.core"]
if "all" in flags:
omnigraph_extensions = []
for ext_name in self.__ext_information:
if ext_name.startswith("omni.graph"):
omnigraph_extensions.append(ext_name)
include_nodes = "verbose" in flags
output = {
"flags": {
"verbose": include_nodes,
"extensions": omnigraph_extensions,
},
"paths": {ext: self.__ext_information[ext][0].path for ext in omnigraph_extensions},
"apps": {},
}
# Add direct downstream dependencies to the extension info based on the known dependencies
self.__create_downstream_dependencies()
# Expand the entire downstream tree of dependencies for all extensions based on the computed edges
self.__expand_downstream_dependencies()
# Populate the per-extension output for each of the requested output extensions
for ext_name in omnigraph_extensions:
output[ext_name] = self.__get_dependent_output(ext_name)
if include_nodes:
(output[ext_name], output["apps"][ext_name]) = self.__add_nodes_to_extensions(output[ext_name])
# Pipe the output to the final destination
self.__set_output(json.dumps(output, indent=4), tooltip)
| 12,847 | Python | 49.384314 | 120 | 0.572741 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/categories.py | """Support for the widget that dumps the categories OmniGraph knows about."""
import json
from typing import Callable
import omni.graph.core as og
import omni.graph.tools as ogt
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
from ..toolkit_utils import help_button
__all__ = ["ToolkitWidgetCategories"]
# ==============================================================================================================
class ToolkitWidgetCategories:
ID = "DumpCategories"
TOOLTIP = "Dump out the list of recognized node type categories"
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable):
self.__button = None
self.__help_button = None
self.__set_output = set_output_callback
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__help_button")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the node type categories"""
self.__button = DestructibleButton(
"Dump Categories",
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True))
assert self.__help_button
# --------------------------------------------------------------------------------------------------------------
def __on_click(self, force_help: bool = False):
"""Callback executed when the Dump Categories button is clicked"""
if force_help:
text = json.dumps({"help": "Dump the current list of recognized node type categories"}, indent=4)
else:
categories = {}
interface = og.get_node_categories_interface()
for category_name, category_description in interface.get_all_categories().items():
categories[category_name] = category_description
text = json.dumps({"nodeTypeCategories": categories}, indent=4)
tooltip = "Node Type Categories"
self.__set_output(text, tooltip)
| 2,529 | Python | 41.166666 | 116 | 0.524318 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/extensions_used.py | """Support for the widget that dumps the categories OmniGraph knows about."""
import json
from typing import Callable
import omni.graph.core as og
import omni.graph.tools as ogt
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
__all__ = ["ToolkitWidgetExtensionsUsed"]
# ==============================================================================================================
class ToolkitWidgetExtensionsUsed:
ID = "ExtensionsUsed"
LABEL = "Extensions Used By Nodes"
TOOLTIP = "List all of the extensions used by OmniGraph nodes in the scene"
RESULTS_TOOLTIP = "Extensions used by OmniGraph nodes in the scene"
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable, extension_information: og.ExtensionInformation):
self.__button = None
self.__extension_information = extension_information
self.__set_output = set_output_callback
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__extension_information")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the list of nodes and their extensions from the scene"""
self.__button = DestructibleButton(
self.LABEL,
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
# --------------------------------------------------------------------------------------------------------------
def __on_click(self):
"""Callback executed when the Extensions Used button is clicked"""
try:
enabled_node_types, _ = self.__extension_information.get_nodes_by_extension()
text = json.dumps(enabled_node_types, indent=4)
except Exception as error: # noqa: PLW0703
text = str(error)
self.__set_output(text, self.RESULTS_TOOLTIP)
| 2,319 | Python | 41.181817 | 119 | 0.530401 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_toolkit/widgets/fabric_contents.py | """Support for the widget that dumps the categories OmniGraph knows about."""
import json
from typing import Callable
import omni.graph.core as og
import omni.graph.tools as ogt
import omni.ui as ui
from ...style import BUTTON_WIDTH
from ...utils import DestructibleButton
from ..toolkit_utils import help_button
from .flag_manager import FlagManager
__all__ = ["ToolkitWidgetFabricContents"]
# ==============================================================================================================
class ToolkitWidgetFabricContents:
ID = "DumpFabricContents"
TOOLTIP = "Dump the contents of the OmniGraph Fabric cache"
# ----------------------------------------------------------------------
# Checkboxes representing flags for the JSON serialization of the graph context and graph objects
# KEY: ID of the checkbox for the flag
# VALUE: (Label Text, Tooltip Text, Default Value)
FLAGS = {
"jsonFlagMaps": ("maps", "Show the context-independent attribute mapping information", False),
"jsonFlagDetails": ("noDataDetail", "Hide the detailed attribute data in FlatCache", False),
"jsonFlagLimit": ("limit", "Limit the number of output array elements to 100", False),
"jsonFlagUnreferenced": ("unreferenced", "Show the connections between nodes in the graph", False),
}
# ----------------------------------------------------------------------
def __init__(self, set_output_callback: Callable):
self.__button = None
self.__flag_managers = {}
self.__help_button = None
self.__set_output = set_output_callback
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the widgets are being deleted to provide clean removal and prevent leaks"""
ogt.destroy_property(self, "__button")
ogt.destroy_property(self, "__flag_managers")
ogt.destroy_property(self, "__help_button")
ogt.destroy_property(self, "__set_output")
# ----------------------------------------------------------------------
def build(self):
"""Build the UI section with the functionality to dump the contents of Fabric"""
self.__button = DestructibleButton(
"Dump Fabric",
name=self.ID,
width=BUTTON_WIDTH,
tooltip=self.TOOLTIP,
clicked_fn=self.__on_click,
)
assert self.__button
self.__help_button = help_button(lambda x, y, b, m: self.__on_click(force_help=True))
assert self.__help_button
for checkbox_id, (flag, tooltip, default_value) in self.FLAGS.items():
self.__flag_managers[checkbox_id] = FlagManager(checkbox_id, flag, tooltip, default_value)
with ui.HStack(spacing=5):
self.__flag_managers[checkbox_id].checkbox()
# --------------------------------------------------------------------------------------------------------------
def __on_click(self, force_help: bool = False):
"""Callback executed when the Dump Fabric button is clicked"""
result = []
if force_help:
flags = ["help"]
else:
flags = [flag_manager.name for flag_manager in self.__flag_managers.values() if flag_manager.is_set]
tooltip = f"Fabric contents, filtered with flags {flags}"
for ctx in og.get_compute_graph_contexts():
json_string = "Not generated"
try:
json_string = og.OmniGraphInspector().as_json(ctx, flags=flags)
result.append(json.loads(json_string))
except json.JSONDecodeError as error:
self.__set_output(f"Error decoding json for context {ctx}: {error}\n{json_string}", json_string)
return
self.__set_output(json.dumps(result, indent=4), tooltip)
| 3,872 | Python | 44.034883 | 116 | 0.551136 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/templates/template_SetViewportMode.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
import omni.graph.core as og
import omni.ui as ui
from omni.graph.ui import OmniGraphBase
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH
from pxr import Sdf, Usd
ATTRIB_LABEL_STYLE = {"alignment": ui.Alignment.RIGHT_TOP}
MODE_NAMES = ["Default", "Scripted"]
class ModeAttributeModel(ui.AbstractItemModel, OmniGraphBase):
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, item, value):
super().__init__()
self.token = item
self.model = ui.SimpleStringModel(value)
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict):
OmniGraphBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._allowed_tokens = [ModeAttributeModel.AllowedTokenItem(i, t) for i, t in enumerate(MODE_NAMES)]
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._updating_value = False
self._has_index = False
self._update_value()
self._has_index = True
def get_item_children(self, item):
return self._allowed_tokens
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def _current_index_changed(self, model):
if not self._has_index:
return
# if we're updating from USD notice change to UI, don't call set_value
if self._updating_value:
return
index = model.as_int
if self.set_value(index):
self._item_changed(None)
def _update_value(self, force=False):
was_updating_value = self._updating_value
self._updating_value = True
if (
OmniGraphBase._update_value(self, force)
and (0 <= self._value < len(self._allowed_tokens))
and (self._value != self._current_index.as_int)
):
self._current_index.set_value(self._value)
self._item_changed(None)
self._updating_value = was_updating_value
def _on_dirty(self):
self._item_changed(None)
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.controller = og.Controller()
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = self.controller.node(self.node_prim_path)
self.mode_model = None
def _mode_build_fn(self, *args):
with ui.HStack(spacing=HORIZONTAL_SPACING):
ui.Label("Mode", name="label", style=ATTRIB_LABEL_STYLE, width=LABEL_WIDTH)
ui.Spacer(width=HORIZONTAL_SPACING)
with ui.ZStack():
attr_path = self.node_prim_path.AppendProperty("inputs:mode")
self.mode_model = ModeAttributeModel(self.compute_node_widget.stage, [attr_path], False, {})
ui.ComboBox(self.mode_model)
# Called by compute_node_widget to apply UI when selection changes
def apply(self, props):
def find_prop(name):
return next((p for p in props if p.prop_name == name), None)
# Retrieve the input and output attributes that exist on the node
all_attributes = self.node.get_attributes()
input_attribs = [
attrib.get_name()
for attrib in all_attributes
if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT
and attrib.get_name()[:7] == "inputs:"
and attrib.get_resolved_type().role != og.AttributeRole.EXECUTION
]
output_attribs = [
attrib.get_name()
for attrib in all_attributes
if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT
and attrib.get_name()[:8] == "outputs:"
and attrib.get_resolved_type().role != og.AttributeRole.EXECUTION
]
mode_attrib = "inputs:mode"
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
# Custom enum-style input for inputs:mode
prop = find_prop(mode_attrib)
if prop is not None:
CustomLayoutProperty(prop.prop_name, mode_attrib[7:], self._mode_build_fn)
for input_attrib in input_attribs:
prop = find_prop(input_attrib)
if prop is not None and input_attrib != mode_attrib:
CustomLayoutProperty(prop.prop_name, input_attrib[7:])
with CustomLayoutGroup("Outputs"):
for output_attrib in output_attribs:
prop = find_prop(output_attrib)
if prop is not None:
CustomLayoutProperty(prop.prop_name, output_attrib[8:])
return frame.apply(props)
| 5,591 | Python | 37.833333 | 113 | 0.626185 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/templates/template_Button.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 functools import partial
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
self.icon_textbox_widgets = {}
self.icon_selector_window = None
self.icon_selector_window_previous_directory = None
self.icon_attribs = [
"inputs:idleIcon",
"inputs:hoverIcon",
"inputs:pressedIcon",
"inputs:disabledIcon",
]
def show_icon_selector_window(self, icon_attrib_name: str):
# Create and show the file browser window which is used to select icon
try:
from omni.kit.window.filepicker import FilePickerDialog
except ImportError:
# Do nothing if the module cannot be imported
return
def __on_click_okay(filename: str, dirname: str):
# Hardcode a forward slash rather than using os.path.join,
# because the dirname will always use forward slash even on Windows machines
chosen_file = dirname + "/" + filename
self.icon_textbox_widgets[icon_attrib_name].set_value(chosen_file)
self.icon_selector_window_previous_directory = self.icon_selector_window.get_current_directory()
self.icon_selector_window.hide()
def __on_click_cancel(file_name: str, directory_name: str):
self.icon_selector_window_previous_directory = self.icon_selector_window.get_current_directory()
self.icon_selector_window.hide()
self.icon_selector_window = FilePickerDialog(
"Select an Icon",
click_apply_handler=__on_click_okay,
click_cancel_handler=__on_click_cancel,
allow_multi_selection=False,
)
self.icon_selector_window.show(self.icon_selector_window_previous_directory)
def icon_attrib_build_fn(self, ui_prop: UsdPropertyUiEntry, *args):
# Build the attribute label, textbox and browse button that's displayed on the property panel
icon_attrib_name = ui_prop.prop_name
self.icon_textbox_widgets[icon_attrib_name] = UsdPropertiesWidgetBuilder._string_builder( # noqa: PLW0212
self.compute_node_widget.stage,
icon_attrib_name,
ui_prop.property_type,
ui_prop.metadata,
[self.node_prim_path],
{"style": {"alignment": ui.Alignment.RIGHT_TOP}},
)
ui.Spacer(width=5)
ui.Button(
"Browse",
width=0,
clicked_fn=partial(self.show_icon_selector_window, icon_attrib_name),
)
def apply(self, props):
# Called by compute_node_widget to apply UI when selection changes
def find_prop(name):
try:
return next((p for p in props if p.prop_name == name))
except StopIteration:
return None
# Retrieve the input and output attributes that exist on the node
all_attributes = self.node.get_attributes()
input_attribs = [
attrib.get_name()
for attrib in all_attributes
if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT
and attrib.get_name()[:7] == "inputs:"
]
output_attribs = [
attrib.get_name()
for attrib in all_attributes
if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT
and attrib.get_name()[:8] == "outputs:"
]
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for input_attrib in input_attribs:
prop = find_prop(input_attrib)
if prop is not None and input_attrib not in self.icon_attribs:
CustomLayoutProperty(prop.prop_name, input_attrib[7:])
for icon_attrib in self.icon_attribs:
prop = find_prop(icon_attrib)
if prop is not None:
build_fn = partial(self.icon_attrib_build_fn, prop)
CustomLayoutProperty(prop.prop_name, icon_attrib[7:], build_fn)
with CustomLayoutGroup("Outputs"):
for output_attrib in output_attribs:
prop = find_prop(output_attrib)
if prop is not None:
CustomLayoutProperty(prop.prop_name, output_attrib[8:])
return frame.apply(props)
| 5,416 | Python | 41.653543 | 114 | 0.624631 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/metadata_manager.py | """
Classes and functions relating to the handling of both attribute and node metadata in the OgnNodeDescriptionEditor
"""
from contextlib import suppress
from typing import Callable, Dict, Optional
import carb
import omni.graph.tools as ogt
from omni import ui
from ..style import name_value_hstack, name_value_label # noqa: PLE0402
from .ogn_editor_utils import DestructibleButton, find_unique_name
# ======================================================================
class NameValueTreeManager:
"""Class that provides a simple interface to ui.TreeView model and delegate management for name/value lists.
Class Hierarchy Properties:
_model: NameValueModel containing a single name:value element
_delegate: EditableDelegate object managing the tree view interaction
Usage:
def __on_model_changed(new_dictionary):
print(f"Model changed to {new_dictionary})
my_dictionary = {"Hello": "Greeting", "World": "Scope"}
my_manager = NameValueTreeManager(my_dictionary, __on_model_changed)
ui.TreeView(my_manager.model)
"""
# ----------------------------------------------------------------------
class NameValueModel(ui.AbstractItemModel):
"""Represents the model for name-value table."""
class NameValueItem(ui.AbstractItem):
"""Single key/value pair in the model, plus the index in the overall model of this item"""
def __init__(self, key: str, value: str):
"""Initialize both of the models to the key/value pairs"""
super().__init__()
self.name_model = ui.SimpleStringModel(key)
self.value_model = ui.SimpleStringModel(value)
def destroy(self):
"""Destruction of the underlying models"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
ogt.destroy_property(self, "name_model")
ogt.destroy_property(self, "value_model")
def __repr__(self):
"""Return a nice representation of the string pair"""
return f'NameValueModel("{self.name_model.as_string} : {self.value_model.as_string}")'
# ----------------------------------------------------------------------
def __init__(self, metadata_values: Dict[str, str]):
"""Initialize the children into sorted tuples from the dictionary"""
ogt.dbg_ui(f"NameValueModel({metadata_values}))")
super().__init__()
self.__children = []
self.__metadata_values = {}
self.set_values(metadata_values)
def destroy(self):
"""Cleanup when the model is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__metadata_values = None
ogt.destroy_property(self, "__children")
def set_values(self, metadata_values: Dict[str, str]):
"""Define the children based on the new dictionary of key/value pairs"""
ogt.dbg_ui(f"Set values in NameValueModel to {metadata_values}")
self.__metadata_values = metadata_values
self.__rebuild_children()
def __rebuild_children(self):
"""Set the child string list, either for the initial state or after editing"""
ogt.dbg_ui(f"Rebuilding children from {self.__metadata_values}")
self.__children = [
self.NameValueItem(key, self.__metadata_values[key]) for key in sorted(self.__metadata_values.keys())
]
# Insert a blank entry at the begining for adding new values
self.__children.append(self.NameValueItem("", ""))
self._item_changed(None)
def add_child(self):
"""Add a new default child to the list"""
ogt.dbg_ui("Add a new key/value pair")
suggested_name = find_unique_name("metadataName", self.__metadata_values)
self.__metadata_values[suggested_name] = "metadataValue"
self.__rebuild_children()
def remove_child(self, key_value: str):
"""Remove the child corresponding to the given item from the list"""
ogt.dbg_ui(f"Removing key {key_value}")
try:
del self.__metadata_values[key_value]
except KeyError:
carb.log_error(f"Could not find child with key value of {key_value} for removal")
self.__rebuild_children()
def get_item_count(self):
"""Returns the number of children (i.e. rows in the tree widget)."""
return len(self.__children)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return the empty list.
return item.model if item is not None else self.__children
def get_item_value_model_count(self, item):
"""The number of columns, always 2 since the data is key/value pairs"""
return 3
def get_item_value_model(self, item, column_id: int):
"""Returns the model for the item's column. Only columns 0 and 1 will be requested"""
return [item.name_model, item.name_model, item.value_model][column_id]
# ----------------------------------------------------------------------
class EditableDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
Internal Properties:
__add_button: Widget managing the button to add new elements
__remove_buttons: Widget list managing the button to remove existing elements
__stack_widgets: Widget list managing the editable fields
__subscription: Subscription object for the callback on end of an edit
__value_change_cb: Function to call when any values change
"""
def __init__(self, value_change_cb: Callable):
"""Initialize the state with no subscription on the end edit; it will be used later"""
super().__init__()
self.__add_button = None
self.__remove_buttons = []
self.__subscription = None
self.__value_change_cb = value_change_cb
self.__stack_widgets = []
def destroy(self):
"""Release any hanging references"""
ogt.destroy_property(self, "__add_button")
ogt.destroy_property(self, "__remove_buttons")
self.__subscription = None
self.__value_change_cb = None
with suppress(AttributeError):
for stack_widget in self.__stack_widgets:
stack_widget.set_mouse_double_clicked_fn(None)
self.__stack_widgets = []
def build_branch(self, model, item, column_id: int, level: int, expanded: bool):
"""Create a branch widget that opens or closes subtree"""
def build_header(self, column_id: int):
"""Set up the header entry at the named column"""
ogt.dbg_ui(f"Build header for column {column_id}")
header_style = "TreeView.Header"
if column_id == 0:
ui.Label("", width=20, style_type_name_override=header_style)
else:
ui.Label("Name" if column_id == 1 else "Value", style_type_name_override=header_style)
def __on_add_item(self, model):
"""Callback hit when the button to add a new item was pressed"""
ogt.dbg_ui("Add new item")
model.add_child()
if self.__value_change_cb is not None:
self.__value_change_cb(model)
def __on_remove_item(self, model, item):
"""Callback hit when the button to remove an existing item was pressed"""
ogt.dbg_ui(f"Remove item '{item.name_model.as_string}'")
model.remove_child(item.name_model.as_string)
if self.__value_change_cb is not None:
self.__value_change_cb(model)
def __on_double_click(self, button, field, label):
"""Called when the user double-clicked the item in TreeView"""
if button != 0:
return
ogt.dbg_ui(f"Double click on {label}")
# Make Field visible when double clicked
field.visible = True
field.focus_keyboard()
# When editing is finished (enter pressed of mouse clicked outside of the viewport)
self.__subscription = field.model.subscribe_end_edit_fn(
lambda m, f=field, l=label: self.__on_end_edit(m, f, l)
)
assert self.__subscription
def __on_end_edit(self, model, field, label):
"""Called when the user is editing the item and pressed Enter or clicked outside of the item"""
ogt.dbg_ui(f"Ended edit of '{label.text}' as '{model.as_string}'")
field.visible = False
label.text = model.as_string
# TODO: Verify that this is not duplicating an existing entry
self.__subscription = None
if self.__value_change_cb is not None:
self.__value_change_cb(model)
def build_widget(self, model, item, column_id: int, level: int, expanded: bool):
"""Create a widget per column per item"""
ogt.dbg_ui(
f"Build widget on {model.__class__.__name__} for item {item}"
f" in column {column_id} at {level} expansion {expanded}"
)
if column_id == 0:
if item.name_model.as_string:
self.__remove_buttons.append(
DestructibleButton(
width=20,
height=20,
style_type_name_override="RemoveElement",
clicked_fn=lambda: self.__on_remove_item(model, item),
)
)
else:
self.__add_button = DestructibleButton(
width=20,
height=20,
style_type_name_override="AddElement",
clicked_fn=lambda: self.__on_add_item(model),
)
assert self.__add_button
else:
stack = ui.ZStack(height=20)
with stack:
value_model = model.get_item_value_model(item, column_id)
if not item.name_model.as_string:
ui.Label("")
else:
label = ui.Label(value_model.as_string)
field = ui.StringField(value_model, visible=False)
# Start editing when double clicked
stack.set_mouse_double_clicked_fn(
lambda x, y, b, m, f=field, l=label: self.__on_double_click(b, f, l)
)
self.__stack_widgets.append(stack)
# ----------------------------------------------------------------------
def __init__(self, value_dictionary: Dict[str, str], value_change_cb: Optional[Callable]):
"""Initialize the model and delegate information from the dictionary"""
self._model = self.NameValueModel(value_dictionary)
self._delegate = self.EditableDelegate(value_change_cb)
# ----------------------------------------------------------------------
def destroy(self):
"""Cleanup when the manager is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self._model = None
self._delegate.destroy()
self._delegate = None
# ======================================================================
class MetadataManager(NameValueTreeManager):
"""Class that handles interaction with the node metadata fields."""
def list_values_changed(self, what):
new_metadata = {}
for child in self._model.get_item_children(None):
if child.name_model.as_string:
new_metadata[child.name_model.as_string] = child.value_model.as_string
# Edit the metadata based on new values and reset the widget to keep a single blank row
self.__controller.filtered_metadata = new_metadata
self._model.set_values(new_metadata)
def __init__(self, controller):
"""Initialize the fields inside the given controller and set up the initial frame"""
super().__init__(controller.filtered_metadata, self.list_values_changed)
self.__controller = controller
# Whenever values are updated the metadata list is synchronized with the set of non-empty metadata name models.
# This allows creation of new metadata values by adding text in the final empty field, and removal
# of existing metadata values by erasing the name. This avoids extra clutter in the UI with add/remove
# buttons, though it's important that the tooltip explain this.
with name_value_hstack():
name_value_label("Metadata:", "Name/Value pairs to store as metadata.")
self.__metadata_tree = ui.TreeView(
self._model,
delegate=self._delegate,
root_visible=False,
header_visible=True,
height=0,
column_widths=[30],
)
assert self.__metadata_tree
def destroy(self):
"""Destroy the widget and cleanup the callbacks"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
super().destroy()
ogt.destroy_property(self, "__metadata_tree")
self.__controller = None
| 13,902 | Python | 45.654362 | 119 | 0.555244 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/main_controller.py | """
Controller part of the Model-View-Controller providing editing capabilities to OGN files
"""
from typing import Dict, Union
import omni.graph.tools as ogt
from carb import log_warn
from .attribute_properties import AttributeListController
from .change_management import ChangeManager
from .main_model import Model
from .node_properties import NodePropertiesController
from .ogn_editor_utils import show_wip
from .test_configurations import TestListController
# TODO: Introduce methods in the node generator to allow translation between attribute type name and component values
# TODO: Immediate parsing, with parse errors shown in the "Raw" frame
# ======================================================================
class Controller(ChangeManager):
"""
Class responsible for coordinating changes to the OGN internal model.
External Properties:
ogn_data: Generated value of the OGN dictionary for the controlled model
Internal Properties:
__model: The main model being controlled, which encompasses all of the submodels
__node_properties_controller: Controller for the section containing node properties
__input_attribute_controller: Controller for the section containing input attributes
__output_attribute_controller: Controller for the section containing output attributes
__tests_controller: Controller for the section containing algorithm tests
"""
def __init__(self, model: Model, initial_contents: Union[None, str, Dict]):
"""Initialize the model being controlled"""
super().__init__()
self.__model = model
self.node_properties_controller = None
self.input_attribute_controller = None
self.output_attribute_controller = None
self.tests_controller = None
self.set_ogn_data(initial_contents)
# ----------------------------------------------------------------------
def destroy(self):
"""Called when the controller is destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
super().destroy()
# The main controller owns all sub-controllers so destroy them here
ogt.destroy_property(self, "node_properties_controller")
ogt.destroy_property(self, "input_attribute_controller")
ogt.destroy_property(self, "output_attribute_controller")
ogt.destroy_property(self, "tests_controller")
self.__model = None
# ----------------------------------------------------------------------
def set_ogn_data(self, new_contents: Union[None, str, Dict]):
"""Reset the underlying model to new values"""
ogt.dbg_ui(f"Controller: set_ogn_data to {new_contents}")
try:
self.__model.set_ogn_data(new_contents)
self.node_properties_controller = NodePropertiesController(self.__model.node_properties_model)
self.input_attribute_controller = AttributeListController(self.__model.input_attribute_model)
self.output_attribute_controller = AttributeListController(self.__model.output_attribute_model)
if show_wip():
self.tests_controller = TestListController(
self.__model.tests_model, self.input_attribute_controller, self.output_attribute_controller
)
# Change callbacks on the main controller should also be executed by the child controllers when they change
self.node_properties_controller.forward_callbacks_to(self)
self.input_attribute_controller.forward_callbacks_to(self)
self.output_attribute_controller.forward_callbacks_to(self)
if show_wip():
self.tests_controller.forward_callbacks_to(self)
except Exception as error: # noqa: PLW0703
log_warn(f"Error redefining the OGN data - {error}")
# ----------------------------------------------------------------------
@property
def ogn_data(self) -> Dict:
"""Return the current full OGN data content, reassembled from the component pieces"""
return self.__model.ogn_data
# ----------------------------------------------------------------------
def is_dirty(self) -> bool:
"""Return True if the contents have been modified since being set clean"""
return self.__model.is_dirty
# ----------------------------------------------------------------------
def set_clean(self):
"""Reset the current status of the data to be clean (e.g. after a file save)."""
ogt.dbg_ui("Controller: set_clean")
self.__model.set_clean()
| 4,607 | Python | 47 | 119 | 0.619926 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/change_management.py | """
Collection of classes to use for managing reactions to changes to models
"""
from typing import Callable, List, Optional, Union
import omni.graph.tools as ogt
# ======================================================================
class ChangeMessage:
"""Message packet to send when a change is encountered.
Created as a class so that other messages can override it and add more information.
External Properties:
caller: Object that triggered the change
"""
def __init__(self, caller):
"""Set up the basic message information"""
self.caller = caller
def __str__(self) -> str:
"""Return a string with the contents of the message"""
return str(self.caller.__class__.__name__)
# ================================================================================
class RenameMessage(ChangeMessage):
"""Encapsulation of a message sent when an attribute name changes"""
def __init__(self, caller, old_name: str, new_name: str):
"""Set up a message with information needed to indicate a name change"""
super().__init__(caller)
self.old_name = old_name
self.new_name = new_name
def __str__(self) -> str:
"""Returns a human-readable representation of the name change information"""
caller_info = super().__str__()
return f"Name change {self.old_name} -> {self.new_name} (from {caller_info})"
# ======================================================================
class ChangeManager:
"""Base class to provide the ability to set and react to value changes
External Properties:
callback_forwarders: List of change manager whose callbacks are also to be executed
change_callbacks: List of callbacks to invoke when a change happens
"""
def __init__(self, change_callbacks: Optional[Union[List, Callable]] = None):
"""Initialize the callback list"""
self.change_callbacks = []
self.callback_forwarders = []
if change_callbacks is not None:
self.add_change_callback(change_callbacks)
def destroy(self):
"""Called when the manager is being destroyed, usually from the derived class's destroy"""
self.change_callbacks = []
self.callback_forwarders = []
# ----------------------------------------------------------------------
def on_change(self, change_message=None):
"""Called when the controller has modified some data"""
ogt.dbg_ui(f"on_change({change_message})")
message = ChangeMessage(self) if change_message is None else change_message
# By passing in the caller we facilitate more intelligent responses with callback sharing
for callback in self.change_callbacks:
callback(message)
# Call all of the forwarded change callbacks as well, specifying this manager as the initiator
message.caller = self
for callback_forwarder in self.callback_forwarders:
ogt.dbg_ui(f"...forwarding change to {callback_forwarder.__class__.__name__}")
callback_forwarder.on_change(message)
# ----------------------------------------------------------------------
def add_change_callback(self, callback: Union[Callable, List[Callable]]):
"""Add a function to be called when the controller modifies some data"""
if isinstance(callback, list):
self.change_callbacks = callback
elif isinstance(callback, Callable):
self.change_callbacks.append(callback)
# ----------------------------------------------------------------------
def remove_change_callback(self, callback: Callable):
"""Remove a function to be called when the controller modifies some data"""
try:
if isinstance(callback, list):
_ = [self.remove_change_callback(child) for child in callback]
else:
self.change_callbacks.remove(callback)
except ValueError:
ogt.dbg_ui(f"Tried to remove non-existent callback {callback.name}")
# ----------------------------------------------------------------------
def forward_callbacks_to(self, parent_manager):
"""Set the callbacks on this change manager to include those existing on the parent
This is done lazily so that any new callbacks added later will also be handled.
Args:
parent_manager: ChangeManager whose callbacks are also to be executed by this manager
"""
self.callback_forwarders.append(parent_manager)
| 4,570 | Python | 41.324074 | 102 | 0.580744 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/attribute_list_manager.py | """
Manager class for the combo box that lets you select from a list of attribute names.
"""
from typing import Callable, List
import omni.graph.tools as ogt
from carb import log_warn
from omni import ui
from .ogn_editor_utils import ComboBoxOptions
# ======================================================================
# ID values for widgets that are editable or need updating
ID_ATTR_LIST = "attributeList"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {ID_ATTR_LIST: "Attribute name (without namespace)"}
# ======================================================================
class AttributeListComboBox(ui.AbstractItemModel):
"""Implementation of a combo box that shows attribute base data types available"""
def __init__(self, initial_value: str, available_attribute_names: List[str]):
"""Initialize the attribute base type combo box details"""
super().__init__()
self.__available_attribute_names = available_attribute_names
self.__current_index = ui.SimpleIntModel()
self.item_selected_callback = None
try:
self.__current_index.set_value(available_attribute_names.index(initial_value))
except ValueError:
log_warn(f"Initial attribute type {initial_value} not recognized")
self.__old_value = self.__current_index.as_int
self.__current_index.add_value_changed_fn(self.__on_attribute_selected)
# Using a list comprehension instead of values() guarantees the sorted ordering
self.__items = [ComboBoxOptions(attribute_type_name) for attribute_type_name in available_attribute_names]
def destroy(self):
"""Cleanup when the widget is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__available_attribute_names = None
ogt.destroy_property(self, "__current_index")
ogt.destroy_property(self, "__items")
def get_item_children(self, item):
"""Get the model children of this item"""
return self.__items
def get_item_value_model(self, item, column_id: int):
"""Get the model at the specified column_id"""
if item is None:
return self.__current_index
return item.model
def add_child(self, child_name: str):
"""Callback invoked when a child is added"""
self.__items.append(ComboBoxOptions(child_name))
self._item_changed(None)
def rename_child(self, old_name: str, new_name: str):
"""Callback invoked when a child is renamed"""
for item in self.__items:
if item.model.as_string == old_name:
ogt.dbg_ui("Found combo box item to rename")
item.model.set_value(new_name)
break
self._item_changed(None)
def remove_child(self, child_name: str):
"""Callback invoked when a child is removed to adjust for the fact that higher indexes must decrement"""
selected = self.__current_index.as_int
for (index, item) in enumerate(self.__items):
if item.model.as_string == child_name:
ogt.dbg_ui(f"Removing combo box item {index} = {child_name}")
if selected > index:
self.__current_index.set_value(selected - 1)
self.__items.pop(index)
break
index += 1
self._item_changed(None)
def __on_attribute_selected(self, new_value: ui.SimpleIntModel):
"""Callback executed when a new base type was selected"""
try:
ogt.dbg_ui(f"Set selected attribute to {new_value.as_int} from {self.__current_index.as_int}")
new_attribute_name = self.__available_attribute_names[new_value.as_int]
ogt.dbg_ui(f"Type name is {new_attribute_name}")
if self.item_selected_callback is not None:
ogt.dbg_ui(f"...calling into {self.item_selected_callback}")
self.item_selected_callback(new_attribute_name)
self.__old_value = new_value.as_int
except ValueError as error:
log_warn(f"Attribute selection rejected - {error}")
new_value.set_value(self.__old_value)
except KeyError as error:
log_warn(f"Attribute selection could not be found - {error}")
new_value.set_value(self.__old_value)
except IndexError:
log_warn(f"Attribute {new_value.as_int} was selected but there is no such attribute")
new_value.set_value(self.__old_value)
self._item_changed(None)
# ======================================================================
class AttributeListManager:
"""Handle the combo box and responses for getting and setting attribute base type values
Internal Properties:
__widget: ComboBox widget controlling the base type
__widget_model: Model for the ComboBox value
"""
def __init__(self, initial_value: str, available_attribute_names: List[str], item_selected_callback: Callable):
"""Set up the initial UI and model
Args:
initial_value: Initially selected value
available_attribute_names: List of potential names
"""
self.__widget_model = AttributeListComboBox(initial_value, available_attribute_names)
self.__widget_model.item_selected_callback = item_selected_callback
self.__widget = ui.ComboBox(
self.__widget_model, alignment=ui.Alignment.LEFT_BOTTOM, name=ID_ATTR_LIST, tooltip=TOOLTIPS[ID_ATTR_LIST]
)
assert self.__widget
def destroy(self):
"""Cleanup when the object is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
ogt.destroy_property(self, "__widget")
ogt.destroy_property(self, "__widget_model")
def on_child_added(self, child_name: str):
"""Callback invoked when a child is added"""
self.__widget_model.add_child(child_name)
def on_child_renamed(self, old_name: str, new_name: str):
"""Callback invoked when a child is renamed"""
self.__widget_model.rename_child(old_name, new_name)
def on_child_removed(self, child_name: str):
"""Callback invoked when a child is removed to adjust for the fact that higher indexes must decrement"""
self.__widget_model.remove_child(child_name)
| 6,413 | Python | 42.931507 | 118 | 0.609075 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/memory_type_manager.py | """
Support for the combo box representing the choice of attribute memory types.
Shared between the node and attribute properties since both allow that choice.
"""
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
from carb import log_warn
from omni import ui
from ..style import name_value_label # noqa: PLE0402
from .ogn_editor_utils import ComboBoxOptions
# ======================================================================
# ID values for widgets that are editable or need updating
ID_MEMORY_TYPE = "memoryType"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {ID_MEMORY_TYPE: "The physical location of attribute data. Attribute values override node values"}
# ======================================================================
class MemoryTypeComboBox(ui.AbstractItemModel):
"""Implementation of a combo box that shows types of memory locations available
Internal Properties:
__controller: Controller object manipulating the underlying memory model
__current_index: Model containing the combo box selection
__items: List of options available to choose from in the combo box
__subscription: Contains the scoped subscription object for value changes
"""
OPTION_CPU = "Store Attribute Memory on CPU"
OPTION_CUDA = "Store Attribute Memory on GPU (CUDA style)"
OPTION_ANY = "Choose Attribute Memory Location at Runtime"
OPTIONS = [ogn.MemoryTypeValues.CPU, ogn.MemoryTypeValues.CUDA, ogn.MemoryTypeValues.ANY]
OPTION_NAME = {
ogn.MemoryTypeValues.CPU: OPTION_CPU,
ogn.MemoryTypeValues.CUDA: OPTION_CUDA,
ogn.MemoryTypeValues.ANY: OPTION_ANY,
}
def __init__(self, controller):
"""Initialize the memory type combo box details"""
super().__init__()
self.__controller = controller
self.__current_index = ui.SimpleIntModel()
self.__current_index.set_value(self.OPTIONS.index(self.__controller.memory_type))
self.__subscription = self.__current_index.subscribe_value_changed_fn(self.__on_memory_type_changed)
assert self.__subscription
# Using a list comprehension instead of values() guarantees the ordering
self.__items = [ComboBoxOptions(self.OPTION_NAME[memory_type]) for memory_type in self.OPTIONS]
def destroy(self):
"""Called when the manager is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__controller = None
self.__subscription = None
ogt.destroy_property(self, "__current_index")
ogt.destroy_property(self, "__items")
def get_item_children(self, item):
"""Get the model children of this item"""
return self.__items
def get_item_value_model(self, item, column_id: int):
"""Get the model at the specified column_id"""
if item is None:
return self.__current_index
return item.model
def __on_memory_type_changed(self, new_value: ui.SimpleIntModel):
"""Callback executed when a new memory type was selected"""
try:
new_memory_type = self.OPTION_NAME[self.OPTIONS[new_value.as_int]]
ogt.dbg_ui(f"Set memory type to {new_value.as_int} - {new_memory_type}")
self.__controller.memory_type = self.OPTIONS[new_value.as_int]
self._item_changed(None)
except (AttributeError, KeyError) as error:
log_warn(f"Node memory type '{new_value.as_int}' was rejected - {error}")
# ======================================================================
class MemoryTypeManager:
"""Handle the combo box and responses for getting and setting the memory type location
Internal Properties:
__controller: Controller for the data of the attribute this will modify
__widget: ComboBox widget controlling the base type
__widget_model: Model for the ComboBox value
"""
def __init__(self, controller):
"""Set up the initial UI and model
Args:
controller: AttributePropertiesController in charge of the data for the attribute being managed
"""
self.__controller = controller
name_value_label("Memory Type:", TOOLTIPS[ID_MEMORY_TYPE])
self.__widget_model = MemoryTypeComboBox(controller)
self.__widget = ui.ComboBox(
self.__widget_model,
alignment=ui.Alignment.LEFT_BOTTOM,
name=ID_MEMORY_TYPE,
tooltip=TOOLTIPS[ID_MEMORY_TYPE],
)
assert self.__widget
assert self.__controller
def destroy(self):
"""Called when the manager is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__controller = None
ogt.destroy_property(self, "__widget")
ogt.destroy_property(self, "__widget_model")
| 4,910 | Python | 40.974359 | 109 | 0.625051 |
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/_impl/omnigraph_node_description_editor/node_language_manager.py | """
Support for the combo box representing the choice of node languages.
"""
import omni.graph.tools as ogt
import omni.graph.tools.ogn as ogn
from carb import log_warn
from omni import ui
from ..style import name_value_label # noqa: PLE0402
from .ogn_editor_utils import ComboBoxOptions
# ======================================================================
# ID values for widgets that are editable or need updating
ID_NODE_LANGUAGE = "nodeLanguage"
# ======================================================================
# Tooltips for the editable widgets
TOOLTIPS = {ID_NODE_LANGUAGE: "The language in which the node is implemented, e.g. Python or C++"}
# ======================================================================
class NodeLanguageComboBox(ui.AbstractItemModel):
"""Implementation of a combo box that shows types of implementation languages available
Internal Properties:
__controller: Controller object manipulating the underlying memory model
__current_index: Model containing the combo box selection
__items: List of options available to choose from in the combo box
__subscription: Contains the scoped subscription object for value changes
"""
OPTION_CPP = "Node Is Implemented In C++"
OPTION_PYTHON = "Node Is Implemented In Python"
OPTIONS = [ogn.LanguageTypeValues.CPP, ogn.LanguageTypeValues.PYTHON]
OPTION_NAMES = {OPTIONS[0]: OPTION_CPP, OPTIONS[1]: OPTION_PYTHON}
def __init__(self, controller):
"""Initialize the node language combo box details"""
super().__init__()
self.__controller = controller
self.__current_index = ui.SimpleIntModel()
self.__current_index.set_value(self.OPTIONS.index(ogn.check_node_language(self.__controller.node_language)))
self.__subscription = self.__current_index.subscribe_value_changed_fn(self.__on_language_changed)
assert self.__subscription
assert self.__controller
# Using a list comprehension instead of values() guarantees the ordering
self.__items = [ComboBoxOptions(self.OPTION_NAMES[node_language]) for node_language in self.OPTIONS]
def destroy(self):
"""Clean up when the widget is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__subscription = None
self.__controller = None
ogt.destroy_property(self, "__current_index")
ogt.destroy_property(self, "__items")
def get_item_children(self, item):
"""Get the model children of this item"""
return self.__items
def get_item_value_model(self, item, column_id: int):
"""Get the model at the specified column_id"""
if item is None:
return self.__current_index
return item.model
def __on_language_changed(self, new_value: ui.SimpleIntModel):
"""Callback executed when a new language was selected"""
try:
new_node_language = self.OPTION_NAMES[self.OPTIONS[new_value.as_int]]
ogt.dbg_ui(f"Set node language to {new_value.as_int} - {new_node_language}")
self.__controller.node_language = self.OPTIONS[new_value.as_int]
self._item_changed(None)
except (AttributeError, KeyError) as error:
log_warn(f"Node language '{new_value.as_int}' was rejected - {error}")
# ======================================================================
class NodeLanguageManager:
"""Handle the combo box and responses for getting and setting the node implementation language
Internal Properties:
__controller: Controller for the data of the attribute this will modify
__widget: ComboBox widget controlling the base type
__widget_model: Model for the ComboBox value
"""
def __init__(self, controller):
"""Set up the initial UI and model
Args:
controller: AttributePropertiesController in charge of the data for the attribute being managed
"""
self.__controller = controller
name_value_label("Implementation Language:", TOOLTIPS[ID_NODE_LANGUAGE])
self.__widget_model = NodeLanguageComboBox(controller)
self.__widget = ui.ComboBox(
self.__widget_model,
alignment=ui.Alignment.LEFT_BOTTOM,
name=ID_NODE_LANGUAGE,
tooltip=TOOLTIPS[ID_NODE_LANGUAGE],
)
assert self.__widget
assert self.__controller
def destroy(self):
"""Called to clean up when the widget is being destroyed"""
ogt.dbg_ui(f"destroy::{self.__class__.__name__}")
self.__controller = None
ogt.destroy_property(self, "__widget")
ogt.destroy_property(self, "__widget_model")
| 4,740 | Python | 41.330357 | 116 | 0.622363 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.