file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnOnWidgetClicked.rst
.. _omni_graph_ui_nodes_OnWidgetClicked_1: .. _omni_graph_ui_nodes_OnWidgetClicked: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Widget Clicked (BETA) :keywords: lang-en omnigraph node graph:action,ui compute-on-request ui_nodes on-widget-clicked On Widget Clicked (BETA) ======================== .. <description> Event node which fires when a UI widget with the specified identifier is clicked. This node should be used in combination with UI creation nodes such as OgnButton. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Widget Identifier (*inputs:widgetIdentifier*)", "``token``", "A unique identifier identifying the widget. This should be specified in the UI creation node such as OgnButton.", "" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Clicked (*outputs:clicked*)", "``execution``", "Executed when the widget is clicked", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.OnWidgetClicked" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "True" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "On Widget Clicked (BETA)" "Categories", "graph:action,ui" "Generated Class Name", "OgnOnWidgetClickedDatabase" "Python Module", "omni.graph.ui_nodes"
1,908
reStructuredText
26.666666
183
0.592767
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnVStack.rst
.. _omni_graph_ui_nodes_VStack_1: .. _omni_graph_ui_nodes_VStack: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Stack (BETA) :keywords: lang-en omnigraph node graph:action,ui ui_nodes v-stack Stack (BETA) ============ .. <description> Contruct a Stack on the Viewport. All child widgets of Stack will be placed in a row, column or layer based on the direction input. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Create (*inputs:create*)", "``execution``", "Input execution to create and show the widget", "None" "Direction (*inputs:direction*)", "``token``", "The direction the widgets will be stacked.", "TOP_TO_BOTTOM" "", "*allowedTokens*", "BACK_TO_FRONT,BOTTOM_TO_TOP,FRONT_TO_BACK,LEFT_TO_RIGHT,RIGHT_TO_LEFT,TOP_TO_BOTTOM", "" "Parent Widget Path (*inputs:parentWidgetPath*)", "``token``", "The absolute path to the parent widget.", "" "inputs:style", "``string``", "Style to be applied to the stack and its children. This can later be changed with the WriteWidgetStyle node.", "None" "Widget Identifier (*inputs:widgetIdentifier*)", "``token``", "An optional unique identifier for the widget. Can be used to refer to this widget in other places such as the OnWidgetClicked node.", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Created (*outputs:created*)", "``execution``", "Executed when the widget is created", "None" "Widget Path (*outputs:widgetPath*)", "``token``", "The absolute path to the created widget", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.VStack" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Stack (BETA)" "Categories", "graph:action,ui" "Generated Class Name", "OgnVStackDatabase" "Python Module", "omni.graph.ui_nodes"
2,461
reStructuredText
32.27027
207
0.60707
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnReadViewportHoverState.rst
.. _omni_graph_ui_nodes_ReadViewportHoverState_1: .. _omni_graph_ui_nodes_ReadViewportHoverState: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Read Viewport Hover State (BETA) :keywords: lang-en omnigraph node ui threadsafe ui_nodes read-viewport-hover-state Read Viewport Hover State (BETA) ================================ .. <description> Read the state of the last viewport hover event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Use Normalized Coords (*inputs:useNormalizedCoords*)", "``bool``", "When true, the components of 2D position and velocity outputs are scaled to between 0 and 1, where 0 is top/left and 1 is bottom/right. When false, components are in viewport render resolution pixels.", "False" "Viewport (*inputs:viewport*)", "``token``", "Name of the viewport window to watch for hover events", "Viewport" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Is Hovered (*outputs:isHovered*)", "``bool``", "True if the specified viewport is currently hovered", "None" "Is Valid (*outputs:isValid*)", "``bool``", "True if a valid event state was detected and the outputs of this node are valid, and false otherwise", "None" "Position (*outputs:position*)", "``double[2]``", "The current mouse position if the specified viewport is currently hovered, otherwise (0,0)", "None" "Velocity (*outputs:velocity*)", "``double[2]``", "A vector representing the change in position of the mouse since the previous frame if the specified viewport is currently hovered, otherwise (0,0)", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.ReadViewportHoverState" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Read Viewport Hover State (BETA)" "Categories", "ui" "Generated Class Name", "OgnReadViewportHoverStateDatabase" "Python Module", "omni.graph.ui_nodes"
2,682
reStructuredText
36.263888
283
0.634228
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnGetViewportRenderer.rst
.. _omni_graph_ui_nodes_GetViewportRenderer_1: .. _omni_graph_ui_nodes_GetViewportRenderer: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Get Viewport Renderer :keywords: lang-en omnigraph node viewport ui_nodes get-viewport-renderer Get Viewport Renderer ===================== .. <description> Gets the renderer being used by the target viewport. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Viewport (*inputs:viewport*)", "``token``", "Name of the viewport, or empty for the default viewport", "Viewport" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Renderer (*outputs:renderer*)", "``token``", "The renderer being used by the target viewport", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.GetViewportRenderer" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Get Viewport Renderer" "Categories", "viewport" "Generated Class Name", "OgnGetViewportRendererDatabase" "Python Module", "omni.graph.ui_nodes"
1,684
reStructuredText
23.779411
118
0.578979
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnWriteWidgetStyle.rst
.. _omni_graph_ui_nodes_WriteWidgetStyle_1: .. _omni_graph_ui_nodes_WriteWidgetStyle: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Write Widget Style (BETA) :keywords: lang-en omnigraph node graph:action,ui ReadOnly ui_nodes write-widget-style Write Widget Style (BETA) ========================= .. <description> Sets a widget's style properties. This node should be used in combination with UI creation nodes such as Button. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:style", "``string``", "The style to set the widget to.", "" "Widget Identifier (*inputs:widgetIdentifier*)", "``token``", "A unique identifier identifying the widget. This is only valid within the current graph. This should be specified in the UI creation node such as OgnButton.", "" "Widget Path (*inputs:widgetPath*)", "``token``", "Full path to the widget. If present this will be used insted of 'widgetIdentifier'. Unlike 'widgetIdentifier' this is valid across all graphs.", "" "inputs:write", "``execution``", "Input execution", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:written", "``execution``", "Output execution", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.WriteWidgetStyle" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Write Widget Style (BETA)" "Categories", "graph:action,ui" "Generated Class Name", "OgnWriteWidgetStyleDatabase" "Python Module", "omni.graph.ui_nodes"
2,176
reStructuredText
29.661971
228
0.60432
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnOnViewportHovered.rst
.. _omni_graph_ui_nodes_OnViewportHovered_1: .. _omni_graph_ui_nodes_OnViewportHovered: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Viewport Hovered (BETA) :keywords: lang-en omnigraph node graph:action,ui threadsafe compute-on-request ui_nodes on-viewport-hovered On Viewport Hovered (BETA) ========================== .. <description> Event node which fires when the specified viewport is hovered over. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played", "True" "", "*literalOnly*", "1", "" "Viewport (*inputs:viewport*)", "``token``", "Name of the viewport window to watch for hover events", "Viewport" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Began (*outputs:began*)", "``execution``", "Enabled when the hover begins", "None" "Ended (*outputs:ended*)", "``execution``", "Enabled when the hover ends", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.OnViewportHovered" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "On Viewport Hovered (BETA)" "Categories", "graph:action,ui" "Generated Class Name", "OgnOnViewportHoveredDatabase" "Python Module", "omni.graph.ui_nodes"
2,125
reStructuredText
28.527777
171
0.592
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnOnViewportScrolled.rst
.. _omni_graph_ui_nodes_OnViewportScrolled_1: .. _omni_graph_ui_nodes_OnViewportScrolled: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Viewport Scrolled (BETA) :keywords: lang-en omnigraph node graph:action,ui threadsafe compute-on-request ui_nodes on-viewport-scrolled On Viewport Scrolled (BETA) =========================== .. <description> Event node which fires when a viewport scroll event occurs in the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played", "True" "", "*literalOnly*", "1", "" "Use Normalized Coords (*inputs:useNormalizedCoords*)", "``bool``", "When true, the components of the 2D position output are scaled to between 0 and 1, where 0 is top/left and 1 is bottom/right. When false, components are in viewport render resolution pixels.", "False" "", "*literalOnly*", "1", "" "Viewport (*inputs:viewport*)", "``token``", "Name of the viewport window to watch for scroll events", "Viewport" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Position (*outputs:position*)", "``double[2]``", "The position at which the viewport scroll event occurred", "None" "Scroll Value (*outputs:scrollValue*)", "``float``", "The number of mouse wheel clicks scrolled up if positive, or scrolled down if negative", "None" "Scrolled (*outputs:scrolled*)", "``execution``", "Enabled when a viewport scroll event occurs in the specified viewport", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.OnViewportScrolled" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "On Viewport Scrolled (BETA)" "Categories", "graph:action,ui" "Generated Class Name", "OgnOnViewportScrolledDatabase" "Python Module", "omni.graph.ui_nodes"
2,695
reStructuredText
34.946666
273
0.621892
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnOnViewportPressed.rst
.. _omni_graph_ui_nodes_OnViewportPressed_1: .. _omni_graph_ui_nodes_OnViewportPressed: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: On Viewport Pressed (BETA) :keywords: lang-en omnigraph node graph:action,ui threadsafe compute-on-request ui_nodes on-viewport-pressed On Viewport Pressed (BETA) ========================== .. <description> Event node which fires when the specified viewport is pressed, and when that press is released. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Gesture (*inputs:gesture*)", "``token``", "The input gesture to trigger viewport press events", "Left Mouse Press" "", "*displayGroup*", "parameters", "" "", "*literalOnly*", "1", "" "", "*allowedTokens*", "Left Mouse Press,Right Mouse Press,Middle Mouse Press", "" "Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played", "True" "", "*literalOnly*", "1", "" "Use Normalized Coords (*inputs:useNormalizedCoords*)", "``bool``", "When true, the components of 2D position outputs are scaled to between 0 and 1, where 0 is top/left and 1 is bottom/right. When false, components are in viewport render resolution pixels.", "False" "", "*literalOnly*", "1", "" "Viewport (*inputs:viewport*)", "``token``", "Name of the viewport window to watch for press events", "Viewport" "", "*literalOnly*", "1", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Is Release Position Valid (*outputs:isReleasePositionValid*)", "``bool``", "True if the press was released inside of the viewport, and false otherwise", "None" "Press Position (*outputs:pressPosition*)", "``double[2]``", "The position at which the viewport was pressed (valid when either 'Pressed' or 'Released' is enabled)", "None" "Pressed (*outputs:pressed*)", "``execution``", "Enabled when the specified viewport is pressed, populating 'Press Position' with the current mouse position", "None" "Release Position (*outputs:releasePosition*)", "``double[2]``", "The position at which the press was released, or (0,0) if the press was released outside of the viewport or the viewport is currently pressed (valid when 'Ended' is enabled and 'Is Release Position Valid' is true)", "None" "Released (*outputs:released*)", "``execution``", "Enabled when the press is released, populating 'Release Position' with the current mouse position and setting 'Is Release Position Valid' to true if the press is released inside of the viewport. If the press is released outside of the viewport, 'Is Release Position Valid' is set to false and 'Release Position' is set to (0,0).", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.OnViewportPressed" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "On Viewport Pressed (BETA)" "Categories", "graph:action,ui" "Generated Class Name", "OgnOnViewportPressedDatabase" "Python Module", "omni.graph.ui_nodes"
3,764
reStructuredText
45.481481
392
0.647715
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnReadViewportScrollState.rst
.. _omni_graph_ui_nodes_ReadViewportScrollState_1: .. _omni_graph_ui_nodes_ReadViewportScrollState: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Read Viewport Scroll State (BETA) :keywords: lang-en omnigraph node ui threadsafe ui_nodes read-viewport-scroll-state Read Viewport Scroll State (BETA) ================================= .. <description> Read the state of the last viewport scroll event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Use Normalized Coords (*inputs:useNormalizedCoords*)", "``bool``", "When true, the components of the 2D position output are scaled to between 0 and 1, where 0 is top/left and 1 is bottom/right. When false, components are in viewport render resolution pixels.", "False" "Viewport (*inputs:viewport*)", "``token``", "Name of the viewport window to watch for scroll events", "Viewport" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Is Valid (*outputs:isValid*)", "``bool``", "True if a valid event state was detected and the outputs of this node are valid, and false otherwise", "None" "Position (*outputs:position*)", "``double[2]``", "The last position at which a viewport scroll event occurred in the specified viewport", "None" "Scroll Value (*outputs:scrollValue*)", "``float``", "The number of mouse wheel clicks scrolled up if positive, or scrolled down if negative", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.ReadViewportScrollState" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Read Viewport Scroll State (BETA)" "Categories", "ui" "Generated Class Name", "OgnReadViewportScrollStateDatabase" "Python Module", "omni.graph.ui_nodes"
2,507
reStructuredText
34.323943
273
0.629438
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnLockViewportRender.rst
.. _omni_graph_ui_nodes_LockViewportRender_1: .. _omni_graph_ui_nodes_LockViewportRender: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Lock Viewport Render :keywords: lang-en omnigraph node graph:action,viewport ui_nodes lock-viewport-render Lock Viewport Render ==================== .. <description> Locks and unlocks viewport render. Viewport render is frozen at the frame when it is locked, while computation and UI update are still executed as normal. It fades out back to the current frame when it is unlocked, two output execution attributes - fadeStarted and fadeComplete - will be triggered separately during the fading progress. The node manages the lock state for its target viewport and takes action according to the lock state when an input execution attribute is triggered. A node is able to unlock the target viewort only if it has locked the target viewport. .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Fade Time (*inputs:fadeTime*)", "``double``", "The duration of fading in time (seconds) when being unlocked", "1.0" "inputs:lock", "``execution``", "The input execution attribute for locking viewport render", "None" "inputs:unlock", "``execution``", "The input execution attribute for unlocking viewport render", "None" "Viewport (*inputs:viewport*)", "``token``", "Name of the viewport, or empty for the default viewport", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:fadeComplete", "``execution``", "Triggered when fading is complete", "None" "outputs:fadeStarted", "``execution``", "Triggered when fading is started", "None" "outputs:locked", "``execution``", "Triggered when viewport render is locked", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.LockViewportRender" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Lock Viewport Render" "Categories", "graph:action,viewport" "Generated Class Name", "OgnLockViewportRenderDatabase" "Python Module", "omni.graph.ui_nodes"
2,705
reStructuredText
36.068493
572
0.644732
omniverse-code/kit/exts/omni.graph.ui_nodes/ogn/docs/OgnReadWidgetProperty.rst
.. _omni_graph_ui_nodes_ReadWidgetProperty_1: .. _omni_graph_ui_nodes_ReadWidgetProperty: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Read Widget Property (BETA) :keywords: lang-en omnigraph node graph:action,ui WriteOnly ui_nodes read-widget-property Read Widget Property (BETA) =========================== .. <description> Read the value of a widget's property (height, tooltip, etc). .. </description> Installation ------------ To use this node enable :ref:`omni.graph.ui_nodes<ext_omni_graph_ui_nodes>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Property Name (*inputs:propertyName*)", "``token``", "Name of the property to read.", "" "Widget Identifier (*inputs:widgetIdentifier*)", "``token``", "Unique identifier for the widget. This is only valid within the current graph.", "" "Widget Path (*inputs:widgetPath*)", "``token``", "Full path to the widget. If present this will be used insted of 'widgetIdentifier'. Unlike 'widgetIdentifier' this is valid across all graphs.", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Value (*outputs:value*)", "``['bool', 'double', 'int', 'string']``", "The value of the property.", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.ui_nodes.ReadWidgetProperty" "Version", "1" "Extension", "omni.graph.ui_nodes" "Has State?", "False" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "uiName", "Read Widget Property (BETA)" "Categories", "graph:action,ui" "Generated Class Name", "OgnReadWidgetPropertyDatabase" "Python Module", "omni.graph.ui_nodes"
2,069
reStructuredText
28.571428
202
0.59014
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnReadViewportPressStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.ReadViewportPressState Read the state of the last viewport press event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnReadViewportPressStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.ReadViewportPressState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isPressed outputs.isReleasePositionValid outputs.isValid outputs.pressPosition outputs.releasePosition Predefined Tokens: tokens.LeftMouseDrag tokens.RightMouseDrag tokens.MiddleMouseDrag """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport press events', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Press", "RightMouseDrag": "Right Mouse Press", "MiddleMouseDrag": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Press"'}, True, "Left Mouse Press", False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for press events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''), ('outputs:isPressed', 'bool', 0, 'Is Pressed', 'True if the specified viewport is currently pressed', {}, True, None, False, ''), ('outputs:isReleasePositionValid', 'bool', 0, 'Is Release Position Valid', 'True if the press was released inside of the viewport, and false otherwise', {}, True, None, False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:pressPosition', 'double2', 0, 'Press Position', 'The position at which the specified viewport was last pressed', {}, True, None, False, ''), ('outputs:releasePosition', 'double2', 0, 'Release Position', 'The position at which the last press on the specified viewport was released,\nor (0,0) if the press was released outside of the viewport or the viewport is currently pressed', {}, True, None, False, ''), ]) class tokens: LeftMouseDrag = "Left Mouse Press" RightMouseDrag = "Right Mouse Press" MiddleMouseDrag = "Middle Mouse Press" class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def gesture(self): data_view = og.AttributeValueHelper(self._attributes.gesture) return data_view.get() @gesture.setter def gesture(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gesture) data_view = og.AttributeValueHelper(self._attributes.gesture) data_view.set(value) @property def useNormalizedCoords(self): data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) return data_view.get() @useNormalizedCoords.setter def useNormalizedCoords(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.useNormalizedCoords) data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) data_view.set(value) @property def viewport(self): data_view = og.AttributeValueHelper(self._attributes.viewport) return data_view.get() @viewport.setter def viewport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewport) data_view = og.AttributeValueHelper(self._attributes.viewport) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isPressed(self): data_view = og.AttributeValueHelper(self._attributes.isPressed) return data_view.get() @isPressed.setter def isPressed(self, value): data_view = og.AttributeValueHelper(self._attributes.isPressed) data_view.set(value) @property def isReleasePositionValid(self): data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) return data_view.get() @isReleasePositionValid.setter def isReleasePositionValid(self, value): data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) data_view.set(value) @property def isValid(self): data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): data_view = og.AttributeValueHelper(self._attributes.isValid) data_view.set(value) @property def pressPosition(self): data_view = og.AttributeValueHelper(self._attributes.pressPosition) return data_view.get() @pressPosition.setter def pressPosition(self, value): data_view = og.AttributeValueHelper(self._attributes.pressPosition) data_view.set(value) @property def releasePosition(self): data_view = og.AttributeValueHelper(self._attributes.releasePosition) return data_view.get() @releasePosition.setter def releasePosition(self, value): data_view = og.AttributeValueHelper(self._attributes.releasePosition) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadViewportPressStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadViewportPressStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadViewportPressStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
9,771
Python
48.604061
469
0.670044
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnOnViewportPressedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.OnViewportPressed Event node which fires when the specified viewport is pressed, and when that press is released. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnViewportPressedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.OnViewportPressed Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.onlyPlayback inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isReleasePositionValid outputs.pressPosition outputs.pressed outputs.releasePosition outputs.released Predefined Tokens: tokens.LeftMouseDrag tokens.RightMouseDrag tokens.MiddleMouseDrag """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport press events', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Press", "RightMouseDrag": "Right Mouse Press", "MiddleMouseDrag": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Press"'}, True, "Left Mouse Press", False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for press events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''), ('outputs:isReleasePositionValid', 'bool', 0, 'Is Release Position Valid', 'True if the press was released inside of the viewport, and false otherwise', {}, True, None, False, ''), ('outputs:pressPosition', 'double2', 0, 'Press Position', "The position at which the viewport was pressed (valid when either 'Pressed' or 'Released' is enabled)", {}, True, None, False, ''), ('outputs:pressed', 'execution', 0, 'Pressed', "Enabled when the specified viewport is pressed, populating 'Press Position' with the current mouse position", {}, True, None, False, ''), ('outputs:releasePosition', 'double2', 0, 'Release Position', "The position at which the press was released, or (0,0) if the press was released outside of the viewport\nor the viewport is currently pressed (valid when 'Ended' is enabled and 'Is Release Position Valid' is true)", {}, True, None, False, ''), ('outputs:released', 'execution', 0, 'Released', "Enabled when the press is released, populating 'Release Position' with the current mouse position\nand setting 'Is Release Position Valid' to true if the press is released inside of the viewport.\nIf the press is released outside of the viewport, 'Is Release Position Valid' is set to false\nand 'Release Position' is set to (0,0).", {}, True, None, False, ''), ]) class tokens: LeftMouseDrag = "Left Mouse Press" RightMouseDrag = "Right Mouse Press" MiddleMouseDrag = "Middle Mouse Press" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.pressed = og.AttributeRole.EXECUTION role_data.outputs.released = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def gesture(self): data_view = og.AttributeValueHelper(self._attributes.gesture) return data_view.get() @gesture.setter def gesture(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gesture) data_view = og.AttributeValueHelper(self._attributes.gesture) data_view.set(value) @property def onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) data_view.set(value) @property def useNormalizedCoords(self): data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) return data_view.get() @useNormalizedCoords.setter def useNormalizedCoords(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.useNormalizedCoords) data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) data_view.set(value) @property def viewport(self): data_view = og.AttributeValueHelper(self._attributes.viewport) return data_view.get() @viewport.setter def viewport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewport) data_view = og.AttributeValueHelper(self._attributes.viewport) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isReleasePositionValid(self): data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) return data_view.get() @isReleasePositionValid.setter def isReleasePositionValid(self, value): data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) data_view.set(value) @property def pressPosition(self): data_view = og.AttributeValueHelper(self._attributes.pressPosition) return data_view.get() @pressPosition.setter def pressPosition(self, value): data_view = og.AttributeValueHelper(self._attributes.pressPosition) data_view.set(value) @property def pressed(self): data_view = og.AttributeValueHelper(self._attributes.pressed) return data_view.get() @pressed.setter def pressed(self, value): data_view = og.AttributeValueHelper(self._attributes.pressed) data_view.set(value) @property def releasePosition(self): data_view = og.AttributeValueHelper(self._attributes.releasePosition) return data_view.get() @releasePosition.setter def releasePosition(self, value): data_view = og.AttributeValueHelper(self._attributes.releasePosition) data_view.set(value) @property def released(self): data_view = og.AttributeValueHelper(self._attributes.released) return data_view.get() @released.setter def released(self, value): data_view = og.AttributeValueHelper(self._attributes.released) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnViewportPressedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnViewportPressedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnViewportPressedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,292
Python
50.56621
505
0.67136
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnReadPickStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.ReadPickState Read the state of the last picking event from the specified viewport. Note that picking events must be enabled on the specified viewport using a SetViewportMode node. """ import numpy import usdrt import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnReadPickStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.ReadPickState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.trackedPrimPaths inputs.trackedPrims inputs.usePaths inputs.viewport Outputs: outputs.isTrackedPrimPicked outputs.isValid outputs.pickedPrim outputs.pickedPrimPath outputs.pickedWorldPos Predefined Tokens: tokens.LeftMouseClick tokens.RightMouseClick tokens.MiddleMouseClick tokens.LeftMousePress tokens.RightMousePress tokens.MiddleMousePress """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger a picking event', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Click,Right Mouse Click,Middle Mouse Click,Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseClick": "Left Mouse Click", "RightMouseClick": "Right Mouse Click", "MiddleMouseClick": "Middle Mouse Click", "LeftMousePress": "Left Mouse Press", "RightMousePress": "Right Mouse Press", "MiddleMousePress": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Click"'}, True, "Left Mouse Click", False, ''), ('inputs:trackedPrimPaths', 'token[]', 0, 'Tracked Prim Paths', "Optionally specify a set of prims (by paths) to track whether or not they got picked\n(only affects the value of 'Is Tracked Prim Picked')", {}, False, None, True, 'Use the trackedPrims input instead'), ('inputs:trackedPrims', 'target', 0, 'Tracked Prims', "Optionally specify a set of prims to track whether or not they got picked\n(only affects the value of 'Is Tracked Prim Picked')", {ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, False, [], False, ''), ('inputs:usePaths', 'bool', 0, 'Use Paths', "When true, 'Tracked Prim Paths' is used, otherwise 'Tracked Prims' is used", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for picking events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''), ('outputs:isTrackedPrimPicked', 'bool', 0, 'Is Tracked Prim Picked', 'True if a tracked prim got picked in the last picking event,\nor if any prim got picked if no tracked prims are specified', {}, True, None, False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:pickedPrim', 'target', 0, 'Picked Prim', 'The picked prim, or an empty target if nothing got picked', {}, True, [], False, ''), ('outputs:pickedPrimPath', 'token', 0, 'Picked Prim Path', 'The path of the prim picked in the last picking event, or an empty string if nothing got picked', {}, True, None, True, 'Use the pickedPrim output instead'), ('outputs:pickedWorldPos', 'point3d', 0, 'Picked World Position', 'The XYZ-coordinates of the point in world space at which the prim got picked,\nor (0,0,0) if nothing got picked', {}, True, None, False, ''), ]) class tokens: LeftMouseClick = "Left Mouse Click" RightMouseClick = "Right Mouse Click" MiddleMouseClick = "Middle Mouse Click" LeftMousePress = "Left Mouse Press" RightMousePress = "Right Mouse Press" MiddleMousePress = "Middle Mouse Press" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.trackedPrims = og.AttributeRole.TARGET role_data.outputs.pickedPrim = og.AttributeRole.TARGET role_data.outputs.pickedWorldPos = og.AttributeRole.POSITION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def gesture(self): data_view = og.AttributeValueHelper(self._attributes.gesture) return data_view.get() @gesture.setter def gesture(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gesture) data_view = og.AttributeValueHelper(self._attributes.gesture) data_view.set(value) @property def trackedPrimPaths(self): data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) return data_view.get() @trackedPrimPaths.setter def trackedPrimPaths(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.trackedPrimPaths) data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) data_view.set(value) self.trackedPrimPaths_size = data_view.get_array_size() @property def trackedPrims(self): data_view = og.AttributeValueHelper(self._attributes.trackedPrims) return data_view.get() @trackedPrims.setter def trackedPrims(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.trackedPrims) data_view = og.AttributeValueHelper(self._attributes.trackedPrims) data_view.set(value) self.trackedPrims_size = data_view.get_array_size() @property def usePaths(self): data_view = og.AttributeValueHelper(self._attributes.usePaths) return data_view.get() @usePaths.setter def usePaths(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.usePaths) data_view = og.AttributeValueHelper(self._attributes.usePaths) data_view.set(value) @property def viewport(self): data_view = og.AttributeValueHelper(self._attributes.viewport) return data_view.get() @viewport.setter def viewport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewport) data_view = og.AttributeValueHelper(self._attributes.viewport) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.pickedPrim_size = None self._batchedWriteValues = { } @property def isTrackedPrimPicked(self): data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked) return data_view.get() @isTrackedPrimPicked.setter def isTrackedPrimPicked(self, value): data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked) data_view.set(value) @property def isValid(self): data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): data_view = og.AttributeValueHelper(self._attributes.isValid) data_view.set(value) @property def pickedPrim(self): data_view = og.AttributeValueHelper(self._attributes.pickedPrim) return data_view.get(reserved_element_count=self.pickedPrim_size) @pickedPrim.setter def pickedPrim(self, value): data_view = og.AttributeValueHelper(self._attributes.pickedPrim) data_view.set(value) self.pickedPrim_size = data_view.get_array_size() @property def pickedPrimPath(self): data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath) return data_view.get() @pickedPrimPath.setter def pickedPrimPath(self, value): data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath) data_view.set(value) @property def pickedWorldPos(self): data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos) return data_view.get() @pickedWorldPos.setter def pickedWorldPos(self, value): data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadPickStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadPickStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadPickStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
12,176
Python
48.702041
640
0.662861
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnSetViewportFullscreenDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.SetViewportFullscreen Toggles fullscreen on/off for viewport(s) and visibility on/off for all other panes. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSetViewportFullscreenDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.SetViewportFullscreen Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.mode Outputs: outputs.exec Predefined Tokens: tokens.Default tokens.Fullscreen tokens.HideUI """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:exec', 'execution', 0, None, 'The input execution', {}, True, None, False, ''), ('inputs:mode', 'token', 0, 'Mode', 'The mode to toggle fullscreen on/off for viewport(s) and visibility on/off for all other panes:\n\n"Default" - Windowed viewport(s) with all other panes shown.\n"Fullscreen" - Fullscreen viewport(s) with all other panes hidden.\n"Hide UI" - Windowed viewport(s) with all other panes hidden.', {ogn.MetadataKeys.ALLOWED_TOKENS: 'Default,Fullscreen,Hide UI', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"Default": "Default", "Fullscreen": "Fullscreen", "HideUI": "Hide UI"}', ogn.MetadataKeys.DEFAULT: '"Default"'}, True, "Default", False, ''), ('outputs:exec', 'execution', 0, None, 'The output execution', {}, True, None, False, ''), ]) class tokens: Default = "Default" Fullscreen = "Fullscreen" HideUI = "Hide UI" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def mode(self): data_view = og.AttributeValueHelper(self._attributes.mode) return data_view.get() @mode.setter def mode(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.mode) data_view = og.AttributeValueHelper(self._attributes.mode) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSetViewportFullscreenDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSetViewportFullscreenDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSetViewportFullscreenDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
6,593
Python
45.765957
582
0.664493
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnPrintTextDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.PrintText Prints some text to the system log or to the screen """ import sys import traceback import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnPrintTextDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.PrintText Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.logLevel inputs.text inputs.toScreen inputs.viewport Outputs: outputs.execOut Predefined Tokens: tokens.Info tokens.Warning tokens.Error """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:execIn', 'execution', 0, 'In', 'Execution input', {}, True, None, False, ''), ('inputs:logLevel', 'token', 0, 'Log Level', 'The logging level for the message [Info, Warning, Error]', {ogn.MetadataKeys.ALLOWED_TOKENS: 'Info,Warning,Error', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '["Info", "Warning", "Error"]', ogn.MetadataKeys.DEFAULT: '"Info"'}, True, "Info", False, ''), ('inputs:text', 'string', 0, 'Text', 'The text to print', {}, True, "", False, ''), ('inputs:toScreen', 'bool', 0, 'To Screen', 'When true, displays the text on the viewport for a few seconds, as well as the log', {}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport if printing to screen, or empty for the default viewport', {}, True, "", False, ''), ('outputs:execOut', 'execution', 0, 'Out', 'Execution Output', {}, True, None, False, ''), ]) class tokens: Info = "Info" Warning = "Warning" Error = "Error" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.execIn = og.AttributeRole.EXECUTION role_data.inputs.text = og.AttributeRole.TEXT role_data.outputs.execOut = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execIn", "logLevel", "text", "toScreen", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.execIn, self._attributes.logLevel, self._attributes.text, self._attributes.toScreen, self._attributes.viewport] self._batchedReadValues = [None, "Info", "", False, ""] @property def execIn(self): return self._batchedReadValues[0] @execIn.setter def execIn(self, value): self._batchedReadValues[0] = value @property def logLevel(self): return self._batchedReadValues[1] @logLevel.setter def logLevel(self, value): self._batchedReadValues[1] = value @property def text(self): return self._batchedReadValues[2] @text.setter def text(self, value): self._batchedReadValues[2] = value @property def toScreen(self): return self._batchedReadValues[3] @toScreen.setter def toScreen(self, value): self._batchedReadValues[3] = value @property def viewport(self): return self._batchedReadValues[4] @viewport.setter def viewport(self, value): self._batchedReadValues[4] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnPrintTextDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnPrintTextDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnPrintTextDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui_nodes.PrintText' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnPrintTextDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnPrintTextDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnPrintTextDatabase(node) try: compute_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnPrintTextDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnPrintTextDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnPrintTextDatabase.PER_NODE_DATA[node.node_id()] def on_connection_or_disconnection(*args): per_node_data['_db'] = None node.register_on_connected_callback(on_connection_or_disconnection) node.register_on_disconnected_callback(on_connection_or_disconnection) @staticmethod def release(node): release_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnPrintTextDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnPrintTextDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui_nodes") node_type.set_metadata(ogn.MetadataKeys.TAGS, "logging,toast,debug") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Print Text") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "debug") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Prints some text to the system log or to the screen") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnPrintTextDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None @staticmethod def register(node_type_class): OgnPrintTextDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnPrintTextDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui_nodes.PrintText")
13,270
Python
43.089701
300
0.62208
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnOnPickedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.OnPicked Event node which fires when a picking event occurs in the specified viewport. Note that picking events must be enabled on the specified viewport using a SetViewportMode node. """ import numpy import usdrt import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnPickedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.OnPicked Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.onlyPlayback inputs.trackedPrims inputs.viewport Outputs: outputs.isTrackedPrimPicked outputs.missed outputs.picked outputs.pickedPrim outputs.pickedPrimPath outputs.pickedWorldPos outputs.trackedPrimPaths Predefined Tokens: tokens.LeftMouseClick tokens.RightMouseClick tokens.MiddleMouseClick tokens.LeftMousePress tokens.RightMousePress tokens.MiddleMousePress """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger a picking event', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Click,Right Mouse Click,Middle Mouse Click,Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseClick": "Left Mouse Click", "RightMouseClick": "Right Mouse Click", "MiddleMouseClick": "Middle Mouse Click", "LeftMousePress": "Left Mouse Press", "RightMousePress": "Right Mouse Press", "MiddleMousePress": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Click"'}, True, "Left Mouse Click", False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:trackedPrims', 'target', 0, 'Tracked Prims', "Optionally specify a set of tracked prims that will cause 'Picked' to fire when picked", {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOW_MULTI_INPUTS: '1'}, False, [], False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for picking events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''), ('outputs:isTrackedPrimPicked', 'bool', 0, 'Is Tracked Prim Picked', "True if a tracked prim got picked, or if any prim got picked if no tracked prims are specified\n(will always be true when 'Picked' fires, and false when 'Missed' fires)", {}, True, None, False, ''), ('outputs:missed', 'execution', 0, 'Missed', 'Enabled when an attempted picking did not pick a tracked prim,\nor when nothing gets picked if no tracked prims are specified', {}, True, None, False, ''), ('outputs:picked', 'execution', 0, 'Picked', 'Enabled when a tracked prim is picked,\nor when any prim is picked if no tracked prims are specified', {}, True, None, False, ''), ('outputs:pickedPrim', 'target', 0, 'Picked Prim', 'The picked prim, or an empty target if nothing got picked', {}, True, [], False, ''), ('outputs:pickedPrimPath', 'token', 0, 'Picked Prim Path', 'The path of the picked prim, or an empty string if nothing got picked', {}, True, None, True, 'Use the pickedPrim output instead'), ('outputs:pickedWorldPos', 'point3d', 0, 'Picked World Position', 'The XYZ-coordinates of the point in world space at which the prim got picked,\nor (0,0,0) if nothing got picked', {}, True, None, False, ''), ('outputs:trackedPrimPaths', 'token[]', 0, 'Tracked Prim Paths', "A list of the paths of the prims specified in 'Tracked Prims'", {}, True, None, False, ''), ]) class tokens: LeftMouseClick = "Left Mouse Click" RightMouseClick = "Right Mouse Click" MiddleMouseClick = "Middle Mouse Click" LeftMousePress = "Left Mouse Press" RightMousePress = "Right Mouse Press" MiddleMousePress = "Middle Mouse Press" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.trackedPrims = og.AttributeRole.TARGET role_data.outputs.missed = og.AttributeRole.EXECUTION role_data.outputs.picked = og.AttributeRole.EXECUTION role_data.outputs.pickedPrim = og.AttributeRole.TARGET role_data.outputs.pickedWorldPos = og.AttributeRole.POSITION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def gesture(self): data_view = og.AttributeValueHelper(self._attributes.gesture) return data_view.get() @gesture.setter def gesture(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gesture) data_view = og.AttributeValueHelper(self._attributes.gesture) data_view.set(value) @property def onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) data_view.set(value) @property def trackedPrims(self): data_view = og.AttributeValueHelper(self._attributes.trackedPrims) return data_view.get() @trackedPrims.setter def trackedPrims(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.trackedPrims) data_view = og.AttributeValueHelper(self._attributes.trackedPrims) data_view.set(value) self.trackedPrims_size = data_view.get_array_size() @property def viewport(self): data_view = og.AttributeValueHelper(self._attributes.viewport) return data_view.get() @viewport.setter def viewport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewport) data_view = og.AttributeValueHelper(self._attributes.viewport) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.pickedPrim_size = None self.trackedPrimPaths_size = None self._batchedWriteValues = { } @property def isTrackedPrimPicked(self): data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked) return data_view.get() @isTrackedPrimPicked.setter def isTrackedPrimPicked(self, value): data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked) data_view.set(value) @property def missed(self): data_view = og.AttributeValueHelper(self._attributes.missed) return data_view.get() @missed.setter def missed(self, value): data_view = og.AttributeValueHelper(self._attributes.missed) data_view.set(value) @property def picked(self): data_view = og.AttributeValueHelper(self._attributes.picked) return data_view.get() @picked.setter def picked(self, value): data_view = og.AttributeValueHelper(self._attributes.picked) data_view.set(value) @property def pickedPrim(self): data_view = og.AttributeValueHelper(self._attributes.pickedPrim) return data_view.get(reserved_element_count=self.pickedPrim_size) @pickedPrim.setter def pickedPrim(self, value): data_view = og.AttributeValueHelper(self._attributes.pickedPrim) data_view.set(value) self.pickedPrim_size = data_view.get_array_size() @property def pickedPrimPath(self): data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath) return data_view.get() @pickedPrimPath.setter def pickedPrimPath(self, value): data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath) data_view.set(value) @property def pickedWorldPos(self): data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos) return data_view.get() @pickedWorldPos.setter def pickedWorldPos(self, value): data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos) data_view.set(value) @property def trackedPrimPaths(self): data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) return data_view.get(reserved_element_count=self.trackedPrimPaths_size) @trackedPrimPaths.setter def trackedPrimPaths(self, value): data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) data_view.set(value) self.trackedPrimPaths_size = data_view.get_array_size() def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnPickedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnPickedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnPickedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
12,859
Python
48.844961
676
0.66226
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnReadMouseStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.ReadMouseState Reads the current state of the mouse. You can choose which mouse element this node is associated with. When mouse element is chosen to be a button, only outputs:isPressed is meaningful. When coordinates are chosen, only outputs:coords and outputs:window are meaningful. Pixel coordinates are the position of the mouse cursor in screen pixel units with (0,0) top left. Normalized coordinates are values between 0-1 where 0 is top/left and 1 is bottom/right. By default, coordinates are relative to the application window, but if 'Use Relative Coords' is set to true, then coordinates are relative to the workspace window containing the mouse pointer. """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnReadMouseStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.ReadMouseState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.mouseElement inputs.useRelativeCoords Outputs: outputs.coords outputs.isPressed outputs.window Predefined Tokens: tokens.LeftButton tokens.RightButton tokens.MiddleButton tokens.ForwardButton tokens.BackButton tokens.MouseCoordsNormalized tokens.MouseCoordsPixel """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:mouseElement', 'token', 0, 'Mouse Element', 'The mouse input to check the state of', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Button,Right Button,Middle Button,Forward Button,Back Button,Normalized Mouse Coordinates,Pixel Mouse Coordinates', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftButton": "Left Button", "RightButton": "Right Button", "MiddleButton": "Middle Button", "ForwardButton": "Forward Button", "BackButton": "Back Button", "MouseCoordsNormalized": "Normalized Mouse Coordinates", "MouseCoordsPixel": "Pixel Mouse Coordinates"}', ogn.MetadataKeys.DEFAULT: '"Left Button"'}, True, "Left Button", False, ''), ('inputs:useRelativeCoords', 'bool', 0, 'Use Relative Coords', "When true, the output 'coords' is made relative to the workspace window containing the\nmouse pointer instead of the entire application window", {}, True, False, False, ''), ('outputs:coords', 'float2', 0, None, 'The coordinates of the mouse. If the mouse element selected is a button, this will output a zero vector.', {}, True, None, False, ''), ('outputs:isPressed', 'bool', 0, None, 'True if the button is currently pressed, false otherwise. If the mouse element selected\nis a coordinate, this will output false.', {}, True, None, False, ''), ('outputs:window', 'token', 0, None, "The name of the workspace window containing the mouse pointer if 'Use Relative Coords' is true\nand the mouse element selected is a coordinate", {}, True, None, False, ''), ]) class tokens: LeftButton = "Left Button" RightButton = "Right Button" MiddleButton = "Middle Button" ForwardButton = "Forward Button" BackButton = "Back Button" MouseCoordsNormalized = "Normalized Mouse Coordinates" MouseCoordsPixel = "Pixel Mouse Coordinates" class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def mouseElement(self): data_view = og.AttributeValueHelper(self._attributes.mouseElement) return data_view.get() @mouseElement.setter def mouseElement(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.mouseElement) data_view = og.AttributeValueHelper(self._attributes.mouseElement) data_view.set(value) @property def useRelativeCoords(self): data_view = og.AttributeValueHelper(self._attributes.useRelativeCoords) return data_view.get() @useRelativeCoords.setter def useRelativeCoords(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.useRelativeCoords) data_view = og.AttributeValueHelper(self._attributes.useRelativeCoords) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def coords(self): data_view = og.AttributeValueHelper(self._attributes.coords) return data_view.get() @coords.setter def coords(self, value): data_view = og.AttributeValueHelper(self._attributes.coords) data_view.set(value) @property def isPressed(self): data_view = og.AttributeValueHelper(self._attributes.isPressed) return data_view.get() @isPressed.setter def isPressed(self, value): data_view = og.AttributeValueHelper(self._attributes.isPressed) data_view.set(value) @property def window(self): data_view = og.AttributeValueHelper(self._attributes.window) return data_view.get() @window.setter def window(self, value): data_view = og.AttributeValueHelper(self._attributes.window) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadMouseStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadMouseStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadMouseStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
8,753
Python
49.895349
666
0.681595
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnReadViewportHoverStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.ReadViewportHoverState Read the state of the last viewport hover event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnReadViewportHoverStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.ReadViewportHoverState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isHovered outputs.isValid outputs.position outputs.velocity """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position and velocity outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for hover events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''), ('outputs:isHovered', 'bool', 0, 'Is Hovered', 'True if the specified viewport is currently hovered', {}, True, None, False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:position', 'double2', 0, 'Position', 'The current mouse position if the specified viewport is currently hovered, otherwise (0,0)', {}, True, None, False, ''), ('outputs:velocity', 'double2', 0, 'Velocity', 'A vector representing the change in position of the mouse since the previous frame\nif the specified viewport is currently hovered, otherwise (0,0)', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def useNormalizedCoords(self): data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) return data_view.get() @useNormalizedCoords.setter def useNormalizedCoords(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.useNormalizedCoords) data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) data_view.set(value) @property def viewport(self): data_view = og.AttributeValueHelper(self._attributes.viewport) return data_view.get() @viewport.setter def viewport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewport) data_view = og.AttributeValueHelper(self._attributes.viewport) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isHovered(self): data_view = og.AttributeValueHelper(self._attributes.isHovered) return data_view.get() @isHovered.setter def isHovered(self, value): data_view = og.AttributeValueHelper(self._attributes.isHovered) data_view.set(value) @property def isValid(self): data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): data_view = og.AttributeValueHelper(self._attributes.isValid) data_view.set(value) @property def position(self): data_view = og.AttributeValueHelper(self._attributes.position) return data_view.get() @position.setter def position(self, value): data_view = og.AttributeValueHelper(self._attributes.position) data_view.set(value) @property def velocity(self): data_view = og.AttributeValueHelper(self._attributes.velocity) return data_view.get() @velocity.setter def velocity(self, value): data_view = og.AttributeValueHelper(self._attributes.velocity) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadViewportHoverStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadViewportHoverStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadViewportHoverStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
7,873
Python
47.906832
342
0.668741
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnDrawDebugCurveDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.DrawDebugCurve Given a set of curve points, draw a curve in the viewport """ import numpy import sys import traceback import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnDrawDebugCurveDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.DrawDebugCurve Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.closed inputs.color inputs.curvepoints inputs.execIn Outputs: outputs.execOut """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:closed', 'bool', 0, 'Closed', 'When true, connect the last point to the first', {}, True, False, False, ''), ('inputs:color', 'color3f', 0, 'Color', 'The color of the curve', {}, True, [0.0, 0.0, 0.0], False, ''), ('inputs:curvepoints', 'double3[]', 0, 'Curve Points', 'The curve to be drawn', {}, True, [], False, ''), ('inputs:execIn', 'execution', 0, 'In', 'Execution input', {}, True, None, False, ''), ('outputs:execOut', 'execution', 0, 'Out', 'Execution Output', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.color = og.AttributeRole.COLOR role_data.inputs.execIn = og.AttributeRole.EXECUTION role_data.outputs.execOut = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"closed", "color", "execIn", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.closed, self._attributes.color, self._attributes.execIn] self._batchedReadValues = [False, [0.0, 0.0, 0.0], None] @property def curvepoints(self): data_view = og.AttributeValueHelper(self._attributes.curvepoints) return data_view.get() @curvepoints.setter def curvepoints(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.curvepoints) data_view = og.AttributeValueHelper(self._attributes.curvepoints) data_view.set(value) self.curvepoints_size = data_view.get_array_size() @property def closed(self): return self._batchedReadValues[0] @closed.setter def closed(self, value): self._batchedReadValues[0] = value @property def color(self): return self._batchedReadValues[1] @color.setter def color(self, value): self._batchedReadValues[1] = value @property def execIn(self): return self._batchedReadValues[2] @execIn.setter def execIn(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnDrawDebugCurveDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnDrawDebugCurveDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnDrawDebugCurveDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui_nodes.DrawDebugCurve' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnDrawDebugCurveDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnDrawDebugCurveDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnDrawDebugCurveDatabase(node) try: compute_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnDrawDebugCurveDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnDrawDebugCurveDatabase.PER_NODE_DATA[node.node_id()] def on_connection_or_disconnection(*args): per_node_data['_db'] = None node.register_on_connected_callback(on_connection_or_disconnection) node.register_on_disconnected_callback(on_connection_or_disconnection) @staticmethod def release(node): release_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnDrawDebugCurveDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnDrawDebugCurveDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui_nodes") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Draw Debug Curve") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "debug") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Given a set of curve points, draw a curve in the viewport") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnDrawDebugCurveDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None @staticmethod def register(node_type_class): OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnDrawDebugCurveDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui_nodes.DrawDebugCurve")
12,801
Python
43.762238
136
0.626357
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnSetViewportModeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.SetViewportMode Sets the mode of a specified viewport window to 'Scripted' mode or 'Default' mode when executed. 'Scripted' mode disables default viewport interaction and enables placing UI elements over the viewport. 'Default' mode is the default state of the viewport, and entering it will destroy any UI elements on the viewport. Executing with 'Enable Viewport Mouse Events' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by viewport mouse event nodes, including 'On Viewport Dragged' and 'Read Viewport Drag State'. Executing with 'Enable Picking' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by the 'On Picked' and 'Read Pick State' nodes. """ import sys import traceback import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSetViewportModeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.SetViewportMode Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.enablePicking inputs.enableViewportMouseEvents inputs.execIn inputs.mode inputs.passClicksThru inputs.viewport Outputs: outputs.defaultMode outputs.scriptedMode outputs.widgetPath """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:enablePicking', 'bool', 0, 'Enable Picking', "Enable/Disable picking prims in the specified viewport when in 'Scripted' mode", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:enableViewportMouseEvents', 'bool', 0, 'Enable Viewport Mouse Events', "Enable/Disable viewport mouse events on the specified viewport when in 'Scripted' mode", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''), ('inputs:mode', 'int', 0, 'Mode', "The mode to set the specified viewport to when this node is executed (0: 'Default', 1: 'Scripted')", {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('inputs:passClicksThru', 'bool', 0, 'Pass Clicks Thru', "Allow mouse clicks to affect the viewport while in 'Scripted' mode.\n\nIn 'Scripted' mode mouse clicks are prevented from reaching the viewport to avoid accidentally\nselecting prims or interacting with the viewport's own UI. Setting this attribute true will\nallow clicks to reach the viewport. This is in addition to interacting with the widgets created\nby UI nodes so if a button widget appears on top of some geometry in the viewport, clicking on\nthe button will not only trigger the button but could also select the geometry. To avoid this,\nput the button inside a Stack widget and use a WriteWidgetProperty node to set the Stack's\n'content_clipping' property to 1.", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to set the mode of', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''), ('outputs:defaultMode', 'execution', 0, 'Default Mode', "Fires when this node is successfully executed with 'Mode' set to 'Default'", {}, True, None, False, ''), ('outputs:scriptedMode', 'execution', 0, 'Scripted Mode', "Fires when this node is successfully executed with 'Mode' set to 'Scripted'", {}, True, None, False, ''), ('outputs:widgetPath', 'token', 0, 'Widget Path', "When the viewport enters 'Scripted' mode, a container widget is created under which other UI may be parented.\nThis attribute provides the absolute path to that widget, which can be used as the 'parentWidgetPath'\ninput to various UI nodes, such as Button. When the viewport exits 'Scripted' mode,\nthe container widget and all the UI within it will be destroyed.", {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.execIn = og.AttributeRole.EXECUTION role_data.outputs.defaultMode = og.AttributeRole.EXECUTION role_data.outputs.scriptedMode = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"enablePicking", "enableViewportMouseEvents", "execIn", "mode", "passClicksThru", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.enablePicking, self._attributes.enableViewportMouseEvents, self._attributes.execIn, self._attributes.mode, self._attributes.passClicksThru, self._attributes.viewport] self._batchedReadValues = [False, False, None, 0, False, "Viewport"] @property def enablePicking(self): return self._batchedReadValues[0] @enablePicking.setter def enablePicking(self, value): self._batchedReadValues[0] = value @property def enableViewportMouseEvents(self): return self._batchedReadValues[1] @enableViewportMouseEvents.setter def enableViewportMouseEvents(self, value): self._batchedReadValues[1] = value @property def execIn(self): return self._batchedReadValues[2] @execIn.setter def execIn(self, value): self._batchedReadValues[2] = value @property def mode(self): return self._batchedReadValues[3] @mode.setter def mode(self, value): self._batchedReadValues[3] = value @property def passClicksThru(self): return self._batchedReadValues[4] @passClicksThru.setter def passClicksThru(self, value): self._batchedReadValues[4] = value @property def viewport(self): return self._batchedReadValues[5] @viewport.setter def viewport(self, value): self._batchedReadValues[5] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"defaultMode", "scriptedMode", "widgetPath", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def defaultMode(self): value = self._batchedWriteValues.get(self._attributes.defaultMode) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.defaultMode) return data_view.get() @defaultMode.setter def defaultMode(self, value): self._batchedWriteValues[self._attributes.defaultMode] = value @property def scriptedMode(self): value = self._batchedWriteValues.get(self._attributes.scriptedMode) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.scriptedMode) return data_view.get() @scriptedMode.setter def scriptedMode(self, value): self._batchedWriteValues[self._attributes.scriptedMode] = value @property def widgetPath(self): value = self._batchedWriteValues.get(self._attributes.widgetPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.widgetPath) return data_view.get() @widgetPath.setter def widgetPath(self, value): self._batchedWriteValues[self._attributes.widgetPath] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSetViewportModeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSetViewportModeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSetViewportModeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui_nodes.SetViewportMode' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnSetViewportModeDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnSetViewportModeDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnSetViewportModeDatabase(node) try: compute_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnSetViewportModeDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnSetViewportModeDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnSetViewportModeDatabase.PER_NODE_DATA[node.node_id()] def on_connection_or_disconnection(*args): per_node_data['_db'] = None node.register_on_connected_callback(on_connection_or_disconnection) node.register_on_disconnected_callback(on_connection_or_disconnection) @staticmethod def release(node): release_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnSetViewportModeDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnSetViewportModeDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui_nodes") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Set Viewport Mode (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Sets the mode of a specified viewport window to 'Scripted' mode or 'Default' mode when executed.\n 'Scripted' mode disables default viewport interaction and enables placing UI elements over the viewport. 'Default' mode is the default state of the viewport, and entering it will destroy any UI elements on the viewport.\n Executing with 'Enable Viewport Mouse Events' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by viewport mouse event nodes, including 'On Viewport Dragged' and 'Read Viewport Drag State'.\n Executing with 'Enable Picking' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by the 'On Picked' and 'Read Pick State' nodes.") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnSetViewportModeDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None @staticmethod def register(node_type_class): OgnSetViewportModeDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnSetViewportModeDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui_nodes.SetViewportMode")
17,641
Python
51.195266
804
0.655575
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/OgnOnViewportDraggedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui_nodes.OnViewportDragged Event node which fires when a viewport drag event occurs in the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnViewportDraggedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui_nodes.OnViewportDragged Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.onlyPlayback inputs.useNormalizedCoords inputs.viewport Outputs: outputs.began outputs.ended outputs.finalPosition outputs.initialPosition Predefined Tokens: tokens.LeftMouseDrag tokens.RightMouseDrag tokens.MiddleMouseDrag """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport drag events', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Drag,Right Mouse Drag,Middle Mouse Drag', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Drag", "RightMouseDrag": "Right Mouse Drag", "MiddleMouseDrag": "Middle Mouse Drag"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Drag"'}, True, "Left Mouse Drag", False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for drag events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, "Viewport", False, ''), ('outputs:began', 'execution', 0, 'Began', "Enabled when the drag begins, populating 'Initial Position' with the current mouse position", {}, True, None, False, ''), ('outputs:ended', 'execution', 0, 'Ended', "Enabled when the drag ends, populating 'Final Position' with the current mouse position", {}, True, None, False, ''), ('outputs:finalPosition', 'double2', 0, 'Final Position', "The mouse position at which the drag ended (valid when 'Ended' is enabled)", {}, True, None, False, ''), ('outputs:initialPosition', 'double2', 0, 'Initial Position', "The mouse position at which the drag began (valid when either 'Began' or 'Ended' is enabled)", {}, True, None, False, ''), ]) class tokens: LeftMouseDrag = "Left Mouse Drag" RightMouseDrag = "Right Mouse Drag" MiddleMouseDrag = "Middle Mouse Drag" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.began = og.AttributeRole.EXECUTION role_data.outputs.ended = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def gesture(self): data_view = og.AttributeValueHelper(self._attributes.gesture) return data_view.get() @gesture.setter def gesture(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gesture) data_view = og.AttributeValueHelper(self._attributes.gesture) data_view.set(value) @property def onlyPlayback(self): data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) return data_view.get() @onlyPlayback.setter def onlyPlayback(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.onlyPlayback) data_view = og.AttributeValueHelper(self._attributes.onlyPlayback) data_view.set(value) @property def useNormalizedCoords(self): data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) return data_view.get() @useNormalizedCoords.setter def useNormalizedCoords(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.useNormalizedCoords) data_view = og.AttributeValueHelper(self._attributes.useNormalizedCoords) data_view.set(value) @property def viewport(self): data_view = og.AttributeValueHelper(self._attributes.viewport) return data_view.get() @viewport.setter def viewport(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewport) data_view = og.AttributeValueHelper(self._attributes.viewport) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def began(self): data_view = og.AttributeValueHelper(self._attributes.began) return data_view.get() @began.setter def began(self, value): data_view = og.AttributeValueHelper(self._attributes.began) data_view.set(value) @property def ended(self): data_view = og.AttributeValueHelper(self._attributes.ended) return data_view.get() @ended.setter def ended(self, value): data_view = og.AttributeValueHelper(self._attributes.ended) data_view.set(value) @property def finalPosition(self): data_view = og.AttributeValueHelper(self._attributes.finalPosition) return data_view.get() @finalPosition.setter def finalPosition(self, value): data_view = og.AttributeValueHelper(self._attributes.finalPosition) data_view.set(value) @property def initialPosition(self): data_view = og.AttributeValueHelper(self._attributes.initialPosition) return data_view.get() @initialPosition.setter def initialPosition(self, value): data_view = og.AttributeValueHelper(self._attributes.initialPosition) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnViewportDraggedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnViewportDraggedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnViewportDraggedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
10,185
Python
48.207729
496
0.664507
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnOnViewportHovered.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 <OgnOnViewportHoveredDatabase.h> #include "ViewportHoverNodeCommon.h" #include <omni/kit/IApp.h> #include <omni/ui/Workspace.h> namespace omni { namespace graph { namespace ui_nodes { class OgnOnViewportHovered { public: struct InternalState { carb::events::ISubscriptionPtr hoverBeganSub; carb::events::ISubscriptionPtr hoverEndedSub; ViewportHoverEventPayloads eventPayloads; ViewportHoverEventStates eventStates; } m_internalState; exec::unstable::Stamp m_setStamp; // stamp set when the event occurs exec::unstable::SyncStamp m_syncStamp; // stamp set by each instance static void initialize(GraphContextObj const&, NodeObj const& nodeObj) { OgnOnViewportHovered& state = OgnOnViewportHoveredDatabase::sSharedState<OgnOnViewportHovered>(nodeObj); // Subscribe to hover events 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) { OgnOnViewportHovered& state = OgnOnViewportHoveredDatabase::sSharedState<OgnOnViewportHovered>(nodeObj); state.m_internalState.eventPayloads.clear(); state.m_internalState.eventPayloads.setHoverBeganPayload(e->payload); state.m_setStamp.next(); if (nodeObj.iNode->isValid(nodeObj)) nodeObj.iNode->requestCompute(nodeObj); } } ); state.m_internalState.hoverEndedSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kHoverEndedEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnOnViewportHovered& state = OgnOnViewportHoveredDatabase::sSharedState<OgnOnViewportHovered>(nodeObj); state.m_internalState.eventPayloads.setHoverEndedPayload(e->payload); state.m_setStamp.next(); if (nodeObj.iNode->isValid(nodeObj)) nodeObj.iNode->requestCompute(nodeObj); } } ); } } static void release(const NodeObj& nodeObj) { OgnOnViewportHovered& state = OgnOnViewportHoveredDatabase::sSharedState<OgnOnViewportHovered>(nodeObj); // Unsubscribe from hover events if (state.m_internalState.hoverBeganSub.get()) state.m_internalState.hoverBeganSub.detach()->unsubscribe(); if (state.m_internalState.hoverEndedSub.get()) state.m_internalState.hoverEndedSub.detach()->unsubscribe(); } static bool compute(OgnOnViewportHoveredDatabase& db) { if (checkNodeDisabledForOnlyPlay(db)) return true; OgnOnViewportHovered& sharedState = db.sharedState<OgnOnViewportHovered>(); OgnOnViewportHovered& perInstanceState = db.perInstanceState<OgnOnViewportHovered>(); if(perInstanceState.m_syncStamp.makeSync(sharedState.m_setStamp)) { if (sharedState.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); } // Process event payloads and update event state bool hoverBegan = false; for (auto const& hoverBeganPayload : sharedState.m_internalState.eventPayloads.hoverBeganPayloads()) { if (!hoverBeganPayload.second.isValid) continue; auto& eventStateValue = sharedState.m_internalState.eventStates[hoverBeganPayload.first]; eventStateValue.isHovered = true; if (std::strcmp(viewportWindowName, hoverBeganPayload.first.viewportWindowName) == 0) { hoverBegan = true; } } bool hoverEnded = false; for (auto const& hoverEndedPayload : sharedState.m_internalState.eventPayloads.hoverEndedPayloads()) { if (!hoverEndedPayload.second.isValid) continue; auto& eventStateValue = sharedState.m_internalState.eventStates[hoverEndedPayload.first]; if (eventStateValue.isHovered) { eventStateValue.isHovered = false; if (std::strcmp(viewportWindowName, hoverEndedPayload.first.viewportWindowName) == 0) { hoverEnded = true; } } } // Get event state and set outputs auto it = sharedState.m_internalState.eventStates.find({viewportWindowName}); if (it != sharedState.m_internalState.eventStates.end()) { if (hoverEnded) { db.outputs.began() = kExecutionAttributeStateDisabled; db.outputs.ended() = kExecutionAttributeStateEnabled; } else if (hoverBegan) { db.outputs.began() = kExecutionAttributeStateEnabled; db.outputs.ended() = kExecutionAttributeStateDisabled; } else { db.outputs.began() = kExecutionAttributeStateDisabled; db.outputs.ended() = kExecutionAttributeStateDisabled; } } } return true; } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
6,678
C++
36.948863
112
0.581761
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSlider.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.kit.app import omni.ui as ui from . import UINodeCommon class OgnSlider: @staticmethod def internal_state(): return UINodeCommon.OgnUINodeInternalState() @staticmethod def compute(db) -> bool: # OM-97733: This node hasn't been converted to use the widget registry yet. Let's discourage # its use. db.log_warning("The Slider node is unsupported and may not behave as expected.") if db.inputs.create != og.ExecutionAttributeState.DISABLED: min_value = db.inputs.min max_value = db.inputs.max step = db.inputs.step if step <= 0: db.log_error("The step size of the slider must be positive!") return False width = db.inputs.width if width <= 0: db.log_error("The width of the slider must be positive!") return False widget_identifier = UINodeCommon.get_unique_widget_identifier(db) parent_widget = UINodeCommon.get_parent_widget(db) if parent_widget is None: return False # Tear down previously created widget if db.internal_state.created_widget is not None: UINodeCommon.tear_down_widget(db) def on_slider_finished_dragging(model): if not db.internal_state.created_widget.enabled: return message_bus = omni.kit.app.get_app().get_message_bus_event_stream() event_name = "value_changed_" + widget_identifier reg_event_name = UINodeCommon.registered_event_name(event_name) payload = {"newValue": model.get_value_as_float(), "valueType": "float"} message_bus.push(reg_event_name, payload=payload) # Now create the button widget and register callbacks with parent_widget: db.internal_state.created_frame = ui.Frame() with db.internal_state.created_frame: with ui.HStack(content_clipping=1): db.internal_state.created_widget = ui.FloatSlider( identifier=widget_identifier, width=width, min=min_value, max=max_value, step=step, ) db.internal_state.created_widget.model.set_value((min_value + max_value) / 2) db.internal_state.created_widget.model.add_end_edit_fn(on_slider_finished_dragging) db.outputs.created = og.ExecutionAttributeState.ENABLED db.outputs.widgetPath = UINodeCommon.find_widget_path(db.internal_state.created_widget) return True if db.inputs.tearDown != og.ExecutionAttributeState.DISABLED: return UINodeCommon.tear_down_widget(db) if db.inputs.show != og.ExecutionAttributeState.DISABLED: return UINodeCommon.show_widget(db) if db.inputs.hide != og.ExecutionAttributeState.DISABLED: return UINodeCommon.hide_widget(db) if db.inputs.enable != og.ExecutionAttributeState.DISABLED: return UINodeCommon.enable_widget(db) if db.inputs.disable != og.ExecutionAttributeState.DISABLED: return UINodeCommon.disable_widget(db) db.log_warning("Unexpected execution with no execution input enabled") return False
3,974
Python
39.979381
107
0.614494
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnLockViewportRender.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from enum import Enum, auto from omni.graph.core import ExecutionAttributeState from omni.graph.ui_nodes.ogn.OgnLockViewportRenderDatabase import OgnLockViewportRenderDatabase from omni.kit.viewport.utility import get_active_viewport_window class LockState(Enum): """Enum for lock state""" UNLOCKED = auto() """The target has been unlocked.""" LOCKED = auto() """The target has been locked.""" UNLOCKING = auto() """The target is being unlocked.""" class OgnLockViewportRenderInternalState: """Convenience class for maintaining per-node state information""" def __init__(self): self._lock_state = LockState.UNLOCKED self._viewport_name = "" self._viewport_api = None self._viewport_widget = None self._previous_freeze_frame = None self._previous_display_delegate = None self._elapsed_time = 0.0 self._fading_time = 1.0 @property def lock_state(self) -> LockState: return self._lock_state @lock_state.setter def lock_state(self, state: LockState): self._lock_state = state @property def viewport_name(self): return self._viewport_name @viewport_name.setter def viewport_name(self, name): self._viewport_name = name @property def viewport_api(self): return self._viewport_api @viewport_api.setter def viewport_api(self, api): assert api is not None self._viewport_api = api @property def viewport_widget(self): return self._viewport_widget @viewport_widget.setter def viewport_widget(self, widget): assert widget is not None self._viewport_widget = widget @property def previous_freeze_frame(self): return self._previous_freeze_frame @previous_freeze_frame.setter def previous_freeze_frame(self, freeze_frame): assert isinstance(freeze_frame, bool) self._previous_freeze_frame = freeze_frame @property def previous_display_delegate(self): return self._previous_display_delegate @previous_display_delegate.setter def previous_display_delegate(self, display_delegate): assert display_delegate is not None self._previous_display_delegate = display_delegate @property def elapsed_time(self) -> float: return self._elapsed_time @elapsed_time.setter def elapsed_time(self, time: float): self._elapsed_time = time @property def fading_time(self) -> float: return self._fading_time @fading_time.setter def fading_time(self, time: float): self._fading_time = time def restore_freeze_frame(self): if self._viewport_api is not None: assert isinstance(self._previous_freeze_frame, bool) self._viewport_api.freeze_frame = self._previous_freeze_frame self._viewport_api = None self._previous_freeze_frame = None def restore_display_delegate(self): if self._viewport_widget is not None: self._viewport_widget.display_delegate = self._previous_display_delegate self._viewport_widget = None self._previous_display_delegate = None class OgnLockViewportRender: """ Locks and unlocks viewport render. """ @staticmethod def internal_state(): """Return an object that will contain per-node state information""" return OgnLockViewportRenderInternalState() @staticmethod def unlock_immediately_if_locked(internal_state): """Unlock viewport render immediately if locked""" assert isinstance(internal_state, OgnLockViewportRenderInternalState) if internal_state.lock_state != LockState.UNLOCKED: internal_state.restore_display_delegate() internal_state.restore_freeze_frame() internal_state.lock_state = LockState.UNLOCKED @staticmethod def release(node): """When a node is removed it will get a release call for cleanup""" internal_state = OgnLockViewportRenderDatabase.per_node_internal_state(node) if internal_state is not None: OgnLockViewportRender.unlock_immediately_if_locked(internal_state) @staticmethod def compute(db) -> bool: """Compute the outputs from the current inputs""" try: # An extension is generally not allowed to force a specific viewport backend like omni.kit.widget.viewport # to be loaded; instead it is the application that controls which viewport to be loaded. If the following # import fails at runtime, it is because omni.kit.widget.viewport is not loaded by the application, then # the node won't be supported to lock and unlock viewport render. from omni.kit.widget.viewport.display_delegate import OverlayViewportDisplayDelegate locked_exec_attr_state = ExecutionAttributeState.DISABLED fade_started_exec_attr_state = ExecutionAttributeState.DISABLED fade_complete_exec_attr_state = ExecutionAttributeState.DISABLED internal_state = db.internal_state # If target viewport is changed, make sure viewport render is unlocked for the previous viewport viewport_name = db.inputs.viewport if internal_state.viewport_name != viewport_name: OgnLockViewportRender.unlock_immediately_if_locked(internal_state) internal_state.viewport_name = viewport_name if db.inputs.lock == ExecutionAttributeState.ENABLED: if internal_state.lock_state == LockState.UNLOCKED: # sanity check assert ( internal_state.viewport_api is None and internal_state.viewport_widget is None and internal_state.previous_freeze_frame is None and internal_state.previous_display_delegate is None ), "Invalid internal state" viewport_window = get_active_viewport_window(viewport_name) assert viewport_window, f"Unknown viewport window {viewport_name}" viewport_api = viewport_window.viewport_api viewport_widget = viewport_window.viewport_widget # We need to restore the display delegate to the previous one when unlocking viewport render internal_state.viewport_api = viewport_api internal_state.viewport_widget = viewport_widget internal_state.previous_freeze_frame = viewport_api.freeze_frame internal_state.previous_display_delegate = viewport_widget.display_delegate # Signal other viewport elements that the viewport is locked so certain things won't update viewport_api.freeze_frame = True # Set to a new display delegate that overlays the locked frame on top of the renderer output viewport_widget.display_delegate = OverlayViewportDisplayDelegate(viewport_api) locked_exec_attr_state = ExecutionAttributeState.ENABLED internal_state.lock_state = LockState.LOCKED else: if internal_state.lock_state == LockState.LOCKED: # Start updating relevant parts of the viewport now that the transition has begun internal_state.restore_freeze_frame() internal_state.elapsed_time = 0.0 internal_state.fading_time = max(db.inputs.fadeTime, 0.0) # Push this node in a latent state. Note the output connection of the `fadeStarted` attribute # can't be activated at the same tick because only 1 activated output is permited per compute, # therefore it has to be activated until the next tick. fade_complete_exec_attr_state = ExecutionAttributeState.LATENT_PUSH internal_state.lock_state = LockState.UNLOCKING elif internal_state.lock_state == LockState.UNLOCKING: elapsed_time = internal_state.elapsed_time fading_time = internal_state.fading_time assert elapsed_time >= 0.0 and fading_time >= 0.0 if elapsed_time == 0.0: fade_started_exec_attr_state = ExecutionAttributeState.ENABLED elif elapsed_time < fading_time: display_delegate = internal_state.viewport_widget.display_delegate assert isinstance(display_delegate, OverlayViewportDisplayDelegate) display_delegate.set_overlay_alpha(1.0 - elapsed_time / fading_time) elif elapsed_time >= fading_time: # Reset the display delegate to the previous one that was used before locking viewport render internal_state.restore_display_delegate() # Output attribute connection is activated and the latent state is finished for this node fade_complete_exec_attr_state = ExecutionAttributeState.LATENT_FINISH internal_state.lock_state = LockState.UNLOCKED internal_state.elapsed_time += db.abi_context.get_elapsed_time() db.outputs.locked = locked_exec_attr_state db.outputs.fadeStarted = fade_started_exec_attr_state db.outputs.fadeComplete = fade_complete_exec_attr_state except Exception as error: # noqa: PLW0703 db.log_error(str(error)) return False return True
10,244
Python
38.555984
118
0.640863
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnComboBox.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.kit.app import omni.ui as ui from . import UINodeCommon class ComboBoxItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.model = ui.SimpleStringModel(text) class ComboBoxModel(ui.AbstractItemModel): def __init__(self, item_list): super().__init__() self._current_index = ui.SimpleIntModel(0) self._current_index.add_value_changed_fn(lambda index_model: self._item_changed(None)) self._items = [ComboBoxItem(text) for text in item_list] def get_item_children(self, item=None): return self._items def get_item_value_model(self, item=None, column_id=0): if item is None: return self._current_index return item.model class OgnComboBox: @staticmethod def internal_state(): return UINodeCommon.OgnUINodeInternalState() @staticmethod def compute(db) -> bool: # OM-97733: This node hasn't been converted to use the widget registry yet. Let's discourage # its use. db.log_warning("The ComboBox node is unsupported and may not behave as expected.") if db.inputs.create != og.ExecutionAttributeState.DISABLED: item_list = db.inputs.itemList if not item_list: db.log_error("The combo box must have at least one item!") return False width = db.inputs.width if width <= 0: db.log_error("The width of the combo box must be positive!") return False widget_identifier = UINodeCommon.get_unique_widget_identifier(db) parent_widget = UINodeCommon.get_parent_widget(db) if parent_widget is None: return False # Tear down previously created widget if db.internal_state.created_widget is not None: UINodeCommon.tear_down_widget(db) def on_combox_box_item_changed(model, item): if not db.internal_state.created_widget.enabled: return current_index = model.get_item_value_model().as_int selected_child = model.get_item_children()[current_index] selected_value = model.get_item_value_model(selected_child).as_string message_bus = omni.kit.app.get_app().get_message_bus_event_stream() event_name = "value_changed_" + widget_identifier reg_event_name = UINodeCommon.registered_event_name(event_name) payload = {"newValue": selected_value, "valueType": "string"} message_bus.push(reg_event_name, payload=payload) # Now create the button widget and register callbacks with parent_widget: db.internal_state.created_frame = ui.Frame() with db.internal_state.created_frame: with ui.HStack(content_clipping=1): db.internal_state.created_widget = ui.ComboBox( ComboBoxModel(item_list), identifier=widget_identifier, width=width, ) db.internal_state.created_widget.model.add_item_changed_fn(on_combox_box_item_changed) db.outputs.created = og.ExecutionAttributeState.ENABLED db.outputs.widgetPath = UINodeCommon.find_widget_path(db.internal_state.created_widget) return True if db.inputs.tearDown != og.ExecutionAttributeState.DISABLED: return UINodeCommon.tear_down_widget(db) if db.inputs.show != og.ExecutionAttributeState.DISABLED: return UINodeCommon.show_widget(db) if db.inputs.hide != og.ExecutionAttributeState.DISABLED: return UINodeCommon.hide_widget(db) if db.inputs.enable != og.ExecutionAttributeState.DISABLED: return UINodeCommon.enable_widget(db) if db.inputs.disable != og.ExecutionAttributeState.DISABLED: return UINodeCommon.disable_widget(db) db.log_warning("Unexpected execution with no execution input enabled") return False
4,651
Python
38.092437
110
0.627607
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnGetCameraPosition.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 <OgnGetCameraPositionDatabase.h> #include "CameraState.h" #include "NodeUtils.h" namespace omni { namespace graph { namespace ui_nodes { class OgnGetCameraPosition { public: static bool compute(OgnGetCameraPositionDatabase& db) { PXR_NS::UsdPrim prim = getPrimFromPathOrRelationship(db, OgnGetCameraPositionAttributes::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 position; cameraState.getCameraPosition(position); carb::Double3& positionAttrib = reinterpret_cast<carb::Double3&>(db.outputs.position()); positionAttrib = position; return true; } }; REGISTER_OGN_NODE() } } }
1,340
C++
23.381818
119
0.708209
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/UINodeCommon.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 <omni/graph/core/ogn/UsdTypes.h> #include <carb/dictionary/IDictionary.h> #include <carb/events/EventsUtils.h> #include <carb/events/IEvents.h> #include <algorithm> #include <cstring> #include <map> #include <memory> #include <utility> namespace omni { namespace graph { namespace ui_nodes { /** * Checks if the node with `inputs:onlyPlayback` should be disabled, because playback is not happening. * * @param[in] db The node OGN Database object * @return true if the node should be disabled */ template<typename NodeDb> bool checkNodeDisabledForOnlyPlay(NodeDb const& db) { return db.inputs.onlyPlayback() && (not db.abi_context().iContext->getIsPlaying(db.abi_context())); } /** * Memoizes constant copies of C-strings to reduce heap allocation calls when passing equivalent C-strings between scopes. */ class StringMemo { public: /** * Finds or creates a constant copy of the input C-string having the same lifetime as this StringMemo object. * * @param[in] cstr A null-terminated C-style string * @return An equivalent constant C-style string */ char const* lookup(char const* cstr) { if (!cstr) return nullptr; auto it = m_map.find(cstr); if (it == m_map.end()) { std::unique_ptr<char const, cstr_deleter> cstr_copy {cstrdup(cstr)}; char const* cstr_copy_ptr = cstr_copy.get(); m_map.emplace(cstr_copy_ptr, std::move(cstr_copy)); return cstr_copy_ptr; } return it->first; } private: static char* cstrdup(const char *cstr) { std::size_t const len = std::strlen(cstr); char* new_copy = static_cast<char*>(std::malloc(len + 1)); if (!new_copy) return nullptr; std::memcpy(new_copy, cstr, len + 1); return new_copy; } struct cstr_cmp { bool operator()(char const* a, char const* b) const { return std::strcmp(a, b) < 0; } }; struct cstr_deleter{ void operator()(char const* p) const { std::free(const_cast<char*>(p)); } }; std::map<char const*, std::unique_ptr<char const, cstr_deleter>, cstr_cmp> m_map; }; } } }
2,694
C
25.165048
122
0.641797
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/ViewportPressNodeCommon.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_nodes { constexpr carb::events::EventType kPressBeganEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.press.began"); constexpr carb::events::EventType kPressEndedEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.press.ended"); class ViewportPressEventPayloads { 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 PressBeganValue { pxr::GfVec2d pressPositionNorm; pxr::GfVec2d pressPositionPixel; bool isValid; }; struct PressEndedValue { pxr::GfVec2d releasePositionNorm; pxr::GfVec2d releasePositionPixel; bool isReleasePositionValid; bool isValid; }; // Store a press began event payload void setPressBeganPayload(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")) }; pressBeganPayloadMap[key] = PressBeganValue { 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 press ended event payload void setPressEndedPayload(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")) }; pressEndedPayloadMap[key] = PressEndedValue { 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<bool>(payload, "pos_valid"), true }; } // Invalidate all stored payloads void clear() { for (auto& p : pressBeganPayloadMap) { p.second.isValid = false; } for (auto& p : pressEndedPayloadMap) { p.second.isValid = false; } } bool empty() { if (std::any_of(pressBeganPayloadMap.begin(), pressBeganPayloadMap.end(), [](auto const& p) { return p.second.isValid; })) { return false; } if (std::any_of(pressEndedPayloadMap.begin(), pressEndedPayloadMap.end(), [](auto const& p) { return p.second.isValid; })) { return false; } return true; } std::map<Key, PressBeganValue> const& pressBeganPayloads() { return pressBeganPayloadMap; } std::map<Key, PressEndedValue> const& pressEndedPayloads() { return pressEndedPayloadMap; } private: std::map<Key, PressBeganValue> pressBeganPayloadMap; std::map<Key, PressEndedValue> pressEndedPayloadMap; StringMemo stringMemo; }; using ViewportPressEventStateKey = ViewportPressEventPayloads::Key; struct ViewportPressEventStateValue { pxr::GfVec2d pressPositionNorm = {0.0, 0.0}; pxr::GfVec2d pressPositionPixel = {0.0, 0.0}; pxr::GfVec2d releasePositionNorm = {0.0, 0.0}; pxr::GfVec2d releasePositionPixel = {0.0, 0.0}; bool isPressed = false; bool isReleasePositionValid = false; }; using ViewportPressEventStates = std::map<ViewportPressEventStateKey, ViewportPressEventStateValue>; } } }
4,802
C
27.589286
118
0.600583
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnWriteWidgetStyle.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 OgnWriteWidgetStyle: @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 style_string = db.inputs.style if not style_string: db.log_error("No style provided.") 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.set_style(style) db.outputs.written = og.ExecutionAttributeState.ENABLED return True db.log_warning("Unexpected execution with no execution input enabled") return False
2,150
Python
37.410714
107
0.607907
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/ViewportDragManipulator.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__ = ["ViewportDragManipulatorFactory"] 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.drag.began" EVENT_NAME_CHANGED = "omni.graph.viewport.drag.changed" EVENT_NAME_ENDED = "omni.graph.viewport.drag.ended" GESTURE_NAMES = ["Left Mouse Drag", "Right Mouse Drag", "Middle Mouse Drag"] class DoNotPrevent(sc.GestureManager): def can_be_prevented(self, gesture): return False class ViewportDragGesture(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_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._start_pos_valid = False self._started_moving = False self._start_pos_norm = None self._start_pos_pixel = None def on_began(self): mouse = self.sender.gesture_payload.mouse resolution = self._viewport_api.resolution # Start 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 # Start position in viewport resolution pixels pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1]) # Store start position and wait for on_changed to send self._start_pos_valid = True self._started_moving = False self._start_pos_norm = pos_norm self._start_pos_pixel = pos_pixel def on_changed(self): if not self._start_pos_valid: return mouse = self.sender.gesture_payload.mouse mouse_moved = self.sender.gesture_payload.mouse_moved resolution = self._viewport_api.resolution # Current 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 # Current position in viewport resolution pixels pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1]) # Velocity in normalized coords 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]) # Velocity in viewport resolution pixels vel_pixel = (vel_norm[0] * resolution[0], vel_norm[1] * resolution[1]) if not self._started_moving: payload = { "viewport": self._viewport_window_name, "gesture": self._gesture_name, "start_pos_norm_x": self._start_pos_norm[0], "start_pos_norm_y": self._start_pos_norm[1], "start_pos_pixel_x": self._start_pos_pixel[0], "start_pos_pixel_y": self._start_pos_pixel[1], "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_began, payload=payload) self._started_moving = True else: 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], "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) def on_ended(self): if self._start_pos_valid and self._started_moving: payload = { "viewport": self._viewport_window_name, "gesture": self._gesture_name, } 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 ViewportDragManipulator(sc.Manipulator): def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs): super().__init__(*args, **kwargs) self._gestures = [ ViewportDragGesture(viewport_api, viewport_window_name, 0), # left mouse drag ViewportDragGesture(viewport_api, viewport_window_name, 1), # right mouse drag ViewportDragGesture(viewport_api, viewport_window_name, 2), # middle mouse drag ] 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 ViewportDragManipulatorFactory(desc: dict) -> ViewportDragManipulator: # noqa: N802 manip = ViewportDragManipulator(desc.get("viewport_api"), desc.get("viewport_window_name")) manip.categories = () manip.name = f"ViewportDragManipulator.{desc.get('viewport_window_name')}" return manip
6,711
Python
38.482353
95
0.60453
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnReadViewportPressState.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 <OgnReadViewportPressStateDatabase.h> #include "ViewportPressNodeCommon.h" #include <omni/kit/IApp.h> #include <omni/ui/Workspace.h> namespace omni { namespace graph { namespace ui_nodes { class OgnReadViewportPressState { public: struct InternalState { carb::events::ISubscriptionPtr pressBeganSub; carb::events::ISubscriptionPtr pressEndedSub; ViewportPressEventPayloads eventPayloads; ViewportPressEventStates eventStates; } m_internalState; exec::unstable::Stamp m_setStamp; // stamp set when the event occurs exec::unstable::SyncStamp m_syncStamp; // stamp set by each instance // // Process event payloads and update event states immediately after receiving each payload static void updateEventStates(ViewportPressEventStates& eventStates, ViewportPressEventPayloads& eventPayloads) { for (auto const& pressBeganPayload : eventPayloads.pressBeganPayloads()) { if (!pressBeganPayload.second.isValid) continue; auto& eventStateValue = eventStates[pressBeganPayload.first]; eventStateValue.pressPositionNorm = pressBeganPayload.second.pressPositionNorm; eventStateValue.pressPositionPixel = pressBeganPayload.second.pressPositionPixel; eventStateValue.releasePositionNorm = {0.0, 0.0}; eventStateValue.releasePositionPixel = {0.0, 0.0}; eventStateValue.isPressed = true; eventStateValue.isReleasePositionValid = false; } for (auto const& pressEndedPayload : eventPayloads.pressEndedPayloads()) { if (!pressEndedPayload.second.isValid) continue; auto& eventStateValue = eventStates[pressEndedPayload.first]; if (eventStateValue.isPressed) { eventStateValue.releasePositionNorm = pressEndedPayload.second.releasePositionNorm; eventStateValue.releasePositionPixel = pressEndedPayload.second.releasePositionPixel; eventStateValue.isPressed = false; eventStateValue.isReleasePositionValid = pressEndedPayload.second.isReleasePositionValid; } } eventPayloads.clear(); } static void initialize(GraphContextObj const&, NodeObj const& nodeObj) { OgnReadViewportPressState& state = OgnReadViewportPressStateDatabase::sSharedState<OgnReadViewportPressState>(nodeObj); // Subscribe to press events if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>()) { state.m_internalState.pressBeganSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kPressBeganEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnReadViewportPressState& state = OgnReadViewportPressStateDatabase::sSharedState<OgnReadViewportPressState>(nodeObj); state.m_internalState.eventPayloads.setPressBeganPayload(e->payload); state.m_setStamp.next(); updateEventStates(state.m_internalState.eventStates, state.m_internalState.eventPayloads); } } ); state.m_internalState.pressEndedSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kPressEndedEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnReadViewportPressState& state = OgnReadViewportPressStateDatabase::sSharedState<OgnReadViewportPressState>(nodeObj); state.m_internalState.eventPayloads.setPressEndedPayload(e->payload); state.m_setStamp.next(); updateEventStates(state.m_internalState.eventStates, state.m_internalState.eventPayloads); } } ); } } static void release(const NodeObj& nodeObj) { OgnReadViewportPressState& state = OgnReadViewportPressStateDatabase::sSharedState<OgnReadViewportPressState>(nodeObj); // Unsubscribe from press events if (state.m_internalState.pressBeganSub.get()) state.m_internalState.pressBeganSub.detach()->unsubscribe(); if (state.m_internalState.pressEndedSub.get()) state.m_internalState.pressEndedSub.detach()->unsubscribe(); } static bool compute(OgnReadViewportPressStateDatabase& db) { OgnReadViewportPressState& sharedState = db.sharedState<OgnReadViewportPressState>(); OgnReadViewportPressState& perInstanceState = db.perInstanceState<OgnReadViewportPressState>(); if(perInstanceState.m_syncStamp.makeSync(sharedState.m_setStamp)) { // 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 press state auto it = sharedState.m_internalState.eventStates.find({viewportWindowName, gestureName}); if (it != sharedState.m_internalState.eventStates.end()) { if (db.inputs.useNormalizedCoords()) { db.outputs.pressPosition() = it->second.pressPositionNorm; db.outputs.releasePosition() = it->second.releasePositionNorm; } else { db.outputs.pressPosition() = it->second.pressPositionPixel; db.outputs.releasePosition() = it->second.releasePositionPixel; } db.outputs.isReleasePositionValid() = it->second.isReleasePositionValid; db.outputs.isPressed() = it->second.isPressed; db.outputs.isValid() = true; } else { db.outputs.pressPosition() = {0.0, 0.0}; db.outputs.releasePosition() = {0.0, 0.0}; db.outputs.isReleasePositionValid() = false; db.outputs.isPressed() = false; db.outputs.isValid() = false; } } return true; } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
7,263
C++
38.912088
115
0.61655
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/ViewportClickNodeCommon.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_nodes { constexpr carb::events::EventType kClickEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.click"); class ViewportClickEventPayloads { 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 { pxr::GfVec2d positionNorm; pxr::GfVec2d positionPixel; 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 { 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 }; } // 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,803
C
25.205607
107
0.590082
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/PickingManipulator.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__ = ["PickingManipulatorFactory"] from typing import Any, List, Optional import carb import omni.kit.app import omni.kit.commands from omni.ui import scene as sc EVENT_NAME = "omni.graph.picking" CLICK_GESTURE_NAMES = ["Left Mouse Click", "Right Mouse Click", "Middle Mouse Click"] PRESS_GESTURE_NAMES = ["Left Mouse Press", "Right Mouse Press", "Middle Mouse Press"] SEQ_LIMIT = 128 class DoNotPrevent(sc.GestureManager): def can_be_prevented(self, gesture): return False # Custom gesture that triggers a picking query on mouse press, and sends the result on both mouse press and end of click class PickingGesture(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._click_gesture_name = CLICK_GESTURE_NAMES[mouse_button] self._press_gesture_name = PRESS_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() # Sequence number for associating picking queries with gestures self._seq = 0 # Bool to track whether the mouse button was initially pressed over the 3D viewport or not # (does not need to be an array like the rest since _query_completed does not need to check it) self._began = False # Sequence number indexed bools to control the following execution order cases for mouse click: # 1: on_began -> _query_completed -> on_ended # 2: on_began -> _query_completed -> on_changed (cancelled) -> on_ended # 3: on_began -> on_ended -> _query_completed # 4: on_began -> on_changed (cancelled) -> _query_completed -> on_ended # 5: on_began -> on_changed (cancelled) -> on_ended -> _query_completed self._ended = [False] * SEQ_LIMIT # True if the mouse button has been released without moving the mouse self._cancelled = [False] * SEQ_LIMIT # True if the mouse was moved while pressed, cancelling the click self._result_stored = [False] * SEQ_LIMIT # True if the picking query has completed and stored its result # Sequence number indexed temporary buffers to hold the picking result self._picked_prim_path = [None] * SEQ_LIMIT self._world_space_pos = [None] * SEQ_LIMIT # Callback to request_query called when the picking query completes def _query_completed(self, seq: int, picked_prim_path: str, world_space_pos: Optional[List[float]], *args): # Handle mouse press: # Send the picked prim path and picked world position in an event payload # Include the viewport window name and gesture name to filter on the receiving end press_payload = { "viewport": self._viewport_window_name, "gesture": self._press_gesture_name, "path": picked_prim_path, "pos_x": world_space_pos[0] if world_space_pos else 0.0, "pos_y": world_space_pos[1] if world_space_pos else 0.0, "pos_z": world_space_pos[2] if world_space_pos else 0.0, } self._message_bus.push(self._event_type, payload=press_payload) # Handle cases for mouse click if self._cancelled[seq]: return if self._ended[seq]: # Case 3: Click has already ended and we were waiting on the query to complete, so send the payload now click_payload = { "viewport": self._viewport_window_name, "gesture": self._click_gesture_name, "path": picked_prim_path, "pos_x": world_space_pos[0] if world_space_pos else 0.0, "pos_y": world_space_pos[1] if world_space_pos else 0.0, "pos_z": world_space_pos[2] if world_space_pos else 0.0, } self._message_bus.push(self._event_type, payload=click_payload) else: # Case 1 or 2: Click has not completed yet, so save the picking result and wait until mouse is released self._picked_prim_path[seq] = picked_prim_path self._world_space_pos[seq] = world_space_pos self._result_stored[seq] = True def _query_completed_seq(self, seq: int): return lambda *args: self._query_completed(seq, *args) # Called when the specified mouse button is pressed def on_began(self): # Get the next sequence number and reset the control bools self._seq = (self._seq + 1) % SEQ_LIMIT self._began = False self._ended[self._seq] = False self._cancelled[self._seq] = False self._result_stored[self._seq] = False self._picked_prim_path[self._seq] = None self._world_space_pos[self._seq] = None # Get the mouse position in normalized coords and check if the mouse is actually over the 3D viewport mouse = self.sender.gesture_payload.mouse resolution = self._viewport_api.resolution pos_norm, _ = self._viewport_api.map_ndc_to_texture(mouse) if pos_norm is None or not all(0.0 <= x <= 1.0 for x in pos_norm): return self._began = True # Get the mouse position in viewport resolution pixels and request a picking query pos_pixel = (int(pos_norm[0] * resolution[0]), int((1.0 - pos_norm[1]) * resolution[1])) self._viewport_api.request_query( pos_pixel, self._query_completed_seq(self._seq), query_name=f"omni.graph.ui_nodes.PickingManipulator.{id(self)}", ) # Called when the mouse is moved while pressed, cancelling the click def on_changed(self): if not self._began: return self._cancelled[self._seq] = True # Called when the specified mouse button is released def on_ended(self): if not self._began or self._cancelled[self._seq]: return if self._result_stored[self._seq]: # Case 1: The picking query has already completed and we have the result saved, so send the payload now picked_prim_path = self._picked_prim_path[self._seq] world_space_pos = self._world_space_pos[self._seq] click_payload = { "viewport": self._viewport_window_name, "gesture": self._click_gesture_name, "path": picked_prim_path, "pos_x": world_space_pos[0] if world_space_pos else 0.0, "pos_y": world_space_pos[1] if world_space_pos else 0.0, "pos_z": world_space_pos[2] if world_space_pos else 0.0, } self._message_bus.push(self._event_type, payload=click_payload) else: # Case 3: The picking query has not completed yet, so wait until it completes to send the payload self._ended[self._seq] = True # Custom manipulator containing a screen that contains the gestures class PickingManipulator(sc.Manipulator): def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs): super().__init__(*args, **kwargs) self._gestures = [ PickingGesture(viewport_api, viewport_window_name, 0), # left mouse click/press PickingGesture(viewport_api, viewport_window_name, 1), # right mouse click/press PickingGesture(viewport_api, viewport_window_name, 2), # middle mouse click/press ] self._screen = None self._transform = None self.name = None self.categories = () def on_build(self): # Create a transform and put a screen in it (must hold a reference to keep the sc.Screen alive) self._transform = sc.Transform() with self._transform: # sc.Screen is an invisible rectangle that is always in front of and entirely covers the viewport camera # By attaching the gestures to this screen, the gestures can be triggered by clicking anywhere 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 PickingManipulatorFactory(desc: dict) -> PickingManipulator: # noqa: N802 manip = PickingManipulator(desc.get("viewport_api"), desc.get("viewport_window_name")) manip.categories = () manip.name = f"PickingManipulator.{desc.get('viewport_window_name')}" return manip
9,093
Python
45.397959
120
0.638953
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetCameraPosition.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 <OgnSetCameraPositionDatabase.h> #include "CameraState.h" #include "NodeUtils.h" #include <pxr/base/gf/vec3d.h> namespace omni { namespace graph { namespace ui_nodes { class OgnSetCameraPosition { public: static bool compute(OgnSetCameraPositionDatabase& db) { PXR_NS::UsdPrim prim = getPrimFromPathOrRelationship(db, OgnSetCameraPositionAttributes::inputs::prim.m_token); if (!prim) return false; auto position = db.inputs.position(); auto rotate = db.inputs.rotate(); auto camera = PXR_NS::UsdGeomCamera(prim); if (!camera) return false; CameraState cameraState(std::move(camera)); bool ok = cameraState.setCameraPosition({ position[0], position[1], position[2] }, rotate); if (!ok) { db.logError("Could not set position for camera %s", prim.GetPath().GetText()); } db.outputs.execOut() = kExecutionAttributeStateEnabled; return true; } }; REGISTER_OGN_NODE() } } }
1,541
C++
23.870967
119
0.683971
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnReadViewportScrollState.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 <OgnReadViewportScrollStateDatabase.h> #include "ViewportScrollNodeCommon.h" #include <omni/kit/IApp.h> #include <omni/ui/Workspace.h> namespace omni { namespace graph { namespace ui_nodes { class OgnReadViewportScrollState { public: struct InternalState { carb::events::ISubscriptionPtr scrollSub; ViewportScrollEventPayloads eventPayloads; } m_internalState; exec::unstable::Stamp m_setStamp; // stamp set when the event occurs exec::unstable::SyncStamp m_syncStamp; // stamp set by each instance static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { OgnReadViewportScrollState& state = OgnReadViewportScrollStateDatabase::sSharedState<OgnReadViewportScrollState>(nodeObj); // 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) { OgnReadViewportScrollState& state = OgnReadViewportScrollStateDatabase::sSharedState<OgnReadViewportScrollState>(nodeObj); state.m_internalState.eventPayloads.setPayload(e->payload); state.m_setStamp.next(); } } ); } } static void release(const NodeObj& nodeObj) { OgnReadViewportScrollState& state = OgnReadViewportScrollStateDatabase::sSharedState<OgnReadViewportScrollState>(nodeObj); // Unsubscribe from scroll events if (state.m_internalState.scrollSub.get()) state.m_internalState.scrollSub.detach()->unsubscribe(); } static bool compute(OgnReadViewportScrollStateDatabase& db) { OgnReadViewportScrollState& sharedState = db.sharedState<OgnReadViewportScrollState>(); OgnReadViewportScrollState& perInstanceState = db.perInstanceState<OgnReadViewportScrollState>(); if(perInstanceState.m_syncStamp.makeSync(sharedState.m_setStamp)) { // Get the targeted viewport and gesture 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 = sharedState.m_internalState.eventPayloads.getPayloadValue(viewportWindowName); if (eventPayloadValuePtr) { db.outputs.scrollValue() = eventPayloadValuePtr->scrollValue; db.outputs.position() = db.inputs.useNormalizedCoords() ? eventPayloadValuePtr->positionNorm : eventPayloadValuePtr->positionPixel; db.outputs.isValid() = true; } else { db.outputs.scrollValue() = 0.0f; db.outputs.position() = {0.0, 0.0}; db.outputs.isValid() = false; } } return true; } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
3,820
C++
35.740384
147
0.638743
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnOnWidgetValueChanged.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from contextlib import suppress import omni.graph.core as og from omni.graph.ui_nodes.ogn.OgnOnWidgetValueChangedDatabase import OgnOnWidgetValueChangedDatabase from . import UINodeCommon class OgnOnWidgetValueChanged: @staticmethod def try_resolve_output_attribute(node, attr_name, attr_type): out_attr = node.get_attribute(attr_name) attr_type_valid = attr_type.base_type != og.BaseDataType.UNKNOWN if out_attr.get_resolved_type().base_type != og.BaseDataType.UNKNOWN and ( not attr_type_valid or attr_type != out_attr.get_resolved_type() ): out_attr.set_resolved_type(og.Type(og.BaseDataType.UNKNOWN)) if attr_type_valid and out_attr.get_resolved_type().base_type == og.BaseDataType.UNKNOWN: out_attr.set_resolved_type(attr_type) @staticmethod def internal_state(): return UINodeCommon.OgnUIEventNodeInternalState() @staticmethod def compute(db) -> bool: widget_identifier = db.inputs.widgetIdentifier if not widget_identifier: return True event_name = "value_changed_" + widget_identifier if db.internal_state.first_time_subscribe(db.node, event_name): return True payload = db.internal_state.try_pop_event() if payload is None: return True if "valueType" in payload.get_keys(): value_type = payload["valueType"] OgnOnWidgetValueChanged.try_resolve_output_attribute( db.node, "outputs:newValue", og.AttributeType.type_from_ogn_type_name(value_type) ) if "newValue" in payload.get_keys(): new_value = payload["newValue"] db.outputs.newValue = new_value db.outputs.valueChanged = og.ExecutionAttributeState.ENABLED return True # ---------------------------------------------------------------------------- @staticmethod def release(node): # Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing # after the node has been released. with suppress(og.OmniGraphError): state = OgnOnWidgetValueChangedDatabase.per_node_internal_state(node) state.release()
2,695
Python
35.931506
101
0.66308
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnDrawDebugCurve.py
""" This is the implementation of the OGN node defined in OgnDrawDebugCurve.ogn """ import carb import numpy as np import omni.debugdraw as dd import omni.graph.core as og class OgnDrawDebugCurve: """ Draws a curve using omni.debugdraw """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" curvepoints = db.inputs.curvepoints color = db.inputs.color closed = db.inputs.closed try: ddi = dd._debugDraw.acquire_debug_draw_interface() # noqa: PLW0212 rgb_bytes = (np.clip(color, 0, 1.0) * 255).astype("uint8").tobytes() argb_bytes = b"\xff" + rgb_bytes argb = int.from_bytes(argb_bytes, byteorder="big") carbpoints = [carb.Float3(p.tolist()) for p in curvepoints] # carb.log_warn(f'{color} = {argb_bytes} = {argb}, {carbpoints[0]}, {carbpoints[1]}') for i in range(len(carbpoints) - 1): ddi.draw_line(carbpoints[i], argb, carbpoints[i + 1], argb) if closed: ddi.draw_line(carbpoints[-1], argb, carbpoints[0], argb) except Exception as error: # noqa: PLW0703 import traceback raise RuntimeError(traceback.format_exc()) from error db.outputs.execOut = og.ExecutionAttributeState.ENABLED return True
1,376
Python
33.424999
97
0.606105
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnOnNewFrame.py
""" This is the implementation of the OGN node defined in OgnOnNewFrame.ogn """ from contextlib import suppress import omni.graph.core as og import omni.usd from omni.graph.ui_nodes.ogn.OgnOnNewFrameDatabase import OgnOnNewFrameDatabase from omni.kit.viewport.utility import get_viewport_from_window_name class OgnOnNewFrameInternalState: """Convenience class for maintaining per-node state information""" def __init__(self): """Instantiate the per-node state information.""" # This subscription object controls the lifetime of our callback, it will be # cleaned up automatically when our node is destroyed self.sub = None # Set when the callback has triggered self.is_set = False # The last payload received self.payload = None # The node instance handle self.node = None # The viewport we are watching frames for self.viewport_handle = None def on_event(self, e): """The event callback""" if e is None: return self.is_set = True viewport_handle = e.payload["viewport_handle"] if viewport_handle != self.viewport_handle: return self.payload = e.payload # Tell the evaluator we need to be computed if self.node.is_valid(): self.node.request_compute() def first_time_subscribe(self, node: og.Node, viewport_handle: int) -> bool: """Checked call to set up carb subscription Args: node: The node instance viewport_handle: The handle for the viewport to watch Returns: True if we subscribed, False if we are already subscribed """ if self.sub is not None and self.viewport_handle != viewport_handle: # event name changed since we last subscribed, unsubscribe self.sub.unsubscribe() self.sub = None if self.sub is None: self.sub = ( omni.usd.get_context() .get_rendering_event_stream() .create_subscription_to_push_by_type( int(omni.usd.StageRenderingEventType.NEW_FRAME), self.on_event, name=f"omni.graph.action.__on_new_frame.{node.node_id()}", ) ) self.viewport_handle = viewport_handle self.node = node self.payload = None return True return False def try_pop_event(self): """Pop the payload of the last event received, or None if there is no event to pop""" if self.is_set: self.is_set = False payload = self.payload self.payload = None return payload return None # ====================================================================== class OgnOnNewFrame: @staticmethod def internal_state(): """Returns an object that will contain per-node state information""" return OgnOnNewFrameInternalState() @staticmethod def compute(db) -> bool: viewport_name = db.inputs.viewport viewport_api = get_viewport_from_window_name(viewport_name) if not viewport_api: return True state = db.internal_state # XXX: Note this may be incorrect, viewport_handle is not stable (and may be None) viewport_handle = viewport_api.frame_info.get("viewport_handle") if state.first_time_subscribe(db.node, viewport_handle): return True payload = state.try_pop_event() if payload is None: return True # Copy the event dict contents into the output bundle db.outputs.frameNumber = payload["frame_number"] db.outputs.execOut = og.ExecutionAttributeState.ENABLED return True # ---------------------------------------------------------------------------- @staticmethod def release(node): # Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing # after the node has been released. with suppress(og.OmniGraphError): state = OgnOnNewFrameDatabase.per_node_internal_state(node) if state.sub: state.sub.unsubscribe() state.sub = None
4,332
Python
33.388889
101
0.587719
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportMode.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from dataclasses import dataclass from threading import Lock from typing import Any, Callable, Dict, Optional import omni.graph.core as og import omni.ui as ui from omni.graph.ui_nodes.ogn.nodes.OgnVStack import OgnVStack from omni.graph.ui_nodes.ogn.OgnSetViewportModeDatabase import OgnSetViewportModeDatabase from omni.kit.viewport.utility import get_active_viewport_and_window from omni.ui import scene as sc from omni.ui_query import OmniUIQuery from .PickingManipulator import PickingManipulatorFactory # noqa: PLE0402 from .ViewportClickManipulator import ViewportClickManipulatorFactory # noqa: PLE0402 from .ViewportDragManipulator import ViewportDragManipulatorFactory # noqa: PLE0402 from .ViewportHoverManipulator import ViewportHoverManipulatorFactory # noqa: PLE0402 from .ViewportPressManipulator import ViewportPressManipulatorFactory # noqa: PLE0402 from .ViewportScrollManipulator import ViewportScrollManipulatorFactory # noqa: PLE0402 UI_FRAME_NAME = "omni.graph.SetViewportMode" VIEWPORT_OVERLAY_NAME = "OG_overlay" IS_LOCK_REQUIRED = True class NoLock: def __init__(self): pass def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass class OgnSetViewportMode: @dataclass class ViewportState: viewport_click_manipulator: Optional[Any] = None viewport_press_manipulator: Optional[Any] = None viewport_drag_manipulator: Optional[Any] = None viewport_hover_manipulator: Optional[Any] = None viewport_scroll_manipulator: Optional[Any] = None picking_manipulator: Optional[Any] = None __viewport_states: Dict[str, ViewportState] = {} __do_it_lock: Optional[Any] = Lock() if IS_LOCK_REQUIRED else NoLock() @staticmethod def compute(db) -> bool: if db.inputs.execIn == og.ExecutionAttributeState.DISABLED: return False with OgnSetViewportMode.__do_it_lock: result = OgnSetViewportMode.__do_it( db.inputs.mode, db.inputs.viewport, db.abi_context, db.outputs, db.log_error, db.inputs.enableViewportMouseEvents, db.inputs.enablePicking, db.inputs.passClicksThru, ) if result: if db.inputs.mode == 0: db.outputs.defaultMode = og.ExecutionAttributeState.ENABLED db.outputs.scriptedMode = og.ExecutionAttributeState.DISABLED elif db.inputs.mode == 1: db.outputs.defaultMode = og.ExecutionAttributeState.DISABLED db.outputs.scriptedMode = og.ExecutionAttributeState.ENABLED return True db.outputs.defaultMode = og.ExecutionAttributeState.DISABLED db.outputs.scriptedMode = og.ExecutionAttributeState.DISABLED return False @staticmethod def __do_it( mode: int, viewport_window_name: str, context: og.GraphContext, outputs: OgnSetViewportModeDatabase.ValuesForOutputs, log_fn: Optional[Callable], viewport_mouse_events_enabled: bool, picking_enabled: bool, pass_clicks_thru: bool, ) -> bool: # Validate the viewport window name if not viewport_window_name: if log_fn is not None: log_fn(f"Viewport window '{viewport_window_name}' not found") return False viewport_api, viewport_window = get_active_viewport_and_window(window_name=viewport_window_name) if viewport_window is None: if log_fn is not None: log_fn(f"Viewport window '{viewport_window_name}' not found") return False if hasattr(viewport_api, "legacy_window"): if log_fn is not None: log_fn(f"Legacy viewport window '{viewport_window_name}' not compatible with Set Viewport Mode") return False # Default mode if mode == 0: # Destroy the manipulators OgnSetViewportMode.__viewport_states[viewport_window_name] = OgnSetViewportMode.__viewport_states.get( viewport_window_name, OgnSetViewportMode.ViewportState() ) viewport_state = OgnSetViewportMode.__viewport_states[viewport_window_name] if viewport_state.viewport_click_manipulator is not None: viewport_state.viewport_click_manipulator.destroy() viewport_state.viewport_click_manipulator = None if viewport_state.viewport_press_manipulator is not None: viewport_state.viewport_press_manipulator.destroy() viewport_state.viewport_press_manipulator = None if viewport_state.viewport_drag_manipulator is not None: viewport_state.viewport_drag_manipulator.destroy() viewport_state.viewport_drag_manipulator = None if viewport_state.viewport_hover_manipulator is not None: viewport_state.viewport_hover_manipulator.destroy() viewport_state.viewport_hover_manipulator = None if viewport_state.viewport_scroll_manipulator is not None: viewport_state.viewport_scroll_manipulator.destroy() viewport_state.viewport_scroll_manipulator = None if viewport_state.picking_manipulator is not None: viewport_state.picking_manipulator.destroy() viewport_state.picking_manipulator = None # Destroy the ui.ZStack and sc.SceneView if they exist frame = viewport_window.get_frame(UI_FRAME_NAME) frame_children = ui.Inspector.get_children(frame) if frame_children: widget_container = frame_children[0] widget_container_children = ui.Inspector.get_children(widget_container) if widget_container_children: scene_view = widget_container_children[0] viewport_api.remove_scene_view(scene_view) scene_view.scene.clear() scene_view.destroy() OgnVStack.deregister_widget(context, VIEWPORT_OVERLAY_NAME) widget_container.destroy() frame.clear() # Clear output widget path outputs.widgetPath = "" # Scripted mode elif mode == 1: # Create the ui.ZStack and sc.SceneView if they don't exist frame = viewport_window.get_frame(UI_FRAME_NAME) frame_children = ui.Inspector.get_children(frame) if frame_children: widget_container = frame_children[0] else: with frame: widget_container = ui.ZStack(identifier=VIEWPORT_OVERLAY_NAME) # Register the container widget so that graphs can access its properties, like size. OgnVStack.register_widget(context, VIEWPORT_OVERLAY_NAME, widget_container) widget_container.content_clipping = not pass_clicks_thru widget_container_children = ui.Inspector.get_children(widget_container) if widget_container_children: scene_view = widget_container_children[0] else: with widget_container: scene_view = sc.SceneView(child_windows_input=0) viewport_api.add_scene_view(scene_view) # Destroy any existing manipulators and create the enabled manipulators OgnSetViewportMode.__viewport_states[viewport_window_name] = OgnSetViewportMode.__viewport_states.get( viewport_window_name, OgnSetViewportMode.ViewportState() ) viewport_state = OgnSetViewportMode.__viewport_states[viewport_window_name] if viewport_state.viewport_click_manipulator is not None: viewport_state.viewport_click_manipulator.destroy() viewport_state.viewport_click_manipulator = None if viewport_state.viewport_press_manipulator is not None: viewport_state.viewport_press_manipulator.destroy() viewport_state.viewport_press_manipulator = None if viewport_state.viewport_drag_manipulator is not None: viewport_state.viewport_drag_manipulator.destroy() viewport_state.viewport_drag_manipulator = None if viewport_state.viewport_hover_manipulator is not None: viewport_state.viewport_hover_manipulator.destroy() viewport_state.viewport_hover_manipulator = None if viewport_state.viewport_scroll_manipulator is not None: viewport_state.viewport_scroll_manipulator.destroy() viewport_state.viewport_scroll_manipulator = None if viewport_state.picking_manipulator is not None: viewport_state.picking_manipulator.destroy() viewport_state.picking_manipulator = None with scene_view.scene: if viewport_mouse_events_enabled: viewport_state.viewport_click_manipulator = ViewportClickManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) viewport_state.viewport_press_manipulator = ViewportPressManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) viewport_state.viewport_drag_manipulator = ViewportDragManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) viewport_state.viewport_hover_manipulator = ViewportHoverManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) viewport_state.viewport_scroll_manipulator = ViewportScrollManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) if picking_enabled: viewport_state.picking_manipulator = PickingManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) # Set output widget path outputs.widgetPath = OmniUIQuery.get_widget_path(viewport_window, widget_container) return True
11,087
Python
43
114
0.638496
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/ViewportScrollManipulator.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__ = ["ViewportScrollManipulatorFactory"] 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.scroll" class DoNotPrevent(sc.GestureManager): def can_be_prevented(self, gesture): return False class ViewportScrollGesture(sc.ScrollGesture): 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 = 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): 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, "pos_norm_x": pos_norm[0], "pos_norm_y": pos_norm[1], "pos_pixel_x": pos_pixel[0], "pos_pixel_y": pos_pixel[1], "scroll": self.scroll[0], } self._message_bus.push(self._event_type, payload=payload) class ViewportScrollManipulator(sc.Manipulator): def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs): super().__init__(*args, **kwargs) self._gestures = [ViewportScrollGesture(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 ViewportScrollManipulatorFactory(desc: dict) -> ViewportScrollManipulator: # noqa: N802 manip = ViewportScrollManipulator(desc.get("viewport_api"), desc.get("viewport_window_name")) manip.categories = () manip.name = f"ViewportScrollManipulator.{desc.get('viewport_window_name')}" return manip
3,047
Python
33.636363
97
0.65146
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnOnWidgetClicked.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from contextlib import suppress import omni.graph.core as og from omni.graph.ui_nodes.ogn.OgnOnWidgetClickedDatabase import OgnOnWidgetClickedDatabase from . import UINodeCommon class OgnOnWidgetClicked: @staticmethod def internal_state(): return UINodeCommon.OgnUIEventNodeInternalState() @staticmethod def compute(db) -> bool: widget_identifier = db.inputs.widgetIdentifier if not widget_identifier: return True event_name = "clicked_" + widget_identifier if db.internal_state.first_time_subscribe(db.node, event_name): return True payload = db.internal_state.try_pop_event() if payload is None: return True # Currently payload is an empty dictionary db.outputs.clicked = og.ExecutionAttributeState.ENABLED return True # ---------------------------------------------------------------------------- @staticmethod def release(node): # Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing # after the node has been released. with suppress(og.OmniGraphError): state = OgnOnWidgetClickedDatabase.per_node_internal_state(node) state.release()
1,709
Python
32.529411
101
0.679345
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/CameraState.cpp
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "CameraState.h" #include <carb/settings/ISettings.h> #include <omni/timeline/ITimeline.h> #include <omni/usd/UsdUtils.h> using namespace omni::graph::ui_nodes; static const PXR_NS::TfToken kCenterOfInterest("omni:kit:centerOfInterest"); static bool checkPositionAndTarget(const PXR_NS::GfVec3d& position, const PXR_NS::GfVec3d& target) { // If position and target are coincident, fail if ((position - target).GetLengthSq() <= std::numeric_limits<double>::epsilon()) { return false; } return true; } static PXR_NS::GfVec3d getCameraUp(PXR_NS::UsdStageRefPtr stage) { PXR_NS::TfToken upAxis = PXR_NS::UsdGeomGetStageUpAxis(stage); if (upAxis == PXR_NS::UsdGeomTokens->x) { return { 1, 0, 0 }; } if (upAxis == PXR_NS::UsdGeomTokens->z) { return { 0, 0, 1 }; } return { 0, 1, 0 }; } CameraState::CameraState(PXR_NS::UsdGeomCamera camera, const PXR_NS::UsdTimeCode* time) : m_camera(std::move(camera)) , m_timeCode(time ? *time : omni::timeline::getTimeline()->getCurrentTime() * m_camera.GetPrim().GetStage()->GetTimeCodesPerSecond()) { } void CameraState::getCameraPosition(carb::Double3& position) const { PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear(); PXR_NS::GfVec3d worldPos = worldXform.Transform(PXR_NS::GfVec3d(0, 0, 0)); position = { worldPos[0], worldPos[1], worldPos[2] }; } void CameraState::getCameraTarget(carb::Double3& target) const { PXR_NS::GfVec3d localCenterOfInterest; PXR_NS::UsdAttribute coiAttr = m_camera.GetPrim().GetAttribute(kCenterOfInterest); if (!coiAttr || !coiAttr.Get(&localCenterOfInterest, m_timeCode)) { localCenterOfInterest = { 0, 0, -1 }; } PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear(); PXR_NS::GfVec3d worldCenterOfInterest = worldXform.Transform(localCenterOfInterest); target = { worldCenterOfInterest[0], worldCenterOfInterest[1], worldCenterOfInterest[2] }; } bool CameraState::setCameraPosition(const carb::Double3& worldPosition, bool rotate) { PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear(); PXR_NS::GfMatrix4d parentXform = m_camera.ComputeParentToWorldTransform(m_timeCode); PXR_NS::GfMatrix4d invParentXform = parentXform.GetInverse(); PXR_NS::GfMatrix4d initialLocalXform = worldXform * invParentXform; PXR_NS::GfVec3d posInParent = invParentXform.Transform(PXR_NS::GfVec3d(worldPosition.x, worldPosition.y, worldPosition.z)); PXR_NS::UsdPrim camPrim = m_camera.GetPrim(); PXR_NS::UsdAttribute coiAttr; PXR_NS::GfVec3d prevLocalCenterOfInterest; PXR_NS::GfMatrix4d newLocalXform; if (rotate) { const PXR_NS::GfVec3d camUp = getCameraUp(camPrim.GetStage()); coiAttr = camPrim.GetAttribute(kCenterOfInterest); if (!coiAttr || !coiAttr.Get(&prevLocalCenterOfInterest, m_timeCode)) { prevLocalCenterOfInterest = { 0, 0, -1 }; } PXR_NS::GfVec3d coiInParent = invParentXform.Transform(worldXform.Transform(prevLocalCenterOfInterest)); if (!checkPositionAndTarget(posInParent, coiInParent)) { return false; } newLocalXform = PXR_NS::GfMatrix4d(1).SetLookAt(posInParent, coiInParent, camUp).GetInverse(); } else { newLocalXform = initialLocalXform; } newLocalXform.SetTranslateOnly(posInParent); omni::usd::UsdUtils::setLocalTransformMatrix(camPrim, newLocalXform, m_timeCode); if (coiAttr) { PXR_NS::GfVec3d prevWorldCOI = worldXform.Transform(prevLocalCenterOfInterest); PXR_NS::GfVec3d newLocalCOI = (newLocalXform * parentXform).GetInverse().Transform(prevWorldCOI); omni::usd::UsdUtils::setAttribute(coiAttr, newLocalCOI, m_timeCode); } return true; } bool CameraState::setCameraTarget(const carb::Double3& worldTarget, bool rotate) { PXR_NS::UsdPrim camPrim = m_camera.GetPrim(); PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear(); PXR_NS::GfMatrix4d parentXform = m_camera.ComputeParentToWorldTransform(m_timeCode); PXR_NS::GfMatrix4d invParentXform = parentXform.GetInverse(); PXR_NS::GfMatrix4d initialLocalXform = worldXform * invParentXform; PXR_NS::GfVec3d gfWorldTarget(worldTarget.x, worldTarget.y, worldTarget.z); PXR_NS::GfVec3d prevLocalCenterOfInterest; PXR_NS::UsdAttribute coiAttr = camPrim.GetAttribute(kCenterOfInterest); if (!coiAttr || !coiAttr.Get(&prevLocalCenterOfInterest, m_timeCode)) { prevLocalCenterOfInterest = { 0, 0, -1 }; } PXR_NS::GfVec3d posInParent = invParentXform.Transform(initialLocalXform.Transform(PXR_NS::GfVec3d(0, 0, 0))); PXR_NS::GfMatrix4d newLocalXform; PXR_NS::GfVec3d newLocalCenterOfInterest; if (rotate) { // Rotate camera to look at new target, leaving it where it is PXR_NS::GfVec3d camUp = getCameraUp(camPrim.GetStage()); PXR_NS::GfVec3d coiInParent = invParentXform.Transform(gfWorldTarget); if (!checkPositionAndTarget(posInParent, coiInParent)) { return false; } newLocalXform = PXR_NS::GfMatrix4d(1).SetLookAt(posInParent, coiInParent, camUp).GetInverse(); newLocalCenterOfInterest = (newLocalXform * parentXform).GetInverse().Transform(gfWorldTarget); } else { // Camera keeps orientation and distance relative to target // Calculate movement of center-of-interest in parent's space PXR_NS::GfVec3d targetMove = invParentXform.Transform(gfWorldTarget) - invParentXform.Transform(worldXform.Transform(prevLocalCenterOfInterest)); // Copy the camera's local transform newLocalXform = initialLocalXform; // And move it by the delta newLocalXform.SetTranslateOnly(posInParent + targetMove); } if (rotate) { omni::usd::UsdUtils::setAttribute(coiAttr, newLocalCenterOfInterest, m_timeCode); } omni::usd::UsdUtils::setLocalTransformMatrix(camPrim, newLocalXform, m_timeCode); return true; }
6,675
C++
38.270588
153
0.708914
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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 db.outputs.cameraPrim = [active_camera] except Exception as error: # pylint: disable=broad-except db.log_error(str(error)) return False return True
752
Python
27.961537
84
0.650266
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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): """ Resolves the type of an output property based on a widget attribute. This assumes the output attribute has the 'unvalidated' metadata set to true OmniGraphError raised on failure. """ if not isinstance(widget, ui.Widget): raise og.OmniGraphError(f"Attempt to resolve property on non-widget object '{widget}'.") widget_desc = widget.identifier or repr(widget) if not hasattr(widget, property_name): raise og.OmniGraphError(f"Widget '{widget_desc}' has no property '{property_name}'.") 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: raise og.OmniGraphError(f"Cannot resolve output type: {type(prop_value)}") 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) @staticmethod def get_property_value(widget: ui.Widget, property_name: str, attribute: og.RuntimeAttribute): """ Retrieves the value of a property from a widget and writes it to the given node attribute. OmniGraphError raised on failure. """ if not isinstance(widget, ui.Widget): raise og.OmniGraphError(f"Attempt to get property value from non-widget object '{widget}'.") widget_desc = widget.identifier or repr(widget) if not hasattr(widget, property_name): raise og.OmniGraphError(f"Widget '{widget_desc}' has no property '{property_name}'.") 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 # Property value is retrieved 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 except ValueError: pass else: raise og.OmniGraphError(f"Unsupported property type: {prop_type}") raise og.OmniGraphError(f"Attempt to get property '{property_name}' from widget '{widget_desc}' failed.") @staticmethod def set_property_value(widget: ui.Widget, property_name: str, attribute: og.RuntimeAttribute): """ Retrieves the value of a node attribute and writes it to the given widget property. OmniGraphError raised on failure. """ if not isinstance(widget, ui.Widget): raise og.OmniGraphError(f"Attempt to set property value on non-widget object '{widget}'.") widget_desc = widget.identifier or repr(widget) if not hasattr(widget, property_name): raise og.OmniGraphError(f"Widget '{widget_desc}' has no property '{property_name}'.") 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 except ValueError: pass elif prop_type in (bool, int, float, str): try: setattr(widget, property_name, prop_type(value)) return 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 except ValueError: pass return elif prop_type == ui.Direction: direction = to_ui_direction(value) if direction is not None: try: setattr(widget, property_name, direction) return except ValueError: pass return else: raise og.OmniGraphError(f"Unsupported property 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." ) if isinstance(value, str) and prop_type != str: raise og.OmniGraphError( f"Cannot set value onto widget '{widget_desc}' property '{property_name}': " f"string value '{value}' cannot be converted to {prop_type}." ) raise og.OmniGraphError( f"Cannot set value of type {type(value)} onto widget '{widget_desc}' " f"property '{property_name}' (type {prop_type})" ) @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,571
Python
38.064407
119
0.622458
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes { class OgnReadPickState { public: struct InternalState { carb::events::ISubscriptionPtr pickingSub; PickingEventPayloads eventPayloads; } m_internalState; exec::unstable::Stamp m_setStamp; // stamp set when the event occurs exec::unstable::SyncStamp m_syncStamp; // stamp set by each instance static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { OgnReadPickState& state = OgnReadPickStateDatabase::sSharedState<OgnReadPickState>(nodeObj); // 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::sSharedState<OgnReadPickState>(nodeObj); state.m_internalState.eventPayloads.setPayload(e->payload); state.m_setStamp.next(); } } ); } } static void release(const NodeObj& nodeObj) { OgnReadPickState& state = OgnReadPickStateDatabase::sSharedState<OgnReadPickState>(nodeObj); // Unsubscribe from picking events if (state.m_internalState.pickingSub.get()) state.m_internalState.pickingSub.detach()->unsubscribe(); } static bool compute(OgnReadPickStateDatabase& db) { OgnReadPickState& sharedState = db.sharedState<OgnReadPickState>(); OgnReadPickState& perInstanceState = db.perInstanceState<OgnReadPickState>(); if(perInstanceState.m_syncStamp.makeSync(sharedState.m_setStamp)) { // 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 = sharedState.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) { TargetPath pickedPrim = db.stringToPath(pickedPrimPath); // 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& trackedPrimPaths = 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 (trackedPrimPaths.empty()) isTrackedPrimPicked = true; else isTrackedPrimPicked = std::any_of(trackedPrimPaths.begin(), trackedPrimPaths.end(), [&db, pickedPrimPath](NameToken const& path) { return (std::strcmp(db.tokenToString(path), pickedPrimPath) == 0); }); } else { // Get the list of tracked prims const auto& trackedPrims = db.inputs.trackedPrims(); // 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 (trackedPrims.empty()) isTrackedPrimPicked = true; else isTrackedPrimPicked = std::any_of(trackedPrims.begin(), trackedPrims.end(), [pickedPrim](TargetPath const& trackedPrim) { return (trackedPrim == pickedPrim); }); } db.outputs.pickedPrim().resize(1); db.outputs.pickedPrim()[0] = pickedPrim; db.outputs.pickedPrimPath() = db.stringToToken(pickedPrimPath); } else { // No prim is picked at all, so a tracked prim certainly isn't picked isTrackedPrimPicked = false; db.outputs.pickedPrim().resize(0); db.outputs.pickedPrimPath() = Token(); } // Set outputs db.outputs.pickedWorldPos() = pickedWorldPos; db.outputs.isTrackedPrimPicked() = isTrackedPrimPicked; db.outputs.isValid() = true; } else { db.outputs.pickedPrim().resize(0); db.outputs.pickedPrimPath() = Token(); db.outputs.pickedWorldPos() = {0, 0, 0}; db.outputs.isTrackedPrimPicked() = false; db.outputs.isValid() = false; } } return true; } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
7,001
C++
39.473988
138
0.566633
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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): if not isinstance(placer, ui.Placer): raise og.OmniGraphError( f"Attempt to get value of property {property_name} on non-placer object '{placer}'." ) if property_name not in OgnPlacer.get_property_names(placer, False): raise og.OmniGraphError(f"'{property_name}' is not a readable property of placer '{placer.identifier}'") super(OgnPlacer, OgnPlacer).get_property_value(placer, property_name, attribute) @staticmethod def set_property_value(placer: ui.Placer, property_name: str, attribute: og.RuntimeAttribute): if not isinstance(placer, ui.Placer): raise og.OmniGraphError( f"Attempt to set value of property {property_name} on non-placer object '{placer}'." ) if property_name not in OgnPlacer.get_property_names(placer, True): raise og.OmniGraphError(f"'{property_name}' is not a writeable property of placer '{placer.identifier}'") 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,171
Python
41.743801
117
0.637014
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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): if not isinstance(stack, ui.Stack): raise og.OmniGraphError(f"Attempt to resolve property on non-stack object '{stack}'.") if property_name not in OgnVStack.get_property_names(stack, False): raise og.OmniGraphError(f"'{property_name}' is not a readable property of stack '{stack.identifier}'") super(OgnVStack, OgnVStack).resolve_output_property(stack, property_name, attribute) @staticmethod def get_property_value(stack: ui.Stack, property_name: str, attribute: og.RuntimeAttribute): if not isinstance(stack, ui.Stack): raise og.OmniGraphError(f"Attempt to get value of property {property_name} on non-stack object '{stack}'.") if property_name not in OgnVStack.get_property_names(stack, False): raise og.OmniGraphError(f"'{property_name}' is not a readable property of stack '{stack.identifier}'") super(OgnVStack, OgnVStack).get_property_value(stack, property_name, attribute) @staticmethod def set_property_value(stack: ui.Stack, property_name: str, attribute: og.RuntimeAttribute): if not isinstance(stack, ui.Stack): raise og.OmniGraphError(f"Attempt to set value of property {property_name} on non-stack object '{stack}'.") if property_name not in OgnVStack.get_property_names(stack, True): raise og.OmniGraphError(f"'{property_name}' is not a writeable property of stack '{stack.identifier}'") 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,542
Python
44.809917
119
0.659148
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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): if not isinstance(button, ui.Button): raise og.OmniGraphError(f"Attempt to resolve property on non-button object '{button}'.") if property_name not in OgnButton.get_property_names(button, False): raise og.OmniGraphError(f"'{property_name}' is not a readable property of button '{button.identifier}'") super(OgnButton, OgnButton).resolve_output_property(button, property_name, attribute) @staticmethod def get_property_value(button: ui.Button, property_name: str, attribute: og.RuntimeAttribute): if not isinstance(button, ui.Button): raise og.OmniGraphError( f"Attempt to get value of property {property_name} on non-button object '{button}'." ) if property_name not in OgnButton.get_property_names(button, False): raise og.OmniGraphError(f"'{property_name}' is not a readable property of button '{button.identifier}'") super(OgnButton, OgnButton).get_property_value(button, property_name, attribute) @staticmethod def set_property_value(button: ui.Button, property_name: str, attribute: og.RuntimeAttribute): if not isinstance(button, ui.Button): raise og.OmniGraphError( f"Attempt to set value of property {property_name} on non-button object '{button}'." ) if property_name not in OgnButton.get_property_names(button, True): raise og.OmniGraphError(f"'{property_name}' is not a writeable property of button '{button.identifier}'") 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,600
Python
44.212328
117
0.632576
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes { 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,106
C
25.357142
89
0.748644
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes { 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,318
C++
22.981818
117
0.703338
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnGetViewportRenderer.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.kit.viewport.utility import get_viewport_from_window_name class OgnGetViewportRenderer: """ Gets the renderer being used by the specified viewport. """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" try: viewport = db.inputs.viewport viewport_api = get_viewport_from_window_name(viewport) renderer = "" if viewport_api is not None: engine_name = viewport_api.hydra_engine render_mode = viewport_api.render_mode if engine_name == "rtx": if render_mode == "RaytracedLighting": renderer = "RTX: Realtime" elif render_mode == "PathTracing": renderer = "RTX: Path Tracing" elif engine_name == "iray": if render_mode == "iray": renderer = "RTX: Iray" elif engine_name == "pxr": renderer = "Pixar Storm" if renderer == "": db.log_error(f"Unknown Hydra engine '{engine_name}' and render mode '{render_mode}'") else: db.log_error(f"Unknown viewport window '{viewport}'") db.outputs.renderer = renderer except Exception as error: # noqa: PLW0703 db.log_error(str(error)) return False return True
1,910
Python
33.745454
105
0.581675
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes/omni/graph/ui_nodes/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_nodes { class OgnOnViewportDragged { public: struct InternalState { carb::events::ISubscriptionPtr dragBeganSub; carb::events::ISubscriptionPtr dragChangedSub; carb::events::ISubscriptionPtr dragEndedSub; ViewportDragEventPayloads eventPayloads; ViewportDragEventStates eventStates; } m_internalState; exec::unstable::Stamp m_setStamp; // stamp set when the event occurs exec::unstable::SyncStamp m_syncStamp; // stamp set by each instance static void initialize(GraphContextObj const&, NodeObj const& nodeObj) { OgnOnViewportDragged& state = OgnOnViewportDraggedDatabase::sSharedState<OgnOnViewportDragged>(nodeObj); // 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::sSharedState<OgnOnViewportDragged>(nodeObj); state.m_internalState.eventPayloads.clear(); // clear prev payloads when we have a new drag state.m_internalState.eventPayloads.setDragBeganPayload(e->payload); state.m_setStamp.next(); 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::sSharedState<OgnOnViewportDragged>(nodeObj); 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::sSharedState<OgnOnViewportDragged>(nodeObj); state.m_internalState.eventPayloads.setDragEndedPayload(e->payload); state.m_setStamp.next(); if (nodeObj.iNode->isValid(nodeObj)) nodeObj.iNode->requestCompute(nodeObj); } } ); } } static void release(const NodeObj& nodeObj) { OgnOnViewportDragged& state = OgnOnViewportDraggedDatabase::sSharedState<OgnOnViewportDragged>(nodeObj); // 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& sharedState = db.sharedState<OgnOnViewportDragged>(); OgnOnViewportDragged& perInstanceState = db.perInstanceState<OgnOnViewportDragged>(); if( perInstanceState.m_syncStamp.makeSync(sharedState.m_setStamp)) { if (sharedState.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 : sharedState.m_internalState.eventPayloads.dragBeganPayloads()) { if (!dragBeganPayload.second.isValid) continue; auto& eventStateValue = sharedState.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 : sharedState.m_internalState.eventPayloads.dragChangedPayloads()) { if (!dragChangedPayload.second.isValid) continue; auto& eventStateValue = sharedState.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 : sharedState.m_internalState.eventPayloads.dragEndedPayloads()) { if (!dragEndedPayload.second.isValid) continue; auto& eventStateValue = sharedState.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; } } } // Get event state and set outputs auto it = sharedState.m_internalState.eventStates.find({viewportWindowName, gestureName}); if (it != sharedState.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
9,383
C++
41.080717
150
0.592561
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes/omni/graph/ui_nodes/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_nodes/omni/graph/ui_nodes/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_nodes { 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,067
C
29.465517
120
0.578888
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportFullscreen.cpp
// Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #include "OgnSetViewportFullscreenDatabase.h" #include <omni/kit/IAppWindow.h> #include <omni/kit/KitUtils.h> namespace omni { namespace graph { namespace ui_nodes { class OgnSetViewportFullscreen { public: static bool compute(OgnSetViewportFullscreenDatabase& db) { NameToken const mode = db.inputs.mode(); bool fullscreen = false; bool hideUI = false; if (mode == OgnSetViewportFullscreenDatabase::tokens.Default) { fullscreen = false; hideUI = false; } else if (mode == OgnSetViewportFullscreenDatabase::tokens.Fullscreen) { fullscreen = true; hideUI = true; } else if (mode == OgnSetViewportFullscreenDatabase::tokens.HideUI) { fullscreen = false; hideUI = true; } else { CARB_ASSERT(false, "Invalid mode"); } carb::settings::ISettings* settings = omni::kit::getSettings(); // Only toggle fullscreen on/off when displayModeLock is off. if (!settings->get<bool>("/app/window/displayModeLock")) { setFullscreen(fullscreen); } settings->set("/app/window/hideUi", hideUI); db.outputs.exec() = kExecutionAttributeStateEnabled; return true; } private: static void setFullscreen(bool fullscreen) { omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow(); CARB_ASSERT(appWindow); if (appWindow) { appWindow->setFullscreen(fullscreen); } } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
2,103
C++
24.349397
77
0.630052
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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: # pylint: disable=broad-except db.log_error(str(error)) return False
2,717
Python
30.97647
90
0.536621
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes { 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,631
C
28.030928
122
0.600604
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes { 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; exec::unstable::Stamp m_setStamp; // stamp set when the event occurs exec::unstable::SyncStamp m_syncStamp; // stamp set by each instance // 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::sSharedState<OgnReadViewportHoverState>(nodeObj); // 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::sSharedState<OgnReadViewportHoverState>(nodeObj); state.m_internalState.eventPayloads.setHoverBeganPayload(e->payload); state.m_setStamp.next(); } } ); state.m_internalState.hoverChangedSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kHoverChangedEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj); state.m_internalState.eventPayloads.setHoverChangedPayload(e->payload); state.m_setStamp.next(); } } ); state.m_internalState.hoverEndedSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kHoverEndedEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj); state.m_internalState.eventPayloads.setHoverEndedPayload(e->payload); state.m_setStamp.next(); } } ); state.m_internalState.updateSub = carb::events::createSubscriptionToPush( app->getUpdateEventStream(), [nodeObj](carb::events::IEvent* e) { if (e) { OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj); updateEventStates(state.m_internalState.eventStates, state.m_internalState.eventPayloads); state.m_setStamp.next(); } } ); } } static void release(const NodeObj& nodeObj) { OgnReadViewportHoverState& state = OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj); // 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& sharedState = db.sharedState<OgnReadViewportHoverState>(); OgnReadViewportHoverState& perInstanceState = db.perInstanceState<OgnReadViewportHoverState>(); if(perInstanceState.m_syncStamp.makeSync(sharedState.m_setStamp)) { // 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 = sharedState.m_internalState.eventStates.find({viewportWindowName}); if (it != sharedState.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
9,050
C++
38.697368
115
0.589724
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes { class OgnOnPicked { public: struct InternalState { carb::events::ISubscriptionPtr pickingSub; PickingEventPayloads eventPayloads; } m_internalState; exec::unstable::Stamp m_setStamp; // stamp set when the event occurs exec::unstable::SyncStamp m_syncStamp; // stamp set by each instance static void initialize(GraphContextObj const&, NodeObj const& nodeObj) { OgnOnPicked& state = OgnOnPickedDatabase::sSharedState<OgnOnPicked>(nodeObj); // 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::sSharedState<OgnOnPicked>(nodeObj); state.m_internalState.eventPayloads.clear(); // invalidate previous payloads state.m_internalState.eventPayloads.setPayload(e->payload); state.m_setStamp.next(); if (nodeObj.iNode->isValid(nodeObj)) nodeObj.iNode->requestCompute(nodeObj); } } ); } } static void release(const NodeObj& nodeObj) { OgnOnPicked& state = OgnOnPickedDatabase::sSharedState<OgnOnPicked>(nodeObj); // 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; auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>(); auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>(); if (!pathInterface || !tokenInterface) { CARB_LOG_ERROR("Failed to initialize path or token interface"); return 0; } OgnOnPicked& sharedState = db.sharedState<OgnOnPicked>(); OgnOnPicked& perInstanceState = db.perInstanceState<OgnOnPicked>(); if(perInstanceState.m_syncStamp.makeSync(sharedState.m_setStamp)) { if (sharedState.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 = sharedState.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; const auto& trackedPrims = db.inputs.trackedPrims(); // First determine if any prim is picked bool const isAnyPrimPicked = pickedPrimPath && pickedPrimPath[0] != '\0'; if (isAnyPrimPicked) { TargetPath pickedPrim = db.stringToPath(pickedPrimPath); // 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 (trackedPrims.empty()) isTrackedPrimPicked = true; else isTrackedPrimPicked = std::any_of(trackedPrims.begin(), trackedPrims.end(), [pickedPrim](TargetPath const& trackedPrim) { return (trackedPrim == pickedPrim); }); db.outputs.pickedPrim().resize(1); db.outputs.pickedPrim()[0] = pickedPrim; db.outputs.pickedPrimPath() = db.stringToToken(pickedPrimPath); } else { // No prim is picked at all, so a tracked prim certainly isn't picked isTrackedPrimPicked = false; db.outputs.pickedPrim().resize(0); db.outputs.pickedPrimPath() = Token(); } // Set outputs db.outputs.pickedWorldPos() = pickedWorldPos; db.outputs.isTrackedPrimPicked() = isTrackedPrimPicked; auto& trackedPrimPaths = db.outputs.trackedPrimPaths(); trackedPrimPaths.resize(trackedPrims.size()); std::transform(trackedPrims.begin(), trackedPrims.end(), trackedPrimPaths.begin(), [tokenInterface, pathInterface](TargetPath const& trackedPrim) { return tokenInterface->getHandle(pathInterface->getText(trackedPrim)); }); if (isTrackedPrimPicked) { db.outputs.picked() = kExecutionAttributeStateEnabled; db.outputs.missed() = kExecutionAttributeStateDisabled; } else { db.outputs.picked() = kExecutionAttributeStateDisabled; db.outputs.missed() = kExecutionAttributeStateEnabled; } } } return true; } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
6,992
C++
38.96
138
0.589674
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnButton.post.rst
Further information on the button operation can be found in the documentation of :py:class:`omni.ui.Button`.
109
reStructuredText
53.999973
108
0.798165
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportRenderer.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.graph.core as og import omni.graph.tools.ogn as ogn from omni.kit.viewport.utility import get_viewport_from_window_name class OgnSetViewportRenderer: """ Sets renderer for the target viewport. """ # renderer: (hd_engine, render_mode) RENDERER_CONFIGS = { "RTX: Realtime": ("rtx", "RaytracedLighting"), "RTX: Path Tracing": ("rtx", "PathTracing"), "RTX: Iray": ("iray", "iray"), } @staticmethod def initialize(context, node): """Assign default value and allowed tokens for the inputs:renderer attribute""" renderers = [] # Query which engines are enabled. setting = carb.settings.get_settings().get("/renderer/enabled") engines = setting.split(",") if setting else ["rtx", "iray"] # Third-party Hydra render delegates are ignored as requested by OM-75851, but they can be included if needed. for renderer, (engine, _) in OgnSetViewportRenderer.RENDERER_CONFIGS.items(): if engine in engines: renderers.append(renderer) allowed_tokens = ",".join(renderers) attr = node.get_attribute("inputs:renderer") attr.set_metadata(ogn.MetadataKeys.ALLOWED_TOKENS, allowed_tokens) # If the attr is not authored, its default value will be the first enabled renderer. if attr.get() == "" and len(renderers) > 0: attr.set(renderers[0]) @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" try: renderer = db.inputs.renderer if renderer != "": viewport = db.inputs.viewport viewport_api = get_viewport_from_window_name(viewport) if viewport_api is not None: allowed_tokens = db.attributes.inputs.renderer.get_metadata(ogn.MetadataKeys.ALLOWED_TOKENS) renderers = allowed_tokens.split(",") if renderer in renderers and renderer in OgnSetViewportRenderer.RENDERER_CONFIGS: hd_engine, render_mode = OgnSetViewportRenderer.RENDERER_CONFIGS[renderer] # Update the legacy "/renderer/active" setting for anyone that may be watching for it carb.settings.get_settings().set("/renderer/active", hd_engine) viewport_api.set_hd_engine(hd_engine, render_mode) else: db.log_error(f"Unknown renderer '{renderer}'") else: db.log_error(f"Unknown viewport window '{viewport}'") db.outputs.exec = og.ExecutionAttributeState.ENABLED except Exception as error: # noqa: PLW0703 db.log_error(str(error)) return False return True
3,271
Python
37.952381
118
0.62886
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes/omni/graph/ui_nodes/ogn/nodes/OgnButton.pre.rst
Here is an example of a button that was created using the text ``Press Me``: .. image:: ../../../../../source/extensions/omni.graph.ui_nodes/docs/PressMe.png :alt: "Press Me" Button
187
reStructuredText
36.599993
80
0.663102
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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_nodes { // 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 = omni::fabric::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 == omni::fabric::kUninitializedToken) windowToken = db.stringToToken(""); db.outputs.window() = windowToken; } return true; } }; REGISTER_OGN_NODE() } // namespace ui_nodes } // namespace graph } // namespace omni
5,438
C++
32.574074
134
0.545053
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportResolution.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.graph.core as og from omni.kit.viewport.utility import get_viewport_from_window_name class OgnSetViewportResolution: """ Sets the resolution of the target viewport. """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" try: viewport = db.inputs.viewport viewport_api = get_viewport_from_window_name(viewport) if viewport_api is not None: resolution = db.inputs.resolution if resolution[0] > 0 and resolution[1] > 0: viewport_api.resolution = resolution else: db.log_error(f"Invalid resolution {resolution[0]}x{resolution[1]}.") else: db.log_error(f"Unknown viewport window '{viewport}'") db.outputs.exec = og.ExecutionAttributeState.ENABLED except Exception as error: # noqa: PLW0703 db.log_error(str(error)) return False return True
1,461
Python
33.809523
88
0.651608
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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. # import omni.graph.core as og 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 try: callbacks.resolve_output_property(widget, property_name, db.node.get_attribute("outputs:value")) except og.OmniGraphError as og_error: db.log_error( f"Could resolve outputs from '{property_name}' for {widget_summary}\n{og_error}", add_context=False ) 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 try: callbacks.get_property_value(widget, property_name, db.outputs.value) except og.OmniGraphError as og_error: db.log_error(f"Could not get value of '{property_name}' on {widget_summary}\n{og_error}", add_context=False) return False return True
3,584
Python
43.259259
120
0.646484
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnGetViewportResolution.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.kit.viewport.utility import get_viewport_from_window_name class OgnGetViewportResolution: """ Gets the resolution of the target viewport. """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" try: viewport = db.inputs.viewport viewport_api = get_viewport_from_window_name(viewport) if viewport_api is not None: db.outputs.resolution = viewport_api.resolution else: db.outputs.resolution = (0, 0) db.log_error(f"Unknown viewport window '{viewport}'") except Exception as error: # noqa: PLW0703 db.log_error(str(error)) return False return True
1,199
Python
32.333332
76
0.668891
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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: # pylint: disable=broad-except db.log_error(str(error)) return False db.outputs.execOut = og.ExecutionAttributeState.ENABLED return True
1,503
Python
32.422222
86
0.626081
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/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 try: callbacks.set_property_value(widget, property_name, db.inputs.value) except og.OmniGraphError as og_error: db.log_error( f"Could not set value of '{property_name}' on {widget_summary}\n{og_error}", add_context=False ) return False db.outputs.written = og.ExecutionAttributeState.ENABLED return True db.log_warning("Unexpected execution with no execution input enabled") return False
3,457
Python
44.499999
114
0.612381
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/scripts/variant_utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # 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 re from typing import Any, Optional import omni.graph.core as og import omni.ui as ui from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry from usdrt import Sdf, Usd def print_widget_tree(widget: ui.Widget, level: int = 0): # Prints the widget tree to the console for child in ui.Inspector.get_children(widget): print_widget_tree(child, level + 1) def get_descendants(widget: ui.Widget): # Returns a list of all descendants of the given widget kids = [] local_kids = ui.Inspector.get_children(widget) kids.extend(local_kids) for k in local_kids: child_kids = get_descendants(k) kids.extend(child_kids) return kids def get_attr_value(prim: Usd.Prim, attr_name: str) -> Any: # Returns the value of the given attribute from usdrt if prim: attr = prim.GetAttribute(attr_name) if attr: return og.Controller().get(attribute=prim.GetAttribute(attr_name)) return False def get_use_path(stage: Usd.Stage, node_prim_path: Sdf.Path) -> bool: # Returns the value of the usePath input attribute prim = stage.GetPrimAtPath(node_prim_path) if prim: return get_attr_value(prim, "inputs:usePath") return False def get_attr_has_connections(prim: Usd.Prim, attr_name: str) -> bool: # Returns True if the attribute has authored connections if prim: attr = prim.GetAttribute(attr_name) if attr: return attr.HasAuthoredConnections() return False def get_target_prim(stage: Usd.Stage, node_prim_path: Sdf.Path) -> Optional[Usd.Prim]: # Return the target prim if it exists depending on the value of the usePath input attribute. # If usePath is True, the target prim is the prim at the path specified by the primPath input attribute. # If usePath is False, the target prim is the first target of the prim relationship. prim = stage.GetPrimAtPath(node_prim_path) if prim: if get_attr_value(prim, "inputs:usePath"): prim_path = get_attr_value(prim, "inputs:primPath") if prim_path is not None: return stage.GetPrimAtPath(prim_path) else: rel = prim.GetRelationship("inputs:prim") if rel.IsValid(): targets = rel.GetTargets() if targets: return stage.GetPrimAtPath(targets[0]) return None def pretty_name(name: str) -> str: # Returns a pretty name for the given property name = name.split(":")[-1] name = name[0].upper() + name[1:] name = re.sub(r"([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", r"\1 ", name) return name def override_display_name(prop: UsdPropertyUiEntry): # Overrides the display name of the given property with a consistent format prop_name = pretty_name(prop.prop_name) prop.override_display_name(prop_name)
3,240
Python
34.615384
108
0.675617
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/scripts/variants.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # 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, Optional import omni.graph.core as og import omni.ui as ui from omni.graph.ui import OmniGraphAttributeModel, OmniGraphPropertiesWidgetBuilder 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.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH from usdrt import Sdf, Usd from .variant_utils import ( # noqa PLE0402 get_attr_has_connections, get_attr_value, get_descendants, get_target_prim, get_use_path, override_display_name, pretty_name, ) ATTRIB_LABEL_STYLE = {"alignment": ui.Alignment.RIGHT_TOP} class VariantTokenModel(TfTokenAttributeModel): """Model for selecting the variant set name. We modify the list to show variant sets which are available on the target prim.""" class AllowedTokenItem(ui.AbstractItem): def __init__(self, item, label): """ Args: item: the variant set 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 super().__init__(stage, attribute_paths, self_refresh, metadata) def _get_allowed_tokens(self, _): # Override of TfTokenAttributeModel to specialize what tokens are to be shown # Returns the attributes we want to let the user select from prim = self._stage.GetPrimAtPath(self._node_prim_path) if not prim: return [] self._target_prim = get_target_prim(self._stage, self._node_prim_path) tokens = self._get_tokens(self._target_prim) current_value = og.Controller().get(attribute=self._get_attributes()[0]) if current_value and current_value not in tokens: tokens.append(current_value) tokens.insert(0, "") return tokens @staticmethod def _item_factory(item): # Construct the item for the model label = item return VariantTokenModel.AllowedTokenItem(item, label) def _update_allowed_token(self, **kwargs): # Override of TfTokenAttributeModel to specialize the model items super()._update_allowed_token(token_item=self._item_factory) def _get_tokens(self, prim: Usd.Prim) -> List[str]: return [] class VariantSetNamesTokenModel(VariantTokenModel): def _get_variant_set_names(self, prim: Usd.Prim) -> List[str]: if prim: variant_sets = prim.GetVariantSets() variant_sets_names = list(variant_sets.GetNames()) return variant_sets_names return [] def _get_tokens(self, prim: Usd.Prim) -> List[str]: return self._get_variant_set_names(prim) class VariantNamesTokenModel(VariantTokenModel): def _get_variant_names(self, prim: Usd.Prim) -> List[str]: node_prim = self._stage.GetPrimAtPath(self._node_prim_path) if node_prim and prim: variant_sets = prim.GetVariantSets() variant_set_name = get_attr_value(node_prim, "inputs:variantSetName") variant_set = variant_sets.GetVariantSet(variant_set_name) variant_sets_names = list(variant_set.GetVariantNames()) return variant_sets_names return [] def _get_tokens(self, prim: Usd.Prim) -> List[str]: return self._get_variant_names(prim) # noinspection PyProtectedMember class CustomVariantLayout: """Custom layout for the variant set and variant name attributes""" def __init__(self, compute_node_widget): self.enable = True self.compute_node_widget = compute_node_widget self.prim_path_layout = None self.prim_path_model = None self.use_path_model = False self.prim_rel_layout = None self.prim_rel_model = None self.variant_set_name_token_model = None self.variant_set_name_string_model = None self.variant_name_token_model = None self.variant_name_string_model = None self.variant_set_name_string_layout = None self.variant_set_name_token_layout = None self.variant_name_string_layout = None self.variant_name_token_layout = None def get_node_prim_path(self): node_prim_path = self.compute_node_widget.payload[-1] return node_prim_path def get_use_path(self): stage = self.compute_node_widget.stage node_prim_path = self.get_node_prim_path() use_path = get_use_path(stage, node_prim_path) return use_path @staticmethod def _set_child_string_field_enabled(widget: ui.Widget, enabled: bool): for child in get_descendants(widget): if isinstance(child, ui.StringField): child.enabled = enabled def _get_target_prim(self) -> Usd.Prim: return get_target_prim(self.compute_node_widget.stage, self.get_node_prim_path()) def _get_attr_has_connections(self, attr_name: str) -> bool: stage = self.compute_node_widget.stage node_prim_path = self.get_node_prim_path() prim = stage.GetPrimAtPath(node_prim_path) return get_attr_has_connections(prim, attr_name) def _token_builder(self, ui_prop: UsdPropertyUiEntry): return OmniGraphPropertiesWidgetBuilder._tftoken_builder( # noqa: PLW0212 stage=self.compute_node_widget.stage, attr_name=ui_prop.prop_name, type_name=ui_prop.property_type, metadata=ui_prop.metadata, prim_paths=[self.get_node_prim_path()], additional_label_kwargs={"style": ATTRIB_LABEL_STYLE}, additional_widget_kwargs={"no_allowed_tokens_model_cls": OmniGraphAttributeModel}, ) def _relationship_builder(self, ui_prop: UsdPropertyUiEntry, changed_fn): return OmniGraphPropertiesWidgetBuilder._relationship_builder( # noqa: PLW0212 stage=self.compute_node_widget.stage, attr_name=ui_prop.prop_name, metadata=ui_prop.metadata, prim_paths=[self.get_node_prim_path()], additional_label_kwargs={"style": ATTRIB_LABEL_STYLE}, additional_widget_kwargs={ "on_remove_target": changed_fn, "target_picker_on_add_targets": changed_fn, "targets_limit": 1, }, ) def _bool_builder(self, ui_prop: UsdPropertyUiEntry): return OmniGraphPropertiesWidgetBuilder._bool_builder( # noqa: PLW0212 stage=self.compute_node_widget.stage, attr_name=ui_prop.prop_name, type_name=ui_prop.property_type, metadata=ui_prop.metadata, prim_paths=[self.get_node_prim_path()], additional_label_kwargs={"style": ATTRIB_LABEL_STYLE}, ) def _combo_box_builder(self, ui_prop: UsdPropertyUiEntry, model_cls, changed_fn=None): stage = self.compute_node_widget.stage node_prim_path = self.get_node_prim_path() with ui.HStack(spacing=HORIZONTAL_SPACING): prop_name = pretty_name(ui_prop.prop_name) ui.Label(prop_name, name="label", style=ATTRIB_LABEL_STYLE, width=LABEL_WIDTH) ui.Spacer(width=HORIZONTAL_SPACING) with ui.ZStack(): attr_path = node_prim_path.AppendProperty(ui_prop.prop_name) # Build the token-selection widget when prim is known model = model_cls(stage, [attr_path], False, {}, node_prim_path) ui.ComboBox(model) if changed_fn: model._current_index.add_value_changed_fn(changed_fn) # noqa PLW0212 return model def _prim_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *_): # Build the token input prim path widget self.prim_path_layout = ui.HStack(spacing=0) with self.prim_path_layout: self.prim_path_model = self._token_builder(ui_prop) self._update_prim_path() self.prim_path_model.add_value_changed_fn(self._on_target_prim_path_changed) def _update_prim_path(self): use_path = self.get_use_path() attr_has_connections = self._get_attr_has_connections("inputs:primPath") self.prim_path_layout.enabled = use_path enabled = use_path and not attr_has_connections self._set_child_string_field_enabled(self.prim_path_layout, enabled) def _prim_rel_build_fn(self, ui_prop: UsdPropertyUiEntry, *_): # Build the relationship input prim widget self.prim_rel_layout = ui.HStack(spacing=0) with self.prim_rel_layout: self.prim_rel_model = self._relationship_builder(ui_prop, self._on_target_prim_rel_changed) self._update_prim_rel() def _update_prim_rel(self): self.prim_rel_layout.enabled = not self.get_use_path() def _use_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *_): # Build the boolean toggle for inputs:usePath self.use_path_model = self._bool_builder(ui_prop) self.use_path_model.add_value_changed_fn(self._on_use_path_changed) def _variant_set_name_build_fn(self, ui_prop: UsdPropertyUiEntry, *_): # Build the VariantSetName widget # Build the simple string input for data-driven variant set name and a ComboBox for when there are # variants and no data-driven variant set name self.variant_set_name_string_layout = ui.HStack(spacing=0) with self.variant_set_name_string_layout: self.variant_set_name_string_model = self._token_builder(ui_prop) self.variant_set_name_token_layout = ui.HStack(spacing=0) with self.variant_set_name_token_layout: self.variant_set_name_token_model = self._combo_box_builder( ui_prop, VariantSetNamesTokenModel, self._on_variant_set_changed ) self._update_variant_set_visibility() def _update_variant_set_visibility(self): # Show the string input if the prim is unknown or if the attribute has connections # otherwise show the token input if self.variant_set_name_string_layout and self.variant_set_name_token_layout: attr_has_connections = self._get_attr_has_connections("inputs:variantSetName") target_prim = self._get_target_prim() use_string = not target_prim or attr_has_connections self.variant_set_name_string_layout.visible = use_string self.variant_set_name_token_layout.visible = not use_string def _update_variant_set_name(self): # Update the variant set name widget visibility when the target prim changes self._update_variant_set_visibility() if self.variant_set_name_token_model: self.variant_set_name_token_model._set_dirty() # noqa: PLW0212 if self.variant_set_name_string_model: self.variant_set_name_string_model._set_dirty() # noqa: PLW0212 def _variant_name_build_fn(self, ui_prop: UsdPropertyUiEntry, *_): # Build the VariantName widget # Build the simple string input for data-driven variant name and a ComboBox for when there are # variants and no data-driven variant name self.variant_name_string_layout = ui.HStack(spacing=0) with self.variant_name_string_layout: self.variant_name_string_model = self._token_builder(ui_prop) self.variant_name_token_layout = ui.HStack(spacing=0) with self.variant_name_token_layout: self.variant_name_token_model = self._combo_box_builder(ui_prop, VariantNamesTokenModel) self._update_variant_name_visibility() def _update_variant_name_visibility(self): # Show the string input if the prim is unknown or if the attribute has connections # otherwise show the token input attr_has_connections = self._get_attr_has_connections("inputs:variantName") target_prim = self._get_target_prim() if self.variant_name_string_layout and self.variant_name_token_layout: use_string = not target_prim or attr_has_connections self.variant_name_string_layout.visible = use_string self.variant_name_token_layout.visible = not use_string def _update_variant_name(self): # Update the variant name widget visibility when the target prim changes self._update_variant_name_visibility() if self.variant_name_token_model: self.variant_name_token_model._set_dirty() # noqa: PLW0212 if self.variant_name_string_model: self.variant_name_string_model._set_dirty() # noqa: PLW0212 def _on_target_prim_rel_changed(self, *_): # When the inputs:primRel token changes update the relevant widgets self.prim_rel_model._set_dirty() # noqa: PLW0212 self._update_prim_rel() self._update_variant_set_name() self._update_variant_name() def _on_target_prim_path_changed(self, *_): # When the inputs:primPath token changes update the relevant widgets self._update_variant_set_name() self._update_variant_name() def _on_use_path_changed(self, _): # When the usePath toggle changes update the relevant widgets self._update_prim_rel() self._update_prim_path() self._update_variant_set_name() self._update_variant_name() def _on_variant_set_changed(self, _): # When the variantSet changes update the relevant widgets self._update_variant_name() def apply(self, props): # Apply the property values to the compute node def find_prop(name) -> Optional[UsdPropertyUiEntry]: try: return next((p for p in props if p.prop_name == name)) except StopIteration: return None frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Inputs"): prop_fuctions = [ ("prim", self._prim_rel_build_fn), ("usePath", self._use_path_build_fn), ("primPath", self._prim_path_build_fn), ("variantSetName", self._variant_set_name_build_fn), ("variantName", self._variant_name_build_fn), ] for prop_name, build_fn in prop_fuctions: prop = find_prop(f"inputs:{prop_name}") if prop: override_display_name(prop) CustomLayoutProperty(prop.prop_name, None, build_fn=partial(build_fn, prop)) with CustomLayoutGroup("Outputs"): for attr in ["exists", "success", "variantSetNames", "variantName"]: prop = find_prop(f"outputs:{attr}") if prop: CustomLayoutProperty(prop.prop_name, pretty_name(prop.prop_name)) return frame.apply(props)
16,097
Python
41.251968
113
0.63751
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/tests/test_ui_nodes.py
# noqa: PLC0302 import unittest from pathlib import Path from typing import Any, Dict, List import carb import carb.settings import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from omni.kit import ui_test from omni.kit.ui_test.input import ( emulate_mouse_drag_and_drop, emulate_mouse_move, emulate_mouse_move_and_click, emulate_mouse_scroll, ) from omni.kit.ui_test.vec2 import Vec2 from omni.ui.tests.test_base import OmniUiTest EXT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.graph.ui_nodes}")) class TestUINodes(OmniUiTest): def __init__(self, tests=()): super().__init__(tests) self.settings = carb.settings.get_settings() # The first value for each setting is what we want to set it to, the second is where we will store # its original value. self.viewport_settings: Dict[str, List[Any, Any]] = { "/persistent/app/viewport/displayOptions": [0, None], "/app/viewport/grid/enabled": [False, None], "/persistent/app/viewport/{vp_id}/guide/grid/visible": [False, None], "/persistent/app/viewport/{vp_id}/guide/axis/visible": [False, None], # This doesn't currently work while the test is running so we set it in the test args instead. # "/persistent/app/viewport/{vp_id}/hud/visible": [False, None], } self.TEST_GRAPH_PATH = "/World/TestGraph" self.wait_frames_for_visual_update = 5 # It takes 6 frames for the nodes and connections to all draw in their proper positions. self.wait_frames_for_graph_draw = 6 # Wait 10 frames for commands to execute and the graph to update self.wait_frames_for_commands = 10 async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() self.viewport_name, self.viewport_id = self.get_viewport_name_and_id() self._golden_img_dir = EXT_PATH.absolute().resolve().joinpath("data/golden_images") # Make sure the viewport looks the same as when we generated the golden images. for setting, values in self.viewport_settings.items(): key = setting.format(vp_id=self.viewport_id) values[1] = self.settings.get(key) self.settings.set(key, values[0]) await omni.usd.get_context().new_stage_async() self.stage = omni.usd.get_context().get_stage() async def tearDown(self): self._golden_img_dir = None await super().tearDown() # Restore viewport settings. for setting, (values) in self.viewport_settings.items(): key = setting.format(vp_id=self.viewport_id) if values[1] is None: self.settings.destroy_item(key) else: self.settings.set(key, values[1]) values[1] = None omni.usd.get_context().close_stage() # Activate OnClosing node def get_viewport_name_and_id(self): try: import omni.kit.viewport.window as vp viewport = next(vp.get_viewport_window_instances()) return (viewport.name, viewport.viewport_api.id) except StopIteration as exc: raise og.OmniGraphError("Legacy viewport not supported for UI nodes.") from exc def create_graph(self) -> og.Graph: """Create an execution graph.""" return og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"}) async def edit_ui_execution_graph(self, graph_path: str, graph_node_data: dict, error_thrown=False): """Edit graph with nodes, connections and values common to all tests.""" keys = og.Controller.Keys data = og.Controller.edit( graph_path, { keys.CREATE_NODES: [ ("onLoaded", "omni.graph.action.OnLoaded"), ("viewport", "omni.graph.ui_nodes.SetViewportMode"), ("viewportClose", "omni.graph.ui_nodes.SetViewportMode"), ("onClosing", "omni.graph.action.OnClosing"), ] + graph_node_data.get(keys.CREATE_NODES, []), keys.CONNECT: [ ("onLoaded.outputs:execOut", "viewport.inputs:execIn"), ("onClosing.outputs:execOut", "viewportClose.inputs:execIn"), ] + graph_node_data.get(keys.CONNECT, []), keys.SET_VALUES: [ ("viewport.inputs:viewport", self.viewport_name), ("viewportClose.inputs:viewport", self.viewport_name), ("viewport.inputs:mode", 1), ("viewport.inputs:enablePicking", True), ] + graph_node_data.get(keys.SET_VALUES, []), }, ) # There's no graph window so we're not actually waiting for it to draw, but we still need # to give some time for all the connections to resolve. if error_thrown: with ogts.ExpectedError(): await ui_test.wait_n_updates(self.wait_frames_for_graph_draw) else: await ui_test.wait_n_updates(self.wait_frames_for_graph_draw) return data def get_attribute(self, attribute, node): return og.Controller.get(og.Controller.attribute(attribute, node)) def get_attribute_and_assert_equals(self, attribute, node, expected): attr = self.get_attribute(attribute, node) self.assertEquals(attr, expected) def get_attribute_and_assert_list_equals(self, attribute, node, expected): attr = self.get_attribute(attribute, node).tolist() self.assertListEqual(attr, expected) def get_attribute_and_assert_list_almost_equals(self, attribute, node, expected): attr = self.get_attribute(attribute, node).tolist() for a, e in zip(attr, expected): self.assertAlmostEquals(a, e) def assert_compute_message(self, node, error_message, severity=og.Severity.ERROR): error = node.get_compute_messages(severity)[0].split("\n")[0] self.assertEquals(error, error_message) async def test_button_ui(self): """Test UI button""" graph = self.create_graph() widget_identifier = "testbutton" keys = og.Controller.Keys (_, (_, viewport, _, _, button, click, counter), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("button", "omni.graph.ui_nodes.Button"), ("click", "omni.graph.ui_nodes.OnWidgetClicked"), ("counter", "omni.graph.action.Counter"), ], keys.CONNECT: [ ("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "button.inputs:create"), ("click.outputs:clicked", "counter.inputs:execIn"), ], keys.SET_VALUES: [ ("button.inputs:widgetIdentifier", widget_identifier), ("click.inputs:widgetIdentifier", widget_identifier), ("button.inputs:text", "THIS IS A TEST BUTTON"), ("button.inputs:style", '{"background_color": "green"}'), ], }, ) # Click the button await emulate_mouse_move_and_click(Vec2(50, 55)) self.get_attribute_and_assert_equals( "inputs:parentWidgetPath", button, self.get_attribute("outputs:widgetPath", viewport) ) self.get_attribute_and_assert_equals( "inputs:create", button, self.get_attribute("outputs:scriptedMode", viewport) ) self.get_attribute_and_assert_equals("inputs:widgetIdentifier", button, widget_identifier) self.get_attribute_and_assert_equals("inputs:widgetIdentifier", click, widget_identifier) # Test button click event self.get_attribute_and_assert_equals("outputs:count", counter, 1) await self.finalize_test_no_image() async def test_set_viewport_mode(self): """Test SetViewportMode UI node""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, viewport, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.SET_VALUES: [("viewport.inputs:mode", 0)], }, ) self.get_attribute_and_assert_equals("outputs:scriptedMode", viewport, 0) self.get_attribute_and_assert_equals("outputs:defaultMode", viewport, 1) await self.finalize_test_no_image() async def test_on_viewport_clicked(self): """Test OnViewportClicked and ReadViewportClickState UI nodes""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, on_viewport_clicked, viewport_click_state, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("on_viewport_clicked", "omni.graph.ui_nodes.OnViewportClicked"), ("viewport_click_state", "omni.graph.ui_nodes.ReadViewportClickState"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport_click_state.outputs:position", "to_string.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ("on_viewport_clicked.outputs:clicked", "print.inputs:execIn"), ], keys.SET_VALUES: [ ("viewport.inputs:enableViewportMouseEvents", True), ("on_viewport_clicked.inputs:viewport", self.viewport_name), ("viewport_click_state.inputs:viewport", self.viewport_name), ("on_viewport_clicked.inputs:onlyPlayback", False), ], }, ) # Click inside viewport await emulate_mouse_move_and_click(Vec2(85, 255)) position = [72.40223463687151, 158.88268156424587] # Translated (x, y) position fo the mouse click self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_clicked, "Left Mouse Click") self.get_attribute_and_assert_equals("inputs:gesture", viewport_click_state, "Left Mouse Click") self.get_attribute_and_assert_list_almost_equals("outputs:position", on_viewport_clicked, position) self.get_attribute_and_assert_list_almost_equals("outputs:position", viewport_click_state, position) self.get_attribute_and_assert_equals("outputs:isValid", viewport_click_state, True) await self.finalize_test_no_image() async def test_on_viewport_pressed(self): """Test OnViewportPressed UI node""" graph = self.create_graph() keys = og.Controller.Keys ( _, (_, _, _, _, on_viewport_pressed, viewport_press_state, _, _, _, _), _, _, ) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("on_viewport_pressed", "omni.graph.ui_nodes.OnViewportPressed"), ("viewport_press_state", "omni.graph.ui_nodes.ReadViewportPressState"), ("to_string", "omni.graph.nodes.ToString"), ("to_string2", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ("print2", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport_press_state.outputs:pressPosition", "to_string.inputs:value"), ("viewport_press_state.outputs:releasePosition", "to_string2.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ("to_string2.outputs:converted", "print2.inputs:text"), ("on_viewport_pressed.outputs:pressed", "print.inputs:execIn"), ("on_viewport_pressed.outputs:released", "print2.inputs:execIn"), ], keys.SET_VALUES: [ ("viewport.inputs:enableViewportMouseEvents", True), ("on_viewport_pressed.inputs:viewport", self.viewport_name), ("viewport_press_state.inputs:viewport", self.viewport_name), ("on_viewport_pressed.inputs:onlyPlayback", False), ], }, ) # Click inside viewport await emulate_mouse_move_and_click(Vec2(85, 255)) position = [72.40223463687151, 158.88268156424587] # Translated (x, y) position fo the mouse click self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_pressed, "Left Mouse Press") self.get_attribute_and_assert_equals("inputs:gesture", viewport_press_state, "Left Mouse Press") self.get_attribute_and_assert_list_equals("outputs:pressPosition", on_viewport_pressed, position) self.get_attribute_and_assert_list_equals("outputs:releasePosition", on_viewport_pressed, position) self.get_attribute_and_assert_list_equals("outputs:pressPosition", viewport_press_state, position) self.get_attribute_and_assert_list_equals("outputs:releasePosition", viewport_press_state, position) self.get_attribute_and_assert_equals("outputs:isReleasePositionValid", viewport_press_state, True) self.get_attribute_and_assert_equals("outputs:isPressed", viewport_press_state, False) self.get_attribute_and_assert_equals("outputs:isValid", viewport_press_state, True) await self.finalize_test_no_image() async def test_on_viewport_scrolled(self): """Test OnViewportScrolled UI node""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, on_viewport_scrolled, viewport_scroll_state, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("on_viewport_scrolled", "omni.graph.ui_nodes.OnViewportScrolled"), ("viewport_scroll_state", "omni.graph.ui_nodes.ReadViewportScrollState"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport_scroll_state.outputs:position", "to_string.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ("on_viewport_scrolled.outputs:scrolled", "print.inputs:execIn"), ], keys.SET_VALUES: [ ("viewport.inputs:enableViewportMouseEvents", True), ("on_viewport_scrolled.inputs:viewport", self.viewport_name), ("viewport_scroll_state.inputs:viewport", self.viewport_name), ("on_viewport_scrolled.inputs:onlyPlayback", False), ], }, ) # Click inside viewport await emulate_mouse_move(Vec2(85, 255)) await emulate_mouse_scroll(Vec2(0, 900)) # (x, y) make a variable position = [72.40223463687151, 158.88268156424587] self.get_attribute_and_assert_equals("outputs:scrolled", on_viewport_scrolled, 1) self.get_attribute_and_assert_list_equals("outputs:position", on_viewport_scrolled, position) self.get_attribute_and_assert_list_equals("outputs:position", viewport_scroll_state, position) self.get_attribute_and_assert_equals("outputs:scrollValue", on_viewport_scrolled, 1) self.get_attribute_and_assert_equals("outputs:scrollValue", viewport_scroll_state, 1) self.get_attribute_and_assert_equals("outputs:isValid", viewport_scroll_state, True) await self.finalize_test_no_image() async def test_on_viewport_hovered(self): """Test OnViewportHovered UI node""" graph = self.create_graph() await emulate_mouse_move(Vec2(0, 0)) # Move the cursor away from final position keys = og.Controller.Keys (_, (_, _, _, _, on_viewport_hover, viewport_hover_state, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("on_viewport_hover", "omni.graph.ui_nodes.OnViewportHovered"), ("viewport_hover_state", "omni.graph.ui_nodes.ReadViewportHoverState"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport_hover_state.outputs:position", "to_string.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ("on_viewport_hover.outputs:began", "print.inputs:execIn"), ], keys.SET_VALUES: [ ("viewport.inputs:enableViewportMouseEvents", True), ("on_viewport_hover.inputs:viewport", self.viewport_name), ("viewport_hover_state.inputs:viewport", self.viewport_name), ("on_viewport_hover.inputs:onlyPlayback", False), ], }, ) # Click inside viewport await emulate_mouse_move(Vec2(85, 255)) position = [72.40223463687151, 158.88268156424587] self.get_attribute_and_assert_equals("outputs:began", on_viewport_hover, 1) self.get_attribute_and_assert_equals("outputs:isHovered", viewport_hover_state, True) self.get_attribute_and_assert_equals("outputs:isValid", viewport_hover_state, True) self.get_attribute_and_assert_list_equals("outputs:position", viewport_hover_state, position) await self.finalize_test_no_image() async def test_on_viewport_dragged(self): """Test OnViewportDrag UI node""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, on_viewport_dragged, viewport_drag_state, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("on_viewport_dragged", "omni.graph.ui_nodes.OnViewportDragged"), ("viewport_drag_state", "omni.graph.ui_nodes.ReadViewportDragState"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport_drag_state.outputs:currentPosition", "to_string.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ("on_viewport_dragged.outputs:ended", "print.inputs:execIn"), ], keys.SET_VALUES: [ ("viewport.inputs:enableViewportMouseEvents", True), ("on_viewport_dragged.inputs:viewport", self.viewport_name), ("viewport_drag_state.inputs:viewport", self.viewport_name), ("on_viewport_dragged.inputs:onlyPlayback", False), ], }, ) # Click inside viewport await emulate_mouse_drag_and_drop(Vec2(85, 255), Vec2(100, 455)) start_position = [72.40223463687151, 158.88268156424587] end_position = [85.81005586592177, 337.6536312849162] self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_dragged, "Left Mouse Drag") self.get_attribute_and_assert_list_equals("outputs:initialPosition", on_viewport_dragged, start_position) self.get_attribute_and_assert_list_equals("outputs:finalPosition", on_viewport_dragged, end_position) self.get_attribute_and_assert_list_equals("outputs:currentPosition", viewport_drag_state, end_position) self.get_attribute_and_assert_list_equals("outputs:initialPosition", viewport_drag_state, start_position) self.get_attribute_and_assert_list_equals("outputs:velocity", viewport_drag_state, [0, 0]) self.get_attribute_and_assert_equals("outputs:isValid", viewport_drag_state, True) self.get_attribute_and_assert_equals("outputs:isDragInProgress", viewport_drag_state, False) await self.finalize_test_no_image() async def test_on_viewport_dragged_began(self): """Test OnViewportDrag UI node where we begin the drag but don't complete it.""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, on_viewport_dragged, viewport_drag_state, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("on_viewport_dragged", "omni.graph.ui_nodes.OnViewportDragged"), ("viewport_drag_state", "omni.graph.ui_nodes.ReadViewportDragState"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport_drag_state.outputs:currentPosition", "to_string.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ("on_viewport_dragged.outputs:began", "print.inputs:execIn"), ], keys.SET_VALUES: [ ("viewport.inputs:enableViewportMouseEvents", True), ("on_viewport_dragged.inputs:viewport", self.viewport_name), ("viewport_drag_state.inputs:viewport", self.viewport_name), ("on_viewport_dragged.inputs:onlyPlayback", False), ], }, ) # Click inside viewport await emulate_mouse_drag_and_drop(Vec2(85, 255), Vec2(100, 455)) start_position = [72.40223463687151, 158.88268156424587] velocity = [0.8938547486033599, 22.346368715083777] self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_dragged, "Left Mouse Drag") self.get_attribute_and_assert_list_equals("outputs:initialPosition", on_viewport_dragged, start_position) self.get_attribute_and_assert_list_equals("outputs:initialPosition", viewport_drag_state, start_position) self.get_attribute_and_assert_list_equals("outputs:velocity", viewport_drag_state, velocity) self.get_attribute_and_assert_equals("outputs:isValid", viewport_drag_state, True) self.get_attribute_and_assert_equals("outputs:isDragInProgress", viewport_drag_state, True) await self.finalize_test_no_image() async def test_read_window_size_viewport_connection(self): """Test ReadWindowSize UI node with the viewport/window widget path connection""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport.outputs:scriptedMode", "print.inputs:execIn"), ("viewport.outputs:widgetPath", "read_window_size.inputs:widgetPath"), ("read_window_size.outputs:height", "to_string.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ], keys.SET_VALUES: [ ("read_window_size.inputs:isViewport", True), ], }, ) self.get_attribute_and_assert_equals("outputs:width", read_window_size, 1440) self.get_attribute_and_assert_equals("outputs:height", read_window_size, 900) await self.finalize_test_no_image() async def test_read_window_size(self): """Test ReadWindowSize UI node with the viewport/window name""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport.outputs:scriptedMode", "print.inputs:execIn"), ("read_window_size.outputs:height", "to_string.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ], keys.SET_VALUES: [ ("read_window_size.inputs:isViewport", True), ("read_window_size.inputs:name", self.viewport_name), ], }, ) self.get_attribute_and_assert_equals("outputs:width", read_window_size, 1440) self.get_attribute_and_assert_equals("outputs:height", read_window_size, 900) await self.finalize_test_no_image() async def test_read_window_size_no_window(self): """Test ReadWindowSize UI node without window (error flow)""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport.outputs:scriptedMode", "print.inputs:execIn"), ("read_window_size.outputs:height", "to_string.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ], keys.SET_VALUES: [ ("read_window_size.inputs:isViewport", True), ], }, error_thrown=True, ) warning = "OmniGraph Warning: No window name or widgetPath provided." self.assert_compute_message(read_window_size, warning, og.Severity.WARNING) await self.finalize_test_no_image() async def test_read_window_size_invalid_window(self): """Test ReadWindowSize UI node with invalid window name (error flow)""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport.outputs:scriptedMode", "print.inputs:execIn"), ("read_window_size.outputs:height", "to_string.inputs:value"), ("to_string.outputs:converted", "print.inputs:text"), ], keys.SET_VALUES: [ ("read_window_size.inputs:isViewport", True), ("read_window_size.inputs:name", "invalid-viewport"), ], }, error_thrown=True, ) error = "OmniGraph Error: No viewport named 'invalid-viewport' found." self.assert_compute_message(read_window_size, error, og.Severity.ERROR) await self.finalize_test_no_image() async def test_write_widget_property(self): """Test WriteWidgetProperty UI node""" graph = self.create_graph() widget_identifier = "testbutton1" keys = og.Controller.Keys (_, (_, viewport, _, _, button, click, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("button", "omni.graph.ui_nodes.Button"), ("click", "omni.graph.ui_nodes.OnWidgetClicked"), ("write", "omni.graph.ui_nodes.WriteWidgetProperty"), ("string", "omni.graph.nodes.ConstantString"), ], keys.CONNECT: [ ("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "button.inputs:create"), ("click.outputs:clicked", "write.inputs:write"), ("string.inputs:value", "write.inputs:value"), ], keys.SET_VALUES: [ ("button.inputs:widgetIdentifier", widget_identifier), ("click.inputs:widgetIdentifier", widget_identifier), ("button.inputs:text", "THIS IS A TEST BUTTON"), ("button.inputs:style", '{"background_color": "green"}'), ("string.inputs:value", "NEW BUTTON"), ("write.inputs:widgetIdentifier", widget_identifier), ("write.inputs:propertyName", "text"), ], }, ) # Click the button to trigger property write await emulate_mouse_move_and_click(Vec2(50, 55)) self.get_attribute_and_assert_equals( "inputs:parentWidgetPath", button, self.get_attribute("outputs:widgetPath", viewport) ) self.get_attribute_and_assert_equals( "inputs:create", button, self.get_attribute("outputs:scriptedMode", viewport) ) self.get_attribute_and_assert_equals("inputs:widgetIdentifier", button, widget_identifier) self.get_attribute_and_assert_equals("inputs:widgetIdentifier", click, widget_identifier) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_write_widget_property.png", ) async def test_read_widget_property(self): """Test ReadWidgetProperty UI node""" graph = self.create_graph() widget_identifier = "testbutton1" keys = og.Controller.Keys (_, (_, _, _, _, button, read, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("button", "omni.graph.ui_nodes.Button"), ("read", "omni.graph.ui_nodes.ReadWidgetProperty"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "button.inputs:create"), ("button.outputs:created", "print.inputs:execIn"), ("read.outputs:value", "print.inputs:text"), ], keys.SET_VALUES: [ ("button.inputs:widgetIdentifier", widget_identifier), ("button.inputs:text", "THIS IS A TEST BUTTON"), ("button.inputs:style", '{"background_color": "green"}'), ("read.inputs:widgetIdentifier", widget_identifier), ("read.inputs:propertyName", "text"), ], }, ) self.get_attribute_and_assert_equals("inputs:text", button, self.get_attribute("outputs:value", read)) await self.finalize_test_no_image() async def test_write_widget_property_with_widget_path(self): """Test WriteWidgetProperty UI node""" graph = self.create_graph() widget_identifier = "testbutton1" keys = og.Controller.Keys await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("button", "omni.graph.ui_nodes.Button"), ("click", "omni.graph.ui_nodes.OnWidgetClicked"), ("write", "omni.graph.ui_nodes.WriteWidgetProperty"), ("string", "omni.graph.nodes.ConstantString"), ], keys.CONNECT: [ ("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "button.inputs:create"), ("click.outputs:clicked", "write.inputs:write"), ("string.inputs:value", "write.inputs:value"), ("button.outputs:widgetPath", "write.inputs:widgetPath"), ], keys.SET_VALUES: [ ("button.inputs:widgetIdentifier", widget_identifier), ("click.inputs:widgetIdentifier", widget_identifier), ("button.inputs:text", "THIS IS A TEST BUTTON"), ("button.inputs:style", '{"background_color": "green"}'), ("string.inputs:value", "NEW BUTTON"), ("write.inputs:propertyName", "text"), ], }, ) # Click the button to trigger property write await emulate_mouse_move_and_click(Vec2(50, 55)) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_write_widget_property_with_widget_path.png", ) async def test_write_widget_style(self): """Test WriteWidgetProperty UI node""" graph = self.create_graph() widget_identifier = "testbutton1" keys = og.Controller.Keys await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("button", "omni.graph.ui_nodes.Button"), ("write", "omni.graph.ui_nodes.WriteWidgetStyle"), ], keys.CONNECT: [ ("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "button.inputs:create"), ("button.outputs:created", "write.inputs:write"), ], keys.SET_VALUES: [ ("button.inputs:widgetIdentifier", widget_identifier), ("button.inputs:text", "A BUTTON"), ("write.inputs:widgetIdentifier", widget_identifier), ("write.inputs:style", '{"background_color": "blue"}'), ], }, ) # Click the viewport to see it await emulate_mouse_move_and_click(Vec2(80, 255)) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_write_widget_style.png", ) async def test_write_widget_style_with_widget_path(self): """Test WriteWidgetProperty UI node""" graph = self.create_graph() keys = og.Controller.Keys await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("button", "omni.graph.ui_nodes.Button"), ("write", "omni.graph.ui_nodes.WriteWidgetStyle"), ], keys.CONNECT: [ ("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "button.inputs:create"), ("button.outputs:created", "write.inputs:write"), ("button.outputs:widgetPath", "write.inputs:widgetPath"), ], keys.SET_VALUES: [ ("button.inputs:text", "A BUTTON"), ("write.inputs:style", '{"background_color": "blue"}'), ], }, ) # Click the viewport to see it await emulate_mouse_move_and_click(Vec2(80, 255)) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_write_widget_style_with_widget_path.png", ) async def test_placer(self): """Test Placer UI node""" graph = self.create_graph() keys = og.Controller.Keys await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("button", "omni.graph.ui_nodes.Button"), ("placer", "omni.graph.ui_nodes.Placer"), ], keys.CONNECT: [ ("viewport.outputs:widgetPath", "placer.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "placer.inputs:create"), ("placer.outputs:widgetPath", "button.inputs:parentWidgetPath"), ("placer.outputs:created", "button.inputs:create"), ], keys.SET_VALUES: [ ("button.inputs:text", "THIS IS A PLACED BUTTON"), ("button.inputs:style", '{"background_color": "blue"}'), ("placer.inputs:position", (20.0, 250.0)), ], }, ) # Click the viewport await emulate_mouse_move_and_click(Vec2(50, 55)) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_placer.png" ) async def test_vstack_and_spacer(self): """Test VStack and Spacer UI nodes""" buttons = 3 colors = ["green", "blue", "orange"] stack = [f"button{b}" for b in range(buttons)] stack.insert(1, "spacer") # To ensure a consistent ordering of the children within the stack, the creation of the stack triggers the # creation of its first child widget and each child then triggers the creation of the next one. widget_creation_connections = [("stack.outputs:created", f"{stack[0]}.inputs:create")] for i in range(len(stack) - 1): widget_creation_connections += [(f"{stack[i]}.outputs:created", f"{stack[i+1]}.inputs:create")] graph = self.create_graph() keys = og.Controller.Keys await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("stack", "omni.graph.ui_nodes.VStack"), ("spacer", "omni.graph.ui_nodes.Spacer"), ] + [(f"button{b}", "omni.graph.ui_nodes.Button") for b in range(buttons)], keys.CONNECT: [ ("viewport.outputs:widgetPath", "stack.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "stack.inputs:create"), ] + widget_creation_connections + [("stack.outputs:widgetPath", f"{widget}.inputs:parentWidgetPath") for widget in stack], keys.SET_VALUES: [("spacer.inputs:height", 100)] + [(f"button{b}.inputs:text", f"Button {b+1}") for b in range(buttons)] + [(f"button{b}.inputs:style", '{"background_color": "' + colors[b] + '"}') for b in range(buttons)], }, ) # Click the viewport await emulate_mouse_move_and_click(Vec2(50, 55)) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_vstack_and_spacer.png" ) async def test_button_negative_size(self): """Test UI button error flow - negative size""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, button), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [("button", "omni.graph.ui_nodes.Button")], keys.CONNECT: [("viewport.outputs:scriptedMode", "button.inputs:create")], keys.SET_VALUES: [("button.inputs:size", (-1, -1))], # Negative size }, error_thrown=True, ) self.assert_compute_message(button, "OmniGraph Error: The size of the widget cannot be negative!") await self.finalize_test_no_image() async def test_button_negative_no_parent_widget(self): """Test UI button error flow - no parent widget""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, button), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [("button", "omni.graph.ui_nodes.Button")], keys.CONNECT: [("viewport.outputs:scriptedMode", "button.inputs:create")], }, error_thrown=True, ) self.assert_compute_message(button, "OmniGraph Error: No parentWidgetPath supplied.") await self.finalize_test_no_image() async def test_button_negative_invalid_style(self): """Test UI button error flow - style not valid""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, button), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [("button", "omni.graph.ui_nodes.Button")], keys.CONNECT: [ ("viewport.outputs:scriptedMode", "button.inputs:create"), ("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"), ], keys.SET_VALUES: [("button.inputs:style", "bad style")], }, error_thrown=True, ) # The expected error message contains the text of a Python SyntaxError exception, which is # different depending on the Python version. So rather than do an exact match on the entire message # we'll just check for some identifying text that is under our control. msg = button.get_compute_messages(og.Severity.ERROR)[0].split("\n")[0] self.assertTrue("OmniGraph Error: 'inputs:style': Invalid style syntax" in msg, "expected syntax error") await self.finalize_test_no_image() async def test_write_widget_property_invalid_widget_identifier(self): """Test WriteWidgetProperty UI node error flow - invalid widget identifier""" graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, write, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("write", "omni.graph.ui_nodes.WriteWidgetProperty"), ("string", "omni.graph.nodes.ConstantString"), ("impulse", "omni.graph.action.OnImpulseEvent"), ], keys.CONNECT: [ ("impulse.outputs:execOut", "write.inputs:write"), ("string.inputs:value", "write.inputs:value"), ], keys.SET_VALUES: [ ("write.inputs:widgetIdentifier", "invalid-id"), ("string.inputs:value", "new style"), ("impulse.state:enableImpulse", True), ("impulse.inputs:onlyPlayback", False), ], }, ) warning = "OmniGraph Warning: No widget with identifier 'invalid-id' found in this graph." self.assert_compute_message(write, warning, og.Severity.WARNING) await self.finalize_test_no_image() async def test_write_widget_property_invalid_widget_path(self): graph = self.create_graph() widget_path = "Viewport//Frame/ZStack[0]/Frame[3]/OG_overlay/Placer[2]/testbutton11" keys = og.Controller.Keys (_, (_, _, _, _, write, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("write", "omni.graph.ui_nodes.WriteWidgetProperty"), ("string", "omni.graph.nodes.ConstantString"), ("impulse", "omni.graph.action.OnImpulseEvent"), ], keys.CONNECT: [ ("impulse.outputs:execOut", "write.inputs:write"), ("string.inputs:value", "write.inputs:value"), ], keys.SET_VALUES: [ ("write.inputs:widgetPath", widget_path), ("string.inputs:value", "new style"), ("impulse.state:enableImpulse", True), ("impulse.inputs:onlyPlayback", False), ], }, ) warning = f"OmniGraph Warning: No widget found at path '{widget_path}'." self.assert_compute_message(write, warning, og.Severity.WARNING) await self.finalize_test_no_image() async def test_write_widget_property_invalid_widget(self): graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, write, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("write", "omni.graph.ui_nodes.WriteWidgetProperty"), ("string", "omni.graph.nodes.ConstantString"), ("impulse", "omni.graph.action.OnImpulseEvent"), ], keys.CONNECT: [ ("impulse.outputs:execOut", "write.inputs:write"), ("string.inputs:value", "write.inputs:value"), ], keys.SET_VALUES: [ ("string.inputs:value", "new style"), ("impulse.state:enableImpulse", True), ("impulse.inputs:onlyPlayback", False), ], }, ) warning = "OmniGraph Warning: No widgetIdentifier or widgetPath provided." self.assert_compute_message(write, warning, og.Severity.WARNING) await self.finalize_test_no_image() async def test_write_widget_property_no_property(self): graph = self.create_graph() widget_identifier = "testbutton1" keys = og.Controller.Keys (_, (_, _, _, _, _, write, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("button", "omni.graph.ui_nodes.Button"), ("write", "omni.graph.ui_nodes.WriteWidgetProperty"), ("string", "omni.graph.nodes.ConstantString"), ], keys.CONNECT: [ ("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "button.inputs:create"), ("button.outputs:created", "write.inputs:write"), ("button.outputs:widgetPath", "write.inputs:widgetPath"), ("string.inputs:value", "write.inputs:value"), ], keys.SET_VALUES: [ ("button.inputs:widgetIdentifier", widget_identifier), ("button.inputs:text", "TEST BUTTON"), ("button.inputs:style", '{"background_color": "green"}'), ("string.inputs:value", "NEW BUTTON"), ], }, error_thrown=True, ) error = "OmniGraph Error: No property provided." self.assert_compute_message(write, error) await self.finalize_test_no_image() async def test_write_widget_property_invalid_property(self): graph = self.create_graph() widget_identifier = "testbutton1" keys = og.Controller.Keys (_, (_, _, _, _, _, write, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("button", "omni.graph.ui_nodes.Button"), ("write", "omni.graph.ui_nodes.WriteWidgetProperty"), ("string", "omni.graph.nodes.ConstantString"), ], keys.CONNECT: [ ("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"), ("viewport.outputs:scriptedMode", "button.inputs:create"), ("button.outputs:created", "write.inputs:write"), ("string.inputs:value", "write.inputs:value"), ], keys.SET_VALUES: [ ("button.inputs:widgetIdentifier", widget_identifier), ("write.inputs:widgetIdentifier", widget_identifier), ("button.inputs:text", "TEST BUTTON"), ("button.inputs:style", '{"background_color": "green"}'), ("string.inputs:value", "NEW BUTTON"), ("write.inputs:propertyName", "invalid-property"), ], }, error_thrown=True, ) error = f"OmniGraph Error: Widget '{widget_identifier}' has no property 'invalid-property'." self.assert_compute_message(write, error) await self.finalize_test_no_image() async def test_get_set_active_viewport_camera(self): graph = self.create_graph() prim_path = "/OmniverseKit_Front" keys = og.Controller.Keys (_, (_, _, _, _, _, get_camera, _, _), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("set_camera", "omni.graph.ui_nodes.SetActiveViewportCamera"), ("get_camera", "omni.graph.ui_nodes.GetActiveViewportCamera"), ("to_string", "omni.graph.nodes.ToString"), ("print", "omni.graph.ui_nodes.PrintText"), ], keys.CONNECT: [ ("viewport.outputs:scriptedMode", "set_camera.inputs:execIn"), ("get_camera.outputs:camera", "to_string.inputs:value"), ("set_camera.outputs:execOut", "print.inputs:execIn"), ("to_string.outputs:converted", "print.inputs:text"), ], keys.SET_VALUES: [ ("set_camera.inputs:viewport", self.viewport_name), ("set_camera.inputs:primPath", prim_path), ], }, ) self.get_attribute_and_assert_equals("outputs:camera", get_camera, prim_path) await self.finalize_test_no_image() # Using emulate_mouse_move_and_click() doesn't trigger the OnPicked node, even when done through the # Script Editor in an interactive session. @unittest.skip("OM-77263: Not working.") async def test_on_picked(self): graph = self.create_graph() keys = og.Controller.Keys (_, (_, _, _, _, _, counter), _, _) = await self.edit_ui_execution_graph( graph, { keys.CREATE_NODES: [ ("on_picked", "omni.graph.ui_nodes.OnPicked"), ("counter", "omni.graph.action.Counter"), ], keys.CONNECT: [ ("on_picked.outputs:picked", "counter.inputs:execIn"), ], keys.SET_VALUES: [ ("on_picked.inputs:viewport", self.viewport_name), ("on_picked.inputs:onlyPlayback", False), ], }, ) await emulate_mouse_move_and_click(Vec2(85, 255)) cube = ogts.create_cube(self.stage, "my_cube", (1, 1, 1)) attr = cube.GetAttribute("size") attr.Set(10.0) await ui_test.wait_n_updates(20) self.get_attribute_and_assert_equals("outputs:count", counter, 1) await self.finalize_test() async def test_pass_clicks_thru(self): await self.create_test_area(width=1200, height=800, block_devices=False) selection: omni.usd.Selection = omni.usd.get_context().get_selection() # Load some geometry so that we have something which can be selected with a mouse click. # The pxr renderer (aka "Storm") has problems selecting implicit geometry such as that generated by # the Cube prim, so we need to use a mesh. (result, error) = await ogts.load_test_file("mesh-cube.usd", use_caller_subdirectory=True) self.assertTrue(result, error) cube_path = "/World/Cube" cube_pos = Vec2(700, 400) # Create an execution graph with a SetViewportMode node and a variable to control its passClicksThru. # An OnVariableChange node triggers the SetViewportMode node whenever the variable's value changes. graph = self.create_graph() keys = og.Controller.Keys controller = og.Controller() controller.edit( graph, { keys.CREATE_VARIABLES: [("passThruMode", "bool", False)], keys.CREATE_NODES: [ ("readVariable", "omni.graph.core.ReadVariable"), ("viewportMode", "omni.graph.ui_nodes.SetViewportMode"), ("variableChanged", "omni.graph.action.OnVariableChange"), # These are needed to ensure that the viewport is set back to default mode when the test is done. ("viewportClose", "omni.graph.ui_nodes.SetViewportMode"), ("onClosing", "omni.graph.action.OnClosing"), ], keys.SET_VALUES: [ ("readVariable.inputs:variableName", "passThruMode"), ("viewportMode.inputs:viewport", self.viewport_name), ("viewportMode.inputs:mode", 1), ("variableChanged.inputs:variableName", "passThruMode"), ("variableChanged.inputs:onlyPlayback", False), ("viewportClose.inputs:viewport", self.viewport_name), ], keys.CONNECT: [ ("readVariable.outputs:value", "viewportMode.inputs:passClicksThru"), ("variableChanged.outputs:changed", "viewportMode.inputs:execIn"), ("onClosing.outputs:execOut", "viewportClose.inputs:execIn"), ], }, ) variable = graph.find_variable("passThruMode") # Make sure nothing is selected and give the viewport some time to settle down. selection.clear_selected_prim_paths() await ui_test.wait_n_updates(2) # Enable passClicksThru and click on the cube. It should be selected. variable.set(graph.get_context(), True) await ui_test.wait_n_updates(2) await emulate_mouse_move_and_click(cube_pos) await ui_test.wait_n_updates(8) self.assertTrue(cube_path in selection.get_selected_prim_paths(), "Selection with passClicksThru True.") # Disable passClicksThru and click on the cube. It should not be selected. selection.clear_selected_prim_paths() variable.set(graph.get_context(), False) await ui_test.wait_n_updates(2) await emulate_mouse_move_and_click(cube_pos) await ui_test.wait_n_updates(8) self.assertFalse(cube_path in selection.get_selected_prim_paths(), "Selection with passClicksThru False.") await self.finalize_test_no_image()
55,826
Python
43.307143
120
0.553846
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/tests/test_omnigraph_action.py
""" Tests that verify action UI-dependent nodes """ import omni.graph.core as og import omni.graph.core.tests as ogts import omni.kit.test import omni.usd from omni.kit.viewport.utility import get_active_viewport from omni.kit.viewport.utility.camera_state import ViewportCameraState from pxr import Gf # ====================================================================== class TestOmniGraphAction(ogts.OmniGraphTestCase): """Encapsulate simple sanity tests""" # ---------------------------------------------------------------------- async def setUp(self): await super().setUp() viewport_api = get_active_viewport() viewport_api.camera_path = "/OmniverseKit_Persp" # ---------------------------------------------------------------------- async def _test_camera_nodes(self, use_prim_connections): """Test camera-related node basic functionality""" keys = og.Controller.Keys controller = og.Controller() viewport_api = get_active_viewport() active_cam = viewport_api.camera_path persp_cam = "/OmniverseKit_Persp" self.assertEqual(active_cam.pathString, persp_cam) (graph, _, _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("SetCam", "omni.graph.ui_nodes.SetActiveViewportCamera"), ], keys.SET_VALUES: [ ("SetCam.inputs:primPath", "/OmniverseKit_Top"), ], keys.CONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")], }, ) await controller.evaluate() active_cam = viewport_api.camera_path self.assertEqual(active_cam.pathString, "/OmniverseKit_Top") # be nice - set it back viewport_api.camera_path = persp_cam # Tests moving the camera and camera target controller.edit( graph, { keys.DISCONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")], }, ) await controller.evaluate() (graph, (_, _, get_pos, get_target), _, _) = controller.edit( graph, { keys.CREATE_NODES: [ ("SetPos", "omni.graph.ui_nodes.SetCameraPosition"), ("SetTarget", "omni.graph.ui_nodes.SetCameraTarget"), ("GetPos", "omni.graph.ui_nodes.GetCameraPosition"), ("GetTarget", "omni.graph.ui_nodes.GetCameraTarget"), ], keys.SET_VALUES: [ ("SetPos.inputs:position", Gf.Vec3d(1.0, 2.0, 3.0)), # Target should be different than position ("SetTarget.inputs:target", Gf.Vec3d(-1.0, -2.0, -3.0)), ], keys.CONNECT: [ ("OnTick.outputs:tick", "SetPos.inputs:execIn"), ("SetPos.outputs:execOut", "SetTarget.inputs:execIn"), ], }, ) if use_prim_connections: controller.edit( graph, { keys.CREATE_NODES: [ ("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"), ("ConstToken", "omni.graph.nodes.ConstantToken"), ], keys.CONNECT: [ ("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"), ("GetPrimAtPath.outputs:prims", "SetPos.inputs:prim"), ("GetPrimAtPath.outputs:prims", "SetTarget.inputs:prim"), ("GetPrimAtPath.outputs:prims", "GetPos.inputs:prim"), ("GetPrimAtPath.outputs:prims", "GetTarget.inputs:prim"), ], keys.SET_VALUES: [ ("SetPos.inputs:usePath", False), ("SetTarget.inputs:usePath", False), ("GetPos.inputs:usePath", False), ("GetTarget.inputs:usePath", False), ("ConstToken.inputs:value", persp_cam), ], }, ) else: controller.edit( graph, { keys.SET_VALUES: [ ("SetPos.inputs:primPath", persp_cam), ("SetTarget.inputs:primPath", persp_cam), ("GetPos.inputs:primPath", persp_cam), ("GetTarget.inputs:primPath", persp_cam), ], }, ) await controller.evaluate() # XXX: May need to force these calls through legacy_viewport as C++ nodes call through to that interface. camera_state = ViewportCameraState(persp_cam) # , viewport=viewport_api, force_legacy_api=True) x, y, z = camera_state.position_world for a, b in zip([x, y, z], [1.0, 2.0, 3.0]): self.assertAlmostEqual(a, b, places=5) x, y, z = camera_state.target_world for a, b in zip([x, y, z], [-1.0, -2.0, -3.0]): self.assertAlmostEqual(a, b, places=5) # evaluate again, because push-evaluator may not have scheduled the getters after the setters await controller.evaluate() get_pos = og.Controller.get(controller.attribute(("outputs:position", get_pos))) for a, b in zip(get_pos, [1.0, 2.0, 3.0]): self.assertAlmostEqual(a, b, places=5) get_target = og.Controller.get(controller.attribute(("outputs:target", get_target))) for a, b in zip(get_target, [-1.0, -2.0, -3.0]): self.assertAlmostEqual(a, b, places=5) # ---------------------------------------------------------------------- async def test_camera_nodes(self): await self._test_camera_nodes(use_prim_connections=False) # ---------------------------------------------------------------------- async def test_camera_nodes_with_prim_connection(self): await self._test_camera_nodes(use_prim_connections=True) # ---------------------------------------------------------------------- async def test_on_new_frame(self): """Test OnNewFrame node""" keys = og.Controller.Keys controller = og.Controller() # Check that the NewFrame node is getting updated when frames are being generated (_, (new_frame_node,), _, _) = controller.edit( "/TestGraph", {keys.CREATE_NODES: [("NewFrame", "omni.graph.ui_nodes.OnNewFrame")]} ) attr = controller.attribute(("outputs:frameNumber", new_frame_node)) await og.Controller.evaluate() frame_num = og.Controller.get(attr) # Need to tick Kit before evaluation in order to update for _ in range(5): await omni.kit.app.get_app().next_update_async() await og.Controller.evaluate() self.assertLess(frame_num, og.Controller.get(attr)) # ------------------------------------------------------------------------- async def test_get_active_camera_viewport_prim_output(self): """Tests the prim output on GetActiveCameraView node returns the correct value""" keys = og.Controller.Keys controller = og.Controller() (graph, (_cam_node, path_node), _, _) = controller.edit( "/TestGraph", { keys.CREATE_NODES: [ ("GetCamera", "omni.graph.ui_nodes.GetActiveViewportCamera"), ("GetPrimPath", "omni.graph.nodes.GetPrimPath"), ], keys.CONNECT: [("GetCamera.outputs:cameraPrim", "GetPrimPath.inputs:prim")], }, ) await og.Controller.evaluate(graph) self.assertEqual(og.Controller.get(("outputs:primPath", path_node)), "/OmniverseKit_Persp") # ------------------------------------------------------------------------- async def test_get_active_camera_viewport_from_file(self): """ Test the prim output on GetActiveCameraView node exists and returns the correct value when an older version of the node is loaded from a file. """ (result, error) = await ogts.load_test_file("GetActiveViewportCamera.usda", use_caller_subdirectory=True) self.assertTrue(result, error) # validate the node and attribute exist after loading. The attribute does not exist in the file cam_node = og.Controller.node("/World/Graph/get_active_camera") self.assertTrue(cam_node.is_valid()) prim_output = og.Controller.attribute("/World/Graph/get_active_camera.outputs:cameraPrim") self.assertTrue(prim_output.is_valid()) # modify the graph and evaluate it, to verify it gets the expected results keys = og.Controller.Keys controller = og.Controller() (graph, nodes, _, _) = controller.edit( "/World/Graph", { keys.CREATE_NODES: [ ("GetPrimPath", "omni.graph.nodes.GetPrimPath"), ], }, ) prim_inputs = nodes[0].get_attribute("inputs:prim") controller.connect(prim_output, prim_inputs) await og.Controller.evaluate(graph) self.assertEqual(og.Controller.get(("outputs:primPath", nodes[0])), "/OmniverseKit_Persp")
9,466
Python
42.828704
113
0.516586
omniverse-code/kit/exts/omni.uiaudio/config/extension.toml
[package] title = "Kit UI Audio" category = "Audio" feature = true version = "1.0.0" description = "An audio API for playing sounds for UI interactions." authors = ["NVIDIA"] keywords = ["audio", "ui"] [dependencies] "carb.audio" = {} [[native.plugin]] path = "bin/*.plugin" [[python.module]] name = "omni.kit.uiaudio"
323
TOML
16.052631
68
0.662539
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/_uiaudio.pyi
""" This module contains bindings to the C++ omni::audio::IUiAudio interface. This provides functionality for playing sounds through the editor UI. Sound files may be in RIFF/WAV, Ogg, or FLAC format. Data in the sound files may use 8, 16, 24, or 32 bit integer samples, or 32 bit floating point samples. Channel counts may be from 1 to 64 If more channels of data are provided than the audio device can play, some channels will be blended together automatically. """ from __future__ import annotations import omni.kit.uiaudio._uiaudio import typing __all__ = [ "IUiAudio", "UiSound", "acquire_ui_audio_interface" ] class IUiAudio(): """ This interface contains functions for playing audio in editor UI. This is intended to be used to provide auditory feedback to the user for events such as errors or long processing steps completing. The sounds loaded by this interface will persist until destroyed and can be played any number of times as needed. Any particular sound file will only be loaded into memory once and will be shared by all callers that try to load it. Each call to create a new sound object must be paired with a call to destroy it once it is no longer needed. Up to 64 sounds may be playing at any given time for the editor UI. Playing a sound will only schedule it to be played then return immediately. The sound will continue to play. Callers can block until a sound has finished playing or query whether it has finished playing by using The IUiAudio::isSoundPlaying() call. It is best practice to use monaural or stereo sounds for this interface since they use less memory, are processed more easily, and will typically play as expected through all devices. Note that if a single long sound object is played multiple times simultaneously, attempting to stop or query the playing sound will only affect the most recently played instance of it. In this case, all other instances will continue playing until they finish naturally. All the function in this interface are in omni.kit.audio.IUiAudio class. To retrieve this object, use get_ui_audio_interface() method: >>> import omni.kit.audio >>> a = omni.kit.audio.get_ui_audio_interface() >>> sound = a.create_sound("${sounds}/test.wav") >>> a.play_sound(sound) """ def create_sound(self, filename: str) -> UiSound: """ Loads a UI sound from local disk. This loads a sound that can be played with play_sound() at a later time. This sound only needs to be loaded once but can be played as many times as needed. When no longer needed, the sound will be destroyed when it is cleared out or is garbage collected. File names passed in here may contain special path markers. The guaranteed set of markers are as follows (note that other special paths may also exist but are not included here): * "*${executable}*": resolves to the directory containing the main executable file. * "*${resources}*": resolves to the 'resources/' folder in the same directory as the main executable file. * "*${sounds}*": resolves to the 'resources/sounds/' folder in the same directory as the main executable. * "*${icons}*": resolves to the 'resources/icons/' folder in the same directory as the main executable. Args: filename: the path to the sound file to load. This should be an absolute path, but can be a relative path that will be resolved using the current working directory for the process. Parts of this path may include some special path specifiers that will be resolved when trying to open the file. See above for more info on special paths. This may not be *None* or an empty string. Returns: If successful, this return the sound object representing the new loaded sound. This sound can be passed to play_sound() later. Each sound object returned here will be destroyed when it is cleared out or garbage collected. Note that destroying the sound object will stop all playing instances of it. However, if more than one reference to the same sound object still exists, destroying one of the sound objects (ie: assigning it to *None* or letting it get garbage collected) will not stop any of the instances from playing. It is best practice to always explicitly stop a sound before destroying it. If the requested sound file could not be found or loaded, None will be returned. """ def get_sound_length(self, sound: UiSound) -> float: """ Retrieves length of a sound in seconds (if known). This calculates the length of a UI sound in seconds. This is just the length of the sound asset in seconds. Args: sound: the sound to retrieve the length for. This may not be *None*. Returns: The play length of the sound in seconds if the asset is loaded and the length can be calculated, or 0.0 otherwise. """ def is_sound_playing(self, sound: UiSound) -> bool: """ Queries whether a sound object is currently playing. This queries whether a sound is currently playing. If this fails, that may mean the sound ended naturally on its own or it was explicitly stopped. Note that this may continue to return true for a short period after a sound has been stopped with stop_sound(). This period may be up to 20 milliseconds in extreme cases but will usually not exceed 10 milliseconds. Args: sound: the sound to query the playing state for. This may not be *None*. Returns: true if the sound object is currently playing, or false if the sound has either finished playing or has not been played yet. """ def play_sound(self, sound: UiSound) -> None: """ Immediately plays the requested UI sound if it is loaded. This plays a single non-looping instance of a UI sound immediately. The UI sound must have already been loaded with create_sound(). If the sound resource was missing or couldn't be loaded, this call will simply be ignored. This will return immediately after scheduling the sound to play. It will never block for the duration of the sound's playback. This sound may be prematurely stopped with stop_sound(). Args: sound: the sound to be played. This may not be *None*. Returns: No return value. """ def stop_sound(self, sound: UiSound) -> None: """ Immediately stops the playback of a sound. This stops the playback of an active sound. If the sound was not playing or had already naturally stopped on its own, this call is ignored. Args: sound: the sound object to stop playback for. This may not be *None*. Returns: No return value. """ pass class UiSound(): """ An opaque object representing a loaded UI sound. This object is used for the IUiAudio interface. These objects may be passed to many of the other methods in the IUiAudio interface to operate on. These objects are acquired from the create_sound() method. The sound object will be destroyed when it is either cleared out (ie: assigned *None*) or gets garbage collected. """ pass def acquire_ui_audio_interface(plugin_name: str = None, library_path: str = None) -> IUiAudio: pass
7,848
unknown
46.283132
103
0.66998
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/__init__.py
""" This module contains bindings for the omni::kit::uiaudio module. This provides functionality for playing and managing sound prims in USD scenes. Sound files may be in RIFF/WAV, Ogg, or FLAC format. Data in the sound files may use 8, 16, 24, or 32 bit integer samples, or 32 bit floating point samples. Channel counts may be from 1 to 64 If more channels of data are provided than the audio device can play, some channels will be blended together automatically. """ from ._uiaudio import * # Cached UI audio instance pointer def get_ui_audio_interface() -> IUiAudio: """ helper method to retrieve a cached version of the IUiAudio interface. Returns: The cached :class:`omni.kit.uiaudio.IUiAudio` interface. This will only be retrieved on the first call. All subsequent calls will return the cached interface object. """ if not hasattr(get_ui_audio_interface, "ui_audio"): get_ui_audio_interface.ui_audio = acquire_ui_audio_interface() return get_ui_audio_interface.ui_audio
1,107
Python
34.741934
91
0.684734
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/tests/test_audio.py
import omni.kit.test import omni.kit.uiaudio class TestAudio(omni.kit.test.AsyncTestCase): # pragma: no cover async def test_ui_audio(self): audio = omni.kit.uiaudio.get_ui_audio_interface() self.assertIsNotNone(audio) # try to load a sound to test with. sound = audio.create_sound("${sounds}/stop.wav") if sound == None: # still try to play the null sound. audio.play_sound(sound) # verify the sound's length is zero. length = audio.get_sound_length(sound) self.assertEqual(length, 0.0) # make sure querying whether the null sound is playing fails. playing = audio.is_sound_playing(sound) self.assertFalse(playing) else: # play the sound. audio.play_sound(sound) # verify that it is playing. playing = audio.is_sound_playing(sound) self.assertTrue(playing) # verify the sound's length is non-zero. length = audio.get_sound_length(sound) self.assertGreater(length, 0.0) # wait so that a user can hear that sound is playing. time.sleep(min(length, 5.0)) # clean up the local reference to the sound. sound = None
1,316
Python
29.627906
73
0.582067
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/tests/__init__.py
from .test_audio import * # pragma: no cover
47
Python
14.999995
45
0.680851
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/hd_renderer_plugins.py
# Copyright (c) 2021-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__ = ["HdRendererPlugins"] from pxr import Tf, Plug class HdRendererPlugins: def __init__(self, callback_fn: callable = None): self.__callback_fn = callback_fn self.__renderers = {} self.__listener = Tf.Notice.RegisterGlobally( "PlugNotice::DidRegisterPlugins", lambda notice, _: self.__add_renderers(notice.GetNewPlugins()) ) self.__add_renderers(Plug.Registry().GetAllPlugins()) def __add_renderers(self, plugins): added = False for renderer in [d for d in Tf.Type("HdRendererPlugin").GetAllDerivedTypes() if d not in self.__renderers]: for plugin in plugins: declared = plugin.GetMetadataForType(renderer) if declared: displayName = declared.get("displayName") self.__renderers[renderer] = {"plugin": plugin, "displayName": displayName} added = True if added: self.__callback_fn(self) @property def renderers(self): for k, v in self.__renderers.items(): yield k, v def destroy(self): if self.__listener: self.__listener.Revoke() self.__listener = None def __del__(self): self.destroy()
1,711
Python
34.666666
115
0.630625
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/style.py
import carb.tokens from pathlib import Path ICON_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.render}")).joinpath("data").joinpath("icons").absolute() ICON_CORE_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.core}")).joinpath("data").joinpath("icons").absolute() UI_STYLE = { "Menu.Item.Icon::Renderer": { "image_url": f"{ICON_PATH}/viewport_renderer.svg" }, "Menu.Item.Button": { "background_color": 0, "margin": 0, "padding": 0, }, "Menu.Item.Button.Image::OptionBox": { "image_url": f"{ICON_CORE_PATH}/settings_submenu.svg" }, }
674
Python
32.749998
148
0.637982
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/extension.py
# Copyright (c) 2021-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__ = ["ViewportRenderMenuBarExtension", "get_instance", "SingleRenderMenuItemBase", "SingleRenderMenuItem"] from .menu_item.single_render_menu_item import SingleRenderMenuItem, SingleRenderMenuItemBase from .renderer_menu_container import RendererMenuContainer import omni.ext from typing import Callable _extension_instance = None def get_instance(): global _extension_instance return _extension_instance class ViewportRenderMenuBarExtension(omni.ext.IExt): """The Entry Point for the Render Settings in Viewport Menu Bar""" def on_startup(self, ext_id): self._render_menu = RendererMenuContainer() global _extension_instance _extension_instance = self def register_menu_item_type(self, menu_item_type: Callable[..., "SingleRenderMenuItemBase"]): """ Register a custom menu type for the default created renderer Args: menu_item_type: callable that will create the menu item """ if self._render_menu: self._render_menu.set_menu_item_type(menu_item_type) def on_shutdown(self): if self._render_menu: self._render_menu.destroy() self._render_menu = None global _extension_instance _extension_instance = None
1,713
Python
32.607842
112
0.718039
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/hd_renderer_list.py
# Copyright (c) 2021-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__ = ["HdEngineRendererMenuFactory"] from .hd_renderer_plugins import HdRendererPlugins import carb _log_issue = carb.log_warn class HdRenderer: def __init__(self, *args): self.pluginID, self.displayName, self.usdPlugin = args def __repr__(self): return f'HdRenderer("{self.pluginID}", "{self.displayName}")' class HdEngineRenderer: def __init__(self, *args): self.engineName, self.renderModePath = args self.renderers = [] def __repr__(self): return f'HdEngineRenderer("{self.engineName}", "{self.renderModePath}", {[r for r in self.renderers]})' class HdRendererList: RTX_RENDER_MODE_PATH = "/rtx/rendermode" IRY_RENDER_MODE_PATH = "/rtx/iray/rendermode" PXR_RENDER_MODE_PATH = "/pxr/rendermode" @classmethod def enabled_engines(cls): engines = carb.settings.get_settings().get("/renderer/enabled") if engines: # Return as an ordered list based on how renderers should display engines = engines.split(",") for engine in ("rtx", "iray", "index", "pxr"): if engine in engines: engines.remove(engine) yield engine else: engines = ("rtx", "iray", "pxr") for engine in engines: yield engine def __init__(self, update_fn: callable = None, engines=None): # Use an OrderedDict to preserve incoming or app-default order when added from collections import OrderedDict self.__renderers = OrderedDict() self.__hd_plugins = None self.__updated_fn = update_fn if not engines: engines = self.enabled_engines() for hdEngine in engines: if hdEngine == "rtx": self.__add_renderer(hdEngine, self.RTX_RENDER_MODE_PATH, "RaytracedLighting", "RTX - Real-Time") self.__add_renderer(hdEngine, self.RTX_RENDER_MODE_PATH, "PathTracing", "RTX - Interactive (Path Tracing)") if carb.settings.get_settings().get("/rtx-transient/aperture/enabled"): self.__add_renderer( hdEngine, self.RTX_RENDER_MODE_PATH, "LightspeedAperture", "RTX - Aperture (Game Path Tracer)" ) elif hdEngine == "iray": self.__add_renderer(hdEngine, self.IRY_RENDER_MODE_PATH, "iray", "RTX - Accurate (Iray)") # No known setting to enable this. if False: self.__add_renderer(hdEngine, self.IRY_RENDER_MODE_PATH, "irt", "RTX - Accurate (Iray Interactive)") elif hdEngine == "index": self.__add_renderer(hdEngine, None, "index", "RTX - Scientific (IndeX)") elif hdEngine == "pxr": self.__hd_plugins = HdRendererPlugins(self.__add_pxr_renderers) self.__add_pxr_renderers(self.__hd_plugins) else: _log_issue(f"Unknown Hydra engine'{hdEngine}'.") def destroy(self): if self.__hd_plugins: self.__hd_plugins.destroy() self.__hd_plugins = None self.__renderers = {} self.__updated_fn = None def __del__(self): self.destroy() def __add_pxr_renderers(self, plugins): for renderer, desc in plugins.renderers: pluginID = renderer.typeName displayName = desc.get("displayName") # Special case Storm's displayName which is still 'GL' if pluginID == "HdStormRendererPlugin": displayName = "Pixar Storm" self.__add_renderer("pxr", self.PXR_RENDER_MODE_PATH, pluginID, displayName, desc.get("plugin")) def __add_renderer(self, engineName: str, renderModePath: str, pluginID: str, displayName=None, usdPlugin=None): if not displayName: displayName = pluginID engineRenderers = self.__renderers.get(engineName) if not engineRenderers: engineRenderers = HdEngineRenderer(engineName, renderModePath) self.__renderers[engineName] = engineRenderers elif any([True for r in engineRenderers.renderers if r.pluginID == pluginID]): return engineRenderers.renderers.append(HdRenderer(pluginID, displayName, usdPlugin)) if self.__updated_fn: self.__updated_fn(self) @property def renderers(self): for k, v in self.__renderers.items(): yield k, v
4,912
Python
38.943089
123
0.608917
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/renderer_menu_container.py
# Copyright (c) 2021-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__ = ["RendererMenuContainer"] from .menu_item.single_render_menu_item import SingleRenderMenuItem from .hd_renderer_list import HdRendererList from .style import UI_STYLE from omni.kit.viewport.menubar.core import ( IconMenuDelegate, ViewportMenuDelegate, SettingComboBoxModel, ViewportMenuContainer, RadioMenuCollection, SelectableMenuItem, MenuDisplayStatus, ) from omni.kit.app import SettingChangeSubscription import omni.ui as ui import omni.usd import carb import os import sys import asyncio from functools import partial from typing import Callable, Dict, List, Sequence, TYPE_CHECKING if TYPE_CHECKING: from .menu_item.single_render_menu_item import SingleRenderMenuItemBase SHADING_MODE = "/exts/omni.kit.viewport.menubar.render/shadingMode" LIGHTING_MODE = "/exts/omni.kit.viewport.menubar.render/lightingMode" MATERIAL_MODE = "/exts/omni.kit.viewport.menubar.render/materialMode" class BoolStringModel(ui.SimpleBoolModel): def __init__(self, setting_path: str, value_map: Sequence[str] = ("default", "disabled"), *args, **kwargs): super().__init__(*args, **kwargs) self.__setting_path = setting_path self.__value_map = value_map self.__settings = carb.settings.get_settings() self.__setting_sub = SettingChangeSubscription(setting_path, self.__setting_changed) self.__in_set = False def __del__(self): self.destroy() def destroy(self): self.__setting_sub = None def __setting_changed(self, item: carb.dictionary._dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: self._value_changed() def get_value_as_string(self) -> bool: return self.__settings.get(self.__setting_path) def get_value_as_bool(self) -> bool: return self.__settings.get(self.__setting_path) == self.__value_map[1] def get_value(self) -> bool: return self.get_value_as_bool() def set_value(self, value: bool) -> bool: cur_value = self.__settings.get(self.__setting_path) str_value = self.__value_map[bool(value)] changed = cur_value != str_value if changed: self.__settings.set(self.__setting_path, str_value) return True return changed class FlashLightModel(BoolStringModel): def set_value(self, value: bool) -> bool: changed = super().set_value(value) if changed: settings = carb.settings.get_settings() settings.set("/rtx/useViewLightingMode", value) # settings.set("/rtx/shadows/enabled", not value) return changed class DisableMaterialModel(BoolStringModel): def set_value(self, value: bool) -> bool: changed = super().set_value(value) if changed: dbg_type = 0 if value else -1 settings = carb.settings.get_settings() settings.set("/rtx/debugMaterialType", dbg_type) wire_mode = settings.get("/rtx/wireframe/mode") if wire_mode: wire_mode = 2 if dbg_type == 0 else 1 settings.set("/rtx/wireframe/mode", wire_mode) return changed class ShadingModeModel(BoolStringModel): def set_value(self, value: bool) -> bool: changed = super().set_value(value) if changed: wire_mode = 0 settings = carb.settings.get_settings() if value: settings.set("/rtx/debugView/target", "") if self.get_value_as_string() == "wireframe": flat_shade = settings.get("/rtx/debugMaterialType") == 0 wire_mode = 2 if flat_shade else 1 settings.set("/rtx/wireframe/mode", wire_mode) return changed class DebugShadingModel(SettingComboBoxModel): def __init__(self, viewport_api): debug_view_items = {} hd_engine = viewport_api.hydra_engine if hd_engine == "rtx": debug_view_items.update({ "Off": "", "3D Motion Vectors [WARNING: Flashing Colors]": "targetMotion", "Barycentrics": "barycentrics", "Beauty After Tonemap": "beautyPostTonemap", "Beauty Before Tonemap": "beautyPreTonemap", "Depth": "depth", "Instance ID": "instanceId", "Interpolated Normal": "normal", "Heat Map: Any Hit": "anyHitCountHeatMap", "Heat Map: Intersection": "intersectionCountHeatMap", "Heat Map: Timing": "timingHeatMap", "SDG: Cross Correspondence": "sdgCrossCorrespondence", "SDG: Motion": "sdgMotion", "Semantic ID": "semanticId", "Tangent U": "tangentu", "Tangent V": "tangentv", "Texture Coordinates 0": "texcoord0", "Texture Coordinates 1": "texcoord1", "Triangle Normal": "triangleNormal", "Triangle Normal (OctEnc)": "triangleNormalOctEnc", # ReLAX Only "Wireframe": "wire", }) render_mode = viewport_api.render_mode if render_mode == "RaytracedLighting": debug_view_items.update({ "RT Ambient Occlusion": "ao", "RT Caustics": "caustics", "RT Denoised Dome Light": "denoisedDomeLightingTex", "RT Denoised Sampled Lighting": "rtDenoisedSampledLighting", "RT Denoised Sampled Lighting Diffuse": "rtDenoiseSampledLightingDiffuse", # ReLAX Only "RT Denoised Sampled Lighting Specular": "rtDenoiseSampledLightingSpecular", # ReLAX Only "RT Developer Debug Texture": "developerDebug", "RT Diffuse GI": "indirectDiffuse", "RT Diffuse GI (Not Accumulated)": "indirectDiffuseNonAccum", "RT Diffuse Reflectance": "diffuseReflectance", "RT Material Normal": "materialGeometryNormal", "RT Material Normal (OctEnc)": "materialGeometryNormalOctEnc", # ReLAX Only "RT Matte Object Compositing Alpha": "matteObjectAlpha", "RT Matte Object Mask": "matteObjectMask", "RT Matte Object View Before Postprocessing": "matteBeforePostprocessing", "RT Noisy Dome Light": "noisyDomeLightingTex", "RT Noisy Sampled Lighting": "rtNoisySampledLighting", "RT Noisy Sampled Lighting (Not Accumulated)": "rtNoisySampledLightingNonAccum", "RT Noisy Sampled Lighting Diffuse": "rtNoisySampledLightingDiffuse", # ReLAX Only "RT Noisy Sampled Lighting Diffuse (Not Accumulated)": "sampledLightingDiffuseNonAccum", "RT Noisy Sampled Lighting Specular": "rtNoisySampledLightingSpecular", # ReLAX Only "RT Noisy Sampled Lighting Specular (Not Accumulated)": "sampledLightingSpecularNonAccum", "RT Radiance": "radiance", "RT Reflections": "reflections", "RT Reflections (Not Accumulated)": "reflectionsNonAccum", "RT Reflections 3D Motion Vectors [WARNING: Flashing Colors]": "reflectionsMotion", "RT Roughness": "roughness", "RT Shadow (last light)": "shadow", "RT Specular Reflectance": "reflectance", "RT Translucency": "translucency", "RT World Position": "worldPosition", }) elif render_mode == "PathTracing": debug_view_items.update({ "PT Adaptive Sampling Error [WARNING: Flashing Colors]": "PTAdaptiveSamplingError", "PT Denoised Result": "pathTracerDenoised", "PT Noisy Result": "pathTracerNoisy", "PT AOV Background": "PTAOVBackground", "PT AOV Diffuse Filter": "PTAOVDiffuseFilter", "PT AOV Direct Illumation": "PTAOVDI", "PT AOV Global Illumination": "PTAOVGI", "PT AOV Reflections": "PTAOVReflections", "PT AOV Reflection Filter": "PTAOVReflectionFilter", "PT AOV Refractions": "PTAOVRefractions", "PT AOV Refraction Filter": "PTAOVRefractionFilter", "PT AOV Self-Illumination": "PTAOVSelfIllum", "PT AOV Volumes": "PTAOVVolumes", "PT AOV World Normal": "PTAOVWorldNormals", "PT AOV World Position": "PTAOVWorldPos", "PT AOV Z-Depth": "PTAOVZDepth", "PT AOV Multimatte0": "PTAOVMultimatte0", "PT AOV Multimatte1": "PTAOVMultimatte1", "PT AOV Multimatte2": "PTAOVMultimatte2", "PT AOV Multimatte3": "PTAOVMultimatte3", "PT AOV Multimatte4": "PTAOVMultimatte4", "PT AOV Multimatte5": "PTAOVMultimatte5", "PT AOV Multimatte6": "PTAOVMultimatte6", "PT AOV Multimatte7": "PTAOVMultimatte7", }) # Sort the above alphabetically names, values = [], [] if debug_view_items: for k, v in (debug_view_items.items()): names.append(k) values.append(v) else: names = [] values = [] super().__init__("/rtx/debugView/target", names, values=values) def _on_change(self, *args, **kwargs) -> None: super()._on_change(*args, **kwargs) current_value = self._settings.get(self._path) if current_value == '': if self._settings.get(SHADING_MODE).startswith("custom:"): self._settings.set(SHADING_MODE, "default") else: self._settings.set(SHADING_MODE, f"custom:{current_value}") self._settings.set("/rtx/wireframe/mode", 0) def empty(self): children = self.get_item_children(None) return len(children) == 0 if children else True def __del__(self): self.destroy() def destroy(self): super().destroy() class MenuContext(): def __init__(self, root_menu: ui.Menu, viewport_api, renderer_changed_fn: Callable): super().__init__() self.__root_menu = root_menu self.__viewport_api = viewport_api self.__destroyable = {} self.__usd_context_sub = viewport_api.usd_context.get_stage_event_stream().create_subscription_to_pop( self.__on_usd_context_event, name=f"omni.kit.viewport.menubar.render.menu_context.{id(self)}" ) self.__renderer_changed_fn = renderer_changed_fn self.__rs_changed_sub = viewport_api.subscribe_to_render_settings_change(self.__render_settings_changed) def __on_usd_context_event(self, event: omni.usd.StageEventType): if event.type == int(omni.usd.StageEventType.SETTINGS_LOADED): self.set_default_state() def __render_settings_changed(self, *args, **kwargs): self.__renderer_changed_fn(self, self.__viewport_api) def set_default_state(self): stage = self.__viewport_api.stage if stage: render_settings = stage.GetMetadata('customLayerData').get('renderSettings', {}) dbg_mat_type = render_settings.get('rtx:debugMaterialType') view_lighting = render_settings.get('rtx:useViewLightingMode') wire_mode = render_settings.get('rtx:wireframe:mode') dbg_target = render_settings.get('rtx:debugView:target') settings = carb.settings.get_settings() settings.set(MATERIAL_MODE, "disabled" if dbg_mat_type == 0 else "default") settings.set(LIGHTING_MODE, "disabled" if view_lighting else "default") if wire_mode: shade_mode = "wireframe" elif dbg_target: shade_mode = f"custom:{dbg_target}" else: shade_mode = "default" settings.set(SHADING_MODE, shade_mode) @property def root_menu(self) -> ui.Menu: return self.__root_menu @property def delegate(self) -> ui.MenuDelegate: return self.root_menu.delegate @property def viewport_api(self): return self.__viewport_api def add_destroyables(self, key: str, destroyables: Sequence): self.destroy(key) self.__destroyable[key] = destroyables def destroy(self, key: str = None): if key is not None: items = self.__destroyable.get(key) if items: for item in items: item.destroy() del self.__destroyable[key] return if self.__usd_context_sub: self.__usd_context_sub = None if self.__rs_changed_sub: self.__rs_changed_sub = None if self.__destroyable: for items in self.__destroyable.values(): for item in items: item.destroy() self.__destroyable = {} if self.__root_menu: self.__root_menu.destroy() self.__root_menu = None class RendererMenuContainer(ViewportMenuContainer): """The menu with the list of renderers""" PXR_IN_USE = "/app/viewport/omni_hydra_pxr_in_use" __enabled_engines = None def __init__(self): super().__init__( name="Renderer", delegate=None, visible_setting_path="/exts/omni.kit.viewport.menubar.render/visible", order_setting_path="/exts/omni.kit.viewport.menubar.render/order", style=UI_STYLE ) self.__render_list = None self.__render_state_subs = None self._folder_exist_popup = None self.__menu_item_type = SingleRenderMenuItem self.__pending_render_change = False self.__menu_context: Dict[int, MenuContext] = {} # FIXME: Grab this now (on startup) as OmniHydraEngineFactoryBase can mutate it on first activation if not RendererMenuContainer.__enabled_engines: RendererMenuContainer.__enabled_engines = HdRendererList.enabled_engines() # We can possibly drop these subscriptions when Viewport-1 is retired; but for now we have to watch for some # common events if both VP-1 and VP-2 are sharing a hydra engine instance. settings = carb.settings.get_settings() self.__render_state_subs = ( settings.subscribe_to_node_change_events(self.PXR_IN_USE, self.__dirty_menu), settings.subscribe_to_node_change_events("/pxr/renderers", self.__dirty_menu), settings.subscribe_to_node_change_events(HdRendererList.PXR_RENDER_MODE_PATH, self.__dirty_menu), settings.subscribe_to_node_change_events(HdRendererList.RTX_RENDER_MODE_PATH, self.__dirty_menu), settings.subscribe_to_node_change_events(HdRendererList.IRY_RENDER_MODE_PATH, self.__dirty_menu), settings.subscribe_to_node_change_events("/renderer/enabled", self.__dirty_renderers), ) # Watch for extension enable/disable to support backgorund renderer loading self.__setup_extenion_watching() def __setup_extenion_watching(self): import omni.kit.app app = omni.kit.app.get_app() if not app: return def setup_ext_hooks(*args, **kwargs): import omni.ext ext_manager = omni.kit.app.get_app().get_extension_manager() if ext_manager: self.__ext_manager_hooks = ext_manager.subscribe_to_extension_enable( self.__ext_enabled, self.__ext_disabled, # ext_name="omni.hydra.*", hook_name="omni.kit.viewport.menubar.render.extension_change", ) if not app.is_app_ready(): self.__app_ready_sub = app.get_startup_event_stream().create_subscription_to_pop_by_type( omni.kit.app.EVENT_APP_READY, setup_ext_hooks, name="omni.kit.viewport.menubar.render.app_ready" ) else: setup_ext_hooks() def set_menu_item_type(self, menu_item_type: Callable[..., "SingleRenderMenuItemBase"]): """ Set the menu type for the default created renderer Args: menu_item_type: callable that will create the menu item """ if menu_item_type is None: menu_item_type = SingleRenderMenuItem if self.__menu_item_type != menu_item_type: self.__menu_item_type = menu_item_type self.__dirty_menu() def __hide_on_click(self, viewport_context: Dict = None): return viewport_context.get("hide_on_click", False) if viewport_context else False def destroy(self): self.__app_ready_sub = None self.__ext_manager_hooks = None if self.__render_list: self.__render_list.destroy() self.__render_list = None if self.__render_state_subs: settings = carb.settings.get_settings() for sub in self.__render_state_subs: settings.unsubscribe_to_change_events(sub) self.__render_state_subs = None for context in self.__menu_context.values(): context.destroy() self.__menu_context = {} super().destroy() @property def render_list(self): """Returns the list of available renderers""" if not self.__render_list: def set_dirty(*args): self.__dirty_menu() self.__render_list = HdRendererList(set_dirty, self.__enabled_engines) return self.__render_list def build_fn(self, viewport_context: Dict): """Entry point for the menu bar""" viewport_api = viewport_context.get('viewport_api') viewport_api_id = viewport_api.id menu_context = self.__menu_context.get(viewport_api_id) if menu_context: menu_context.destroy() root_menu = ui.Menu(self.name, delegate=IconMenuDelegate("Renderer", text=True), on_build_fn=partial(self._build_menu, viewport_context), style=self._style, hide_on_click=self.__hide_on_click(viewport_context) ) self.__menu_context[viewport_api_id] = MenuContext(root_menu, viewport_api, self.__set_menu_label) # It will set the renderer name self.__dirty_menu() def get_display_status(self, factory_args: dict) -> MenuDisplayStatus: viewport_api_id = factory_args['viewport_api'].id context = self.__menu_context[viewport_api_id] if context.delegate.text_visible: return MenuDisplayStatus.LABEL else: return MenuDisplayStatus.MIN def get_require_size(self, factory_args: dict, expand: bool = False) -> float: display_status = self.get_display_status(factory_args) viewport_api_id = factory_args['viewport_api'].id context = self.__menu_context[viewport_api_id] if expand: if display_status == MenuDisplayStatus.LABEL: return 0 else: return context.delegate.text_size else: return 0 def expand(self, factory_args: dict) -> None: viewport_api_id = factory_args['viewport_api'].id context = self.__menu_context[viewport_api_id] if context.delegate.text_visible: return else: context.delegate.text_visible = True if context.root_menu: context.root_menu.invalidate() def can_contract(self, factory_args: dict) -> bool: display_status = self.get_display_status(factory_args) return display_status == MenuDisplayStatus.LABEL def contract(self, factory_args: dict) -> bool: viewport_api_id = factory_args['viewport_api'].id context = self.__menu_context[viewport_api_id] display_status = self.get_display_status(factory_args) if display_status == MenuDisplayStatus.LABEL: context.delegate.text_visible = False if context.root_menu: context.root_menu.invalidate() return True return False def __add_destroyables(self, viewport_api, key: str, destroyables: Sequence): menu_context = self.__menu_context.get(viewport_api.id) assert menu_context, f"No MenuContext for {viewport_api} (id: {viewport_api.id})" menu_context.add_destroyables(key, destroyables) def __build_renderers(self, viewport_context): """Build the menu with the list of the renderers""" viewport_api = viewport_context["viewport_api"] viewport_api_id = viewport_api.id hide_on_click = self.__hide_on_click(viewport_context) settings = carb.settings.get_settings() # See if the omni.hydra.pxr engine is available for use in this Viewport pxr_eng_available = self.__pxr_available(settings, viewport_api) # Example: HdStormRendererPlugin:Storm pxr_rnd_available = settings.get("/pxr/renderers") # Example: rtx current_engine_name = viewport_api.hydra_engine for engine_name, hd_engine_renderer in self.render_list.renderers: is_pxr = engine_name == "pxr" is_engine_current = engine_name == current_engine_name # Only sort renderers of the engine alphabetically for pxr renderers if is_pxr: renderers = sorted( hd_engine_renderer.renderers, key=lambda hd_renderer: hd_renderer.displayName.lower() ) else: renderers = hd_engine_renderer.renderers # Example: /rtx/rendermode render_mode_path = hd_engine_renderer.renderModePath # Get current from settings if is_engine_current: # Example: RaytracedLighting current_render_mode = settings.get(render_mode_path) if render_mode_path else None else: current_render_mode = None for hd_renderer in renderers: # Example: RaytracedLighting render_mode = hd_renderer.pluginID enabled = True if is_pxr: # Check the renderer hasn't actually de-registered itself # And only enable these menu items if omni.hydra.pxr engine is available for this Viewport instance if not pxr_eng_available or (pxr_rnd_available and pxr_rnd_available.find(render_mode) == -1): enabled = False checked = is_engine_current and (render_mode == current_render_mode if render_mode_path else True) def apply(viewport_api, engine_name, render_mode_path, render_mode): """Switch the current renderer""" if True: settings = carb.settings.get_settings() # Set the legacy /renderer/active change for anyone that may be watching for it settings.set('/renderer/active', engine_name) # Now set the render-mode on that engine too if render_mode_path: settings.set(render_mode_path, render_mode) # Finally apply it to the backing texture viewport_api.set_hd_engine(engine_name, render_mode) self.__menu_item_type( hd_renderer.displayName, engine_name, hd_engine_renderer, hd_renderer, viewport_api, enabled=enabled, checked=checked, hide_on_click=hide_on_click, triggered_fn=partial(apply, viewport_api, engine_name, render_mode_path, render_mode), ) def __build_shading_modes(self, viewport_context): """Build the shading modes""" hide_on_click = self.__hide_on_click(viewport_context) viewport_api = viewport_context.get("viewport_api") engine_name = viewport_api.hydra_engine is_rtx_or_pxr = engine_name == "rtx" or engine_name == "pxr" default_shade_mode = SelectableMenuItem( "Default", model=ShadingModeModel(SHADING_MODE, ("wireframe", "default")), delegate=ViewportMenuDelegate(force_checked=True), hide_on_click=hide_on_click, toggle=False, enabled=is_rtx_or_pxr, ) wireframe_mode = SelectableMenuItem( "Wireframe", model=ShadingModeModel(SHADING_MODE, ("default", "wireframe")), delegate=ViewportMenuDelegate(force_checked=True), hide_on_click=hide_on_click, toggle=False, enabled=is_rtx_or_pxr, ) debug_mode = RadioMenuCollection( "Debug View", DebugShadingModel(viewport_api), hide_on_click=hide_on_click, ) debug_mode.enabled = not debug_mode._model.empty() self.__add_destroyables(viewport_api, 'omni.kit.viewport.menubar.render.shading_modes', [default_shade_mode, wireframe_mode, debug_mode]) if not debug_mode.enabled: carb.settings.get_settings().set("/rtx/debugView/target", "") async def toggle_states(): import omni.kit.app await omni.kit.app.get_app().next_update_async() if default_shade_mode.model: default_shade_mode.delegate.checked = default_shade_mode.model.as_bool if wireframe_mode.model: wireframe_mode.delegate.checked = wireframe_mode.model.as_bool import asyncio asyncio.ensure_future(toggle_states()) def __build_preset_modes(self, viewport_context): """Build the first level menu""" hide_on_click = self.__hide_on_click(viewport_context) ui.MenuItem("Load from Preset", triggered_fn=None, hide_on_click=hide_on_click) def __build_render_options(self, viewport_context): # Get the useViewLightingMode and turn on/off shadows based on it viewport_api = viewport_context["viewport_api"] engine_name = viewport_api.hydra_engine is_iray = engine_name == "iray" is_rtx_or_pxr = engine_name == "rtx" or engine_name == "pxr" flash_light = SelectableMenuItem("Camera Light", model=FlashLightModel(LIGHTING_MODE), enabled=is_rtx_or_pxr) disable_mat = SelectableMenuItem("Disable Materials (White Mode)", model=DisableMaterialModel(MATERIAL_MODE), enabled=is_rtx_or_pxr or is_iray) self.__add_destroyables(viewport_api, 'omni.kit.viewport.menubar.render.render_options', [flash_light, disable_mat]) def __build_rendering_settings(self, viewport_context): """Build the rendering settings presets""" # loading settings with menu open results in weird refresh problems, so disabled hide_on_click = True # get presets preset_dict = carb.settings.get_settings().get_settings_dictionary("exts/omni.kit.viewport.menubar.render/presets").get_dict() # remove any unused presets for preset in preset_dict.copy(): if not preset_dict[preset]: del preset_dict[preset] if preset_dict: def get_title(name): return name.replace("_", " ").title() ui.Separator(text="Rendering Settings") with ui.Menu("Load from Preset", hide_on_click=hide_on_click): for preset in preset_dict: ui.MenuItem(f"{get_title(preset)}", triggered_fn=lambda p=preset_dict[preset]: asyncio.ensure_future(self.__load_setting_file(carb.tokens.get_tokens_interface().resolve(p))), hide_on_click=hide_on_click) ui.Separator() ui.MenuItem("Load Preset From File", triggered_fn=lambda v=viewport_context: self.__load_settings(v), hide_on_click=hide_on_click) ui.MenuItem("Save Current as Preset", triggered_fn=lambda v=viewport_context: self.__save_settings(v), hide_on_click=hide_on_click) ui.MenuItem("Reset to Defaults", triggered_fn=self.__reset_settings, hide_on_click=hide_on_click) def __reset_settings(self): omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx") def __save_settings(self, viewport_context): try: from omni.kit.window.file_exporter import get_file_exporter def show_file_exist_popup(usd_path, save_file): try: from omni.kit.widget.prompt import Prompt def on_confirm(usd_path): on_cancel() save_file(usd_path) def on_cancel(): self._folder_exist_popup.hide() self._folder_exist_popup = None if not self._folder_exist_popup: self._folder_exist_popup = Prompt( title="Overwrite", text="The file already exists, are you sure you want to overwrite it?", ok_button_text="Overwrite", cancel_button_text="Cancel", ok_button_fn=lambda: on_confirm(usd_path), cancel_button_fn=on_cancel, ) self._folder_exist_popup.show() except ModuleNotFoundError: carb.log_error("omni.kit.widget.prompt not enabled!") except Exception as exc: carb.log_error(f"__save_settings.show_file_exist_popup errror {exc}") def save_handler(filename: str, dirname: str, extension: str = "", selections: List[str] = []): try: from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser def save_file(usd_path): serialiser = USDSettingsSerialiser() serialiser.save_to_usd(usd_path) final_path = f"{dirname}/{filename}{extension}" if os.path.exists(final_path): show_file_exist_popup(final_path, save_file) else: save_file(final_path) except ModuleNotFoundError: carb.log_error("omni.rtx.window.settings not enabled!") except Exception as exc: carb.log_error(f"__save_settings.save_handler errror {exc}") file_exporter = get_file_exporter() if file_exporter: file_exporter.show_window( title="Save Settings File", export_button_label="Save", export_handler=save_handler, filename_url=carb.tokens.get_tokens_interface().resolve("${cache}/"), file_postfix_options=["settings"]) except ModuleNotFoundError: carb.log_error("omni.kit.window.file_exporter not enabled!") except Exception as exc: carb.log_error(f"__save_settings errror {exc}") def __load_settings(self, viewport_context): try: from omni.kit.window.file_importer import get_file_importer def load_handler(filename: str, dirname: str, selections: List[str]): from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser final_path = f"{dirname}/{filename}" try: serialiser = USDSettingsSerialiser() serialiser.load_from_usd(final_path) except ModuleNotFoundError: carb.log_error("omni.rtx.window.settings not enabled!") except Exception as exc: carb.log_error(f"__save_settings.save_handler errror {exc}") file_importer = get_file_importer() if file_importer: file_importer.show_window( title="Load Settings File", import_button_label="Load", import_handler=load_handler, filename_url=carb.tokens.get_tokens_interface().resolve("${cache}/"), file_postfix_options=["settings"]) except ModuleNotFoundError: carb.log_error("omni.kit.window.file_importer not enabled!") except Exception as exc: carb.log_error(f"__load_settings errror {exc}") async def __load_setting_file(self, preset_name): await omni.kit.app.get_app().next_update_async() try: from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser serialiser = USDSettingsSerialiser() serialiser.load_from_usd(preset_name) except ModuleNotFoundError: carb.log_error("omni.rtx.window.settings not enabled!") except Exception as exc: carb.log_error(f"__load_setting_file errror {exc}") def _build_menu(self, viewport_context): """Build the first level menu""" hide_on_click = self.__hide_on_click(viewport_context) viewport_api = viewport_context.get("viewport_api") if not viewport_api: return menu_context = self.__menu_context.get(viewport_api.id) self.__menu_context[viewport_api.id].root_menu.clear() ui.MenuItemCollection(on_build_fn=lambda *args: self.__build_renderers(viewport_context)) # Rendering Settings self.__build_rendering_settings(viewport_context) # Rendering Mode ui.Separator(text="Rendering Mode") ui.Menu(checkable=True, on_build_fn=lambda *args: self.__build_shading_modes(viewport_context)) ui.Separator() ui.Menu(checkable=True, on_build_fn=lambda *args: self.__build_render_options(viewport_context)) ui.Separator() # This opens a new Window or goes to an existing preference-pane, so close the Menu ui.MenuItem("Preferences", triggered_fn=self.__show_render_preferences, hide_on_click=hide_on_click) # The rest of the menu on the case someone wants to put custom stuff children = self._children if children: ui.Separator() for child in children: child.build_fn(viewport_context) if not menu_context: return self.__set_menu_label(menu_context, viewport_api) def __dirty_menu(self, *args, **kwargs): """Rebuild everything""" for context in self.__menu_context.values(): if context.root_menu: context.root_menu.invalidate() self.dirty = True def __dirty_renderers(self, *args, **kwargs): # On 105.0, changes to /renderer/enabled can/will be recursive if self.__pending_render_change: return self.__pending_render_change = True async def update_render_list(): self.__pending_render_change = False RendererMenuContainer.__enabled_engines = HdRendererList.enabled_engines() self.__render_list = None self.__dirty_menu() from omni.kit.async_engine import run_coroutine run_coroutine(update_render_list()) def __ext_changed(self, ext_name: str, enabled: bool): if not ext_name.startswith("omni.hydra"): return settings = carb.settings.get_settings() managed_hd_exts = settings.get("/exts/omni.kit.viewport.menubar.render/autoManageEnabledList") if not managed_hd_exts: return managed_hd_exts = [ext.lstrip().rstrip() for ext in managed_hd_exts.split(",")] engine_split = ext_name.split(".") if len(engine_split) >= 3: engine_split = engine_split[2].split("-")[0] # Test is this extension is "managed" if engine_split in managed_hd_exts: rnd_enabled = settings.get("/renderer/enabled") or "" rnd_loc = rnd_enabled.find(engine_split) if enabled: if rnd_loc == -1: settings.set("/renderer/enabled", ",".join([rnd_enabled, engine_split])) elif rnd_loc != -1: rnd_enabled = rnd_enabled.split(",") rnd_enabled.remove(engine_split) settings.set("/renderer/enabled", ",".join(rnd_enabled)) self.__dirty_renderers() def __ext_enabled(self, ext_name: str, *args, **kwargs): self.__ext_changed(ext_name, True) def __ext_disabled(self, ext_name: str, *args, **kwargs): self.__ext_changed(ext_name, False) def __pxr_available(self, settings, viewport_api): # See if the omni.hydra.pxr engine is available for use in this Viewport try: usd_context_key = f"'{viewport_api.usd_context_name}':" setting_path = viewport_api._settings_path pxr_eng_in_use = settings.get(self.PXR_IN_USE) if not pxr_eng_in_use: return True # Iterate the list of UsdContext.name => ViewportKey usd_context_key_len = len(usd_context_key) for in_use in pxr_eng_in_use: # Is a omni.hydra.pxr engine instance running for this UsdContext? if in_use.startswith(usd_context_key): # Yes, so the menu must can only be in the Viewport that claims the context if in_use.find(setting_path) == usd_context_key_len: return True # Otherwise this Viewport cannot use omni.hydra.pxr return False # omni.hydra.pxr is not in use for this UsdContext, so it is available return True except Exception: pass return False def __get_current_name(self, viewport_api): """Returns display name of the current renderer""" engine_name = viewport_api.hydra_engine engine_name, hd_engine_renderer = next( (i for i in self.render_list.renderers if i[0] == engine_name), (None, None) ) if not hd_engine_renderer or not hd_engine_renderer.renderers: return self.name # Example: /rtx/rendermode render_mode_path = hd_engine_renderer.renderModePath if not render_mode_path: return hd_engine_renderer.renderers[0].displayName # Example: RaytracedLighting current_render_mode = carb.settings.get_settings().get(render_mode_path) return next((i.displayName for i in hd_engine_renderer.renderers if i.pluginID == current_render_mode), None) def __set_menu_label(self, menu_context: MenuContext, viewport_api): if menu_context is None: menu_context = self.__menu_context.get(viewport_api.id) if menu_context is None: carb.log_error("No MenuContext for this menubar-item") return current_renderer_name = self.__get_current_name(viewport_api) menu_context.root_menu.text = { "RTX - Interactive (Path Tracing)": "RTX - Interactive", "RTX - Accurate (Iray)": "RTX - Accurate", "RTX - Scientific (IndeX)": "RTX - Scientific", }.get(current_renderer_name, str(current_renderer_name)) if current_renderer_name else self.name def __show_render_preferences(self, *args, **kwargs) -> None: try: import omni.kit.window.preferences as preferences async def focus_async(): pref_window = ui.Workspace.get_window("Preferences") if pref_window: pref_window.focus() PAGE_TITLE = "Rendering" inst = preferences.get_instance() if not inst: carb.log_error("Preferences extension is not loaded yet") return pages = preferences.get_page_list() for page in pages: if page.get_title() == PAGE_TITLE: inst.select_page(page) # Show the Window inst.show_preferences_window() # Force the tab to be the active/focused tab (this currently needs to be done in async) asyncio.ensure_future(focus_async()) return page else: carb.log_error("Render Preferences page not found!") except ImportError: carb.log_error("omni.kit.window.preferences not enabled!")
41,744
Python
41.771516
223
0.581952
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/menu_item/single_render_menu_item.py
import abc from typing import Callable import omni.ui as ui from omni.kit.viewport.menubar.core import ViewportMenuDelegate class SingleRenderMenuItemBase(ui.MenuItem): """ A single menu item represent a single camera in the camera list """ def __init__( self, display_name: str, engine_name, hd_engine_renderer, hd_renderer, viewport_api, enabled: bool, checked: bool, hide_on_click: bool, triggered_fn: Callable, ): self.__viewport_api = viewport_api self.__engine_name = engine_name self.__hd_engine_renderer = hd_engine_renderer self.__hd_renderer = hd_renderer self.__options_button = None super().__init__( display_name, enabled=enabled, checkable=True, checked=checked, delegate=ViewportMenuDelegate( force_checked=False, build_custom_widgets=lambda delegate, item: self._build_menuitem_widgets(), ), hide_on_click=hide_on_click, triggered_fn=triggered_fn ) def destroy(self): self.__options_button = None super().destroy() @property def hd_renderer(self): return self.__hd_renderer @property def hd_engine_renderer(self): return self.__hd_engine_renderer @property def engine_name(self): return self.__engine_name @property def viewport_api(self): return self.__viewport_api def _build_menuitem_widgets(self): ui.Spacer(width=10) with ui.VStack(content_clipping=1, width=0): # Button to show renderer settings self.__options_button = ui.Button( style_type_name_override="Menu.Item.Button", name="OptionBox", width=16, height=16, image_width=16, image_height=16, visible=self.checked, clicked_fn=self._option_clicked, ) @abc.abstractmethod def _option_clicked(self): """Function to implement when the option is clicked. Used by RTX Remix""" pass def set_checked(self, checked: bool) -> None: self.checked = checked self.delegate.checked = checked # Only show options button when it is current camera self.__options_button.visible = checked class SingleRenderMenuItem(SingleRenderMenuItemBase): """ A single menu item represent a single camera in the camera list """ def _option_clicked(self): try: from omni.rtx.window.settings import RendererSettingsFactory rs_instance = RendererSettingsFactory.render_settings_extension_instance if rs_instance: rs_instance.show_render_settings(self.engine_name, self.hd_renderer.pluginID, True) except ImportError: pass
2,988
Python
27.740384
99
0.587349
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/tests/test_api.py
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ['TestAPI'] import omni.kit.test import functools from omni.kit.test import AsyncTestCase from unittest.mock import patch, call from omni.kit.viewport.menubar.render import get_instance as _get_menubar_extension from omni.kit.viewport.menubar.render import SingleRenderMenuItem as _SingleRenderMenuItem from omni.kit.viewport.menubar.render import SingleRenderMenuItemBase as _SingleRenderMenuItemBase from omni.kit.viewport.menubar.render.renderer_menu_container import RendererMenuContainer as _RendererMenuContainer class TestAPI(AsyncTestCase): async def test_get_instance(self): extension = _get_menubar_extension() self.assertIsNotNone(extension) async def test_register_custom_menu_item_type(self): def _single_render_menu_item(*args, **kwargs): class SingleRenderMenuItem(_SingleRenderMenuItemBase): pass return SingleRenderMenuItem(*args, **kwargs) extension = _get_menubar_extension() try: with patch.object(_RendererMenuContainer, "set_menu_item_type") as set_menu_item_type_mock: fn = functools.partial(_single_render_menu_item) extension.register_menu_item_type( fn ) self.assertEqual(1, set_menu_item_type_mock.call_count) self.assertEqual(call(fn), set_menu_item_type_mock.call_args) finally: extension.register_menu_item_type(None) async def test_register_regular_menu_item_type(self): def _single_render_menu_item(*args, **kwargs): return _SingleRenderMenuItem(*args, **kwargs) extension = _get_menubar_extension() try: with patch.object(_RendererMenuContainer, "set_menu_item_type") as set_menu_item_type_mock: fn = functools.partial(_single_render_menu_item) extension.register_menu_item_type( fn ) self.assertEqual(1, set_menu_item_type_mock.call_count) self.assertEqual(call(fn), set_menu_item_type_mock.call_args) finally: extension.register_menu_item_type(None)
2,635
Python
40.187499
116
0.677799
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/tests/__init__.py
from .test_api import * from .test_ui import *
47
Python
14.999995
23
0.702128
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/tests/test_ui.py
import omni.kit.test from re import I from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.window import ViewportWindow import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 import omni.usd import omni.kit.app from pathlib import Path import carb.input import functools from omni.kit.viewport.menubar.render import get_instance as _get_menubar_extension from omni.kit.viewport.menubar.render import SingleRenderMenuItemBase as _SingleRenderMenuItemBase CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 400 class TestSettingMenuWindow(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) self._vw = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) self._viewport_api = self._vw.viewport_api await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): self._vw.destroy() del self._vw await super().tearDown() async def __show_render_menu(self, mouse_pos: Vec2 = None): # Enable mouse input app_window = omni.appwindow.get_default_app_window() for device in [carb.input.DeviceType.MOUSE]: app_window.set_input_blocking_state(device, None) await ui_test.emulate_mouse_move(mouse_pos if mouse_pos else Vec2(40, 40)) await ui_test.emulate_mouse_click() await omni.kit.app.get_app().next_update_async() async def __close_render_menu(self): await ui_test.emulate_mouse_move(Vec2(TEST_WIDTH, TEST_HEIGHT)) await ui_test.emulate_mouse_click() await self.wait_n_updates() async def test_render_menu_with_custom_type(self): """Test custom options area item. (This likely breaks order independent testing)""" menu_option_clicked = 0 def _single_render_menu_item(*args, **kwargs): class SingleRenderMenuItem(_SingleRenderMenuItemBase): def _option_clicked(self): nonlocal menu_option_clicked menu_option_clicked += 1 return SingleRenderMenuItem(*args, **kwargs) extension = _get_menubar_extension() self.assertIsNotNone(extension) try: await self.__show_render_menu() self.assertEqual(0, menu_option_clicked) # Simluate a click in options-area, but do it on Storm; not RTX await self.__show_render_menu(Vec2(205, 135)) self.assertEqual(0, menu_option_clicked) extension.register_menu_item_type( functools.partial(_single_render_menu_item) ) await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates() self.assertEqual(1, menu_option_clicked) finally: extension.register_menu_item_type(None) await self.__close_render_menu() await self.finalize_test_no_image() async def test_auto_manage_renderer_list(self): """Test auto management of the renderer menu based on extension load. (This likely breaks order independent testing)""" settings = carb.settings.get_settings() restore_value = settings.get("/renderer/enabled") try: async def change_available_renderers(golden_img_name: str, renderers: str = None): # Close the menu to avoid issues with golden images as menu shrink is animated over time if renderers: settings.set("/renderer/enabled", renderers) await self.__show_render_menu() await self.capture_and_compare( golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name ) await self.__close_render_menu() await change_available_renderers("menubar_default_list_0.png") # Disable everything but RTX await change_available_renderers("menubar_rtx_only.png", "rtx") # Disable everything but Iray and Storm await change_available_renderers("menubar_pxr_iray_only.png", "pxr,iray") # Enable omni.hydra.index extension (Note it will enable RTX as well due to dependencies) omni.kit.app.get_app().get_extension_manager().set_extension_enabled_immediate("omni.hydra.index", True) await change_available_renderers("menubar_all_shipping.png") # Disbale omni.hydra.index extension, and list should be back to menubar_default_list omni.kit.app.get_app().get_extension_manager().set_extension_enabled_immediate("omni.hydra.index", False) await change_available_renderers("menubar_default_list_1.png") finally: settings.set("/renderer/enabled", restore_value if restore_value else "") await self.__close_render_menu() await self.finalize_test_no_image()
5,203
Python
39.976378
127
0.647703
omniverse-code/kit/exts/omni.kit.widget.stage/config/extension.toml
[package] title = "Stage Widget" description = "Stage Widget" version = "2.7.24" category = "Internal" authors = ["NVIDIA"] repository = "" keywords = ["stage", "outliner", "scene"] changelog = "docs/CHANGELOG.md" [dependencies] "omni.activity.core" = {} "omni.kit.context_menu" = {} "omni.ui" = {} "omni.usd" = {} "omni.kit.usd.layers" = {} "omni.usd.schema.physics" = {} "omni.usd.schema.anim" = {} "omni.kit.window.file_exporter" = {} "omni.client" = {} [[python.module]] name = "omni.kit.widget.stage" # Settings. They are applied on the root of global settings. In case of conflict original settings are kept. [settings] persistent.exts."omni.kit.widget.stage".showColumnVisibility = true persistent.exts."omni.kit.widget.stage".showColumnType = true [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/persistent/app/stage/dragDropImport='reference'", "--/persistent/material/stage/dragDropMaterialPath='absolute'", "--/persistent/app/omniverse/filepicker/options_menu/show_details=false", "--no-window" ] dependencies = [ "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.widget.stage", "omni.kit.window.content_browser", "omni.kit.property.material", "omni.kit.window.stage", "omni.kit.ui_test", "omni.kit.test_suite.helpers", "omni.hydra.pxr", "omni.kit.window.viewport", ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop "*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available ] # RTX regression OM-51983 timeout = 600
1,992
TOML
28.746268
122
0.684739
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["StageWidgetExtension"] import omni.ext from .stage_column_delegate_registry import StageColumnDelegateRegistry from .visibility_column_delegate import VisibilityColumnDelegate from .type_column_delegate import TypeColumnDelegate from .delegates import NameColumnDelegate from .stage_actions import register_actions, deregister_actions from .export_utils import _get_stage_open_sub from .stage_style import Styles as StageStyles class StageWidgetExtension(omni.ext.IExt): """The entry point for Stage Window""" def on_startup(self, ext_id): # Register column delegates self._name_column_sub = StageColumnDelegateRegistry().register_column_delegate("Name", NameColumnDelegate) self._type_column_sub = StageColumnDelegateRegistry().register_column_delegate("Type", TypeColumnDelegate) self._visibility_column_sub = StageColumnDelegateRegistry().register_column_delegate("Visibility", VisibilityColumnDelegate) self._ext_name = omni.ext.get_extension_name(ext_id) StageStyles.on_startup() self._registered_hotkeys = [] register_actions(self._ext_name, self) self._stage_open_sub = _get_stage_open_sub() def on_shutdown(self): self._name_column_sub = None self._visibility_column_sub = None self._type_column_sub = None deregister_actions(self._ext_name, self) self._stage_open_sub = None
1,860
Python
42.279069
132
0.746237
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/column_menu.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 .event import Event from .event import EventSubscription from .stage_column_delegate_registry import StageColumnDelegateRegistry from typing import Callable from typing import List from typing import Optional from typing import Tuple from .stage_icons import StageIcons as Icons import omni.ui as ui import weakref class ColumnMenuDelegate(ui.AbstractItemDelegate): """ Delegate is the representation layer. TreeView calls the methods of the delegate to create custom widgets for each item. """ MENU_STYLES = { "Menu.CheckBox": {"background_color": 0x0, "margin": 0}, "Menu.CheckBox::drag": { "image_url": Icons().get("drag"), "color": 0xFF505050, "alignment": ui.Alignment.CENTER, }, "Menu.CheckBox.Image": {"image_url": Icons().get("check_off"), "color": 0xFF8A8777}, "Menu.CheckBox.Image:checked": {"image_url": Icons().get("check_on"), "color": 0x34C7FFFF}, } def __init__(self): super().__init__() def destroy(self): pass def build_header(self, column_id): pass def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" pass def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" with ui.HStack(height=0, style=ColumnMenuDelegate.MENU_STYLES): ui.ToolButton( item.checked_model, style_type_name_override="Menu.CheckBox", width=18, height=18, image_width=18, image_height=18, ) ui.Label(item.name_model.as_string) ui.Image(style_type_name_override="Menu.CheckBox", name="drag", width=10) class ColumnMenuItem(ui.AbstractItem): """Single item of the model""" def __init__(self, model, text, checked): super().__init__() self.name_model = ui.SimpleStringModel(text) self.checked_model = ui.SimpleBoolModel(checked) self.checked_model.add_value_changed_fn(self._on_checked_changed) self.__weak_model = weakref.ref(model) def _on_checked_changed(self, model): model = self.__weak_model() if model: model._item_changed(self) model._on_column_checked_changed([i[0] for i in model.get_columns()]) def __repr__(self): return f'"{self.name_model.as_string}"' class ColumnMenuModel(ui.AbstractItemModel): """ Represents the model for available columns. """ def __init__(self, enabled: Optional[List[str]] = None, accepted: Optional[List[str]] = None): super().__init__() self._column_delegate_sub = StageColumnDelegateRegistry().subscribe_delegate_changed( self._on_column_delegate_changed ) self._accepted = accepted if enabled is None: self._children = [] else: self._children = [ ColumnMenuItem(self, name, True) for name in enabled if not self._accepted or name in self._accepted ] self._on_column_delegate_changed(enabled is None) self._on_column_checked_changed = Event() def destroy(self): self._column_delegate_sub = None self._children = None def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model def get_drag_mime_data(self, item): """Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere""" # As we don't do Drag and Drop to the operating system, we return the string. return item.name_model.as_string def drop_accepted(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called to highlight target when drag and drop.""" # If target_item is None, it's the drop to root. Since it's # list model, we support reorganizetion of root only and we # don't want to create tree. return not target_item and drop_location >= 0 def drop(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called when dropping something to the item.""" try: source_id = self._children.index(source) except ValueError: try: current_names = [c.name_model.as_string for c in self._children] source_id = current_names.index(source) source = self._children[source_id] except ValueError: # Not in the list. This is the source from another model. return if source_id == drop_location: # Nothing to do return self._children.pop(source_id) if drop_location > len(self._children): # Drop it to the end self._children.append(source) else: if source_id < drop_location: # Becase when we removed source, the array became shorter drop_location = drop_location - 1 self._children.insert(drop_location, source) self._item_changed(None) def get_columns(self) -> List[Tuple[str, bool]]: """ Return all the columns in the format `[("Visibility", True), ("Type", False)]` The first item is the column name, and the second item is a flag that is True if the column is enabled. """ current_names = [c.name_model.as_string for c in self._children] current_checked = [c.checked_model.as_bool for c in self._children] return list(zip(current_names, current_checked)) def subscribe_delegate_changed(self, fn: Callable[[List[str]], None]) -> EventSubscription: """ Return the object that will automatically unsubscribe when destroyed. """ return EventSubscription(self._on_column_checked_changed, fn) def _on_column_delegate_changed(self, enabled=False): """Called by StageColumnDelegateRegistry""" current_names = [c.name_model.as_string for c in self._children] column_delegate_names = StageColumnDelegateRegistry().get_column_delegate_names() # Exclude "Name" as it's enabled always. if "Name" in column_delegate_names: column_delegate_names.remove("Name") # Filter columns. We only need the columns that is in self._accepted list. if self._accepted: column_delegate_names = [name for name in column_delegate_names if name in self._accepted] # Form the new list keeping the order of the old columns new_names = [] for name in current_names: if name in column_delegate_names: new_names.append(name) # Put the new columns to the end of the list unused_names = [name for name in column_delegate_names if name not in new_names] new_names += unused_names if current_names == new_names: # Nothing changed return # Create item for new columns and reuse the items for old columns new_children = [] for name in new_names: if name in current_names: i = current_names.index(name) new_children.append(self._children[i]) else: new_children.append(ColumnMenuItem(self, name, enabled)) # Replace children self._children = new_children self._item_changed(None)
8,582
Python
34.912134
116
0.61629
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/abstract_stage_column_delegate.py
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["AbstractStageColumnDelegate", "StageColumnItem"] from pxr import Sdf, Usd from typing import List from .stage_item import StageItem import abc import omni.ui as ui class StageColumnItem: # pragma: no cover """ It's not clear which data we need to pass to build_widget. It's path, but there are potentially other information the column has. To keep API unchanged over the time, we pass data in a struct. It also allow to pass custom data with deriving from this class. """ def __init__(self, path: Sdf.Path, stage: Usd.Stage, enabled: bool, expanded: bool = True): """ ## Arguments `path`: Full path to the item `stage`: USD Stage `enabled`: When false, the widget should be grayed out """ self._path = path self._stage = stage self._enabled = enabled self._expanded = expanded @property def path(self): return self._path @property def stage(self): return self._stage @property def enabled(self): return self._enabled @property def expanded(self): return self._expanded class AbstractStageColumnDelegate(metaclass=abc.ABCMeta): # pragma: no cover """ An abstract object that is used to put the widget to the file browser asynchronously. """ def destroy(self): """Place to release resources.""" pass @property def initial_width(self): """The initial width of the column.""" return ui.Fraction(1) @property def minimum_width(self): return ui.Pixel(10) def build_header(self, **kwargs): """ Build the header widget. If the column is sortable, stage widget will help to build a background rectangle that has hover state to tell user if the column is sortable so all columns don't need to build that by themself. You can override this function to build customized widgets as column header. """ pass @abc.abstractmethod async def build_widget(self, item: StageColumnItem, **kwargs): """ Build the widget for the given path. Works inside Frame in async mode. Once the widget is created, it will replace the content of the frame. It allow to await something for a while and create the widget when the result is available. Args: item (StageColumnItem): DEPRECATED. It includes the non-cached simple prim information. It's better to use keyword argument `stage_item` instead, which provides cached rich information about the prim influened by this column. Keyword Arguments: stage_model (StageModel): The instance of current StageModel. stage_item (StageItem): The current StageItem to build. It's possible that stage_item is None when TreeView enabled display of root node. """ pass def on_header_hovered(self, hovered: bool): """Callback when header area is hovered.""" pass def on_stage_items_destroyed(self, items: List[StageItem]): """ Called when stage items are destroyed to give opportunity to delegate to release corresponding resources. """ pass @property def sortable(self): """ Whether this column is sortable or not. When it's True, stage widget will build header widget with hover and selection state to tell user it's sortable. This is only used to instruct user that this column is sortable from UX. """ return False @property def order(self): """ The order to sort columns. The columns are sorted in ascending order from left to right of the stage widget. So the smaller the order is, the closer the column is to the left of the stage widget. """ return 0
4,398
Python
30.647482
116
0.649613
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_delegate.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["StageDelegate"] from .abstract_stage_column_delegate import AbstractStageColumnDelegate from .abstract_stage_column_delegate import StageColumnItem from .delegates import NameColumnDelegate from .context_menu import ContextMenu from .stage_icons import StageIcons from .stage_model import StageItem from typing import List from functools import partial import asyncio import inspect import weakref import omni.ui as ui class AwaitWithFrame: """ A future-like object that runs the given future and makes sure it's always in the given frame's scope. It allows creating widgets asynchronously. """ def __init__(self, frame: ui.Frame, future: asyncio.Future): self._frame = frame self._future = future def __await__(self): # create an iterator object from that iterable iter_obj = iter(self._future.__await__()) # infinite loop while True: try: with self._frame: yield next(iter_obj) except StopIteration: break self._frame = None self._future = None class ContextMenuEvent: """The object comatible with ContextMenu""" def __init__(self, stage: "pxr.Usd.Stage", path_string, expanded=None): self.type = 0 self.payload = {"stage": stage, "prim_path": path_string, "node_open": expanded} class ContextMenuHandler: """The object that the ContextMenu calls to expand the item""" def __init__(self): self._expand_fn = None self._collapse_fn = None @property def expand_fn(self): return self._expand_fn @expand_fn.setter def expand_fn(self, value): self._expand_fn = value @property def collapse_fn(self): return self._collapse_fn @collapse_fn.setter def collapse_fn(self, value): self._collapse_fn = value def _expand(self, path): if self._expand_fn: self._expand_fn(path) def _collapse(self, path): if self._collapse_fn: self._collapse_fn(path) def context_menu_handler(self, cmd, prim_path): if cmd == "opentree": self._expand(prim_path) elif cmd == "closetree": self._collapse(prim_path) class StageDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._context_menu = ContextMenu() self._context_menu._stage_win = ContextMenuHandler() self._column_delegates: List[AbstractStageColumnDelegate] = [] self._header_layout = None self._header_layout_is_hovered = False self._mouse_pressed_task = None self._on_stage_items_destroyed_sub = None self._name_column_delegate = None @property def model(self): return self._stage_model @model.setter def model(self, value): if self._on_stage_items_destroyed_sub: self._on_stage_items_destroyed_sub.destroy() self._on_stage_items_destroyed_sub = None self._stage_model = value if self._stage_model: self._on_stage_items_destroyed_sub = self._stage_model.subscribe_stage_items_destroyed( self.__on_stage_items_destroyed ) def __on_stage_items_destroyed(self, items: List[StageItem]): for delegate in self._column_delegates: delegate.on_stage_items_destroyed(items) @property def expand_fn(self): return self._context_menu._stage_win.expand_fn @expand_fn.setter def expand_fn(self, value): self._context_menu._stage_win.expand_fn = value @property def collapse_fn(self): return self._context_menu._stage_win.collapse_fn @collapse_fn.setter def collapse_fn(self, value): self._context_menu._stage_win.collapse_fn = value def destroy(self): if self._on_stage_items_destroyed_sub: self._on_stage_items_destroyed_sub.destroy() self._on_stage_items_destroyed_sub = None self._stage_model = None self._context_menu.function_list.pop("rename_item", None) self._context_menu.destroy() self._context_menu = None self._name_column_delegate = None for d in self._column_delegates: d.destroy() self._column_delegates = [] if self._header_layout: self._header_layout.set_mouse_hovered_fn(None) self._header_layout = None if self._mouse_pressed_task: self._mouse_pressed_task.cancel() self._mouse_pressed_task = None def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" if column_id == 0: with ui.HStack(width=20 * (level + 1), height=0): ui.Spacer() if model.can_item_have_children(item): # Draw the +/- icon image_name = "Minus" if expanded else "Plus" ui.Image( StageIcons().get(image_name), width=10, height=10, style_type_name_override="TreeView.Item" ) ui.Spacer(width=5) def on_mouse_pressed(self, button, stage: "pxr.Usd.Stage", item, expanded): """Called when the user press the mouse button on the item""" if button != 1: return async def show_context_menu(stage: "pxr.Usd.Stage", item, expanded): import omni.kit.app await omni.kit.app.get_app().next_update_async() # menu is for context menu only but don't check in on_mouse_pressed func as it can be out of date # check layout_is_hovered here to make sure its updated for current mouse position if self._header_layout_is_hovered: return # Form the event path = item.path if item else None event = ContextMenuEvent(stage, path, expanded) # Show the menu self._context_menu.on_mouse_event(event) self._mouse_pressed_task = None # this function can get called multiple times sometimes with different item values if self._mouse_pressed_task: self._mouse_pressed_task.cancel() self._mouse_pressed_task = None self._mouse_pressed_task = asyncio.ensure_future(show_context_menu(stage, item, expanded)) def build_widget(self, model, item, column_id, level, expanded): """Create a widget per item""" if column_id >= len(self._column_delegates): return if item: column_item = StageColumnItem(item.path, model.stage, not item.instance_proxy, expanded) else: column_item = None stage = model.stage frame = ui.Frame(mouse_pressed_fn=lambda x, y, b, _: self.on_mouse_pressed(b, stage, item, expanded)) # Name column needs special treatment to build frame synchronously so all items will not be built # in the same line. if self._name_column_delegate and self._name_column_delegate == self._column_delegates[column_id]: with frame: self._name_column_delegate.build_widget_sync(column_item, stage_item=item, stage_model=model) else: # This is for back compatibility of old interface. build_widget_func = self._column_delegates[column_id].build_widget argspec = inspect.getfullargspec(build_widget_func) if not argspec.varkw: future = build_widget_func(column_item) else: future = build_widget_func(column_item, stage_item=item, stage_model=model) asyncio.ensure_future(AwaitWithFrame(frame, future)) def __on_header_hovered(self, hovered): self._header_layout_is_hovered = hovered def build_header(self, column_id): if column_id >= len(self._column_delegates): return self._header_layout = ui.ZStack() self._header_layout.set_mouse_hovered_fn(self.__on_header_hovered) with self._header_layout: column_delegate = self._column_delegates[column_id] if column_delegate.sortable: def on_drop_down_hovered(weakref_delegate, hovered): if not weakref_delegate(): return weakref_delegate().on_header_hovered(hovered) hovered_area = ui.Rectangle(name="hovering", style_type_name_override="TreeView.Header") weakref_delegate = weakref.ref(column_delegate) hovered_area.set_mouse_hovered_fn(partial(on_drop_down_hovered, weakref_delegate)) build_header_func = column_delegate.build_header argspec = inspect.getfullargspec(build_header_func) # This is for back compatibility of old interface. if not argspec.varkw: build_header_func() else: build_header_func(stage_model=self.model) def set_highlighting(self, enable: bool = None, text: str = None): """ Specify if the widgets should consider highlighting. Also set the text that should be highlighted in flat mode. """ if self._name_column_delegate: self._name_column_delegate.set_highlighting(enable, text) def set_column_delegates(self, delegates): """Add custom columns""" self._name_column_delegate = None for d in self._column_delegates: d.destroy() self._column_delegates = delegates self._context_menu.function_list.pop("rename_item", None) def rename_item(prim_path): if not self.model: return item = self.model.find(prim_path) if not item: return self._name_column_delegate.rename_item(item) for delegate in delegates: if isinstance(delegate, NameColumnDelegate): self._name_column_delegate = delegate self._context_menu.function_list["rename_item"] = rename_item break def get_name_column_delegate(self): return self._name_column_delegate
10,721
Python
34.269737
119
0.611603
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/event.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # class Event(list): """ A list of callable objects. Calling an instance of this will cause a call to each item in the list in ascending order by index. """ def __call__(self, *args, **kwargs): """Called when the instance is “called” as a function""" # Call all the saved functions for f in self: f(*args, **kwargs) def __repr__(self): """ Called by the repr() built-in function to compute the “official” string representation of an object. """ return f"Event({list.__repr__(self)})" class EventSubscription: """ Event subscription. Event has callback while this object exists. """ def __init__(self, event, fn): """ Save the function, the event, and add the function to the event. """ self._fn = fn self._event = event event.append(self._fn) def destroy(self): if self._fn in self._event: self._event.remove(self._fn) def __del__(self): """Called by GC.""" self.destroy()
1,526
Python
27.81132
76
0.625164
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_style.py
import omni.ui as ui class Styles: ITEM_DARK = None ITEM_GRAY = None ITEM_HOVER = None ITEM_SEL = None ITEM_BG_SEL = None ICON_DARK = None STAGE_WIDGET = None @staticmethod def on_startup(): from .stage_icons import StageIcons as Icons # List Items Styles.ITEM_DARK = 0x7723211F Styles.ITEM_GRAY = 0xFF8A8777 Styles.ITEM_HOVER = 0xFFBBBAAA Styles.ITEM_SEL = 0xFFDDDCCC Styles.ITEM_BG_SEL = 0x66888777 Styles.LIVE_GREEN = 0xFF00B86B Styles.LIVE_SEL = 0xFF00F86E Styles.RELOAD_ORANGE = 0xFF0088CC Styles.RELOAD_SEL = 0xFF00AAFF Styles.STAGE_WIDGET = { "Button.Image::filter": {"image_url": Icons().get("filter"), "color": 0xFF8A8777}, "Button.Image::options": {"image_url": Icons().get("options"), "color": 0xFF8A8777}, "Button.Image::visibility": {"image_url": Icons().get("eye_on"), "color": 0xFF8A8777}, "Button.Image::visibility:checked": {"image_url": Icons().get("eye_off"), "color": 0x88DDDCCC}, "Button.Image::visibility:disabled": {"color": 0x608A8777}, "Button.Image::visibility:selected": {"color": 0xFFCCCCCC}, "Button::filter": {"background_color": 0x0, "margin": 0}, "Button::options": {"background_color": 0x0, "margin": 0}, "Button::visibility": {"background_color": 0x0, "margin": 0, "margin_width": 1}, "Button::visibility:checked": {"background_color": 0x0}, "Button::visibility:hovered": {"background_color": 0x0}, "Button::visibility:pressed": {"background_color": 0x0}, "Label::search": {"color": 0xFF808080, "margin_width": 4}, "Menu.CheckBox": {"background_color": 0x0, "margin": 0}, "Menu.CheckBox::drag": { "image_url": Icons().get("drag"), "color": 0xFF505050, "alignment": ui.Alignment.CENTER, }, "Menu.CheckBox.Image": {"image_url": Icons().get("check_off"), "color": 0xFF8A8777}, "Menu.CheckBox.Image:checked": {"image_url": Icons().get("check_on"), "color": 0x34C7FFFF}, "TreeView": { "background_color": 0xFF23211F, "background_selected_color": 0x664F4D43, "secondary_color": 0xFF403B3B, "border_width": 1.5, }, "TreeView.ScrollingFrame": {"background_color": 0xFF23211F}, "TreeView.Image::object_icon_grey": {"color": 0x80FFFFFF}, "TreeView.Image:disabled": {"color": 0x60FFFFFF}, "TreeView.Item": {"color": Styles.ITEM_GRAY}, "TreeView.Item:disabled": {"color": 0x608A8777}, "TreeView.Item::object_name_grey": {"color": 0xFF4D4B42}, "TreeView.Item::object_name_missing": {"color": 0xFF6F72FF}, "TreeView.Item::object_name_missing:hovered": {"color": 0xFF6F72FF}, "TreeView.Item::object_name_missing:selected": {"color": 0xFF6F72FF}, "TreeView.Item:hovered": {"color": Styles.ITEM_HOVER}, "TreeView.Item:selected": {"color": Styles.ITEM_SEL}, "TreeView.Item.Outdated": {"color": Styles.RELOAD_ORANGE}, "TreeView.Item.Outdated:hovered": {"color": Styles.RELOAD_SEL}, "TreeView.Item.Outdated:selected": {"color": Styles.RELOAD_SEL}, "TreeView.Item.Live": {"color": Styles.LIVE_GREEN}, "TreeView.Item.Live:hovered": {"color": Styles.LIVE_SEL}, "TreeView.Item.Live:selected": {"color": Styles.LIVE_SEL}, "TreeView:selected": {"background_color": Styles.ITEM_BG_SEL}, "TreeView:drop": { "background_color": ui.color.shade(ui.color("#34C7FF3B")), "background_selected_color": ui.color.shade(ui.color("#34C7FF3B")), "border_color": ui.color.shade(ui.color("#2B87AA")), }, # Top of the column section (that has sorting options) "TreeView.Header": {"background_color": 0xFF343432, "color": 0xFFCCCCCC, "font_size": 12}, "TreeView.Header::visibility_header": {"image_url": Icons().get("eye_header"), "color": 0xFF888888}, "TreeView.Header::drop_down_background": {"background_color": 0xE0808080}, "TreeView.Header::drop_down_button": {"background_color": ui.color.white}, "TreeView.Header::drop_down_hovered_area": {"background_color": ui.color.transparent}, "TreeView.Header::hovering": {"background_color": 0x0, "border_radius": 1.5}, "TreeView.Header::hovering:hovered": { "background_color": ui.color.shade(ui.color("#34C7FF3B")), "border_width": 1.5, "border_color": ui.color.shade(ui.color("#2B87AA")) } }
4,877
Python
50.347368
112
0.573098
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/selection_watch.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["DefaultSelectionWatch"] from pxr import Sdf, Trace import omni.usd from typing import Optional class DefaultSelectionWatch(object): """ The object that update selection in TreeView when the scene selection is changed and updated scene selection when TreeView selection is changed. """ def __init__(self, tree_view=None, usd_context=None): self._usd_context = usd_context or omni.usd.get_context() self._selection = None self._in_selection = False self._tree_view = None self._selection = self._usd_context.get_selection() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="Stage Window Selection Update" ) self.set_tree_view(tree_view) self.__filter_string: Optional[str] = None # When True, SelectionWatch should consider filtering self.__filter_checking: bool = False def destroy(self): self._usd_context = None self._selection = None self._stage_event_sub = None self._events = None if self._tree_view: self._tree_view.set_selection_changed_fn(None) self._tree_view = None def set_tree_view(self, tree_view): """Replace TreeView that should show the selection""" if self._tree_view != tree_view: if self._tree_view: self._tree_view.set_selection_changed_fn(None) self._tree_view = tree_view self._tree_view.set_selection_changed_fn(self._on_widget_selection_changed) self._last_selected_prim_paths = None self._on_kit_selection_changed() def set_filtering(self, filter_string: Optional[str]): if filter_string: self.__filter_string = filter_string.lower() else: self.__filter_string = filter_string def enable_filtering_checking(self, enable: bool): """ When `enable` is True, SelectionWatch should consider filtering when changing Kit's selection. """ self.__filter_checking = enable def _on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_kit_selection_changed() @Trace.TraceFunction def _on_kit_selection_changed(self): """Send the selection from Kit to TreeView""" if not self._tree_view or self._in_selection: return # Make sure it's a new selection. It happens that omni.usd sends the same selection twice. No sorting because # the order of selection is important. prim_paths = self._selection.get_selected_prim_paths() if prim_paths == self._last_selected_prim_paths: return self._last_selected_prim_paths = [Sdf.Path(prim_path) for prim_path in prim_paths] # Pump the changes to the model because to select something, TreeView should be updated. self._tree_view.model.update_dirty() selection = [] for path in prim_paths: # Get the selected item and its parents. Expand all the parents of the new selection. full_chain = self._tree_view.model.find_full_chain(path) # When the new object is created, omni.usd sends the selection is changed before the object appears in the # stage and it means we can't select it. In this way it's better to return because we don't have the item # in the model yet. # TODO: Use UsdNotice to track if the object is created. if not full_chain or full_chain[-1].path != path: continue if full_chain: for item in full_chain[:-1]: self._tree_view.set_expanded(item, True, False) # Save the last item in the chain. It's the selected item selection.append(full_chain[-1]) # Send all of this to TreeView. self._in_selection = True self._tree_view.selection = selection self._in_selection = False @Trace.TraceFunction def _on_widget_selection_changed(self, selection): """Send the selection from TreeView to Kit""" if self._in_selection: return prim_paths = [item.path for item in selection if item] # Filter selection if self.__filter_string or self.__filter_checking: # Check if the selected prims are filtered and re-select filtered items only if necessary. filtered_paths = [item.path for item in selection if item and item.filtered] if filtered_paths != prim_paths: filtered_selection = [item for item in selection if item and item.path in filtered_paths] self._tree_view.selection = filtered_selection return if prim_paths == self._last_selected_prim_paths: return # Send the selection to Kit self._in_selection = True old_paths = [sdf_path.pathString for sdf_path in self._last_selected_prim_paths] new_paths = [sdf_path.pathString for sdf_path in prim_paths] omni.kit.commands.execute("SelectPrims", old_selected_paths=old_paths, new_selected_paths=new_paths, expand_in_stage=True) self._in_selection = False self._last_selected_prim_paths = prim_paths
5,914
Python
40.654929
130
0.636287
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/commands.py
__all__ = ["ReorderPrimCommand"] import carb import omni.kit.commands import omni.usd from pxr import Usd, Sdf class ReorderPrimCommand(omni.kit.commands.Command): """ Command to reorder prim in its parent. This command uses the support from USD to override the reorder property, and it will always be authored into the root layer without considering the edit target. """ def __init__(self, stage: Usd.Stage, prim_path: Sdf.Path, move_to_location: int): """ Constructor. Args: stage (Usd.Stage): USD stage. prim_path (Sdf.Path): Prim to reorder. move_to_location (int): Move to the location in its parent. If it's -1, it means to move the prim to the bottom. """ self.__stage = stage self.__prim_path = Sdf.Path(prim_path) self.__move_to_location = move_to_location self.__old_location = -1 self.__success = False def __move_to(self, location): if self.__prim_path == Sdf.Path.emptyPath or self.__prim_path == Sdf.Path.absoluteRootPath: carb.log_warn("Failed to reorder prim as empty path or absolute root path is not supported.") return False prim = self.__stage.GetPrimAtPath(self.__prim_path) if not prim: carb.log_error(f"Failed to reorder prim {self.__prim_path} as prim is not found in the stage.") return False parent_path = self.__prim_path.GetParentPath() parent_prim = self.__stage.GetPrimAtPath(parent_path) if not parent_prim: return all_children = parent_prim.GetAllChildrenNames() total_children = len(all_children) name = self.__prim_path.name if name in all_children: index = all_children.index(name) self.__old_location = index all_children.remove(name) else: index = -1 if index == location: return if location < 0 or location > total_children: location = -1 elif location > index and index != -1: # If it's to move from up to down. location -= 1 all_children.insert(location, name) # Use Sdf API so it can be batched. parent_prim_spec = Sdf.CreatePrimInLayer(self.__stage.GetRootLayer(), parent_path) parent_prim_spec.nameChildrenOrder = all_children self.__success = True return True def do(self): with Usd.EditContext(self.__stage, self.__stage.GetRootLayer()): return self.__move_to(self.__move_to_location) def undo(self): if self.__success: with Usd.EditContext(self.__stage, self.__stage.GetRootLayer()): self.__move_to(self.__old_location) self.__success = False
2,855
Python
32.209302
107
0.592294
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_icons.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["StageIcons"] import omni.kit.app from .singleton import Singleton from pathlib import Path from typing import Union ICON_FOLDER_PATH = Path( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/icons" ) @Singleton class StageIcons: """A singleton that scans the icon folder and returns the icon depending on the type""" class _Event(list): """ A list of callable objects. Calling an instance of this will cause a call to each item in the list in ascending order by index. """ def __call__(self, *args, **kwargs): """Called when the instance is “called” as a function""" # Call all the saved functions for f in self: f(*args, **kwargs) def __repr__(self): """ Called by the repr() built-in function to compute the “official” string representation of an object. """ return f"Event({list.__repr__(self)})" class _EventSubscription: """ Event subscription. _Event has callback while this object exists. """ def __init__(self, event, fn): """ Save the function, the event, and add the function to the event. """ self._fn = fn self._event = event event.append(self._fn) def __del__(self): """Called by GC.""" self._event.remove(self._fn) def __init__(self): self._on_icons_changed = self._Event() # Read all the svg files in the directory self._icons = {icon.stem: str(icon) for icon in ICON_FOLDER_PATH.glob("*.svg")} def set(self, prim_type: str, icon_path: Union[str, Path]): """Set the new icon path for a specific prim type""" if icon_path is None: # Remove the icon if prim_type in self._icons: del self._icons[prim_type] else: self._icons[prim_type] = str(icon_path) self._on_icons_changed() def get(self, prim_type: str, default: Union[str, Path] = None) -> str: """Checks the icon cache and returns the icon if exists""" found = self._icons.get(prim_type) if not found and default: found = self._icons.get(default) if found: return found return "" def subscribe_icons_changed(self, fn): """ Return the object that will automatically unsubscribe when destroyed. """ return self._EventSubscription(self._on_icons_changed, fn)
3,070
Python
30.336734
100
0.595765