file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/exts/omni.kit.audio.test.usd/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-03 ### Changed - Pass tests with either new or old Viewport.
omniverse-code/kit/exts/omni.kit.audio.test.usd/docs/index.rst
omni.kit.audio.test.usd ########################### .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.kit.audio.test.usd/data/tests/audio_test2.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double3 position = (0, 0, 50000) double radius = 500 } dictionary Perspective = { double3 position = (507.1186080917092, 515.1566469182885, 477.7247449900152) double3 target = (7.118608091709076, 15.156646918288269, -22.275255009984324) } dictionary Right = { double3 position = (-50000, 0, -1.1102230246251565e-11) double radius = 500 } dictionary Top = { double3 position = (-4.329780281177466e-12, 50000, 1.1102230246251565e-11) double radius = 500 } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def Listener "Listener" { double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 150) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Listener "Listener_01" { double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (-150, -0, -150) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Listener "Listener_02" { double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (150, 0, -150) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Sound "Sound" { double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } }
omniverse-code/kit/exts/omni.kit.audio.test.usd/data/tests/audio_test.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Front = { double radius = 500 double3 target = (0, 0, 0) } dictionary Perspective = { double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998) double3 target = (0, 0, 0) } dictionary Right = { double radius = 500 double3 target = (0, 0, 0) } dictionary Top = { double radius = 500 double3 target = (0, 0, 0) } string boundCamera = "/OmniverseKit_Persp" } dictionary renderSettings = { float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.009999999776482582 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def Sound "Sound" { uniform asset filePath = @test.wav@ } def Listener "Listener" { } }
omniverse-code/kit/exts/omni.graph.rtxtest/PACKAGE-LICENSES/omni.graph.rtxtest-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.graph.rtxtest/config/extension.toml
[package] version = "1.0.0" title = "OmniGraph Regression Testing For Tests Requiring RTX" category = "Graph" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" description = "Contains test scripts and files used to test the OmniGraph functionality that exercises rendering." repository = "" keywords = ["kit", "omnigraph", "tests"] # Main module for the Python interface [[python.module]] name = "omni.graph.rtxtest" [[native.plugin]] path = "bin/*.plugin" recursive = false # Python array data uses numpy as its format [python.pipapi] requirements = ["numpy"] # Other extensions that need to load in order for this one to work [dependencies] "omni.graph.nodes" = {} "omni.kit.pipapi" = {} "omni.kit.renderer.core" = {} "omni.kit.renderer.capture" = {} "omni.kit.window.viewport" = {} "omni.usd" = {} "omni.rtx.tests" = {} [[test]] timeout = 600 stdoutFailPatterns.exclude = [ # Exclude carb.events leak that only shows up locally "*[Error] [carb.events.plugin]*PooledAllocator*", # Exclude messages which say they should be ignored "*Ignore this error/warning*", ] pythonTests.unreliable = [ "*test_prerender_gpuinterop", # OM-55399 ] [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/__init__.py
"""There is no public API to this module.""" __all__ = [] from ._impl.extension import _PublicExtension # noqa: F401
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/OgnScaleAOVTextureInPlaceDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTextureInPlace Test node for the post render graph, to scale (brighten or darken) an AOV texture in place. """ import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnScaleAOVTextureInPlaceDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTextureInPlace Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.gpu inputs.height inputs.inputAOV inputs.multiplier inputs.rp inputs.width Outputs: outputs.exec outputs.gpu outputs.outputAOVPtr outputs.rp outputs.scheduleResult """ # 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, 'Trigger', {}, True, None, False, ''), ('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''), ('inputs:height', 'int', 0, None, 'The output RP height', {ogn.MetadataKeys.DEFAULT: '1080'}, True, 1080, False, ''), ('inputs:inputAOV', 'token', 0, None, 'The name of the AOV used during processing', {ogn.MetadataKeys.DEFAULT: '"LdrColor"'}, True, "LdrColor", False, ''), ('inputs:multiplier', 'float', 0, None, 'Multiplier applied on the inputAOV to obtain the output', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''), ('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''), ('inputs:width', 'int', 0, None, 'The output RP width', {ogn.MetadataKeys.DEFAULT: '1920'}, True, 1920, False, ''), ('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('outputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, None, False, ''), ('outputs:outputAOVPtr', 'uint64', 0, None, 'The output AOV cuda pointer', {}, True, None, False, ''), ('outputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, None, False, ''), ('outputs:scheduleResult', 'bool', 0, None, 'If set, the cuda task was scheduled, otherwise it was not.', {}, 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.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 gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gpu) data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def height(self): data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.height) data_view = og.AttributeValueHelper(self._attributes.height) data_view.set(value) @property def inputAOV(self): data_view = og.AttributeValueHelper(self._attributes.inputAOV) return data_view.get() @inputAOV.setter def inputAOV(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.inputAOV) data_view = og.AttributeValueHelper(self._attributes.inputAOV) data_view.set(value) @property def multiplier(self): data_view = og.AttributeValueHelper(self._attributes.multiplier) return data_view.get() @multiplier.setter def multiplier(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.multiplier) data_view = og.AttributeValueHelper(self._attributes.multiplier) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rp) data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def width(self): data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.width) data_view = og.AttributeValueHelper(self._attributes.width) 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) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def outputAOVPtr(self): data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr) return data_view.get() @outputAOVPtr.setter def outputAOVPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def scheduleResult(self): data_view = og.AttributeValueHelper(self._attributes.scheduleResult) return data_view.get() @scheduleResult.setter def scheduleResult(self, value): data_view = og.AttributeValueHelper(self._attributes.scheduleResult) 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 = OgnScaleAOVTextureInPlaceDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnScaleAOVTextureInPlaceDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnScaleAOVTextureInPlaceDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/OgnScaleAOVTextureDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTexture Helper node that tests the ComputeParams and ComputeParamsBuilder APIs in Post Render Graph nodes. """ import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnScaleAOVTextureDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTexture Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.gpu inputs.height inputs.inputAOV inputs.multiplier inputs.outputAOV inputs.rp inputs.width Outputs: outputs.exec outputs.gpu outputs.outputAOVPtr outputs.rp outputs.scheduleResult """ # 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, 'Trigger', {}, True, None, False, ''), ('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''), ('inputs:height', 'int', 0, None, 'The output RP height', {ogn.MetadataKeys.DEFAULT: '1080'}, True, 1080, False, ''), ('inputs:inputAOV', 'token', 0, None, 'The name of the AOV used during processing', {ogn.MetadataKeys.DEFAULT: '"LdrColor"'}, True, "LdrColor", False, ''), ('inputs:multiplier', 'float', 0, None, 'Multiplier applied on the inputAOV to obtain the output', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''), ('inputs:outputAOV', 'token', 0, None, 'The name of the AOV used during processing', {ogn.MetadataKeys.DEFAULT: '"scaledAOV"'}, True, "scaledAOV", False, ''), ('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''), ('inputs:width', 'int', 0, None, 'The output RP width', {ogn.MetadataKeys.DEFAULT: '1920'}, True, 1920, False, ''), ('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('outputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, None, False, ''), ('outputs:outputAOVPtr', 'uint64', 0, None, 'The output AOV cuda pointer', {}, True, None, False, ''), ('outputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, None, False, ''), ('outputs:scheduleResult', 'bool', 0, None, 'If set, the cuda task was scheduled, otherwise it was not.', {}, 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.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 gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gpu) data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def height(self): data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.height) data_view = og.AttributeValueHelper(self._attributes.height) data_view.set(value) @property def inputAOV(self): data_view = og.AttributeValueHelper(self._attributes.inputAOV) return data_view.get() @inputAOV.setter def inputAOV(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.inputAOV) data_view = og.AttributeValueHelper(self._attributes.inputAOV) data_view.set(value) @property def multiplier(self): data_view = og.AttributeValueHelper(self._attributes.multiplier) return data_view.get() @multiplier.setter def multiplier(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.multiplier) data_view = og.AttributeValueHelper(self._attributes.multiplier) data_view.set(value) @property def outputAOV(self): data_view = og.AttributeValueHelper(self._attributes.outputAOV) return data_view.get() @outputAOV.setter def outputAOV(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.outputAOV) data_view = og.AttributeValueHelper(self._attributes.outputAOV) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rp) data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def width(self): data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.width) data_view = og.AttributeValueHelper(self._attributes.width) 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) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def outputAOVPtr(self): data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr) return data_view.get() @outputAOVPtr.setter def outputAOVPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def scheduleResult(self): data_view = og.AttributeValueHelper(self._attributes.scheduleResult) return data_view.get() @scheduleResult.setter def scheduleResult(self, value): data_view = og.AttributeValueHelper(self._attributes.scheduleResult) 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 = OgnScaleAOVTextureDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnScaleAOVTextureDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnScaleAOVTextureDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/nodes/OgnScaleAOVTexture.ogn
{ "ScaleAOVTexture": { "version": 1, "description": "Helper node that tests the ComputeParams and ComputeParamsBuilder APIs in Post Render Graph nodes.", "uiName": "Test Node: Exercise the Post Render Graph scaffolding APIs", "icon": { "path": "TestNodeIcon.svg" }, "categories": "internal:test", "exclude": ["tests", "usd", "docs"], "inputs": { "gpu": { "type": "uint64", "description": "Pointer to shared context containing gpu foundations", "metadata": { "uiName": "gpuFoundations" } }, "rp": { "type": "uint64", "description": "Pointer to render product for this view", "metadata": { "uiName": "renderProduct" } }, "exec": { "type": "execution", "description": "Trigger" }, "inputAOV": { "type": "token", "description": "The name of the AOV used during processing", "default": "LdrColor" }, "outputAOV": { "type": "token", "description": "The name of the AOV used during processing", "default": "scaledAOV" }, "width": { "type": "int", "default": 1920, "description": "The output RP width" }, "height": { "type": "int", "default": 1080, "description": "The output RP height" }, "multiplier": { "type": "float", "default": 1.0, "description": "Multiplier applied on the inputAOV to obtain the output" } }, "outputs": { "gpu": { "type": "uint64", "description": "Pointer to shared context containing gpu foundations", "metadata": { "uiName": "gpuFoundations" } }, "rp": { "type": "uint64", "description": "Pointer to render product for this view", "metadata": { "uiName": "renderProduct" } }, "exec": { "type": "execution", "description": "Trigger" }, "outputAOVPtr": { "type": "uint64", "description": "The output AOV cuda pointer" }, "scheduleResult": { "type": "bool", "description": "If set, the cuda task was scheduled, otherwise it was not." } } } }
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/nodes/OgnScaleAOVTextureInPlace.ogn
{ "ScaleAOVTextureInPlace": { "version": 1, "description": "Test node for the post render graph, to scale (brighten or darken) an AOV texture in place.", "uiName": "Test Scale AOV In Place", "icon": { "path": "TestNodeIcon.svg" }, "categories": "internal:test", "exclude": ["tests", "usd", "docs"], "inputs": { "gpu": { "type": "uint64", "description": "Pointer to shared context containing gpu foundations", "metadata": { "uiName": "gpuFoundations" } }, "rp": { "type": "uint64", "description": "Pointer to render product for this view", "metadata": { "uiName": "renderProduct" } }, "exec": { "type": "execution", "description": "Trigger" }, "inputAOV": { "type": "token", "description": "The name of the AOV used during processing", "default": "LdrColor" }, "width": { "type": "int", "default": 1920, "description": "The output RP width" }, "height": { "type": "int", "default": 1080, "description": "The output RP height" }, "multiplier": { "type": "float", "default": 1.0, "description": "Multiplier applied on the inputAOV to obtain the output" } }, "outputs": { "gpu": { "type": "uint64", "description": "Pointer to shared context containing gpu foundations", "metadata": { "uiName": "gpuFoundations" } }, "rp": { "type": "uint64", "description": "Pointer to render product for this view", "metadata": { "uiName": "renderProduct" } }, "exec": { "type": "execution", "description": "Trigger" }, "outputAOVPtr": { "type": "uint64", "description": "The output AOV cuda pointer" }, "scheduleResult": { "type": "bool", "description": "If set, the cuda task was scheduled, otherwise it was not." } } } }
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/nodes/OgnScaleAOVTextureInPlace.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 <OgnScaleAOVTextureInPlaceDatabase.h> #include "OgnTestPostRenderGraphNodeCuda.h" #include <carb/cuda/CudaRuntime.h> #include <omni/graph/image/unstable/ComputeParamsBuilder.h> #include <string> namespace omni { namespace graph { namespace rtxtest { using namespace omni::graph::image::unstable; namespace { /// A wrapper around a texture object class ScopedCudaTextureObject final { cudaTextureObject_t _texObj = 0; public: ScopedCudaTextureObject(cudaMipmappedArray_t mmarr, int mipLevel = 0) { if (!mmarr) return; cudaArray_t levelArray = 0; CUDA_CHECK(cudaGetMipmappedArrayLevel(&levelArray, mmarr, mipLevel)); if (!levelArray) return; struct cudaResourceDesc resDesc; memset(&resDesc, 0, sizeof(resDesc)); resDesc.resType = cudaResourceTypeArray; resDesc.res.array.array = levelArray; struct cudaTextureDesc texDesc; memset(&texDesc, 0, sizeof(texDesc)); texDesc.addressMode[0] = cudaAddressModeClamp; texDesc.addressMode[1] = cudaAddressModeClamp; texDesc.filterMode = cudaFilterModePoint; texDesc.readMode = cudaReadModeElementType; texDesc.normalizedCoords = 1; CUDA_CHECK(cudaCreateTextureObject(&_texObj, &resDesc, &texDesc, nullptr)); } ~ScopedCudaTextureObject() { if (_texObj) { CUDA_CHECK(cudaDestroyTextureObject(_texObj)); } } operator cudaTextureObject_t&() { return _texObj; } }; /// A wrapper around a suface object class ScopedCudaSurfaceObject final { cudaSurfaceObject_t _surfObj = 0; public: ScopedCudaSurfaceObject(cudaMipmappedArray_t mmarr, int mipLevel = 0) { if (!mmarr) return; cudaArray_t levelArray = 0; CUDA_CHECK(cudaGetMipmappedArrayLevel(&levelArray, mmarr, 0)); if (!levelArray) return; struct cudaResourceDesc surfResDesc; memset(&surfResDesc, 0, sizeof(surfResDesc)); surfResDesc.resType = cudaResourceTypeArray; surfResDesc.res.array.array = levelArray; CUDA_CHECK(cudaCreateSurfaceObject(&_surfObj, &surfResDesc)); } ~ScopedCudaSurfaceObject() { if (_surfObj) { CUDA_CHECK(cudaDestroySurfaceObject(_surfObj)); } } operator cudaSurfaceObject_t&() { return _surfObj; } }; } // anonymous namespace class OgnScaleAOVTextureInPlace { public: static bool compute(OgnScaleAOVTextureInPlaceDatabase& db) { // The gpu and rp inputs are passed through to the output. // They are only present here so that the nodes GpuInteropGpuToCpuCopy and GpuInteropCpuToDisk can be connected // after the current test node, to establish the correct topological order in the graph. // An alternate way to do this is to use a dummy execution port for this purpose (this is what the SDG nodes do). // In the future, the data protocol for post render graph nodes should standardize the inputs of the nodes and // prevent the need for passing raw pointers around. db.outputs.gpu() = db.inputs.gpu(); db.outputs.rp() = db.inputs.rp(); auto gpu = reinterpret_cast<GpuFoundationsInterfaces*>(db.inputs.gpu()); auto rp = reinterpret_cast<omni::usd::hydra::HydraRenderProduct*>(db.inputs.rp()); // This node is called in tests and has to fail hard CARB_ASSERT(gpu); CARB_ASSERT(rp); auto result = ComputeParamsBuilder<std::string>{ gpu, rp, db } .addValue("multiplier", db.inputs.multiplier()) .addInputTexture("inputAOV", db.inputs.inputAOV(), [&db](cudaMipmappedArray_t cudaPtr, carb::graphics::TextureDesc const* desc, ComputeParams<std::string>& params) { // the desc pointer is guaranteed to be valid params.add("width", desc->width); params.add("height", desc->height); db.outputs.outputAOVPtr() = reinterpret_cast<uint64_t>(cudaPtr); }) .scheduleCudaTask("TestCudaTask", [](ComputeParams<std::string>* data, cudaStream_t stream) { auto multiplier = data->get<float>("multiplier"); auto inputAOV = data->get<cudaMipmappedArray_t>("inputAOV"); auto width = data->get<uint32_t>("width"); auto height = data->get<uint32_t>("height"); CARB_ASSERT(multiplier != 0.0f); CARB_ASSERT(width != 0.0f); CARB_ASSERT(height != 0.0f); ScopedCudaSurfaceObject textureData(inputAOV); cudaScaleImageInPlace(textureData, multiplier, width, height, stream); }, [](ComputeParams<std::string> const& params) -> bool { return params.hasKey("inputAOV") && params.get<cudaMipmappedArray_t>("inputAOV") != nullptr; }); db.outputs.scheduleResult() = result; return result; } }; REGISTER_OGN_NODE() } // test } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/nodes/OgnTestPostRenderGraphNodeCuda.h
// 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. // #pragma once #include <carb/cuda/CudaRuntime.h> #include <carb/cudainterop/CudaInterop.h> extern "C" void cudaScaleImage(cudaTextureObject_t inputTexture, float multiplier, uint32_t width, uint32_t height, cudaSurfaceObject_t outputTexture, cudaStream_t stream); extern "C" void cudaScaleImageInPlace(cudaSurfaceObject_t textureData, float multiplier, uint32_t width, uint32_t height, cudaStream_t stream);
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/nodes/OgnScaleAOVTexture.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 <OgnScaleAOVTextureDatabase.h> #include "OgnTestPostRenderGraphNodeCuda.h" #include <carb/cuda/CudaRuntime.h> #include <omni/graph/image/unstable/ComputeParamsBuilder.h> #include <string> namespace omni { namespace graph { namespace rtxtest { using namespace omni::graph::image::unstable; namespace { /// A wrapper around a texture object class ScopedCudaTextureObject final { cudaTextureObject_t _texObj = 0; public: ScopedCudaTextureObject(cudaMipmappedArray_t mmarr, int mipLevel = 0) { if (!mmarr) return; cudaArray_t levelArray = 0; CUDA_CHECK(cudaGetMipmappedArrayLevel(&levelArray, mmarr, mipLevel)); if (!levelArray) return; struct cudaResourceDesc resDesc; memset(&resDesc, 0, sizeof(resDesc)); resDesc.resType = cudaResourceTypeArray; resDesc.res.array.array = levelArray; struct cudaTextureDesc texDesc; memset(&texDesc, 0, sizeof(texDesc)); texDesc.addressMode[0] = cudaAddressModeClamp; texDesc.addressMode[1] = cudaAddressModeClamp; texDesc.filterMode = cudaFilterModePoint; texDesc.readMode = cudaReadModeElementType; texDesc.normalizedCoords = 1; CUDA_CHECK(cudaCreateTextureObject(&_texObj, &resDesc, &texDesc, nullptr)); } ~ScopedCudaTextureObject() { if (_texObj) { CUDA_CHECK(cudaDestroyTextureObject(_texObj)); } } operator cudaTextureObject_t&() { return _texObj; } }; /// A wrapper around a suface object class ScopedCudaSurfaceObject final { cudaSurfaceObject_t _surfObj = 0; public: ScopedCudaSurfaceObject(cudaMipmappedArray_t mmarr, int mipLevel = 0) { if (!mmarr) return; cudaArray_t levelArray = 0; CUDA_CHECK(cudaGetMipmappedArrayLevel(&levelArray, mmarr, 0)); if (!levelArray) return; struct cudaResourceDesc surfResDesc; memset(&surfResDesc, 0, sizeof(surfResDesc)); surfResDesc.resType = cudaResourceTypeArray; surfResDesc.res.array.array = levelArray; CUDA_CHECK(cudaCreateSurfaceObject(&_surfObj, &surfResDesc)); } ~ScopedCudaSurfaceObject() { if (_surfObj) { CUDA_CHECK(cudaDestroySurfaceObject(_surfObj)); } } operator cudaSurfaceObject_t&() { return _surfObj; } }; } class OgnScaleAOVTexture { public: static bool compute(OgnScaleAOVTextureDatabase& db) { // The gpu and rp inputs are passed through to the output. // They are only present here so that the nodes GpuInteropGpuToCpuCopy and GpuInteropCpuToDisk can be connected // after the current test node, to establish the correct topological order in the graph. // An alternate way to do this is to use a dummy execution port for this purpose (this is what the SDG nodes do). // In the future, the data protocol for post render graph nodes should standardize the inputs of the nodes and // prevent the need for passing raw pointers around. db.outputs.gpu() = db.inputs.gpu(); db.outputs.rp() = db.inputs.rp(); auto gpu = reinterpret_cast<GpuFoundationsInterfaces*>(db.inputs.gpu()); auto rp = reinterpret_cast<omni::usd::hydra::HydraRenderProduct*>(db.inputs.rp()); // This node is called in tests and has to fail hard CARB_ASSERT(gpu); CARB_ASSERT(rp); auto result = ComputeParamsBuilder<std::string>{ gpu, rp, db } .addValue("multiplier", db.inputs.multiplier()) .addInputTexture("inputAOV", db.inputs.inputAOV(), [&db](cudaMipmappedArray_t cudaPtr, carb::graphics::TextureDesc const* desc, ComputeParams<std::string>& params) { // the desc pointer is guaranteed to be valid params.add("width", desc->width); params.add("height", desc->height); }) .addOutputTexture("outputAOV", db.inputs.outputAOV(), db.inputs.width(), db.inputs.height(), carb::graphics::Format::eRGBA8_UNORM, "TestTexture", [&db](cudaMipmappedArray_t ptr) { db.outputs.outputAOVPtr() = reinterpret_cast<uint64_t>(ptr); }) .scheduleCudaTask("TestCudaTask", [](ComputeParams<std::string>* data, cudaStream_t stream) { auto multiplier = data->get<float>("multiplier"); auto inputAOV = data->get<cudaMipmappedArray_t>("inputAOV"); auto outputAOV = data->get<cudaMipmappedArray_t>("outputAOV"); auto width = data->get<uint32_t>("width"); auto height = data->get<uint32_t>("height"); CARB_ASSERT(multiplier != 0.0f); CARB_ASSERT(width != 0.0f); CARB_ASSERT(height != 0.0f); ScopedCudaTextureObject inputTex(inputAOV); ScopedCudaSurfaceObject outputTex(outputAOV); cudaScaleImage(inputTex, multiplier, width, height, outputTex, stream); }, [](ComputeParams<std::string> const& params) -> bool { return params.hasKey("inputAOV") && params.get<cudaMipmappedArray_t>("inputAOV") != nullptr && params.hasKey("outputAOV") && params.get<cudaMipmappedArray_t>("outputAOV") != nullptr; }); db.outputs.scheduleResult() = result; return result; } }; REGISTER_OGN_NODE() } // test } // namespace graph } // namespace omni
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/_impl/extension.py
"""Support required by the Carbonite extension loader""" import omni.ext from ..bindings._omni_graph_rtxtest import acquire_interface as _acquire_interface # noqa: PLE0402 from ..bindings._omni_graph_rtxtest import release_interface as _release_interface # noqa: PLE0402 class _PublicExtension(omni.ext.IExt): """Object that tracks the lifetime of the Python part of the extension loading""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__interface = None def on_startup(self): """Set up initial conditions for the Python part of the extension""" self.__interface = _acquire_interface() def on_shutdown(self): """Shutting down this part of the extension prepares it for hot reload""" if self.__interface is not None: _release_interface(self.__interface) self.__interface = None
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/__init__.py
"""There is no public API to this module.""" __all__ = [] scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/test_viewport_nodes.py
"""test viewport nodes""" import asyncio import inspect import pathlib import carb.input import omni.graph.core as og import omni.usd from omni.kit.ui_test.input import emulate_keyboard_press from omni.rtx.tests import RtxTest, postLoadTestSettings, testSettings from omni.rtx.tests.test_common import wait_for_update from omni.ui.tests.compare_utils import CompareMetric, capture_and_compare from pxr import UsdGeom EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) GOLDEN_IMG_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/graph/rtxtest/tests/data/golden") # ====================================================================== class TestViewportNodes(RtxTest): def __init__(self, tests=()): super().__init__(tests) self.test_graph_path = "/World/TestGraph" async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() self.add_dir_light() await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def tearDown(self): await super().tearDown() await omni.kit.stage_templates.new_stage_async() @property def __test_name(self) -> str: """ The full name of the test. It has the name of the module, class and the current test function. We use the stack to get the name of the test function and since it's only called from create_test_window and finalize_test, we get the third member. """ return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" async def capture_and_compare(self, image_name: str, threshold=RtxTest.THRESHOLD, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED): """ RtxTest.capture_and_compare() captures directly from the viewport's texture, however, we need to capture from the swap chain in order to take into account the overlay image that hides the current frame during viewport render lock. """ diff = await capture_and_compare(image_name, threshold, GOLDEN_IMG_DIR, True, cmp_metric) if diff != 0: carb.log_warn(f"[{self.__test_name}] the generated image {image_name} has max difference {diff}") if diff >= threshold: self._failedImages.append(image_name) return diff def create_mesh(self, name): """Create a cube mesh""" cube = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) cube.CreatePointsAttr( [ (-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50), ] ) cube.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) cube.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) cube.CreateSubdivisionSchemeAttr("none") return cube async def test_lock_viewport_render(self): """Validate viewport render lock & unlock for OgnLockViewportRender""" # create a cube mesh cube = self.create_mesh("/World/cube") # create action graph controller = og.Controller() graph = controller.create_graph({"graph_path": self.test_graph_path, "evaluator_name": "execution"}) controller.edit( graph, { og.Controller.Keys.CREATE_NODES: [ ("on_keyboard_input_l", "omni.graph.action.OnKeyboardInput"), ("on_keyboard_input_u", "omni.graph.action.OnKeyboardInput"), ("lock_viewport_render", "omni.graph.ui_nodes.LockViewportRender"), ], og.Controller.Keys.CONNECT: [ ("on_keyboard_input_l.outputs:released", "lock_viewport_render.inputs:lock"), ("on_keyboard_input_u.outputs:released", "lock_viewport_render.inputs:unlock"), ], og.Controller.Keys.SET_VALUES: [ ("on_keyboard_input_l.inputs:keyIn", "L"), ("on_keyboard_input_l.inputs:onlyPlayback", False), ("on_keyboard_input_u.inputs:keyIn", "U"), ("on_keyboard_input_u.inputs:onlyPlayback", False), ], }, ) # Initial await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.initial.png") # Lock viewport render await emulate_keyboard_press(carb.input.KeyboardInput.L) await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.locked.png") # Scale the cube scale_op = UsdGeom.Xformable(cube).AddScaleOp() scale = 2.0 scale_op.Set((scale, scale, scale)) await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.scaled.png") # Unlock viewport render and wait for the fading duration (1 second by default) to complete await emulate_keyboard_press(carb.input.KeyboardInput.U) await asyncio.sleep(1.1) await self.capture_and_compare("test_lock_viewport_render.unlocked.png") # Lock viewport render and scale the cube again await emulate_keyboard_press(carb.input.KeyboardInput.L) scale = 3.0 scale_op.Set((scale, scale, scale)) await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.relocked.png") # Remove the node. The viewport render will be automatically unlocked. controller.edit(graph, { og.Controller.Keys.DELETE_NODES: "lock_viewport_render" }) await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.removed.png")
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/test_post_render_graph.py
"""Tests for the post render graph scaffolding APIs""" import carb import inspect import pathlib import omni.graph.core as og import omni.graph.core.tests as ogts import omni.hydratexture from omni.kit.viewport.utility import get_active_viewport import omni.kit.test from omni.kit.test_helpers_gfx.compare_utils import finalize_capture_and_compare, ComparisonMetric from omni.rtx.tests import RtxTest, postLoadTestSettings, testSettings, OUTPUTS_DIR from omni.rtx.tests.test_common import wait_for_update from pxr import Gf, Sdf, Usd, UsdGeom EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/graph/rtxtest/tests/data/golden") THRESHOLD = 1e-4 class TestPostRenderGraphs(RtxTest): @staticmethod def get_aov_list(stage: Usd.Stage, rp_prim_path) -> list[str]: aovs : list[str] = [] render_vars = stage.GetPrimAtPath(rp_prim_path).GetRelationship("orderedVars").GetForwardedTargets() for render_var in render_vars: aov_name = stage.GetPrimAtPath(render_var).GetAttribute("sourceName").Get() aovs.append(aov_name) return aovs @property def __test_name(self) -> str: """ The full name of the test. It has the name of the module, class and the current test function. We use the stack to get the name of the test function and since it's only called from create_test_window and finalize_test, we get the third member. """ return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" def render_product_path(self, hydra_texture) -> str: '''Return a string to the UsdRender.Product used by the texture''' render_product = hydra_texture.get_render_product_path() if render_product and (not render_product.startswith('/')): render_product = '/Render/RenderProduct_' + render_product return render_product def compare_output_image(self, golden_img_name, threshold, output_img_dir: pathlib.Path, golden_img_dir: pathlib.Path, metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED): """Compare an arbitrary image with a golden image. The image generated in the test could be produced by OgnGpuInteropCpuToDisk or some other method.""" diff = finalize_capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric=metric) if diff != 0: carb.log_warn(f"[{self.__test_name}] the generated image {golden_img_name} has max difference {diff}") if (diff is not None) and diff >= threshold: self._failedImages.append(golden_img_name) return diff async def setUpProps(self, stage): # add a couple of prims in the scene cube = ogts.create_cube(stage, "Cube", (255, 0, 0)) sphere = ogts.create_sphere(stage, "Sphere", (0, 255, 0)) xform_cube = UsdGeom.Xformable(cube) xform_cube.AddTranslateOp().Set((0, 30, 40)) xform_cube.AddScaleOp().Set(Gf.Vec3f(30.0)) xform_sphere = UsdGeom.Xformable(sphere) xform_sphere.AddTranslateOp().Set((0, 30, -40)) xform_sphere.AddScaleOp().Set(Gf.Vec3f(25.0)) await wait_for_update(self.ctx, 10) async def setUp(self): await super().setUp() # must apply the test settings to the renderer to ensure that the test setup matches the SDG setup self.set_settings(testSettings) # set up the stage omni.usd.get_context().new_stage() self.add_dir_light() self.add_floor() await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) # renderer renderer = "rtx" if renderer not in self.ctx.get_attached_hydra_engine_names(): omni.usd.add_hydra_engine(renderer, self.ctx) self._stage = self.ctx.get_stage() session_layer = self._stage.GetSessionLayer() with Usd.EditContext(self._stage, session_layer): # set the render product on the active viewport viewport_api = get_active_viewport() if viewport_api: self._render_product_path_0 = viewport_api.render_product_path # create the post render graph pipeline_stage = og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_POSTRENDER execution_model = "push" orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage(pipeline_stage) top_graph = orchestration_graphs[0] self._og_graph_path = f"{self._render_product_path_0}/TestPostRender" compound_node1 = top_graph.create_graph_as_node( "TestPostRender", self._og_graph_path, evaluator=execution_model, is_global_graph=True, is_backed_by_usd=True, backing_type=og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, pipeline_stage=pipeline_stage) self._post_render_graph = compound_node1.get_wrapped_graph() # set the ogPostProcessPath attribute to associate the graph with this render product attr_name = "ogPostProcessPath" self._stage.GetPrimAtPath(self._render_product_path_0).CreateAttribute(attr_name, Sdf.ValueTypeNames.String).Set(self._og_graph_path) # debug sanity check # carb.log_info(f"!!! rp_path:{self._render_product_path_0}") # carb.log_info(f"!!! og_path:{self._og_graph_path}") # carb.log_info(f"!!! rp_aovs: {self.get_aov_list(self._stage, self._render_product_path_0)}") # carb.log_info(f"!!! rp.ogPostProcessPath={self._stage.GetPrimAtPath(self._render_product_path_0).GetAttribute(attr_name).Get()}") # carb.log_info(f"!!! og.nodes={self._post_render_graph.get_nodes()}") async def tearDown(self): await super().tearDown() # ----------------------------------------------------------------------------- async def test_modify_aov(self): """Validate that the post render graph can modify an AOV in place.""" await self.setUpProps(self._stage) await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.graph.rtxtest", golden_img_name="test_modify_aov.initial.png", threshold=THRESHOLD) keys = og.Controller.Keys (_, (_, test_node), _, _) = og.Controller.edit( self._post_render_graph, { keys.CREATE_NODES: [ ("RenderProductEntry", "omni.graph.nodes.GpuInteropRenderProductEntry"), ("TestNode", "omni.graph.rtxtest.ScaleAOVTextureInPlace"), ], keys.CONNECT: [ ("RenderProductEntry.outputs:gpu", "TestNode.inputs:gpu"), ("RenderProductEntry.outputs:rp", "TestNode.inputs:rp"), ("RenderProductEntry.outputs:exec", "TestNode.inputs:exec"), ], keys.SET_VALUES: [ ("TestNode.inputs:inputAOV", "LdrColor"), ("TestNode.inputs:multiplier", 1.5), ("TestNode.inputs:width", self.WINDOW_SIZE[0]), ("TestNode.inputs:height", self.WINDOW_SIZE[1]), ] }, ) await wait_for_update(self.ctx, 10) # Validate that the outputAOVPtr attribute is set. # This attribute is set after getting from the RenderProduct # the pointer of the AOV with the token set on the "inputAOV" attribute. actual = og.Controller.get(og.Controller.attribute("outputs:outputAOVPtr", test_node)) self.assertNotEqual(0, actual) # validate that the scheduleCudaTask() method returned true schedule_result = og.Controller.get(og.Controller.attribute("outputs:scheduleResult", test_node)) self.assertEqual(True, schedule_result) await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.graph.rtxtest", golden_img_name="test_modify_aov.scaled.png", threshold=THRESHOLD) # ----------------------------------------------------------------------------- async def test_create_new_aov(self): """Validate that the post render graph can create new AOVs without throwing.""" # This test allocates a new AOV, saves it to disk and compares it with a golden image # NOTE: the image produced by the test seems to be missing the expected details, indicating # a bug in the test nodes. Since this test does not rely on the actual data in the buffer # being correct, the test is considered valid. await self.setUpProps(self._stage) output_image_dir = OUTPUTS_DIR.joinpath("omni.graph.rtxtest") keys = og.Controller.Keys (_, (_, test_node, _, _), _, _) = og.Controller.edit( self._post_render_graph, { keys.CREATE_NODES: [ ("RenderProductEntry", "omni.graph.nodes.GpuInteropRenderProductEntry"), ("TestNode", "omni.graph.rtxtest.ScaleAOVTexture"), ("GpuToCpuCopy", "omni.graph.examples.cpp.GpuInteropGpuToCpuCopy"), ("CpuToDisk", "omni.graph.examples.cpp.GpuInteropCpuToDisk"), ], keys.CONNECT: [ ("RenderProductEntry.outputs:gpu", "TestNode.inputs:gpu"), ("RenderProductEntry.outputs:rp", "TestNode.inputs:rp"), ("RenderProductEntry.outputs:exec", "TestNode.inputs:exec"), ("TestNode.outputs:gpu", "GpuToCpuCopy.inputs:gpu"), ("TestNode.outputs:rp", "GpuToCpuCopy.inputs:rp"), ("GpuToCpuCopy.outputs:gpu", "CpuToDisk.inputs:gpu"), ("GpuToCpuCopy.outputs:rp", "CpuToDisk.inputs:rp"), ("GpuToCpuCopy.outputs:aovCpu", "CpuToDisk.inputs:aovCpu"), ], keys.SET_VALUES: [ ("TestNode.inputs:inputAOV", "LdrColor"), ("TestNode.inputs:outputAOV", "scaledColor"), ("TestNode.inputs:multiplier", 1.5), ("TestNode.inputs:width", self.WINDOW_SIZE[0]), ("TestNode.inputs:height", self.WINDOW_SIZE[1]), ("GpuToCpuCopy.inputs:aovGpu", "scaledColor"), ("CpuToDisk.inputs:aovGpu", "scaledColor"), ("CpuToDisk.inputs:frameCount", 1), ("CpuToDisk.inputs:saveLocation", str(output_image_dir)), ("CpuToDisk.inputs:fileName", "test_create_new_aov"), # final name: test_create_new_aov_scaledColor.png ("CpuToDisk.inputs:autoFileNumber", 0), ] }, ) await wait_for_update(self.ctx, 10) # validate that the outputAOVPtr attribute is set - this attribute is set after the new AOV is allocated actual = og.Controller.get(og.Controller.attribute("outputs:outputAOVPtr", test_node)) self.assertNotEqual(0, actual) # validate that the scheduleCudaTask() method returned true schedule_result = og.Controller.get(og.Controller.attribute("outputs:scheduleResult", test_node)) self.assertEqual(True, schedule_result) self.compare_output_image( "test_create_new_aov_scaledColor.png", THRESHOLD, output_image_dir, GOLDEN_DIR) # ----------------------------------------------------------------------------- async def test_invalid_input_aov_param__fails(self): """Validate that nodes accessing invalid AOVs do not schedule cuda tasks""" keys = og.Controller.Keys (_, (_, test_node), _, _) = og.Controller.edit( self._post_render_graph, { keys.CREATE_NODES: [ ("RenderProductEntry", "omni.graph.nodes.GpuInteropRenderProductEntry"), ("TestNode", "omni.graph.rtxtest.ScaleAOVTextureInPlace"), ], keys.CONNECT: [ ("RenderProductEntry.outputs:gpu", "TestNode.inputs:gpu"), ("RenderProductEntry.outputs:rp", "TestNode.inputs:rp"), ("RenderProductEntry.outputs:exec", "TestNode.inputs:exec"), ], keys.SET_VALUES: [ ("TestNode.inputs:inputAOV", "InvalidAOVToken"), ("TestNode.inputs:multiplier", 1.5), ("TestNode.inputs:width", self.WINDOW_SIZE[0]), ("TestNode.inputs:height", self.WINDOW_SIZE[1]), ] }, ) await wait_for_update(self.ctx, 10) # the builder will log a warning if an AOV is not found self.assertEqual(len(test_node.get_compute_messages(og.WARNING)), 1) # validate that the scheduleCudaTask() method returned false schedule_result = og.Controller.get(og.Controller.attribute("outputs:scheduleResult", test_node)) self.assertEqual(False, schedule_result)
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/test_gpu_interop.py
"""test gpu interop nodes""" import pathlib import omni.graph.core as og import omni.kit.commands import omni.kit.stage_templates import omni.kit.test import omni.usd from omni.rtx.tests import RtxTest, postLoadTestSettings, testSettings from omni.rtx.tests.test_common import wait_for_update from pxr import UsdGeom EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/graph/rtxtest/tests/data/golden") # ====================================================================== class TestPreRender(RtxTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() self.add_dir_light() await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def tearDown(self): await super().tearDown() await omni.kit.stage_templates.new_stage_async() def create_mesh(self, name): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) box.CreatePointsAttr( [ (-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50), ] ) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box # ---------------------------------------------------------------------- async def test_prerender_gpuinterop(self): controller = og.Controller() keys = og.Controller.Keys() (_, _, _, _) = controller.edit( {"graph_path": "/PushGraph", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_PRERENDER}, { keys.CREATE_NODES: [ ("ConstantString", "omni.graph.nodes.ConstantString"), ("ToToken", "omni.graph.nodes.ToToken"), ("ReadPoints", "omni.graph.nodes.ReadPrimAttribute"), ("Entry", "omni.graph.nodes.RenderPreProcessEntry"), ("Allocator", "omni.graph.nodes.RpResourceExampleAllocator"), ("Deformer", "omni.graph.nodes.RpResourceExampleDeformer"), ("ToHydra", "omni.graph.nodes.RpResourceExampleHydra"), ], keys.CONNECT: [ ("ConstantString.inputs:value", "ToToken.inputs:value"), ("ToToken.outputs:converted", "ReadPoints.inputs:primPath"), ("ToToken.outputs:converted", "Allocator.inputs:primPath"), ("ReadPoints.outputs:value", "Allocator.inputs:points"), ("Entry.outputs:stream", "Allocator.inputs:stream"), ("Allocator.outputs:pointCountCollection", "Deformer.inputs:pointCountCollection"), ("Allocator.outputs:primPathCollection", "Deformer.inputs:primPathCollection"), ("Allocator.outputs:resourcePointerCollection", "Deformer.inputs:resourcePointerCollection"), ("Allocator.outputs:stream", "Deformer.inputs:stream"), ("Deformer.outputs:pointCountCollection", "ToHydra.inputs:pointCountCollection"), ("Deformer.outputs:primPathCollection", "ToHydra.inputs:primPathCollection"), ("Deformer.outputs:resourcePointerCollection", "ToHydra.inputs:resourcePointerCollection"), ], keys.SET_VALUES: [ ("ConstantString.inputs:value", "/World/box"), ("ReadPoints.inputs:usePath", True), ("ReadPoints.inputs:name", "points"), ("Deformer.inputs:deformScale", 50.0), ("Deformer.inputs:positionScale", 100.0), ("ToHydra.inputs:sendToHydra", True), ], }, ) self.create_mesh("/World/box") await wait_for_update(self.ctx, 30) await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.graph.rtxtest", golden_img_name="gpuinterop_prerender_deformer.png", threshold=1e-4, )
omniverse-code/kit/exts/omni.graph.rtxtest/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.0] - 2022-08-30 ### Added - Migrated the prerender graph tests from omni.graph.test
omniverse-code/kit/exts/omni.graph.rtxtest/docs/README.md
# OmniGraph Integration Testing With RTX [omni.graph.rtxtest] This extension contains support for tests that exercise RTX features such as the pre-render graph. ## Published Documentation The automatically-published user guide from this repo can be viewed :ref:`here<index.rst>`
omniverse-code/kit/exts/omni.graph.rtxtest/docs/index.rst
.. _omni.graph.rtxtest: OmniGraph Integration RTX Testing ################################# .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension**: omni.graph.rtxtest,**Documentation Generated**: |today| There were some instabilities in `omni.graph.test` tests that were related to what looked like rendering issues. This extension was created to isolate the requirement for rendering-related libraries so that the other tests could run in headless mode, minimizing the chance of random failures. .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.graph.rtxtest/docs/Overview.md
# OmniGraph Integration RTX Testing ```{csv-table} **Extension**: omni.graph.action,**Documentation Generated**: {sub-ref}`today` ``` There were some instabilities in `omni.graph.test` tests that were related to what looked like rendering issues. This extension was created to isolate the requirement for rendering-related libraries so that the other tests could run in headless mode, minimizing the chance of random failures.
omniverse-code/kit/exts/omni.rtx.shadercache.vulkan/omni/rtx/shadercache/vulkan/__init__.py
from .shadercache_vulkan import ShaderCacheConfig
omniverse-code/kit/exts/omni.rtx.shadercache.vulkan/omni/rtx/shadercache/vulkan/shadercache_vulkan.py
import omni.ext class ShaderCacheConfig(omni.ext.IExt): def on_startup(self, ext_id): """Callback when the extension is starting up""" pass def on_shutdown(self): """Callback when the extension is shutting down""" pass
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/PACKAGE-LICENSES/omni.kit.widget.nucleus_connector-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/config/extension.toml
[package] title = "Kit Nucleus Connector" version = "1.0.3" category = "Internal" description = "Helper extension for connecting to Nucleus servers" authors = ["NVIDIA"] slackids = ["UQY4RMR3N"] repository = "" keywords = ["kit", "ui", "nucleus"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.window.popup_dialog" = {} "omni.client" = {} [[python.module]] name = "omni.kit.widget.nucleus_connector" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.ui_test", ]
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/connector.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. # import asyncio import omni.client import carb from typing import Callable from functools import partial from .ui import ConnectorDialog, AlertPane class NucleusConnector: """ NucleusConnector object helps with connecting to Nucleus servers. """ def __init__(self): self._dialog = None def start_auth_flow(self, host_name, auth_handle: int): """ Called at the start of the authentication cycle. Most importantly, prepares a cancel button so that the user can cancel out of the process if it hangs for any reason. Args: host_name (str): The server host name that the authentication is for auth_handle (int): An integer handle that should be passed to cancel authentication """ # OM-76995: for authentication callback, it is okay to re-use dialogs created since it most often comes from # connection operations already if not self._dialog: self._dialog = ConnectorDialog() # Set dialog fields only if they're empty name = self._dialog.get_value('name') or host_name url = omni.client.make_url(scheme='omniverse', host=self._dialog.get_value('url') or host_name) self._dialog.show_authenticate(name=name, url=url) self._dialog.set_cancel_clicked_fn(partial(self.cancel_auth, auth_handle)) def end_auth_flow(self, auth_handle: int): """Called at the end of the authentication cycle; hides the app dialog""" if self._dialog: self._dialog.hide() self._dialog = None def cancel_auth(self, auth_handle: int, dialog: ConnectorDialog): """ This callback is attached to the dialog's cancel button. It cancels the authentication process. Args: auth_handle (int): An integer handle that should be passed to cancel authentication """ # Cancel the dialog task if self._dialog: self._dialog.cancel_task() self._dialog.hide() self._dialog = None # Cancel the auth flow in the browser omni.client.authentication_cancel(auth_handle) def connect_with_callback(self, name: str = None, url: str = None, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Unless specified, prompts for server name and Url and proceeds to connect to it. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ def on_connect_server(on_success_fn: Callable, on_failed_fn: Callable, dialog: ConnectorDialog, name: str = None, url: str = None, show_waiting: bool = True): if not name: name = dialog.get_value("name") if not url: url = dialog.get_value("url") # OMFP-2249: If no name/url is present, we do nothing (when "ok" button is clicked) if not url and not name: return if show_waiting: dialog.show_waiting() # Give dialog ownership of the task so that it can cancel at will. asyncio.ensure_future(dialog.run_cancellable_task( self.connect_server_async(name, url, on_success_fn, on_failed_fn, dialog=dialog))) def on_cancel(dialog): dialog.cancel_task() dialog.hide() # OM-76995: Create the dialog on demand, so in detached window the dialog window shows up correctly self._dialog = ConnectorDialog() if url: self._dialog.show_authenticate(name=name, url=url) # If server is explicitly specified, then proceed to connect rather than wait for user input. on_connect_server(on_success_fn, on_failed_fn, self._dialog, name=name, url=url) return self._dialog.show(name=name, url=url) self._dialog.set_okay_clicked_fn(partial(on_connect_server, on_success_fn, on_failed_fn)) self._dialog.set_cancel_clicked_fn(on_cancel) async def connect_server_async(self, name: str, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None, retry: bool = False, dialog: ConnectorDialog = None): """ Connects to the named server. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) retry (bool): True if re-trying for second time. dialog (ConnectorDialog): A dialog instance to re-use from parent operation. """ if not url: carb.log_warn(f"Error connecting server, missing Url.") return elif not url.startswith("omniverse://"): url = f"omniverse://{url}" if not name: # If no name specified, then use name of child directory name = list(filter(None, url.split("/")))[-1] if not dialog: dialog = ConnectorDialog() dialog.show_authenticate(name=name, url=url) result, stats = None, None try: # This stat triggers the start of the authentication flow result, stats = await omni.client.stat_async(url) except asyncio.CancelledError: # If this task is cancelled, then sign out completely in order to clear the auth process omni.client.sign_out(url) carb.log_warn(f"Cancelled attempted connection to '{url}'.") return if result == omni.client.Result.OK: dialog.hide() dialog.destroy() if on_success_fn: on_success_fn(name, url) elif result == omni.client.Result.ERROR_CONNECTION and not retry: # Note: Strangely, omni.client returns error if the user has previously connected or disconnected from # this server. In this case, only a reconnect will succeed. omni.client.reconnect(url) await self.connect_server_async( name, url, on_success_fn=on_success_fn, on_failed_fn=on_failed_fn, retry=True, dialog=dialog) else: msg = f"Unable to connect server '{url}'. Please check your internet connection then try again." dialog.show_alert(msg, AlertPane.Warn) if on_failed_fn: on_failed_fn(name, url) async def reconnect_server_async(self, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Re-connects to the named server. Args: url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ if not url: carb.log_warn(f"Error reconnecting server, missing Url.") return name = list(filter(None, url.split("/")))[-1] # OM-76995: Create the dialog on demand, so in detached window the dialog window shows up correctly self._dialog = ConnectorDialog() self._dialog.show_authenticate(name=name, url=url) # Do the reconnect omni.client.reconnect(url) result, stats = None, None try: result, stats = await omni.client.stat_async(url) except asyncio.CancelledError: # If this task is cancelled, then sign out completely in order to clear the auth process omni.client.sign_out(url) carb.log_warn(f"Cancelled attempted connection to '{url}'.") return if result == omni.client.Result.OK: if self._dialog: self._dialog.hide() self._dialog = None if on_success_fn: on_success_fn(name, url) else: msg = f"Unable to connect server '{url}'. Please check your internet connection then try again." if not self._dialog: self._dialog = ConnectorDialog() self._dialog.show_alert(msg, AlertPane.Warn) if on_failed_fn: on_failed_fn(name, url) def destroy(self): """Destructor.""" if self._dialog: self._dialog.destroy() self._dialog = None
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/style.py
from omni import ui from pathlib import Path CURRENT_PATH = Path(__file__).parent DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data") ICON_PATH = DATA_PATH.joinpath("icons") class Colors: Background = ui.color.shade(0xFF23211F, light=0xFF535354) Border = ui.color.shade(0xFFA1A1A1, light=0xFFE0E0E0) ButtonHovered = ui.color.shade(0xFF9A9A9A, light=0xFF9A9A9A) ButtonSelected = ui.color.shade(0xFF9A9A9A, light=0xFF9A9A9A) Text = ui.color.shade(0xFFA1A1A1, light=0xFFE0E0E0) TextWarn = ui.color.shade(0xFF3333A1, light=0xFF3333E0) Url = ui.color.shade(0xFFE8AD4B, light=0xFFE00000) Image = ui.color.shade(0xFFA8A8A8, light=0xFFA8A8A8) ProgressBackground = ui.color.shade(0xFF24211F, light=0xFF24211F) ProgressBorder = ui.color.shade(0xFF323434, light=0xFF323434) ProgressBar = ui.color.shade(0xFFC9974C, light=0xFFC9974C) AlertPaneBackground = ui.color.shade(0xFF3A3A3A, light=0xFF323434) InfoPaneBorder = ui.color.shade(0xFFC9974C, light=0xFFC9974C) WarningPaneBorder = ui.color.shade(0xFF318693, light=0xFF318693) UI_STYLES = { "Dialog": { "background_color": Colors.Background, "margin_width": 8, "margin_height": 8, }, "Image": { "background_color": 0x0, "margin": 0, "padding": 0, "color": Colors.Image, "alignment": ui.Alignment.CENTER, }, "QrCode": { "background_color": 0x0, "margin": 10, "padding": 0, "alignment": ui.Alignment.CENTER, }, "Image.Label": {"color": Colors.Text, "alignment": ui.Alignment.CENTER}, "ProgressBar": { "background_color": Colors.ProgressBackground, "border_width": 2, "border_radius": 0, "border_color": Colors.ProgressBorder, "color": Colors.ProgressBar, "margin": 0, "padding": 0, "alignment": ui.Alignment.LEFT_CENTER, }, "ProgressBar.Frame": { "background_color": 0xFF23211F, "margin": 0, "padding": 0, }, "ProgressBar.Puck": { "background_color": Colors.ProgressBar, "margin": 2, }, "StringField.Url": { "color": Colors.Url, "background_color": 0x0, }, "Label": {"color": Colors.Text}, "Label.Code": { "color": Colors.Text, "alignment": ui.Alignment.CENTER, "font_size": 40, }, "Label.TimeRemaining": {"color": Colors.Url}, "Label.Expired": { "color": Colors.TextWarn, "alignment": ui.Alignment.CENTER }, "AlertPane": { "background_color": Colors.AlertPaneBackground, "color": Colors.Text, "margin": 0, "border_radius": 0.0 }, "AlertPane::info": { "border_color": Colors.InfoPaneBorder, "border_width": 2, }, "AlertPane::warn": { "border_color": Colors.WarningPaneBorder, "border_width": 2, }, "AlertPane.Content": { "background_color": 0x0, "margin_width": 8, "margin_height": 12 }, "AlertPanePane.Clear": { "background_color": 0x0, "border_radius": 0.0, "border_color": Colors.Text, "border_width": 1, "margin": 0, "padding": 2, }, "AlertPane.Clear:hovered": {"background_color": Colors.ButtonHovered}, "AlertPane.Clear.Image": {"image_url": f"{ICON_PATH}/close.svg", "color": Colors.Text}, }
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/device_auth.py
# Copyright (c) 2018-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 asyncio import omni.client import carb from typing import Callable from functools import partial from .ui import DeviceAuthFlowDialog, ConnectorDialog, AlertPane class DeviceAuthConnector: """ DeviceAuthConnector object that helps with connecting to Nucleus servers via device flow. """ def __init__(self): self._conn_status_sub = omni.client.register_connection_status_callback(self._connection_status_changed) self._pending_results = {} # url: (auth_handle, dialog instance) def start_auth_flow(self, auth_handle: int, params: omni.client.AuthDeviceFlowParams): """ Called at the start of the authentication cycle. Shows the user a qrcode of auth url and code that needs to be entered in the auth page. User can cancel the process by clicking the cancel button. Args: auth_handle (int): An integer handle that should be passed to cancel authentication """ dialog = DeviceAuthFlowDialog(params) self._pending_results[params.server] = (auth_handle, dialog) dialog.set_cancel_clicked_fn(partial(self.cancel_auth, auth_handle, params.server)) def end_auth_flow(self, auth_handle: int): """Called at the end of the authentication cycle; hides the app dialog""" # find server from auth handle server = None for server_name, (handle, _) in self._pending_results.items(): if handle == auth_handle: server = server_name break if not server: return _, dialog = self._pending_results.pop(server) if dialog: dialog.hide() dialog = None def cancel_auth(self, auth_handle: int, server: str, dialog: DeviceAuthFlowDialog): """ This callback is attached to the dialog's cancel button. It cancels the authentication process. Args: auth_handle (int): An integer handle that should be passed to cancel authentication server (str): The server url that the auth handle is binding to """ if dialog: dialog.hide() dialog = None if server in self._pending_results: self._pending_results.pop(server) # Cancel the auth flow omni.client.authentication_cancel(auth_handle) def _connection_status_changed(self, server: str, status: omni.client.ConnectionStatus) -> None: """Collect signed in server's service information based upon server status changed.""" # need to strip off the omniverse:// here from the server if server.startswith("omniverse://"): server = server[12:] if server not in self._pending_results: return if status == omni.client.ConnectionStatus.CONNECTED: _, dialog = self._pending_results.pop(server) if dialog: dialog.hide() dialog = None def connect_with_callback(self, name: str = None, url: str = None, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Unless specified, prompts for server name and Url and proceeds to connect to it. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ def on_connect_server(on_success_fn: Callable, on_failed_fn: Callable, dialog: ConnectorDialog, name: str = None, url: str = None, show_waiting: bool = True): if show_waiting: dialog.show_waiting() if not name: name = dialog.get_value("name") if not url: url = dialog.get_value("url") # Give dialog ownership of the task so that it can cancel at will. asyncio.ensure_future(dialog.run_cancellable_task( self.connect_server_async(name, url, on_success_fn, on_failed_fn, dialog=dialog))) def on_cancel(dialog): dialog.cancel_task() dialog.hide() # OM-76995: Create the dialog on demand, so in detached window the dialog window shows up correctly self._dialog = ConnectorDialog() if url: # If server is explicitly specified, then proceed to connect rather than wait for user input. on_connect_server(on_success_fn, on_failed_fn, self._dialog, name=name, url=url) return self._dialog.show(name=name, url=url) self._dialog.set_okay_clicked_fn(partial(on_connect_server, on_success_fn, on_failed_fn)) self._dialog.set_cancel_clicked_fn(on_cancel) async def connect_server_async(self, name: str, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None, retry: bool = False, dialog: ConnectorDialog = None): """ Connects to the named server. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) retry (bool): True if re-trying for second time. dialog (ConnectorDialog): A dialog instance to re-use from parent operation. """ if not url: carb.log_warn(f"Error connecting server, missing Url.") return elif not url.startswith("omniverse://"): url = f"omniverse://{url}" if not name: # If no name specified, then use name of child directory name = list(filter(None, url.split("/")))[-1] result, stats = None, None try: # This stat triggers the start of the authentication flow result, stats = await omni.client.stat_async(url) except asyncio.CancelledError: # If this task is cancelled, then sign out completely in order to clear the auth process omni.client.sign_out(url) carb.log_warn(f"Cancelled attempted connection to '{url}'.") return if result == omni.client.Result.OK: if dialog: dialog.hide() if on_success_fn: on_success_fn(name, url) elif result == omni.client.Result.ERROR_CONNECTION and not retry: # Note: Strangely, omni.client returns error if the user has previously connected or disconnected from # this server. In this case, only a reconnect will succeed. omni.client.reconnect(url) await self.connect_server_async( name, url, on_success_fn=on_success_fn, on_failed_fn=on_failed_fn, retry=True, dialog=dialog) else: msg = f"Unable to connect server '{url}'. Please check your internet connection then try again." if not dialog: dialog = ConnectorDialog() dialog.show_alert(msg, AlertPane.Warn) if on_failed_fn: on_failed_fn(name, url) async def reconnect_server_async(self, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Re-connects to the named server. Args: url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ if not url: carb.log_warn(f"Error reconnecting server, missing Url.") return name = list(filter(None, url.split("/")))[-1] # Do the reconnect omni.client.reconnect(url) result, stats = None, None try: result, stats = await omni.client.stat_async(url) except asyncio.CancelledError: # If this task is cancelled, then sign out completely in order to clear the auth process omni.client.sign_out(url) carb.log_warn(f"Cancelled attempted connection to '{url}'.") return if result == omni.client.Result.OK: if on_success_fn: on_success_fn(name, url) else: if on_failed_fn: on_failed_fn(name, url) def destroy(self): """Destructor.""" if self._pending_results: self._pending_results.clear() self._conn_status_sub = None # Cleanup temp img files created for qrcode import os if os.path.exists(DeviceAuthFlowDialog.TEMP_DIR): try: import shutil shutil.rmtree(DeviceAuthFlowDialog.TEMP_DIR) except OSError as e: carb.log_warn( f"Failed to clean up temp directory {DeviceAuthFlowDialog.TEMP_DIR}, error encountered: {str(e)}")
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/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. # import carb.settings import omni.ext import omni.kit.app import omni.client import asyncio from typing import Callable from functools import partial from .connector import NucleusConnector from .device_auth import DeviceAuthConnector from . import NUCLEUS_CONNECTION_SUCCEEDED_EVENT g_singleton = None # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class NucleusConnectorExtension(omni.ext.IExt): """Helper extension for connecting to Nucleus servers""" def __init__(self): super().__init__() self._connector = None def on_startup(self, ext_id): # Save away this instance as singleton global g_singleton g_singleton = self # OM-98449: Register device auth flow callback if device auth flow is turned on in settings self._device_auth_sub = None settings = carb.settings.get_settings() device_auth = settings.get_as_bool("exts/omni.kit.widget.nucleus_connector/device_auth_flow") if device_auth: # pragma: no cover self._connector = DeviceAuthConnector() self._device_auth_sub = omni.client.register_device_flow_auth_callback(self._on_device_auth) else: self._connector = NucleusConnector() # Set the callback to invoke when authentication requires opening a web browser to complete sign-in. omni.client.set_authentication_message_box_callback(self._on_authenticate) def _on_device_auth(self, auth_handle: int, params: omni.client.AuthDeviceFlowParams): """ This callback is invoked when authentication for device auth flow, instead of auth in the web browser. Args: auth_handle (int): The auth handle that could be used for canceling. params (omni.client.AuthDeviceFlowParams): An object containing info to display to user to complete the auth. if it is None, it means the auth attempt is finished. """ if self._connector: if not params: # Auth is done, either succeeded or failed, result needed to be determined from status callback; # Here we just close out the dialog. self._connector.end_auth_flow(auth_handle) return self._connector.start_auth_flow(auth_handle, params) def _on_authenticate(self, show_alert: bool, host_name: str, auth_handle: int): """ This callback is invoked when the application should show a dialog box letting the user know that a browser window has opened and to complete signing in using the web browser. Args: show_alert (bool): True means to start the authentication cycle and False means to end it host_name (str): The server host name that the authentication is for auth_handle (int): An integer handle that should be passed to cancel authentication """ if self._connector: if show_alert: self._connector.start_auth_flow(host_name, auth_handle) else: self._connector.end_auth_flow(auth_handle) def _on_connect_succeeded(self, callback: Callable, name: str, url: str): """Called when connection is made successfully; invokes the given callback""" # Emit event on successful connection event_stream = omni.kit.app.get_app().get_message_bus_event_stream() if event_stream: event_stream.push(NUCLEUS_CONNECTION_SUCCEEDED_EVENT, payload={"url": url}) if callback: callback(name, url) def _on_connect_failed(self, callback: Callable, name: str, url: str): """Called when connection fails; invokes the given callback""" if callback: callback(name, url) def connect_with_dialog(self, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Prompts for server name and Url and proceeds to connect to it. Args: on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ if self._connector: self._connector.connect_with_callback( on_success_fn=partial(self._on_connect_succeeded, on_success_fn), on_failed_fn=partial(self._on_connect_failed, on_failed_fn)) def connect(self, name: str, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Connects to the named server. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ if self._connector: self._connector.connect_with_callback(name=name, url=url, on_success_fn=partial(self._on_connect_succeeded, on_success_fn), on_failed_fn=partial(self._on_connect_failed, on_failed_fn)) def reconnect(self, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Reconnects to the named server. Args: url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(url: str) """ if self._connector: asyncio.ensure_future(self._connector.reconnect_server_async( url, partial(self._on_connect_succeeded, on_success_fn), partial(self._on_connect_failed, on_failed_fn))) def disconnect(self, url: str): """ Disconnects from the server. Args: url (str): Url of server """ omni.client.sign_out(url) def on_shutdown(self): # Clears the auth callback omni.client.set_authentication_message_box_callback(None) # OM-98449: Clears device auth flow connector and callback self._device_auth_sub = None # Clean up the connector if self._connector: self._connector.destroy() self._connector = None global g_singleton g_singleton = None def get_instance(): return g_singleton
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/__init__.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. # import carb.events NUCLEUS_CONNECTION_SUCCEEDED_EVENT: int = carb.events.type_from_string("omni.kit.widget.nucleus_connector.CONNECTION_SUCCEEDED") from .extension import NucleusConnectorExtension, get_instance def get_nucleus_connector() -> NucleusConnectorExtension: """Returns :class:`NucleusConnectorExtension` interface""" return get_instance()
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/test_helper.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import asyncio from typing import Optional, Union import omni.kit.app from omni.kit import ui_test from .ui import ConnectorDialog, DeviceAuthFlowDialog from . import get_nucleus_connector from .connector import NucleusConnector from .device_auth import DeviceAuthConnector class NucleusConnectorTestHelper: # NOTE Since the file dialog is a singleton, use an async lock to ensure mutex access in unit tests. # During run-time, this is not a issue because the dialog is effectively modal. __async_lock = asyncio.Lock() async def __aenter__(self): await self.__async_lock.acquire() return self async def __aexit__(self, *args): self.__async_lock.release() def get_connector_dialog(self, url: str = None) -> Optional[Union[ConnectorDialog, DeviceAuthFlowDialog]]: ext = get_nucleus_connector() if ext and ext._connector: if isinstance(ext._connector, NucleusConnector) or url is None: return ext._connector._dialog if isinstance(ext._connector, DeviceAuthConnector) and url: return ext._connector._pending_results.get(url, (None, None))[1] return None # pragma: no cover async def wait_for_popup(self, timeout: int = 100, url: str = None): dialog = self.get_connector_dialog(url=url) if dialog: for _ in range(timeout): if dialog.visible: return await omni.kit.app.get_app().next_update_async() raise Exception("Error: The connector dialog never opened.") async def wait_for_close(self, timeout: int = 100, url: str = None): dialog = self.get_connector_dialog(url=url) # OM-76995: Since we are creating the dialog on demand, it is considered ok if the dialog doesn't exist if dialog: for _ in range(timeout): if not dialog.visible: return await omni.kit.app.get_app().next_update_async() raise Exception("Error: The connector dialog never closed.") # pragma: no cover async def click_apply_async(self, name: str = None, url: str = None): """Helper function to click the apply button""" dialog = self.get_connector_dialog() if dialog: dialog.set_value('name', name) dialog.set_value('url', url) ok_button = ui_test.find(f"{dialog._window.title}//Frame/**/Button[0]") await ok_button.click() await ui_test.human_delay() async def click_cancel_async(self, url: str = None): """Helper function to click the cancel button""" dialog = self.get_connector_dialog(url=url) if dialog: cancel_button = ui_test.find(f"{dialog._window.title}//Frame/**/Button[1]") await cancel_button.click() await ui_test.human_delay()
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/ui.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. # import os import sys import tempfile import carb import carb.settings import omni.ui as ui import asyncio import omni.kit.app from omni.kit.async_engine import run_coroutine from typing import Coroutine, Any, Callable, Union from omni.kit.window.popup_dialog.dialog import PopupDialog from omni.kit.window.popup_dialog.form_dialog import FormDialog, FormWidget from .style import UI_STYLES, ICON_PATH class ConnectorDialog(PopupDialog): """The main connection dialog""" def __init__(self): super().__init__( width=400, title="Add Nucleus connection", ok_label="Ok", cancel_label="Cancel", modal=True ) self._form_widget = None self._progress_bar = None self._alert_pane = None self._task = None self._build_ui() def _build_ui(self): field_defs = [ FormDialog.FieldDef("url", "Omniverse:// ", ui.StringField, "", True), FormDialog.FieldDef("name", "Optional Name: ", ui.StringField, ""), ] with self._window.frame: with ui.VStack(style=UI_STYLES, style_type_name_override="Dialog"): # OM-81873: This is a temporary solution for the authentication dialog; add the form widget in a frame # so that it could be easily hidden/shown self._form_frame = ui.Frame() with self._form_frame: self._form_widget = FormWidget("Add a new connection with optional name.", field_defs) with ui.ZStack(): ui.Spacer(height=60) with ui.VStack(): ui.Spacer(height=8) self._progress_bar = LoopProgressBar(puck_size=40) ui.Spacer() # OM-86699: Fix issue with randomly resized connector dialog, specify ZStack width with window width # OM-98771: Substract padding from window width when specifying AlertPane width self._alert_pane = AlertPane(width=self._window.width - 24) self._build_ok_cancel_buttons() self.hide() self.set_cancel_clicked_fn(lambda _: self._on_cancel_fn()) def _on_cancel_fn(self): self.cancel_task() self.hide() def get_value(self, name: str) -> str: if self._form_widget: return self._form_widget.get_value(name) return None def set_value(self, name: str, value: str): if self._form_widget: field = self._form_widget.get_field(name) if field: field.model.set_value(value or '') def destroy(self): self.cancel_task() if self._form_widget: self._form_widget.destroy() self._form_widget = None if self._form_frame: self._form_frame = None self._progress_bar = None if self._alert_pane: self._alert_pane.destroy() self._alert_pane = None super().destroy() def __del__(self): self.destroy() async def run_cancellable_task(self, task: Coroutine) -> Any: """Manages running and cancelling the given task""" if self._task: self.cancel_task() self._task = asyncio.create_task(task) try: return await self._task except asyncio.CancelledError: carb.log_info(f"Cancelling task ... {self._task}") raise except Exception as e: raise finally: self._task = None def cancel_task(self): """Cancels the managed task""" if self._task is not None: self._task.cancel() self._task = None @property def frame(self): return self._window.frame @property def visible(self) -> bool: if self._window: return self._window.visible return False def show(self, name: str = None, url: str = None): """Shows the dialog after resetting to a default state""" broken_url = omni.client.break_url(url or '') host = broken_url.host if broken_url.scheme == 'omniverse' else None self.set_value('url', host) self.set_value('name', name) self._progress_bar.hide() self._alert_pane.hide() self._okay_button.enabled = True self._cancel_button.enabled = True self._okay_button.visible = True self._form_frame.visible = True self._window.visible = True # focus fields on show self._form_widget.focus() def hide(self): self._window.visible = False # reset window title on hide; authentication mode might have reset the window title. self._window.title = self._title def show_waiting(self): if self._alert_pane: self._alert_pane.hide() if self._progress_bar: self._progress_bar.show() # Disable apply button self._okay_button.enabled = False def show_alert(self, msg: str = "", alert_type: int = 0): # hide form widget and OK button self._okay_button.visible = False self._form_frame.visible = False if self._alert_pane: self._alert_pane.show(msg, alert_type=alert_type) if self._progress_bar: self._progress_bar.hide() # Disable apply button self._okay_button.enabled = False self._window.visible = True def show_authenticate(self, name: str, url: str): """Shows the dialog for authentication, when the name and url is already given.""" # hide form widget and OK button self._okay_button.visible = False self._form_frame.visible = False # show login info broken_url = omni.client.break_url(url or '') host = broken_url.host if broken_url.scheme == 'omniverse' else None if self._alert_pane: msg = f"Connecting to ({host}) requires login authentication. Please login from your web browser." self._alert_pane.show(msg, alert_type=AlertPane.Info) # update window title self._window.title = "Login Required" self._window.visible = True class LoopProgressBar: """A looping progress bar""" def __init__(self, puck_size: int = 20, period: float = 120): self._puck_size = puck_size self._period = period self._widget = None self._spacer_left = None self._spacer_right = None self._loop_task = None self._build_ui() def _build_ui(self): self._widget = ui.Frame(visible=False) with self._widget: with ui.ZStack(height=20): ui.Rectangle(style_type_name_override="ProgressBar") with ui.HStack(): self._spacer_left = ui.Spacer(width=ui.Fraction(0)) ui.Rectangle(width=self._puck_size, style_type_name_override="ProgressBar.Puck") self._spacer_right = ui.Spacer(width=ui.Fraction(1)) async def _inf_loop(self): counter = 0 while True: await omni.kit.app.get_app().next_update_async() width = float(counter % self._period) / self._period # Ping-pong width = width * 2 if width > 1.0: width = 2.0 - width self._spacer_left.width = ui.Fraction(width) self._spacer_right.width = ui.Fraction(1.0 - width) counter += 1 def __del__(self): self.hide() self._widget = None def show(self): if self._widget: self._loop_task = asyncio.ensure_future(self._inf_loop()) self._widget.visible = True def hide(self): if self._widget: if self._loop_task is not None: self._loop_task.cancel() self._loop_task = None self._widget.visible = False class AlertPane: """An alert pane for the app dialog.""" Info = 0 Warn = 1 def __init__(self, width: int = 400): self._widget: ui.Frame = None self._frame: ui.Frame = None self._icon_frame: ui.Frame = None self._label: ui.Label = None self._build_ui(width=width) def destroy(self): self._label = None self._frame = None self._widget = None def _build_ui(self, width: int = 400): self._widget = ui.Frame(visible=False, height=0) with self._widget: with ui.ZStack(width=width, style=UI_STYLES): self._frame = ui.Frame() with ui.HStack(spacing=4, style_type_name_override="AlertPane.Content"): self._icon_frame = ui.Frame() self._label = ui.Label("", height=20, word_wrap=True, style_type_name_override="Label") def show(self, msg: str = "", alert_type: int = 0): if self._widget: with self._frame: style_name = "warn" if alert_type == AlertPane.Warn else "info" ui.Rectangle(style_type_name_override="AlertPane", name=style_name) with self._icon_frame: icon = f"{ICON_PATH}/warn.svg" if alert_type == AlertPane.Warn else f"{ICON_PATH}/info.svg" ui.ImageWithProvider(icon, width=16, height=16, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style_type_name_override="Image") if self._label: self._label.text = msg self._widget.visible = True def hide(self): if self._widget: self._widget.visible = False # OM-98450: Add UI for device auth flow class DeviceAuthFlowDialog(PopupDialog): TEMP_DIR = os.path.join(tempfile.gettempdir(), "kit_device_auth_qrcode/") """The main authentication dialog for device auth flow.""" def __init__(self, params: omni.client.AuthDeviceFlowParams): super().__init__( width=400, title="Device Authentication", ok_label="Retry", cancel_label="Cancel", modal=True ) self._image = None self._time_remaining = params.expiration self._server = params.server self._expiration_frame = None self._build_ui(params) self._count_down_task = run_coroutine(self._count_expiration_async()) self._generate_qrcode(params.url) @property def visible(self) -> bool: if self._window: return self._window.visible return False def _build_ui(self, params: omni.client.AuthDeviceFlowParams): with self._window.frame: with ui.VStack(style=UI_STYLES, style_type_name_override="Dialog"): ui.Label(f"Connecting to {params.server}", alignment=ui.Alignment.CENTER) with ui.HStack(): ui.Spacer() self._image = ui.Image(width=128, height=128, style_type_name_override="QrCode") ui.Spacer() with ui.HStack(): ui.Label(f"Please go to ", width=0) # OM-102092: Change URL to be a string field so it is selectable and could be copied # TODO: Note that if the URL is too long, currently it could get clipped and will not display the # entire url; Solution could be: # 1) Have both a label and a string field, and when mouse pressed, switch to string field for # selection; which is a bit hacky, since the string field height need to be dynamically adjusted # 2) have omni.ui.Label support selection of text ui.StringField(ui.SimpleStringModel(params.url), style=UI_STYLES, style_type_name_override="StringField.Url", read_only=True) ui.Label("or scan the qrcode above, and enter the code below:") ui.Spacer(height=2) ui.Label(params.code, style_type_name_override="Label.Code") ui.Spacer(height=2) self._expiration_frame = ui.Frame() with self._expiration_frame: with ui.HStack(spacing=4): ui.Spacer() ui.Label("Code expires in", width=0) self._time_remaining_label = ui.Label( str(self._time_remaining), style_type_name_override="Label.TimeRemaining", width=0) ui.Label("seconds", width=0) ui.Spacer() ui.Spacer(height=10) self._build_ok_cancel_buttons() ui.Spacer(height=30) self.set_cancel_clicked_fn(lambda _: self._on_cancel_fn()) self.set_okay_clicked_fn(lambda _: self._on_retry()) self._okay_button.visible = False def _on_cancel_fn(self): self._count_down_task.cancel() self.hide() def _on_retry(self): self._on_cancel() if not self._server.startswith("omniverse://"): server = "omniverse://" + self._server else: server = self._server omni.client.reconnect(server) def destroy(self): if self._count_down_task: self._count_down_task.cancel() self._count_down_task = None super().destroy() def __del__(self): self.destroy() def hide(self): self._window.visible = False # reset window title on hide; authentication mode might have reset the window title. self._window.title = self._title def show_expired(self): """Show the user when the code has expired.""" with self._expiration_frame: ui.Label("Code has expired. Please try again.", style_type_name_override="Label.Expired") self._okay_button.visible = True def _generate_qrcode(self, url: str): # pragma: no cover """Generates a qrcode from the given url.""" if not os.path.exists(self.TEMP_DIR): os.mkdir(self.TEMP_DIR) # Swap out the : && / since the url we are dealing with are usually something like: "https://a.b.c/x/y", # replacing these special characters with "_" here so we don't end up violating OS naming conventions img_name = url.replace("/", "_").replace(":", "_") img_path = os.path.join(self.TEMP_DIR, f"qr_{img_name}.png") # we could skip generating the qrcode for the same url, since the image would be the same with the same encoding if not os.path.exists(img_path): # try to use qrcode module to generate the image try: import qrcode except ImportError: carb.log_error("Package qrcode not installed. Skipping qr code generation.") return img = qrcode.make(url) img.save(img_path) # update image source url self._image.source_url = img_path async def _count_expiration_async(self): """Counts down the remaining time in seconds before expiration.""" while(self._time_remaining > 0): await asyncio.sleep(1) self._time_remaining -= 1 self._time_remaining_label.text = str(self._time_remaining) self.show_expired()
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/__init__.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. ## from .test_connector import * from .test_device_auth import * from .test_ui import *
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/test_ui.py
## Copyright (c) 2018-2019, 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 asyncio from unittest.mock import patch, Mock import carb.settings import omni.kit.test import omni.ui as ui import omni.kit.ui_test as ui_test from ..ui import ConnectorDialog, DeviceAuthFlowDialog class TestConnectorDialog(omni.kit.test.AsyncTestCase): """Tests for dialog base class""" async def setUp(self): pass async def tearDown(self): pass async def _mock_task_with_results(self): return 1, 2, 3 async def _mock_cancellable_task(self): """After a short delay, hide the dialog. This should result in cancelling this long-lasting task.""" while True: try: await asyncio.sleep(1) except asyncio.CancelledError: return async def test_dialog_resturns_task_results(self): """Test that the dialog returns the results from it child task""" dialog = ConnectorDialog() dialog.show() with dialog.frame: ui.Label("Test label", height=20) results = await dialog.run_cancellable_task(self._mock_task_with_results()) # Confirm returned result self.assertEqual(results, (1, 2, 3)) dialog.destroy() async def test_dialog_cancels_task(self): """Test that hiding the dialog window cancels child task""" dialog = ConnectorDialog() # Hide the dialog a short time later. loop = asyncio.get_event_loop() loop.call_later(2, dialog.cancel_task) dialog.show() with dialog.frame: ui.Label("Test label") await dialog.run_cancellable_task(self._mock_cancellable_task()) # Confirm that child task was cancelled self.assertEqual(dialog._task, None) dialog.destroy() class TestDeviceAuthFlowDialog(omni.kit.test.AsyncTestCase): """Tests for DeviceAuthFlowDialog.""" # omni.client.AuthDeviceFlowParams can't be initiated directly in python since it didn't define constructors; so # for testing had to fake an object with those attrs. class _MockParams(): def __init__(self, server, url, expiration, code) -> None: self.server = server self.url = url self.expiration = expiration self.code = code async def setUp(self): pass async def tearDown(self): pass @staticmethod def _mock_params(server, url, expiration, code): return TestDeviceAuthFlowDialog._MockParams(server, url, expiration, code) async def test_display_and_count_down(self): """Test that the dialog displays correctly and counts down correctly.""" # mock qrcode generation so we don't actually generate that with patch.object(DeviceAuthFlowDialog, "_generate_qrcode") as mock_gen_qrcode: dialog = DeviceAuthFlowDialog(self._mock_params("dummy", "https://dummy/auth/url", 100, "FOOBAR42")) self.assertEqual(100, dialog._time_remaining) # test count down await asyncio.sleep(1.5) self.assertGreaterEqual(99, dialog._time_remaining) # test that qrcode generation is triggered mock_gen_qrcode.assert_called_once_with("https://dummy/auth/url") dialog.hide() dialog.destroy() async def test_cancel(self): """Test that the dialog cancel cancels the authentication and closes.""" # mock qrcode generation so we don't actually generate that with patch.object(DeviceAuthFlowDialog, "_generate_qrcode"): dialog = DeviceAuthFlowDialog(self._mock_params("dummy", "https://dummy/auth/url", 100, "FOOBAR42")) self.assertTrue(dialog.window.visible) self.assertIsNotNone(dialog._count_down_task) await ui_test.human_delay(5) button = ui_test.find_all("Device Authentication//Frame/**/Button[*]")[-1] self.assertIsNotNone(button) self.assertEqual(button.widget.text, "Cancel") await button.click() await ui_test.human_delay(5) # check that count down is cancelled and window is hidden self.assertTrue(dialog._count_down_task.cancelled()) self.assertFalse(dialog.window.visible) async def test_dialog_expiration_and_retry(self): """Test that the dialog correctly counts down and expires, and retry works.""" # mock qrcode generation so we don't actually generate that with patch.object(DeviceAuthFlowDialog, "_generate_qrcode"), patch("omni.client.reconnect") as mock_reconnect: dialog = DeviceAuthFlowDialog(self._mock_params("dummy", "https://dummy/auth/url", 1, "FOOBAR42")) await ui_test.human_delay(5) buttons = ui_test.find_all("Device Authentication//Frame/**/Button[*]") retry, cancel = buttons[0], buttons[1] self.assertFalse(retry.widget.visible) self.assertTrue(cancel.widget.visible) # make sure we meet expiration await asyncio.sleep(1.5) # retry button should be enabled now self.assertTrue(retry.widget.visible) self.assertTrue(cancel.widget.visible) # click retry should cancel and hide the window, and issue a new reconnect await retry.click() await ui_test.human_delay(10) mock_reconnect.assert_called_once_with("omniverse://dummy") self.assertFalse(dialog.window.visible)
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/test_device_auth.py
## Copyright (c) 2018-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 asyncio from unittest.mock import patch, Mock import carb.settings import omni.kit.test import omni.client import omni.kit.ui_test as ui_test from .. import get_nucleus_connector from ..test_helper import NucleusConnectorTestHelper from ..device_auth import DeviceAuthConnector from ..ui import DeviceAuthFlowDialog class TestAddServerWithValidationDeviceAuth(omni.kit.test.AsyncTestCase): """Testing FilePickerView.add_server_with_validation""" # omni.client.AuthDeviceFlowParams can't be initiated directly in python since it didn't define constructors; so # for testing had to fake an object with those attrs. class _MockParams(): def __init__(self, server, url, expiration, code) -> None: self.server = server self.url = url self.expiration = expiration self.code = code async def setUp(self): self._test_name = "ov-test" self._test_url = "omniverse://ov-test" self._expected_stat_results = [omni.client.Result.OK, omni.client.Result.OK] self._stat_latency = 1 self._iter = 0 # patch qrcode generation so we don't acutally install qrcode module and generates the image patch_qrcode_gen = patch.object(DeviceAuthFlowDialog, "_generate_qrcode") patch_qrcode_gen.start() self.addCleanup(patch_qrcode_gen.stop) async def tearDown(self): pass async def _mock_stat_async_impl(self, url: str): # During a stat, omni.client triggers the device auth callback. # The callback was previously set via the subscription method: omni.client.register_device_flow_auth_callback. ext = get_nucleus_connector() if self._iter == 0: if ext: mock_param = TestAddServerWithValidationDeviceAuth._MockParams(url, "https://dummy/auth", 10, "FOOBAR42") ext._on_device_auth(1, mock_param) result = self._expected_stat_results[self._iter] self._iter += 1 # Simulates the latency due to user signing in through device auth await asyncio.sleep(self._stat_latency) ext._on_device_auth(1, None) return result, {} def _mock_auth_cancel_impl(self, auth_handle: int): # A cancellation event also executes the device auth callback, but with the params set to None. ext = get_nucleus_connector() if ext: ext._on_device_auth(auth_handle, None) async def test_connect_with_dialog_succeeds(self): """Testing that connecting to server through dialog succeeds""" under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) # Connector dialog will show up first prompting for user input await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) await connector_helper.wait_for_close() # The device auth flow dialog will show up displaying the qrcode etc. await connector_helper.wait_for_popup(url=self._test_url) await connector_helper.wait_for_close(timeout=1000, url=self._test_url) # Confirm on_success callback called await ui_test.human_delay(10) mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_with_given_url_succeeds(self): under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await ui_test.human_delay(10) # Only the device auth dialog will show up await connector_helper.wait_for_popup(url=self._test_url) await connector_helper.wait_for_close(timeout=1000, url=self._test_url) # Confirm on_success callback called await ui_test.human_delay(10) mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_then_reconnect_succeeds(self): """Testing that when connect fails the first time, retries with a reconnect""" under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() # In this case, the first stat will result in an error, but will succeed after a reconnect self._expected_stat_results = [omni.client.Result.ERROR_CONNECTION, omni.client.Result.OK] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await ui_test.human_delay(10) await connector_helper.wait_for_popup(url=self._test_url) #await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) await connector_helper.wait_for_close(timeout=1000, url=self._test_url) # auth dialog is closed during second stat_async, need wait more time for connect completed await asyncio.sleep(self._stat_latency) # Confirm reconnect attempted and connection succeeded mock_reconnect.assert_called_once_with(self._test_url) mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_with_url_cancelled(self): """Testing that user is able to cancel out of connection flow""" under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.authentication_cancel", side_effect=self._mock_auth_cancel_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await ui_test.human_delay(10) # Only the device auth dialog will show up await connector_helper.wait_for_popup(url=self._test_url) # Click cancel after some time await asyncio.sleep(.5*self._stat_latency) await connector_helper.click_cancel_async(url=self._test_url) await connector_helper.wait_for_close(timeout=1000, url=self._test_url) # Confirm neither callbacks invoked mock_success_fn.assert_not_called() mock_failed_fn.assert_not_called() # make sure we finish the mock stat return await asyncio.sleep(0.5* self._stat_latency) async def test_reconnect_with_given_url_succeeds(self): under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() self._expected_stat_results = [omni.client.Result.OK] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.reconnect(self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) for _ in range(1000): await omni.kit.app.get_app().next_update_async() # Confirm on_success callback called mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() mock_reconnect.assert_called_once_with(self._test_url)
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/test_connector.py
## Copyright (c) 2018-2019, 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 asyncio import omni.kit.test import omni.client from unittest.mock import patch, Mock from .. import get_nucleus_connector from ..test_helper import NucleusConnectorTestHelper class TestAddServerWithValidation(omni.kit.test.AsyncTestCase): """Testing FilePickerView.add_server_with_validation""" async def setUp(self): self._test_name = "ov-test" self._test_url = "omniverse://ov-test" self._expected_stat_results = [omni.client.Result.OK, omni.client.Result.OK] self._stat_latency = 1 self._iter = 0 async def tearDown(self): pass async def _mock_stat_async_impl(self, url: str): # During a stat, omni.client triggers the browser sign in flow by executing the _on_authenticate callback. # The callback was previously set via the subscription method: omni.client.set_authentication_message_box_callback. if self._iter == 0: ext = get_nucleus_connector() if ext: ext._on_authenticate(True, url, 1) result = self._expected_stat_results[self._iter] self._iter += 1 # Simulates the latency due to user signing in through brower await asyncio.sleep(self._stat_latency) return result, {} def _mock_auth_cancel_impl(self, auth_handle: int): # A cancellation event also executes the _on_authenticate callback, but with the first input set to False. ext = get_nucleus_connector() if ext: ext._on_authenticate(False, None, auth_handle) async def test_connect_with_dialog_succeeds(self): """Testing that connecting to server through dialog succeeds""" under_test = get_nucleus_connector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) await connector_helper.wait_for_close(timeout=1000) # Confirm on_success callback called mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_with_given_url_succeeds(self): under_test = get_nucleus_connector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() # Note that it's not necessary to click the apply button; the dialog automatically proceeds to make the # connection, using the given server name and url. await connector_helper.wait_for_close(timeout=1000) # Confirm on_success callback called mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_with_dialog_cancelled(self): """Testing that user is able to cancel out of connection flow""" under_test = get_nucleus_connector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.authentication_cancel", side_effect=self._mock_auth_cancel_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) # Click cancel after some time await asyncio.sleep(.5*self._stat_latency) await connector_helper.click_cancel_async() await connector_helper.wait_for_close(timeout=1000) # Confirm neither callbacks invoked mock_success_fn.assert_not_called() mock_failed_fn.assert_not_called() async def test_connect_then_reconnect_succeeds(self): """Testing that when connect fails the first time, retries with a reconnect""" under_test = get_nucleus_connector() # In this case, the first stat will result in an error, but will succeed after a reconnect self._expected_stat_results = [omni.client.Result.ERROR_CONNECTION, omni.client.Result.OK] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) await connector_helper.wait_for_close(timeout=1000) # Confirm reconnect attempted and connection succeeded mock_reconnect.assert_called_once_with(self._test_url) mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_and_reconnect_fails(self): """Testing that both the connect and reconnect attempts fail""" under_test = get_nucleus_connector() # In this case, the first stat will result in an error, but will succeed after a reconnect self._expected_stat_results = [omni.client.Result.ERROR_CONNECTION, omni.client.Result.ERROR_CONNECTION] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) # Cancel to close the dialog after some time await asyncio.sleep(2.5*self._stat_latency) await connector_helper.click_cancel_async() await connector_helper.wait_for_close(timeout=1000) # Confirm reconnect attempted and connection succeeded mock_reconnect.assert_called_once_with(self._test_url) mock_failed_fn.assert_called_once_with(self._test_name, self._test_url) mock_success_fn.assert_not_called() async def test_reconnect_with_given_url_succeeds(self): under_test = get_nucleus_connector() self._expected_stat_results = [omni.client.Result.OK] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.reconnect(self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) for _ in range(100): dialog = connector_helper.get_connector_dialog() if dialog and dialog.visible: break await omni.kit.app.get_app().next_update_async() await connector_helper.wait_for_close(timeout=1000) # Confirm on_success callback called mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() mock_reconnect.assert_called_once_with(self._test_url)
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.3] - 2023-02-17 ### Added - Adds authentication mode to ConnectorDialog, shows a simplified UI with only login info and cancel button - Connecting to named server/reconnect/auth will now use authentication mode of ConnectorDialog ## [1.0.2] - 2022-12-08 ### Added - No longer cancels unaccounted authentication - Emits event upon successful connection ## [1.0.1] - 2022-09-23 ### Added - Fixes hang on browser login page. ## [1.0.0] - 2022-07-20 ### Added - Initial commit to master.
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/docs/index.rst
omni.kit.widget.nucleus_connector ################################# A helper extension for connecting to the Nucleus server. .. toctree:: :maxdepth: 1 CHANGELOG .. automodule:: omni.kit.widget.nucleus_connector :platform: Windows-x86_64, Linux-x86_64 :members: :show-inheritance: :undoc-members: .. autoclass:: NucleusConnectorExtension :members:
omniverse-code/kit/exts/omni.graph.expression/PACKAGE-LICENSES/omni.graph.expression-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.graph.expression/config/extension.toml
[package] title = "OmniGraph Expression Node" version = "1.1.2" category = "Graph" keywords = ["omnigraph", "expression"] # Main module for the Python interface [[python.module]] name = "omni.graph.expression" # Other extensions that need to load in order for this one to work [dependencies] "omni.graph" = {} "omni.graph.tools" = {} "omni.kit.pipapi" = {} # numpy might be used by the expressions [python.pipapi] requirements = ["numpy"] # SWIPAT filed under: http://nvbugs/3193231 [[native.plugin]] path = "bin/*.plugin" recursive = false [[test]] waiver = "Extension will be deprecated soon" [documentation] deps = [ ["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph refs until that workflow is moved ] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/__init__.py
"""There is no public API to this module.""" __all__ = [] from ._impl.extension import _PublicExtension # noqa: F401 import omni.graph.tools as ogt ogt.DeprecatedImport("Use the omni.graph.scriptnode extension instead")
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/_impl/extension.py
"""Support required by the Carbonite extension loader.""" import omni.ext # binding for C++ plugin interface from ..bindings._omni_graph_expression import acquire_interface as _acquire_interface # noqa: PLE0402 from ..bindings._omni_graph_expression import release_interface as _release_interface # noqa: PLE0402 # python scripted node from ..nodes.OgnExpression import OgnExpression as _OgnExpression # noqa: PLE0402 class _PublicExtension(omni.ext.IExt): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__interface = None def on_startup(self): self.__interface = _acquire_interface() def on_shutdown(self): if self.__interface is not None: _release_interface(self.__interface) self.__interface = None _OgnExpression.on_shutdown()
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/nodes/OgnExpression.py
import asteval import carb import carb.settings import numpy as np import omni.graph.core as cg import omni.kit.pipapi import omni.stageupdate from pxr import Sdf __IMPORT_WHITELIST__ = ["torch", "carb"] def do_import(module, as_name=""): if not as_name: as_name = module as_name = as_name[as_name.rfind(".") + 1 :] if not module.startswith("omni."): exec( # noqa: PLW0122 f""" try: globals()["{as_name}"] = __import__("{module}") except ImportError: print("{module} not found. attempting to install...") omni.kit.pipapi.install("{module}") globals()["{as_name}"] = __import__("{module}") """ ) return as_name, globals()[as_name] def filter_import_list(modules): out = [] for m in modules: if m not in __IMPORT_WHITELIST__: carb.log_warn(f"OgnExpression: import of {m} is not allowed") else: out.append(m) return out __expr_cache__ = {} __stage_subscription__ = None # dummy class for attribute placeholder class Attrs: def __init__(self): return class ExprCache: def __init__(self, node): global __stage_subscription__ self.node = node if not __stage_subscription__: stage_update = omni.stageupdate.get_stage_update_interface() __stage_subscription__ = stage_update.create_stage_update_node( "OgnExpression", None, OgnExpression.on_detach, None, None, None, OgnExpression.on_removed ) self.symTable = asteval.make_symbol_table(use_numpy=False, np=np) self.symTable["inputs"] = Attrs() # self.symTable["outputs"] = Attrs() self.eval = asteval.Interpreter(symtable=self.symTable) @staticmethod def get(node): pp = Sdf.Path(node.get_prim_path()) if pp not in __expr_cache__: return None return __expr_cache__[pp] @staticmethod def clear(prim): if prim in __expr_cache__: # print("clear cache",prim) c = __expr_cache__[prim] c._stage_subscription = None # noqa: PLW0212 del __expr_cache__[prim] @staticmethod def init(node): pp = Sdf.Path(node.get_prim_path()) cache = ExprCache(node) __expr_cache__[pp] = cache return cache class OgnExpression: """Implementation of the OmniGraph expression node""" @staticmethod def get_node_type(): return "Expression" @staticmethod def get_upstream_attr_or_self(attr): """Returns the list of attributes upstream from the given one, or itself if there is nothing upstream""" attributes_upstream = attr.get_upstream_connections() return attributes_upstream if attributes_upstream else [attr] @staticmethod def compute(context, node): # if not carb.settings.get_settings().get("/persistent/omnigraph/allowExprNodeExe"): # return True need_init = False _cache = ExprCache.get(node) if not _cache: # print("initCache", Sdf.Path(node.get_prim_path())) _cache = ExprCache.init(node) if node.get_attribute_exists("import"): # print("import", Sdf.Path(node.get_prim_path())) import_list = OgnExpression.get_upstream_attr_or_self(node.get_attribute("import")) import_list = [m.strip() for m in context.get_attr_value(import_list).split(",") if len(m.strip())] for m in import_list: try: as_name, module = do_import(m) _cache.symTable[as_name] = module except (ImportError, KeyError, NameError): carb.log_error("OgnExpression: failed importing " + m) continue need_init = True attr_names = [n.get_name() for n in node.get_attributes()] in_attr_names = [a for a in attr_names if a.startswith("inputs:")] for ia in in_attr_names: attr = OgnExpression.get_upstream_attr_or_self(node.get_attribute(ia)) setattr(_cache.symTable["inputs"], ia.split(":")[-1], context.get_attr_value(attr)) out_attrs = Attrs() _cache.symTable["outputs"] = out_attrs # for oa in out_attr_names: # attr = OgnExpression.get_upstream_attr_or_self(node.get_attribute(oa)) # setattr(_cache.symTable["outputs"], oa.split(":")[-1], context.get_attr_value(attr)) if need_init and node.get_attribute_exists("initExpr"): init_expr = OgnExpression.get_upstream_attr_or_self(node.get_attribute("initExpr")) init_expr = context.get_attr_value(init_expr) _cache.eval(init_expr) # exec(init_expr) expr = OgnExpression.get_upstream_attr_or_self(node.get_attribute("updateExpr")) expr = context.get_attr_value(expr) _cache.eval(expr) # exec(expr) # lazy update of output values cach_out_attrs_dict = out_attrs.__dict__ out_attr_names = [a for a in attr_names if a.startswith("outputs:")] for out_attr_name in out_attr_names: attr_short_name = out_attr_name[8:] # without "outputs:" prefix if attr_short_name in cach_out_attrs_dict: cache_out_attr_val = cach_out_attrs_dict[attr_short_name] attr = OgnExpression.get_upstream_attr_or_self(node.get_attribute(out_attr_name)) # print("!", out_attr_name, len(cache_out_attr_val), cache_out_attr_val[0]) context.set_attr_value(cache_out_attr_val, attr) return True @staticmethod def on_shutdown(): global __stage_subscription__ __stage_subscription__ = None @staticmethod def on_detach(): global __expr_cache__, __stage_subscription__ __expr_cache__ = {} __stage_subscription__ = None @staticmethod def on_removed(prim): ExprCache.clear(prim) cg.register_node_type(OgnExpression, 1)
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.expression as oge from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphExpressionApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "nodes", "tests"] async def test_api(self): _check_module_api_consistency(oge, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(oge.tests, [], is_test_module=True) # noqa: PLW0212 async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents(oge, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212 _check_public_api_contents(oge.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/tests/__init__.py
"""There is no public API to this module.""" __all__ = [] scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/PACKAGE-LICENSES/omni.kit.widget.searchable_combobox-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.4" #Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Searchable ComboBox" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "ui", "combobox", "search"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" category = "developer" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" description = "Searchable ComboBox Widget" readme = "docs/README.md" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} # Main module of the python interface [[python.module]] name = "omni.kit.widget.searchable_combobox" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.ui_test", "omni.kit.renderer.core", "omni.kit.renderer.capture", "omni.kit.mainwindow", ]
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/combo_model.py
import omni.ui as ui import omni.kit.app class ComboBoxListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) # True when the item is visible self.filtered = True def prefilter(self, filter_name_text: str): if not filter_name_text: self.filtered = True else: self.filtered = filter_name_text in self.name_model.as_string.lower() def __repr__(self): return f'"{self.name_model.as_string}"' class ComboBoxListModel(ui.AbstractItemModel): _instance = None def __init__(self, item_list): super().__init__() self._children = [ComboBoxListItem(item) for item in item_list] global _instance _instance = self def clean(self): global _instance _instance = None def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: return [] return [c for c in self._children if c.filtered] def get_item_value_model_count(self, item): """The number of columns""" return 1 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 get_item_value_model(self, item, column_id): return item.name_model def filter_by_text(self, filter_name_text: str): """Specify the filter string that is used to reduce the model""" for c in self._children: c.prefilter(filter_name_text.lower()) self._item_changed(None) def get_index_for_item(self, item_text: str): for index, item in enumerate(self._children): if item.name_model.get_value_as_string() == item_text: return index return -1 class ComboBoxListDelegate(ui.AbstractItemDelegate): """ Delegate is the representation layer. TreeView calls the methods of the delegate to create custom widgets for each item. """ def __init__(self, flat=False): super().__init__() def clean(self): 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): ui.Label( model.get_item_value_model(item, column_id).as_string, skip_draw_when_clipped=True, elided_text=True, height=18, )
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/search_widget.py
import asyncio import omni.kit.app import omni.ui as ui from enum import IntFlag class SearchModel(ui.AbstractValueModel): def __init__(self, modified_fn): super().__init__() self._modified_fn = modified_fn self.__str = "" def is_in_string(self, string: str): if self.__str == "": return True return self.__str.upper() in string.upper() def set_value(self, value): self.__str = str(value) self._value_changed() if self._modified_fn: self._modified_fn(self.__str) def get_value_as_string(self): return self.__str class SearchWidget: def __init__(self, theme: str, icon_path: str, modified_fn: callable = None): self._search_model = SearchModel(modified_fn=modified_fn) if not icon_path: icon_path = ( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons" ) if theme == "NvidiaDark": SEARCH_BODY_COLOR = 0xFF2D2D2D SEARCH_PLACEHOLDER = 0xFF666666 BUTTON_BACKGROUND_COLOR = 0xFF323434 COMBO_BACKGROUND_COLOR = 0xFF92929 GENERAL_BACKGROUND_COLOR = 0xFF24211F else: SEARCH_BODY_COLOR = 0xFF2D2D2D SEARCH_PLACEHOLDER = 0xFF666666 BUTTON_BACKGROUND_COLOR = 0xFF545454 COMBO_BACKGROUND_COLOR = 0xFF545454 GENERAL_BACKGROUND_COLOR = 0xFF545454 self._style = { # search_button "Button.Image::search_button": { "image_url": f"{icon_path}/search.svg", "background_color": SEARCH_BODY_COLOR, "margin": 0, }, "Button::search_button": {"margin": 0}, "Field::search_button": {"background_color": SEARCH_BODY_COLOR}, "Field::search_button:hovered": {"background_color": SEARCH_BODY_COLOR}, # search placeholder "Label::search_placeholder": {"color": SEARCH_PLACEHOLDER}, # remove button "Button.Image::remove": {"image_url": f"{icon_path}/remove.svg"}, "Button.Image::remove:hovered": {"image_url": f"{icon_path}/remove-hovered.svg"}, "Button::remove": {"background_color": SEARCH_BODY_COLOR, "margin": 0}, "Button::remove:hovered": {"background_color": SEARCH_BODY_COLOR, "margin": 0}, # remove button popup (different colors) "Button::remove_popup": {"background_color": GENERAL_BACKGROUND_COLOR, "margin": 0}, "Button::remove_popup:hovered": {"background_color": GENERAL_BACKGROUND_COLOR, "margin": 0}, "Button.Image::remove_popup": {"image_url": f"{icon_path}/remove.svg"}, "Button.Image::remove_popup:hovered": {"image_url": f"{icon_path}/remove-hovered.svg"}, # find button "Button::find": {"background_color": BUTTON_BACKGROUND_COLOR}, "Button.Image::find": {"image_url": f"{icon_path}/find.svg"}, # listbox button "Button.Image::listbox": {"image_url": f"{icon_path}/listbox.svg"}, "Button::listbox": {"background_color": COMBO_BACKGROUND_COLOR, "padding": 6, "margin": 0}, } def clean(self): self._field = None self._search_field = None self._search_clear = None self._update_fn = None def destroy(self): self._field = None self._search_field = None self._search_clear = None self._update_fn = None del self._search_model def update(self, string): self._placeholder.visible = bool(string == "") self._search_clear.enabled = not self._placeholder.visible def focus(self): async def focus(field): await omni.kit.app.get_app().next_update_async() field.focus_keyboard() asyncio.ensure_future(focus(self._field)) def build_ui(self, width, search_size): def clear_name(field): field.model.set_value("") field.focus_keyboard() with ui.HStack(width=0, height=0, style=self._style): ui.Button("", width=search_size, height=search_size, enabled=False, name="search_button") with ui.ZStack(width=0, height=0): with ui.HStack(width=0, height=0): field = ui.StringField( model=self._search_model, width=width - 46, height=search_size, name="search_button" ) self._search_clear = ui.Button( "", width=search_size, height=search_size, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, enabled=False, clicked_fn=lambda f=field: clear_name(f), name="remove", ) self._placeholder = ui.Label(" Search....", height=search_size, name="search_placeholder") self._field = field self.focus() def set_placeholder_text(self, msg: str): self._placeholder.text = f" {msg}...." enabled = bool(msg == "Search") self._field.enabled = enabled self._field.focus_keyboard(enabled) def set_text(self, new_text: str): changed = bool(self._search_field.model.get_value_as_string() != new_text) self._search_field.model.set_value(new_text) if changed and self._update_fn: self._update_fn(self._search_field.model) def get_text(self): return self._search_field.model.get_value_as_string() def build_ui_popup(self, search_size: float, default_value: str, popup_text: str, index: int, update_fn: callable): def clear_name(name_field): name_field.model.set_value(default_value) if update_fn: update_fn(name_field.model) self._update_fn = update_fn open_button = None name_field = None with omni.ui.VStack(height=0, spacing=0, style={"margin_width": 0}): with ui.HStack(style=self._style): name_field = ui.StringField(height=search_size, enabled=False) name_field.model.set_value(popup_text) ui.Button( "", width=20, height=20, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, clicked_fn=lambda f=name_field: clear_name(f), name="remove_popup", ) open_button = ui.Button("", width=20, height=20, image_width=8, name="listbox") self._search_field = name_field return name_field, open_button
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/__init__.py
from .search_widget import SearchModel, SearchWidget from .combo_model import ComboBoxListItem, ComboBoxListModel, ComboBoxListDelegate from .combo_widget import ComboListBoxWidget, build_searchable_combo_widget
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/combo_widget.py
import asyncio import carb.input import omni.kit.app import omni.appwindow import omni.ui as ui from typing import List from .combo_model import ComboBoxListModel, ComboBoxListDelegate from .search_widget import SearchWidget class ComboListBoxWidget: def __init__( self, search_widget: SearchWidget, item_list: list, theme: str, window_id: str = "SearchableComboBoxWindow", delegate: ui.AbstractItemDelegate = ComboBoxListDelegate(), ): icon_path = ( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons" ) self._height = 32 self._theme = theme self.__parent = None self._window = None self.__frame = None self._placeholder_search_widget = search_widget self._search_widget = SearchWidget(theme=theme, icon_path=icon_path, modified_fn=self._search_updated) self._search_size = 22 self._window_id = window_id self._name_value_model = ComboBoxListModel(item_list) self._name_value_delegate = delegate if theme == "NvidiaDark": BACKGROUND_COLOR = 0xFF3D3B38 FIELD_TEXT_COLOR = 0xFFD5D5D5 FIELD_BORDER_COLOR = 0 FIELD_HOVER_COLOR = 0xFF383838 else: BACKGROUND_COLOR = 0xFF545454 FIELD_TEXT_COLOR = 0xFFD5D5D5 FIELD_BORDER_COLOR = 0 FIELD_HOVER_COLOR = 0xFFACACAF self._window_style = { "Window": { "background_color": BACKGROUND_COLOR, "border_radius": 6, "border_width": 1, "border_color": FIELD_BORDER_COLOR, }, "ScrollingFrame": {"background_color": BACKGROUND_COLOR}, "Field": { "background_color": BACKGROUND_COLOR, "color": FIELD_TEXT_COLOR, "border_color": FIELD_BORDER_COLOR, "border_radius": 1, "border_width": 0.5, "font_size": 16.0, }, "Field:hovered": {"background_color": FIELD_HOVER_COLOR}, "Field:pressed": {"background_color": FIELD_HOVER_COLOR}, "Field::text_field": {"border_width": 0, "font_size": 14.0}, # search "TreeView.Item::search_view": {"margin": 4}, "TreeView:selected": {"background_color": 0xFF333333}, } def set_parent(self, parent): self.__parent = parent def clean(self): if self._name_value_model: self._name_value_model.clean() if self._name_value_delegate: self._name_value_delegate.clean() if self._search_widget: self._search_widget.clean() del self._name_value_model del self._name_value_delegate self._placeholder_search_widget = None self._scrolling_frame = None self._combo_view = None del self._window def _search_updated(self, string): self._search_widget.update(string) self._name_value_model.filter_by_text(string) self._combo_view.scroll_here_y(0.0) def _select_next(self, comboview: ui.TreeView, model: ui.AbstractItemModel, after=True): full_list = model.get_item_children(None) selection = comboview.selection if not selection: comboview.selection = [full_list[0]] else: index = full_list.index(selection[0]) index += 1 if after else -1 if index < 0 or index >= len(full_list): return comboview.selection = [full_list[index]] def _select_index(self, comboview: ui.TreeView, model: ui.AbstractItemModel, index: int): full_list = model.get_item_children(None) selection = comboview.selection if index >= 0 and index < len(full_list): comboview.selection = [full_list[index]] def _get_view_height(self): item_count = len(self._name_value_model.get_item_children(None)) view_height = (min(10, item_count) * self._height + 1.5) + 4 view_height_min = (3 * self._height + 1.5) + 4 try: appwindow = omni.appwindow.get_default_app_window() window_height = appwindow.get_height() window_height = (window_height / ui.Workspace.get_dpi_scale()) - 8 if self._window.position_y + view_height > window_height: adj = ((self._window.position_y + view_height) - window_height) + self._search_size view_height -= adj if view_height < view_height_min: view_height = view_height_min except: pass return view_height def destroy_ui(self, visible): if not visible: self.set_parent(None) self.clean() def build_ui(self): if self._window and self._window.visible: return # Create and show the window self._window = ui.Window( self._window_id, flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE, auto_resize=True, padding_x=0, padding_y=0, ) self._window.frame.set_style(self._window_style) self._window.set_visibility_changed_fn(self.destroy_ui) def view_clicked(view): async def get_selection(): await omni.kit.app.get_app().next_update_async() selection = view.selection model = selection[0].name_model self._placeholder_search_widget.set_text(model.get_value_as_string()) self._window.visible = False asyncio.ensure_future(get_selection()) self._window.position_x = self.__parent.screen_position_x self._window.position_y = self.__parent.screen_position_y + 20 with self._window.frame: with ui.VStack(width=0, height=0): self._search_widget.build_ui(self.__parent.computed_content_width + 40, self._search_size) self._scrolling_frame = ui.ScrollingFrame( height=self._get_view_height(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with self._scrolling_frame: self._combo_view = ui.TreeView( self._name_value_model, delegate=self._name_value_delegate, root_visible=False, header_visible=False, name="search_view", ) self._combo_view.set_mouse_released_fn(lambda x, y, b, c: view_clicked(self._combo_view)) async def scroll_to_item(): await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() item_index = self._name_value_model.get_index_for_item(self._placeholder_search_widget.get_text()) self._select_index(self._combo_view, self._name_value_model, item_index) asyncio.ensure_future(scroll_to_item()) def destroy(self): self.__parent = None self.__frame = None self._scrolling_frame = None self._combo_view = None del self._window def build_searchable_combo_widget( combo_list: List[str], combo_index: int, combo_click_fn: callable, widget_height: int, default_value: str, window_id: str = "SearchableComboBoxWindow", delegate: ui.AbstractItemDelegate = ComboBoxListDelegate(), ) -> SearchWidget: theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" def show_combo_popup( search_widget: SearchWidget, name_field: ui.StringField, combo_index: int, combo_click_fn: callable ): window = ui.Workspace.get_window(window_id) if window: window.visible = False return listbox_widget = ComboListBoxWidget( search_widget=search_widget, item_list=combo_list, window_id=window_id, delegate=delegate, theme=theme ) listbox_widget.set_parent(name_field) listbox_widget.build_ui() search_widget = SearchWidget(theme=theme, icon_path=None) name_field, listbox_button = search_widget.build_ui_popup( search_size=widget_height, default_value=default_value, popup_text=combo_list[combo_index] if combo_index >= 0 else default_value, index=combo_index, update_fn=combo_click_fn, ) name_field.set_mouse_pressed_fn( lambda x, y, b, m, s=search_widget, f=name_field: show_combo_popup(s, f, combo_index, combo_click_fn) ) listbox_button.set_mouse_pressed_fn( lambda x, y, b, m, s=search_widget, f=name_field: show_combo_popup(s, f, combo_index, combo_click_fn) ) return search_widget
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/tests/__init__.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. # from .test_search import *
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/tests/test_search.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import pathlib import carb import omni.ui as ui from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.widget.searchable_combobox import build_searchable_combo_widget, ComboBoxListDelegate class TestSearchableComboWidget(AsyncTestCase): async def test_searchable_combo_widget(self): delegate_called = False class TestDelegate(ComboBoxListDelegate): def build_widget(self, model, item, column_id, level, expanded): nonlocal delegate_called delegate_called = True ui.Label( model.get_item_value_model(item, column_id).as_string, skip_draw_when_clipped=True, elided_text=True, height=18, ) callback_calls = 0 callback_value = None window = ui.Window("WidgetTest", width=1000, height=700) with window.frame: with ui.VStack(height=0, spacing=8, style={"margin_width": 2}): ui.Spacer() with ui.HStack(): ui.Label("Component", width=140) def on_combo_click_fn(model): nonlocal callback_calls callback_calls += 1 self.assertTrue(model.get_value_as_string() == callback_value) component_list = [ "3d Reconstruction", "AEC Experience", "AI Framework", "AI Toybox", "AR Experience", "ArtTech", "Asset Converter Service", "Asset Management", "Physics Research", "PhysX Third Party Integrations", "Pinocchio", "PLC", "Point Clouds", "Pose Tracker", "QA Builds", "QA Needs Repro", "Repo Tools", "Reshade", "Resolvers", "RTX", "RTX Hydra", "RTX MGPU", "RTX Renderer", "Sample Content", "SDG", "Sequencer", "Server Installer", "Showroom", "Synthetic Data", "USD", "USD Delta Library", "USD Hydra", "Kit", "USDRT", "UX", "UX / UI", "Virtual Production", "XR", ] component_index = -1 component_combo = build_searchable_combo_widget( component_list, component_index, on_combo_click_fn, widget_height=18, default_value="Kit", window_id="SearchableComboBoxWindow##test_searchable_combo_widget", delegate=TestDelegate(), ) # test set_text & get_text await ui_test.human_delay() callback_value = "USD" component_combo.set_text("USD") await ui_test.human_delay() self.assertTrue(component_combo.get_text() == "USD") self.assertTrue(callback_calls == 1) # test clear & default clear_widget = ui_test.find("WidgetTest//Frame/**/Button[*].name=='remove_popup'") callback_value = "Kit" await clear_widget.click() self.assertTrue(component_combo.get_text() == "Kit") self.assertTrue(callback_calls == 2) # test combo open and typing text_field = ui_test.find("WidgetTest//Frame/**/StringField[*]") await text_field.click() # TODO: text_field.input("ArtTech") don't work here as it does a double_click await ui_test.emulate_char_press("ArtTech") await ui_test.human_delay() treeview_widget = ui_test.find("SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/TreeView[*]") callback_value = "ArtTech" # y+8 to make sure mouse pointer is on popup window (combobox item list), so 1st item is selected await ui_test.emulate_mouse_move_and_click( ui_test.Vec2(treeview_widget.center.x, treeview_widget.widget.screen_position_y + 8) ) self.assertTrue(component_combo.get_text() == callback_value) self.assertTrue(callback_calls == 3) # holding onto this varaible prevents ComboListBoxWidget from getting garbage collected. treeview_widget = None # test combo open button and typing open_widget = ui_test.find("WidgetTest//Frame/**/Button[*].name=='listbox'") await open_widget.click() # as this opens popup window, need to wait for that to be created and ready to use await ui_test.human_delay() await ui_test.emulate_char_press("Pinocchio") treeview_widget = ui_test.find("SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/TreeView[*]") callback_value = "Pinocchio" # y+8 to make sure mouse pointer is on popup window (combobox item list), so 1st item is selected await ui_test.emulate_mouse_move_and_click( ui_test.Vec2(treeview_widget.center.x, treeview_widget.widget.screen_position_y + 8) ) self.assertTrue(component_combo.get_text() == callback_value) self.assertTrue(callback_calls == 4) # holding onto this varaible prevents ComboListBoxWidget from getting garbage collected. treeview_widget = None # test search clear await text_field.click() await ui_test.emulate_char_press("this will be cleared...") await ui_test.human_delay() clear_widget = ui_test.find( "SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/Button[*].name=='remove'" ) await clear_widget.click() await ui_test.emulate_char_press("Asset Converter Service") treeview_widget = ui_test.find("SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/TreeView[*]") callback_value = "Asset Converter Service" await ui_test.emulate_mouse_move_and_click( ui_test.Vec2(treeview_widget.center.x, treeview_widget.widget.screen_position_y + 8) ) self.assertTrue(component_combo.get_text() == "Asset Converter Service") self.assertTrue(callback_calls == 5) # holding onto this varaible prevents ComboListBoxWidget from getting garbage collected. treeview_widget = None # test delegate was called self.assertTrue(delegate_called)
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.5] - 2022-05-18 + Moved to kit ## [1.0.4] - 2021-11-26 + Fixed test using input ## [1.0.3] - 2021-11-26 + Updated to use omni.kit.ui_test ## [1.0.2] - 2021-11-09 + ETM Fix ## [1.0.1] - 2021-10-25 + Removed omni.usd dependancy ## [1.0.0] - 2021-10-12 + Created
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/docs/README.md
# Searchable ComboBox widget To use: ``` from omni.kit.widget.searchable_combobox import build_searchable_combo_widget def on_combo_click_fn(model): component = model.get_value_as_string() print(f"{component} selected") component_list = ['3d Reconstruction', 'AEC Experience', 'AI Framework', 'AI Toybox', 'AR Experience', 'ArtTech', 'Asset Converter Service', 'Asset Management', 'Physics Research', 'PhysX Third Party Integrations', 'Pinocchio', 'PLC', 'Point Clouds', 'Pose Tracker', 'QA Builds', 'QA Needs Repro', 'Repo Tools', 'Reshade', 'Resolvers', 'RTX', 'RTX Hydra', 'RTX MGPU', 'RTX Renderer', 'Sample Content', 'SDG', 'Sequencer', 'Server Installer', 'Showroom', 'Synthetic Data', 'USD', 'USD Delta Library', 'USD Hydra', 'Kit', 'USDRT', 'UX', 'UX / UI', 'Virtual Production', 'XR'] component_index = -1 self._component_combo = build_searchable_combo_widget(component_list, component_index, on_combo_click_fn, widget_height=18, default_value="Kit") ``` Get combo widget value: ``` component_name = self._component_combo.get_text() ``` Set combo widget value: ``` self._component_combo.set_text("Showroom") ``` Cleanup: ``` self._component_combo.destroy() self._component_combo = None ```
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/docs/index.rst
omni.kit.widget.searchable_combobox ################################### Extension provides combobox widget with search functionality. .. toctree:: :maxdepth: 1 CHANGELOG.md
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/camera_widget_delegate_manager.py
from .abstract_camera_widget_delegate import AbstractCameraButtonDelegate, AbstractCameraMenuItemDelegate from pxr import Sdf class CameraWidgetDelegateManager: def destroy(self): for delegate in AbstractCameraButtonDelegate.get_instances(): delegate.destroy() for delegate in AbstractCameraMenuItemDelegate.get_instances(): delegate.destroy() def __get_all_delegates(self, camera_button_or_menu_item: bool): all_widget_delegates = [] if camera_button_or_menu_item: for delegate in AbstractCameraButtonDelegate.get_instances(): all_widget_delegates.append(delegate) else: for delegate in AbstractCameraMenuItemDelegate.get_instances(): all_widget_delegates.append(delegate) # Sort list in ascending order. all_widget_delegates.sort(key=lambda item: item.order) return all_widget_delegates def build_widgets( self, parent_id, viewport_api, camera_path: Sdf.Path, camera_button_or_menu_item: bool ): """Build all camera widgets for specific camera path with sort based on their orders.""" all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.build_widget(parent_id, viewport_api, camera_path) def on_parent_destroyed(self, parent_id, camera_button_or_menu_item: bool) -> None: # Clean up when parent widget destroyed all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.on_parent_destroyed(parent_id) def on_camera_path_changed(self, parent_id, camera_path, camera_button_or_menu_item: bool): """The camera tracked has changed.""" all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.on_camera_path_changed(parent_id, camera_path)
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/camera_list_delegate.py
__all__ = ["CameraListDelegate"] import carb import omni.usd import omni.ui as ui from typing import Optional from omni.kit.viewport.menubar.core import IconMenuDelegate, USDAttributeModel from pxr import Sdf from .camera_widget_delegate_manager import CameraWidgetDelegateManager class CameraListDelegate(IconMenuDelegate): def __init__(self, viewport_api, widget_delegate_manager: CameraWidgetDelegateManager): self.__model: Optional[USDAttributeModel] = None self.__sub = None self.__viewport_api = viewport_api self.__selected_camera_path = Sdf.Path.emptyPath self.__widget_delegate_manager = widget_delegate_manager super().__init__("UnlockedCamera", text=True, build_custom_widgets=self.__build_custom_widgets) def destroy(self): self.__sub = None if self.__widget_delegate_manager: self.__widget_delegate_manager.on_parent_destroyed(id(self), True) self.__widget_delegate_manager = None super().destroy() def __build_custom_widgets(self, item: ui.MenuItem): if not self.__widget_delegate_manager: return try: self.__widget_delegate_manager.build_widgets( id(self), self.__viewport_api, self.__selected_camera_path, True ) except Exception as e: carb.log_error(f"Failed to build widget: {str(e)}") def _build_icon(self): # with vstack to not trigger menu if click on icon if self._text: with ui.VStack(content_clipping=True, width=0): icon = super()._build_icon() icon.set_mouse_pressed_fn(lambda x, y, b, a: self.__toggle_lock()) else: icon = super()._build_icon() icon.name = self.__get_icon_name() return icon @property def camera_path(self) -> Sdf.Path: return self.__selected_camera_path @camera_path.setter def camera_path(self, path): self.__selected_camera_path = path if self.__widget_delegate_manager: self.__widget_delegate_manager.on_camera_path_changed(id(self), path, True) @property def model(self) -> USDAttributeModel: return self.__model @model.setter def model(self, new_model: USDAttributeModel) -> None: self.__model = new_model icon_name = self.__get_icon_name() if hasattr(self, "icon"): self.icon.name = icon_name else: self._name = icon_name if self.__sub: self.__sub = None if self.__model: self.__sub = self.__model.subscribe_value_changed_fn(self._on_lock_changed) def __get_icon_name(self): if not self.__model: return "UnlockedCameraWithoutHovered" hov_text = "" if bool(self._text) else "WithoutHovered" lock_text = "LockedCamera" if self.__model.as_bool else "UnlockedCamera" return f"{lock_text}{hov_text}" def _on_lock_changed(self, model: ui.AbstractValueModel) -> None: icon_name = self.__get_icon_name() if hasattr(self, "icon"): self.icon.name = icon_name else: self._name = icon_name def __toggle_lock(self): if self.__model: self.__model.set_value(not self.__model.as_bool)
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/style.py
from omni.ui import color as cl import carb.tokens from pathlib import Path ICON_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.camera}")).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::UnlockedCamera": {"image_url": f"{ICON_PATH}/camera_viewport.svg"}, "Menu.Item.Icon::UnlockedCameraWithoutHovered": {"image_url": f"{ICON_PATH}/camera_viewport.svg"}, "Menu.Item.Icon::UnlockedCamera:hovered": {"image_url": f"{ICON_PATH}/lock_dark.svg"}, "Menu.Item.Icon::LockedCamera": {"image_url": f"{ICON_PATH}/viewport_cameras_locked.svg"}, "Menu.Item.Icon::LockedCameraWithoutHovered": {"image_url": f"{ICON_PATH}/viewport_cameras_locked.svg"}, "Menu.Item.Icon::LockedCamera:hovered": {"image_url": f"{ICON_PATH}/unlock_dark.svg"}, "Menu.Item.Icon::Expand": {"image_url": f"{ICON_PATH}/expand.svg", "color": cl.viewport_menubar_background}, "Menu.Item.Icon::Expand:checked": {"image_url": f"{ICON_PATH}/contract.svg"}, "Menu.Item.Icon::Lock": {"image_url": f"{ICON_PATH}/unlock_dark.svg", "color": cl.viewport_menubar_background}, "Menu.Item.Icon::Lock:checked": {"image_url": f"{ICON_PATH}/lock_dark.svg"}, "Menu.Item.Icon::Sample": {"image_url": f"{ICON_PATH}/focalSample_viewport.svg"}, "Menu.Item.Icon::Sample:disabled": {"color": cl.viewport_menubar_medium}, "Menu.Item.Icon::Add": {"image_url": f"{ICON_PATH}/add.svg", "color": cl.viewport_menubar_selection_border}, "Menu.Item.Icon::Lens": {"image_url": f"{ICON_PATH}/lens.svg"}, "Menu.Item.Icon::FocalDistance": {"image_url": f"{ICON_PATH}/focal_distance.svg"}, "Menu.Item.Icon::FStop": {"image_url": f"{ICON_PATH}/Fstop.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"}, "Menu.Item.Button.Image::CameraLocked": {"image_url": f"{ICON_PATH}/lock_dark.svg"}, "Menu.Item.Button.Image::CameraUnlocked": {"image_url": f"{ICON_PATH}/unlock_dark.svg"}, "MenuBar.Item::transparent": { # "color": 0, }, }
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/commands.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.kit.commands import omni.usd from pxr import Gf, Sdf, Usd, UsdGeom from typing import Union import carb CAMERA_LOCK_NAME = "omni:kit:cameraLock" class DuplicateCameraCommand(omni.kit.commands.Command): """ Duplicates a camera at a specific time Args: camera_path (str): name of the camera to duplicate. time (float): Time at which to duplicate, or None to use active time usd_context_name (str): The name of a valid omni.UsdContext to target new_camera_path (str): Path to create the new camera at (None for automatic path) """ def __init__(self, camera_path: str = "", time: float = None, usd_context_name: str = '', new_camera_path: str = None): self.__camera_path = camera_path self.__usd_context_name = usd_context_name self.__time = time if time is not None else omni.timeline.get_timeline_interface().get_current_time() self.__new_camera_path = new_camera_path def do(self): if not self.__camera_path: return usd_context = omni.usd.get_context(self.__usd_context_name) if not usd_context: raise RuntimeError(f'UsdContext "{self.self.__usd_context_name}" could not be found') stage = usd_context.get_stage() if not stage: raise RuntimeError(f'UsdContext "{self.self.__usd_context_name}" has no stage') old_prim = stage.GetPrimAtPath(self.__camera_path) if not old_prim: raise RuntimeError(f'Could not find camera prim at "{self.__camera_path}"') if self.__new_camera_path is None: target_path = omni.usd.get_stage_next_free_path(stage, "/Camera", True) else: target_path, self.__new_camera_path = self.__new_camera_path, None omni.kit.commands.execute("CreatePrimWithDefaultXformCommand", prim_path=target_path, prim_type="Camera", create_default_xform=False, stage=stage) new_prim = stage.GetPrimAtPath(target_path) if not new_prim: raise RuntimeError(f'Could not find duplicated prim at "{target_path}"') # Save the created camera path now so any failure below won't kill our undo self.__new_camera_path = target_path timecode = self.__time * stage.GetTimeCodesPerSecond() for attr in old_prim.GetAttributes(): attr_name = attr.GetName() # Skip over any xformOp property (they are not duplicated but created below) if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(attr_name): continue # Skip over the locked property if attr_name == CAMERA_LOCK_NAME: continue value = attr.Get(timecode) if value is not None: new_prim.CreateAttribute(attr.GetName(), attr.GetTypeName()).Set(value) # Now create the transform, taking the original world-space of the source camera and putting it into # the new camera's parent's space. We do this always so that TransformPrim can create the correct # rotation ordering now. parent_xformable = UsdGeom.Xformable(new_prim.GetParent()) if parent_xformable: parent_world_xform = omni.usd.get_world_transform_matrix(parent_xformable.GetPrim(), timecode) else: parent_world_xform = Gf.Matrix4d(1) old_camera_prim_world_mtx = omni.usd.get_world_transform_matrix(old_prim, timecode) new_camera_prim_local_mtx = old_camera_prim_world_mtx * parent_world_xform.GetInverse() omni.kit.commands.execute( "TransformPrim", path=new_prim.GetPath(), new_transform_matrix=new_camera_prim_local_mtx, usd_context_name=self.__usd_context_name ) # These won't be undone, but that's ok..undo will delete the prim omni.usd.editor.set_no_delete(new_prim, False) omni.usd.editor.set_hide_in_stage_window(new_prim, False) def undo(self): pass class SetViewportCameraCommand(omni.kit.commands.Command): """ Sets a Viewport's actively bound camera to camera at given path Args: camera_path (Union[str, Sdf.Path): New camera path to bind to viewport. viewport_api: the viewport to target. """ def __init__(self, camera_path: Union[str, Sdf.Path], viewport_api, *args, **kwargs): super().__init__(*args, **kwargs) self.__viewport_api = viewport_api self.__prev_camera = viewport_api.camera_path self.__target_camera = camera_path self.__look_target = None self.__coi_value = None @staticmethod def read_camera_path(viewport_api) -> Sdf.Path: stage = viewport_api.stage if stage: # TODO: 104 Put in proper namespace and per viewport # camera_path = stage.GetMetadataByDictKey("customLayerData", f"cameraSettings:{viewport_api.id}:boundCamera") or # Fallback to < 103.1 boundCamera camera_path = stage.GetMetadataByDictKey("customLayerData", "cameraSettings:boundCamera") if camera_path: prim = stage.GetPrimAtPath(camera_path) if prim and UsdGeom.Camera(prim): return prim.GetPath() return None def __save_to_file(self, camera_path: str): viewport_api = self.__viewport_api stage = viewport_api.stage # Allow (but warn) the case if no Usd.Stage if not stage: carb.log_warn("No Usd.Stage to set boundCamera to") return # Error if not root-layer layer = stage.GetRootLayer() if not layer: carb.log_error("No Usd.Layer to set boundCamera to") return # Move the EditTarget to the root-layer and set meta-data there with Usd.EditContext(stage, Usd.EditTarget(layer)): # TODO: 104 Put in proper namespace and per viewport # stage.SetMetadataByDictKey("customLayerData", f"cameraSettings:{viewport_api.id}boundCamera", camera_path) # Save the legacy version for opening in versions < 103.1 stage.SetMetadataByDictKey("customLayerData", "cameraSettings:boundCamera", camera_path) def do(self): self.__viewport_api.camera_path = self.__target_camera self.__save_to_file(str(self.__target_camera)) def undo(self, look_through=None): # Set the viewport to use the previous camera self.__viewport_api.camera_path = self.__prev_camera self.__save_to_file(str(self.__prev_camera)) class DuplicateViewportCameraCommand(omni.kit.commands.Command): """ Duplicates a Viewport's actively bound camera and bind active camera to the duplicated one. Args: viewport_api: The viewport to target """ def __init__(self, viewport_api, *args, **kwargs): super().__init__(*args, **kwargs) self.__viewport_api = viewport_api def do(self): viewport_api = self.__viewport_api new_camera_path = omni.usd.get_stage_next_free_path(viewport_api.stage, "/Camera", True) omni.kit.commands.execute("DuplicateCameraCommand", camera_path=viewport_api.camera_path, usd_context_name=viewport_api.usd_context_name, new_camera_path=new_camera_path) omni.kit.commands.execute("SetViewportCameraCommand", camera_path=new_camera_path, viewport_api=viewport_api) def undo(self): pass def register_commands(): return omni.kit.commands.register_all_commands_in_module(__name__) def unregister_commands(cmds): omni.kit.commands.unregister_module_commands(cmds)
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/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__ = ["ViewportCameraMenuBarExtension", "get_instance", "SingleCameraMenuItemBase", "SingleCameraMenuItem"] from typing import Callable from .camera_menu_container import CameraMenuContainer from .commands import register_commands, unregister_commands import omni.ext import omni.ui as ui from .menu_item.single_camera_menu_item import SingleCameraMenuItemBase, SingleCameraMenuItem _extension_instance = None def get_instance(): global _extension_instance return _extension_instance class ViewportCameraMenuBarExtension(omni.ext.IExt): """The Entry Point for the Display Settings in Viewport Menu Bar""" def on_startup(self, ext_id): self._camera_menu = CameraMenuContainer() self._cmds = register_commands() global _extension_instance _extension_instance = self def on_shutdown(self): if self._camera_menu: self._camera_menu.destroy() self._camera_menu = None cmds, self._cmds = self._cmds, None unregister_commands(cmds) global _extension_instance _extension_instance = None def register_menu_item_type(self, menu_item_type: Callable[..., "SingleCameraMenuItemBase"]): """ Register a custom menu type for the default created camera Args: menu_item_type: callable that will create the menu item """ if self._camera_menu: self._camera_menu.set_menu_item_type(menu_item_type) def register_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None], order: int = 0): """ Register a custom menu item. Args: create_menu_item_fn (Callable): Callback function to create custom menu item. Kwargs: order (int): Position to put cusom menu item in popup menu window. """ if self._camera_menu: self._camera_menu.register_menu_item(create_menu_item_fn, order=order) def deregister_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None]): """ Deregister a custom menu item. Args: create_menu_item_fn (Callable): Callback function to create custom menu item. """ if self._camera_menu: self._camera_menu.deregister_menu_item(create_menu_item_fn)
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/__init__.py
from .extension import * from .abstract_camera_widget_delegate import *
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/utils.py
import omni.usd from pxr import Sdf, Usd from typing import Optional SESSION_CAMERAS = { "/OmniverseKit_Persp": "Perspective", "/OmniverseKit_Top": "Top", "/OmniverseKit_Front": "Front", "/OmniverseKit_Right": "Right", } def get_camera_display(path: Sdf.Path, stage: Optional[Usd.Stage] = None): name = SESSION_CAMERAS.get(path.pathString, None) if name: return name if stage: camera_prim = stage.GetPrimAtPath(path) if camera_prim: display_name = omni.usd.editor.get_display_name(camera_prim) if display_name: return display_name return path.name
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/abstract_camera_widget_delegate.py
__all__ = ["AbstractCameraButtonDelegate", "AbstractCameraMenuItemDelegate"] import abc import weakref import omni.ui as ui from enum import IntEnum from pxr import Sdf from typing import Optional class AbstractWidgetDelegate(abc.ABC): """ The base class for camera widget delegate. This delegate works for providing the additional camera widget for items of camera list. """ @abc.abstractmethod def build_widget(self, parent_id, viewport_api, camera_path: Sdf.Path) -> Optional[ui.Widget]: """ Builds widget. This must be overrided to provide the layout. parent_id: It's unique id of the camera item, with which you can use to manage the camera widget. viewport_api: Viewport interface. camera_path (Sdf.Path): The camera path to build widget for. """ pass @abc.abstractmethod def on_parent_destroyed(self, parent_id) -> None: """ Called before the destroy of the parent widget. This function can be overrided to release the bound resources specific to the parent. """ pass @abc.abstractmethod def on_camera_path_changed(self, parent_id, camera_path): """The camera tracked has changed.""" pass def destroy(self): """Place to release resources.""" pass @property def order(self) -> int: """ The order of the widget relative to the right of camera label. The lower the order number, the closer the widget to the camera label. """ return 0 class AbstractCameraButtonDelegate(AbstractWidgetDelegate): # Use a list to track all instances __g_registered = [] @classmethod def get_instances(cls): remove = [] # Return a copy to avoid remove in the middle of iterating. all_instances = AbstractCameraButtonDelegate.__g_registered.copy() for wref in all_instances: obj = wref() if obj: yield obj else: remove.append(wref) for wref in remove: AbstractCameraButtonDelegate.__g_registered.remove(wref) def __init__(self): super().__init__() self.__g_registered.append( weakref.ref(self, lambda r: AbstractCameraButtonDelegate.__g_registered.remove(r)) ) def __del__(self): self.destroy() def destroy(self): """Place for releasing resources.""" for wref in AbstractCameraButtonDelegate.__g_registered: if wref() == self: AbstractCameraButtonDelegate.__g_registered.remove(wref) break super().destroy() class AbstractCameraMenuItemDelegate(AbstractWidgetDelegate): # Use a list to track all instances __g_registered = [] @classmethod def get_instances(cls): remove = [] # Return a copy to avoid remove in the middle of iterating. all_instances = AbstractCameraMenuItemDelegate.__g_registered.copy() for wref in all_instances: obj = wref() if obj: yield obj else: remove.append(wref) for wref in remove: AbstractCameraMenuItemDelegate.__g_registered.remove(wref) def __init__(self): super().__init__() self.__g_registered.append( weakref.ref(self, lambda r: AbstractCameraMenuItemDelegate.__g_registered.remove(r)) ) def __del__(self): self.destroy() def destroy(self): """Place for releasing resources.""" for wref in AbstractCameraMenuItemDelegate.__g_registered: if wref() == self: AbstractCameraMenuItemDelegate.__g_registered.remove(wref) break super().destroy() class CameraWidgetDelegateManager: def destroy(self): for delegate in AbstractCameraButtonDelegate.get_instances(): delegate.destroy() for delegate in AbstractCameraMenuItemDelegate.get_instances(): delegate.destroy() def __get_all_delegates(self, camera_button_or_menu_item: bool): all_widget_delegates = [] if camera_button_or_menu_item: for delegate in AbstractCameraButtonDelegate.get_instances(): all_widget_delegates.append(delegate) else: for delegate in AbstractCameraMenuItemDelegate.get_instances(): all_widget_delegates.append(delegate) # Sort list in ascending order. all_widget_delegates.sort(key=lambda item: item.order) def build_widgets( self, parent_id, viewport_api, camera_path: Sdf.Path, camera_button_or_menu_item: bool ): """Build all camera widgets for specific camera path with sort based on their orders.""" all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.build_widget(parent_id, viewport_api, camera_path) def on_parent_destroyed(self, parent_id, camera_button_or_menu_item: bool) -> None: all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.on_parent_destroyed(parent_id) def on_camera_path_changed(self, parent_id, camera_path, camera_button_or_menu_item: bool): all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.on_camera_path_changed(parent_id, camera_path)
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/camera_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__ = ["CameraMenuContainer"] from omni.kit.async_engine import run_coroutine from omni.kit.viewport.menubar.core import ( ViewportMenuDelegate, SeparatorDelegate, ViewportMenuContainer, USDAttributeModel, USDFloatAttributeModel, menu_is_tearable, MenuDisplayStatus ) from .menu_item.lens import CameraLens from .menu_item.focal_distance import CameraFocalDistance from .menu_item.fstop import CameraFStop from .menu_item.auto_exposure import CameraAutoExposure from .menu_item.single_camera_menu_item import SingleCameraMenuItem, NoCameraMenuItem from .menu_item.expand_menu_item import ExpandMenuItem from .commands import SetViewportCameraCommand from .camera_list_delegate import CameraListDelegate from .style import UI_STYLE from .utils import SESSION_CAMERAS, get_camera_display from functools import partial from pxr import Sdf, Tf, Trace, Usd, UsdGeom from typing import Callable, Dict, List, Optional, Set, TYPE_CHECKING, Tuple, Union from .camera_widget_delegate_manager import CameraWidgetDelegateManager import asyncio from dataclasses import dataclass, fields, field import carb import functools import omni.ui as ui import omni.usd import omni.kit.commands import omni.timeline import traceback import weakref import concurrent.futures if TYPE_CHECKING: from .menu_item.single_camera_menu_item import SingleCameraMenuItemBase CAMERA_LOCK_NAME = "omni:kit:cameraLock" def handle_exception(func): """ Decorator to print exception in async functions """ @functools.wraps(func) async def wrapper(*args, **kwargs): try: return await func(*args, **kwargs) except Exception as e: carb.log_error(f"Exception when async '{func}'") carb.log_error(f"{e}") carb.log_error(f"{traceback.format_exc()}") return wrapper def _show_camera_in_menu(prim: Usd.Prim): return prim and prim.IsA(UsdGeom.Camera) and not omni.usd.editor.is_hide_in_ui(prim) class _CameraList: """The object that watches USD for the list of cameras""" def __init__(self, stage, callback): self.__stage: Usd.Stage = stage self.__callback: Callable[[], None] = callback self.__cameras: Set[Sdf.Path] = set() self.__listener = None self.__dirty = True self.__camera_filters = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/filters") or [] self.__usdrt_stage = self.__get_usd_rt_stage(stage) self.__listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.__on_usd_changed, stage) if stage else None self.__dirty_prim_paths: Set[Sdf.Path] = set() self.__prim_changed_task: Optional[concurrent.futures.Future] = None def __del__(self): self.destroy() def destroy(self): if self.__listener: self.__listener.Revoke() self.__listener = None @property def is_dirty(self): return self.__dirty @property def camera_list(self) -> List[Sdf.Path]: # If it's called the first time, we just iterate the whole USD stage for cameras # Note the cast to bool is important in case self.__stage is not None, but also an invalid stage was_dirty, self.__dirty = self.__dirty, False has_stage = bool(self.__stage) if was_dirty and has_stage: self.__cameras: Set[Sdf.Path] = set() if self.__usdrt_stage: for prim_path in self.__usdrt_stage.GetPrimsWithTypeName("Camera"): usd_prim = self.__stage.GetPrimAtPath(prim_path.GetString()) if _show_camera_in_menu(usd_prim) and self.__filter(usd_prim): self.__cameras.add(usd_prim.GetPath()) else: # If it's called the first time, we just iterate the whole USD stage for cameras # Note the cast to bool is important in case self.__stage is not None, but also an invalid stage predicate = Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded) for usd_prim in self.__stage.Traverse(predicate): if _show_camera_in_menu(usd_prim) and self.__filter(usd_prim): self.__cameras.add(usd_prim.GetPath()) return self.__cameras def __filter(self, camera_prim: Usd.Prim) -> bool: path = camera_prim.GetPath().pathString for filter in self.__camera_filters: if path.startswith(filter): return False return True @staticmethod def __get_usd_rt_stage(stage: Usd.Stage): if carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/primQuery/useUsdRt"): try: from pxr import UsdUtils from usdrt import Usd as UsdRtUsd stage_id = UsdUtils.StageCache.Get().GetId(stage).ToLongInt() fabric_active_for_stage = UsdRtUsd.Stage.StageWithHistoryExists(stage_id) if fabric_active_for_stage: return UsdRtUsd.Stage.Attach(stage_id) except (ImportError, ModuleNotFoundError): pass return None @Trace.TraceFunction def __on_usd_changed(self, notice: Tf.Notice, stage: Usd.Stage): """Called by Usd.Notice.ObjectsChanged""" if not bool(self.__stage) or stage != self.__stage: return dirty_prims_paths: List[Sdf.Path] = [] for p in notice.GetResyncedPaths(): if p.IsAbsoluteRootOrPrimPath(): dirty_prims_paths.append(p) if not dirty_prims_paths: return self.__dirty_prim_paths.update(dirty_prims_paths) # Update in the next frame. We need it because we want to accumulate the affected prims if self.__prim_changed_task is None or self.__prim_changed_task.done(): self.__prim_changed_task_or_future = run_coroutine(self.__delayed_prim_changed()) @handle_exception @Trace.TraceFunction async def __delayed_prim_changed(self): """ Create/remove dirty items that was collected from TfNotice. Can be called any time to pump changes. """ if not bool(self.__stage): return # Swap the dirty list to a local and reset the instance state dirty = False dirty_prim_paths, self.__dirty_prim_paths = self.__dirty_prim_paths, set() removed_camera, added_camera = None, None for path in dirty_prim_paths: prim = self.__stage.GetPrimAtPath(path) if _show_camera_in_menu(prim): # Changed or created self.__cameras.add(path) added_camera = path dirty = True else: # Removed or changed type try: self.__cameras.remove(path) removed_camera = path except KeyError: pass dirty = True # For the case with one event that represents and removal and addition of a camera, pass it along as -hint-. # There could be fals-positives (a layer event where only one camera is gone and one added), but even in # that case hinting to the Viewport what to do (leave camera if removed camera was active) isn't horrible. if len(dirty_prim_paths) != 2 or (removed_camera is None) or (added_camera is None): removed_camera, added_camera = None, None if dirty: self.__dirty = True self.__callback(removed_camera, added_camera) self.__prim_changed_task = None @dataclass class MenuContext: root_menu: ui.Menu = None delegate: ui.MenuDelegate = None settings_menu: ui.Menu = None settings_container: ui.ZStack = None settings_width: int = 0 expand_container: ui.ZStack = None expand_item: ExpandMenuItem = None expand_width: int = 0 expand_model: ui.SimpleBoolModel = None saved_expand = False camera_collection: ui.MenuItemCollection = None camera_path: str = None selected_camera_item: ui.MenuItem = None camera_list: Optional[_CameraList] = None stage_sub: carb.Subscription = None expanded_sub: carb.Subscription = None render_settings_changed_sub: carb.Subscription = None lock_menu_sub: carb.Subscription = None settings_items: List[ui.MenuItem] = field(default_factory=list) camera_to_menu: Dict[Sdf.Path, Tuple[SingleCameraMenuItem, bool]] = field(default_factory=dict) def __init__(self, **kwargs): names = set([f.name for f in fields(self)]) for k, v in kwargs.items(): if k in names: setattr(self, k, v) if not hasattr(self, "settings_items"): self.settings_items = [] if not hasattr(self, "camera_to_menu"): self.camera_to_menu = {} class CameraMenuContainer(ViewportMenuContainer): """The menu with the list of cameras""" def __init__(self): super().__init__( name="Camera", delegate=None, visible_setting_path="/exts/omni.kit.viewport.menubar.camera/visible", order_setting_path="/exts/omni.kit.viewport.menubar.camera/order", expand_setting_path="/exts/omni.kit.viewport.menubar.camera/expand", style=UI_STYLE ) self.__menu_item_type = SingleCameraMenuItem self.__lock_models: Dict[Sdf.Path, USDAttributeModel] = {} self.__menu_context: Dict[int, MenuContext] = {} self._create_menu_item_fns: List[List[Callable[["viewport_context", ui.Menu], None]], int] = [] self.register_menu_item(self._build_camera_collections, -100) self.register_menu_item(self._build_create_camera, -90) self.__custom_camera_widget_delegate_manager = CameraWidgetDelegateManager() def set_menu_item_type(self, menu_item_type: Callable[..., "SingleCameraMenuItemBase"]): """ Set the menu type for the default created camera Args: menu_item_type: callable that will create the menu item """ if not menu_item_type: menu_item_type = SingleCameraMenuItem if self.__menu_item_type != menu_item_type: self.__menu_item_type = menu_item_type self.__full_invalidate() def __del__(self): self.destroy() def destroy(self): self.__lock_models = {} for context in self.__menu_context.values(): context.expanded_sub = None context.lock_menu_sub = None if context.render_settings_changed_sub: context.render_settings_changed_sub.destroy() context.render_settings_changed_sub = None self.__custom_camera_widget_delegate_manager.destroy() super().destroy() def __full_invalidate(self): for context in self.__menu_context.values(): context.root_menu.invalidate() context.settings_menu.invalidate() 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.expand_container.visible: return MenuDisplayStatus.EXPAND elif context.delegate.text_visible: return MenuDisplayStatus.LABEL else: return MenuDisplayStatus.MIN def get_require_size(self, factory_args: Dict, expand: bool=False) -> float: viewport_api_id = factory_args['viewport_api'].id context = self.__menu_context[viewport_api_id] display_status = self.get_display_status(factory_args) if expand: if display_status == MenuDisplayStatus.EXPAND: return 0 elif display_status == MenuDisplayStatus.LABEL: return context.settings_width + context.expand_width else: return context.delegate.text_size else: if display_status == MenuDisplayStatus.EXPAND: if context.expand_model.as_bool: return 0 else: return context.settings_width elif display_status == MenuDisplayStatus.LABEL: return 0 else: return context.delegate.text_size def expand(self, factory_args: Dict) -> None: viewport_api_id = factory_args['viewport_api'].id context = self.__menu_context[viewport_api_id] if context.expand_container.visible: return elif context.delegate.text_visible: context.expand_model.set_value(context.saved_expand) context.expand_container.visible = True 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 or display_status == MenuDisplayStatus.EXPAND def contract(self, factory_args: Dict) -> bool: viewport_api_id = factory_args['viewport_api'].id if viewport_api_id not in self.__menu_context: return False context = self.__menu_context[viewport_api_id] display_status = self.get_display_status(factory_args) if display_status == MenuDisplayStatus.EXPAND: context.saved_expand = context.expand_model.as_bool context.expand_model.set_value(False) context.expand_container.visible = False return True elif display_status == MenuDisplayStatus.LABEL: context.delegate.text_visible = False if context.root_menu: context.root_menu.invalidate() return True return False def register_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None], order: int = 0): self._create_menu_item_fns.append((create_menu_item_fn, order)) self.__full_invalidate() def deregister_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None]): found = [item for item in self._create_menu_item_fns if item[0] == create_menu_item_fn] if found: for item in found: self._create_menu_item_fns.remove(item) self.__full_invalidate() 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 # Empty out any existing menu objects self.__menu_context[viewport_api_id] = MenuContext( delegate=CameraListDelegate(viewport_api, self.__custom_camera_widget_delegate_manager) ) # Get a local reference to the new mapped value _menu_context = self.__menu_context[viewport_api_id] _menu_context.root_menu = ui.Menu(menu_compatibility=False, delegate=_menu_context.delegate, style=self._style) _menu_context.root_menu.set_on_build_fn(lambda *args, **kwargs: self._build_menu(viewport_context)) # The Camera property widgets selection menu _menu_context.settings_container = ui.ZStack(width=0) with _menu_context.settings_container: ui.Rectangle(style_type_name_override="Menu.Item.Background") with ui.HStack(width=0): ui.Spacer(width=5) _menu_context.settings_menu = ui.Menu(menu_compatibility=False, direction=ui.Direction.LEFT_TO_RIGHT, style=self._style) _menu_context.settings_menu.set_on_build_fn(lambda *args, **kwargs: self._build_expand(viewport_context)) ui.Spacer(width=5) def __on_settings_changed(id): menu_context = self.__menu_context[viewport_api_id] menu_context.settings_width = max(menu_context.settings_width, menu_context.settings_container.computed_content_width) _menu_context.settings_container.set_computed_content_size_changed_fn(partial(__on_settings_changed, viewport_api_id)) # Delay a frame to hide camera settings if required to get settings width for contract/expand when startup _menu_context.expand_model = ui.SimpleBoolModel(self.expand_model.as_bool) async def __hide_camera_settings_async(menu_context): await omni.kit.app.get_app().next_update_async() menu_context.settings_container.visible = menu_context.expand_model.as_bool if not self.expand_model.as_bool: self.__hide_camera_settings_task_or_future = run_coroutine(__hide_camera_settings_async(_menu_context)) # Menu to expand/contract camera properties _menu_context.expand_container = ui.ZStack(width=0, height=0, style={"padding": 0, "margin": 0}) with _menu_context.expand_container: with ui.Menu(menu_compatibility=False, direction=ui.Direction.LEFT_TO_RIGHT, style=self._style): _menu_context.expand_item = ExpandMenuItem(_menu_context.expand_model) def __on_expand_changed(*args, **kwargs): menu_context = self.__menu_context[viewport_api_id] menu_context.expand_width = max(menu_context.expand_width, menu_context.expand_container.computed_content_width) _menu_context.expand_container.set_computed_content_size_changed_fn(__on_expand_changed) def __on_toggle_expand(*args, **kwargs): menu_context = self.__menu_context[viewport_api_id] menu_context.settings_container.visible = menu_context.expand_model.as_bool menu_context.expand_item.checked = menu_context.expand_model.as_bool # Reset global expand status # Once at least one expanded, set global expanded # Otherwise, set global callpased self.__unsub_global_expand() if menu_context.expand_model.as_bool: self.expand_model.set_value(True) else: expand = False for menu_context in self.__menu_context.values(): if menu_context.expand_model.as_bool: expand = True break self.expand_model.set_value(expand) self.__sub_global_expand() _menu_context.expanded_sub = _menu_context.expand_model.subscribe_value_changed_fn(__on_toggle_expand) self.__sub_global_expand() # When stage opened, rebuild the root menu def on_usd_context_event(event: omni.usd.StageEventType): if event.type == int(omni.usd.StageEventType.OPENED): camera_path = self.__ensure_valid_camera(viewport_api, viewport_api.camera_path) if camera_path: viewport_api.camera_path = camera_path menu_context = self.__menu_context.get(viewport_api_id) if menu_context: menu_context.root_menu.invalidate() menu_context.settings_menu.invalidate() _menu_context.stage_sub = viewport_api.usd_context.get_stage_event_stream().create_subscription_to_pop( on_usd_context_event, name="Viewport MenuBar CameraMenuContainer" ) # Clear out this reference to validate its not being held or used by any callback _menu_context = None def __render_settings_changed(self, camera_path: Sdf.Path, resolution: Tuple[int, int], viewport_api): # The Viewport may have switched to a new camera before out camera list was dirtied context = self.__menu_context[viewport_api.id] if context.camera_to_menu.get(camera_path) is None: # Rebuild but don't check camera validity; the Viewport is sending us the path it is rendering with self.__rebuild_cameras(viewport_api, False) self.__camera_changed(camera_path, viewport_api) def __camera_clicked(self, camera_path: Sdf.Path, viewport_api): context = self.__menu_context[viewport_api.id] if context.camera_path != camera_path: SetViewportCameraCommand(camera_path, viewport_api).do() return # Force the check state back on as it's being toggled off async def force_check(id): selected_cam_item = self.__menu_context[id].selected_camera_item if selected_cam_item and not selected_cam_item.checked: selected_cam_item.checked = True self.__force_check_task_or_future = run_coroutine(force_check(viewport_api.id)) def __camera_changed(self, camera_path: Sdf.Path, viewport_api): context = self.__menu_context[viewport_api.id] if context.camera_path == camera_path: cam_item = context.camera_to_menu.get(camera_path) if cam_item and not cam_item.checked: cam_item.checked = True return # Save the current state now context.camera_path = camera_path # Uncheck anything that is currently selected selected_cam_item = context.selected_camera_item if selected_cam_item: selected_cam_item.checked = False selected_cam_item = None # There is also chance the Camera was changed to an item that doesn't exist cam_item = context.camera_to_menu.get(camera_path) if cam_item: context.selected_camera_item = cam_item # And reset the check state on the new selection cam_item.checked = True # Update the root menu item if context.delegate: context.delegate.text = get_camera_display(camera_path, viewport_api.stage) # Toggle the cam collection marker accordingly if context.camera_collection: context.camera_collection.checked = str(camera_path) not in SESSION_CAMERAS # Need to update the lock item to new camera self.__build_lock_item(viewport_api, camera_path) # Update the active Camera's property widgets by rebuilding them if context: context.settings_menu.invalidate() def __build_lock_item(self, viewport_api, camera_path: Sdf.Path): stage = viewport_api.stage # Lock menu sub is always destroyed context = self.__menu_context.get(viewport_api.id, None) context.lock_menu_sub = None # Possibly no path, so clear any state if not camera_path: self.__lock_models = {} if context and context.delegate: context.delegate.model = None context.delegate.camera_path = None return context.delegate.camera_path = camera_path lock_model = self.__get_lock_model(stage, camera_path) if context and context.delegate: context.delegate.model = lock_model if lock_model: context.lock_menu_sub = lock_model.subscribe_value_changed_fn(lambda m, api=viewport_api: self._on_lock_changed(m, api)) def __get_lock_model(self, stage: Usd.Stage, camera_path: Sdf.Path): if camera_path not in self.__lock_models: if camera_path.pathString in ("/OmniverseKit_Persp", "/OmniverseKit_Front", "/OmniverseKit_Top", "/OmniverseKit_Right"): return None # Lock - Should probably use meta-data, but that needs to be added into allowed-metadata schema # self.__lock_models[camera_path] = USDMetadataModel(stage, camera_path, CAMERA_LOCK_NAME) self.__lock_models[camera_path] = USDAttributeModel(stage, camera_path, CAMERA_LOCK_NAME) return self.__lock_models.get(camera_path) def __get_session_camera_paths(self, stage: Usd.Stage): session_camera_paths = [Sdf.Path(path_str) for path_str in SESSION_CAMERAS] if stage: session_camera_paths = [path for path in session_camera_paths if stage.GetPrimAtPath(path)] return session_camera_paths def _build_cameras(self, viewport_api, session_cameras: bool, ui_shown: bool = False, force_build: bool = False): """Build the menu with the list of the cameras""" context = self.__menu_context.get(viewport_api.id, None) if (not session_cameras) and (not force_build): camera_collection = context.camera_collection if camera_collection and not camera_collection.shown and not camera_collection.teared: return if session_cameras: camera_list = self.__get_session_camera_paths(viewport_api.stage) elif not context.camera_list.is_dirty: # If nothing changed, menu should be up-to-date return else: def sorting_key(sdf_path: Sdf.Path): # Sort based on parentPath/displayName which may lead to an invalid Sdf.Path durring AppendChild display_name = get_camera_display(sdf_path, viewport_api.stage) return f"{sdf_path.GetParentPath().pathString}/{display_name}".lower() camera_list = context.camera_list.camera_list camera_list = sorted(camera_list, key=sorting_key) camera_list = [path for path in camera_list if path.pathString not in SESSION_CAMERAS] if context.camera_collection: context.camera_collection.clear() stage = viewport_api.stage # Check that the current camera path is valid current_camera = viewport_api.camera_path valid_camera_path = self.__ensure_valid_camera(viewport_api, current_camera) if valid_camera_path and (valid_camera_path != current_camera): current_camera = valid_camera_path viewport_api.camera_path = current_camera # Clear any selected selected_cam_item now, its going to be an invalid item soon if context and context.selected_camera_item: context.selected_camera_item.checked = False context.selected_camera_item = None class MenuParentContext: def __enter__(self, *args, **kwargs): return context.camera_collection.__enter__(*args, **kwargs) if not session_cameras else None def __exit__(self, *args, **kwargs): return context.camera_collection.__exit__(*args, **kwargs) if not session_cameras else None with MenuParentContext(): if session_cameras or camera_list: for camera_path in camera_list: checked = current_camera == camera_path menu_item = self.__menu_item_type( camera_path, viewport_api, self.__get_lock_model(stage, camera_path), context.root_menu, lambda camera_path=camera_path: self.__camera_clicked(camera_path, viewport_api), self.__custom_camera_widget_delegate_manager ) context.camera_to_menu[camera_path] = menu_item if checked: context.selected_camera_item = menu_item else: NoCameraMenuItem() # Call camera_changed for the case the camera menu has been invalidated context.camera_path = None self.__camera_changed(current_camera, viewport_api) def __rebuild_cameras(self, viewport_api, check_validity: bool = False, removed_camera: Sdf.Path = None, added_camera: Sdf.Path = None): context = self.__menu_context.get(viewport_api.id, None) camera_collection = context.camera_collection if camera_collection and (camera_collection.shown or camera_collection.teared): # Force a rebuild of the stage cameras now camera_collection.invalidate() camera_collection.clear() self._build_cameras(viewport_api, False, True, True) if not check_validity: return camera_path = viewport_api.camera_path # If there was a single re-synch event where this camera was removed, and a new one added, go to added valid_camera_path = self.__ensure_valid_camera(viewport_api, added_camera if removed_camera == camera_path else camera_path) if valid_camera_path and (valid_camera_path != camera_path): viewport_api.camera_path = valid_camera_path def __ensure_valid_camera(self, viewport_api, camera_path: Sdf.Path): stage = viewport_api.stage if not stage: return camera_path def validate_camera(camera_path): if camera_path: prim = stage.GetPrimAtPath(camera_path) # OM-59033: It does not need the followed camera to be shown in the camera list by checking # _show_camera_in_menu(prim) as follow user mode in live session needs this to switch # camera binding dynamically without adding the camera into camera list. if prim: return Sdf.Path(camera_path) return None # Check if the camera_path is actually a valid camera_path camera_path = validate_camera(camera_path) if camera_path: return camera_path # Check if the info is held in the stage metadata. try: # Wrap in a try-catch so failure reading metadata does not cascade to caller. camera_path = validate_camera(stage.GetMetadataByDictKey('customLayerData', 'cameraSettings:boundCamera')) if camera_path: return camera_path except Tf.ErrorException as e: carb.log_error(f"Error reading Usd.Stage's boundCamera metadata {e}") # Fallback to implicit Perspective if possible (it is deterministic) camera_path = validate_camera('/OmniverseKit_Persp') if camera_path: return camera_path # Finally, try an pass the first valid camera in the list context = self.__menu_context[viewport_api.id] if context and context.camera_list: for known_camera in context.camera_list.camera_list: camera_path = validate_camera(known_camera) if camera_path: return camera_path return None def _build_camera_collections(self, viewport_context, root: ui.Menu): viewport_api = viewport_context.get("viewport_api") context = self.__menu_context.get(viewport_api.id, None) if context.camera_list: context.camera_list.destroy() context.camera_list = _CameraList(viewport_api.stage, partial(self.__rebuild_cameras, viewport_api, True)) # Clear out the Camera-path to MenuItem mapping context.camera_to_menu = {} # Verify current camera exists, changing it if it does not camera_path = viewport_api.camera_path valid_camera_path = self.__ensure_valid_camera(viewport_api, camera_path) if valid_camera_path and (valid_camera_path != camera_path): camera_path = valid_camera_path viewport_api.camera_path = camera_path # Order views session_cameras = self.__get_session_camera_paths(viewport_api.stage) show_stage_cameras = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/showStageCameras") if show_stage_cameras: tearable = menu_is_tearable("omni.kit.viewport.menubar.camera.Cameras") context.camera_collection = ui.MenuItemCollection( "Cameras", checkable=True, checked=camera_path not in session_cameras, delegate=ViewportMenuDelegate(), shown_changed_fn=partial(self._build_cameras, viewport_api, False), tearable=tearable, hide_on_click=False ) def reset_checked(): context.camera_collection.checked = str(viewport_api.camera_path) in SESSION_CAMERAS context.camera_collection.set_triggered_fn(reset_checked) # XXX: This isn't sticking from the usage in constructor context.camera_collection.tearable = tearable self._build_cameras(viewport_api, True) ui.Separator() def _build_create_camera(self, viewport_context, root: ui.Menu): viewport_api = viewport_context.get("viewport_api") ui.MenuItem( "Create from View", delegate=ViewportMenuDelegate(icon_name="Add"), triggered_fn=lambda *args, **kwargs: self._create_from_view(viewport_api), hide_on_click=False ) def _build_menu(self, viewport_context): """Build the first level menu""" # Create a weak-reference to the active Camera menu; this will be passed to registered build functions viewport_api = viewport_context.get("viewport_api") context = self.__menu_context.get(viewport_api.id, None) cam_menu = weakref.proxy(context.root_menu) context.camera_path = viewport_api.camera_path # Need to watch for external changes to Viewport's camera, this is delivered in a render-settings change. if context.render_settings_changed_sub: context.render_settings_changed_sub.destroy() context.render_settings_changed_sub = None context.render_settings_changed_sub = viewport_api.subscribe_to_render_settings_change(self.__render_settings_changed) if context and context.delegate: context.delegate.model = None context.delegate.camera_path = None self.__lock_models = {} self.__build_lock_item(viewport_api, context.camera_path) # Active camera if context.camera_path: text = get_camera_display(context.camera_path, viewport_api.stage) else: text = self.name context.root_menu.text = text # Menu items self._create_menu_item_fns.sort(key=lambda item: item[1]) for (create_fn, order) in self._create_menu_item_fns: create_fn(viewport_context, cam_menu) # The rest of the menu on the case someone wants to put custom stuff if self._children: for child in self._children: child.build_fn(viewport_context) def _build_expand(self, viewport_context) -> None: # This menu has the number of widgets on the right side. # Check if the widgets are expanded viewport_api = viewport_context.get("viewport_api") context = self.__menu_context[viewport_api.id] stage = viewport_api.stage camera_path = viewport_api.camera_path context.settings_items = [] if camera_path: locked = self.__lock_models[camera_path].as_bool if camera_path in self.__lock_models and self.__lock_models[camera_path] else False enabled = not locked show_manual_exposure = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/showManualExposure") if show_manual_exposure: context.settings_items.append( CameraLens( USDFloatAttributeModel(stage, camera_path, "focalLength", draggable=True), enabled=enabled, ) ) ui.MenuItem("", delegate=SeparatorDelegate()) context.settings_items.append( CameraFocalDistance( USDFloatAttributeModel(stage, camera_path, "focusDistance"), viewport_context, enabled=enabled, ) ) ui.MenuItem("", delegate=SeparatorDelegate()) context.settings_items.append( CameraFStop( USDFloatAttributeModel(stage, camera_path, "fStop"), enabled=enabled, ) ) show_auto_exposure = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/showAutoExposure") if show_auto_exposure: if show_manual_exposure: ui.MenuItem("", delegate=SeparatorDelegate()) context.settings_items.append(CameraAutoExposure(None, enabled=enabled)) if camera_path in self.__lock_models and self.__lock_models[camera_path]: self._on_lock_changed(self.__lock_models[camera_path], viewport_api) def _create_from_view(self, viewport_api): omni.kit.commands.execute("DuplicateViewportCameraCommand", viewport_api=viewport_api) def _on_lock_changed(self, model: ui.AbstractValueModel, viewport_api) -> None: is_locked = model.as_bool settings_items = self.__menu_context[viewport_api.id].settings_items for setting in settings_items: setting.enabled = not is_locked def _on_menu_collection_triggered(self, menu: ui.MenuItemCollection, checked: bool): # Revert status here to keep checked status no changing when clicked menu.checked = not checked def __sub_global_expand(self): # Watch for the carb setting, for now treat it as global state and apply to all Viewports def __on_toggle_global_expand(*args, **kwargs): expanded = self.expand_model.as_bool for menu_context in self.__menu_context.values(): menu_context.expand_model.set_value(expanded) self.__expanded_sub = self.expand_model.subscribe_value_changed_fn(__on_toggle_global_expand) def __unsub_global_expand(self): self.__expanded_sub = None
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/single_camera_menu_item.py
import abc from typing import Optional, Callable import carb import omni.ui as ui from typing import Optional, Callable from pxr import Sdf from omni.kit.viewport.menubar.core import ViewportMenuDelegate, LabelMenuDelegate from ..camera_widget_delegate_manager import CameraWidgetDelegateManager from ..utils import get_camera_display class SingleCameraMenuItemBase(ui.MenuItem): """ A single menu item represent a single camera in the camera list """ def __init__( self, camera_path: Sdf.Path, viewport_api, lock_model, root: ui.Menu, triggered_fn: Callable, widget_delegate_manager: CameraWidgetDelegateManager ): self._lock_model = lock_model self.__root = root self.__camera_path = camera_path self.__viewport_api = viewport_api self.__lock_button: Optional[ui.Button] = None self.__lock_model_sub = None self.__options_button = None self.__widget_delegate_manager = widget_delegate_manager super().__init__( get_camera_display(camera_path, viewport_api.stage), checkable=True, checked=viewport_api.camera_path == camera_path, hide_on_click=False, triggered_fn=triggered_fn, delegate=ViewportMenuDelegate( force_checked=False, build_custom_widgets=lambda delegate, item: self._build_menuitem_widgets() ), ) @property def camera_path(self): return self.__camera_path @property def viewport_api(self): return self.__viewport_api def destroy(self): if self.__widget_delegate_manager: self.__widget_delegate_manager.on_parent_destroyed(id(self), False) self.__widget_delegate_manager = None self.__options_button = None super().destroy() self.__lock_model_sub = None def __build_custom_widgets(self): if not self.__widget_delegate_manager: return try: self.__widget_delegate_manager.build_widgets( id(self), self.__viewport_api, self.__camera_path, False ) except Exception as e: carb.log_error(f"Failed to build widget: {str(e)}") def _build_menuitem_widgets(self): """Build additional buttons in the camera menu item""" ui.Spacer(width=10) with ui.VStack(content_clipping=1, width=0): # Button to select camera 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, ) if self._lock_model: # Button to toggle lock status with ui.VStack(content_clipping=1, width=0): self.__lock_button = ui.Button( style_type_name_override="Menu.Item.Button", name=self.__get_lock_button_name(), width=16, height=16, image_width=16, image_height=16, clicked_fn=self.__toggle_camera_lock, ) self.__lock_model_sub = self._lock_model.subscribe_value_changed_fn(self._on_lock_changed) self.__build_custom_widgets() @abc.abstractmethod def _option_clicked(self): """Function to implement when the option is clicked. Used by RTX Remix""" pass def __toggle_camera_lock(self): self._lock_model.set_value(not self._lock_model.as_bool) self.__lock_button.name = self.__get_lock_button_name() def _on_lock_changed(self, model: ui.AbstractValueModel) -> None: self.__lock_button.name = self.__get_lock_button_name() def __get_lock_button_name(self): return "CameraLocked" if self._lock_model.as_bool else "CameraUnlocked" 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 SingleCameraMenuItem(SingleCameraMenuItemBase): """ A single menu item represent a single camera in the camera list """ def _option_clicked(self): self.viewport_api.usd_context.get_selection().set_selected_prim_paths([self.camera_path.pathString], True) class NoCameraMenuItem(ui.MenuItem): """ A single menu item represent a no camera in the camera list """ def __init__(self): super().__init__( "No camera", hide_on_click=False, delegate=LabelMenuDelegate(enabled=False, width=120, alignment=ui.Alignment.CENTER), )
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/lens.py
import asyncio from typing import Tuple, List from pxr import Usd, Sdf import omni.kit.app import omni.ui as ui from omni.ui import constant as fl from .camera_setting import AbstractCameraSetting from omni.kit.viewport.menubar.core import ( SeparatorDelegate, SliderMenuDelegate, ComboBoxMenuDelegate, USDAttributeModel, USDFloatAttributeModel, ComboBoxItem, ComboBoxModel, ) DEFAULT_LENS = [8, 15, 24, 28, 35, 50, 85, 105, 135, 200, (17, 35), (35, 70), (70, 200), (0, 300)] class _CameraLensModel(ComboBoxModel): """The camera lens model has all the lens""" def __init__(self, lens_model: USDFloatAttributeModel): self._values = DEFAULT_LENS self._lens_model = lens_model self.range: Tuple(float, float) = () texts = [] for value in self._values: if isinstance(value, int): texts.append(f"{value} mm") else: texts.append(f"{value[0]} - {value[1]} mm") self._lens_model.add_value_changed_fn(self.__on_lens_changed) super().__init__(texts, self._values, self.display) def destroy(self): super().destroy() self._lens_model.remove_value_changed_fn(self.__on_lens_changed) @property def display(self): lens = self._lens_model.as_float for value in self._values: if isinstance(value, int): if lens == float(value): self.range = (value, value) return value else: min = value[0] max = value[1] if lens <= max and lens >= min: self.range = (min, max) return value default = self._values[-1] return default def _on_current_item_changed(self, item: ComboBoxItem) -> None: if isinstance(item.value, int): self.range = (item.value, item.value) self._lens_model.set_value(float(item.value)) else: # Don't allow 0 for focalLength self.range = (max(0.00001, item.value[0]), item.value[1]) value = self._lens_model.as_float if value > self.range[1] or value < self.range[0]: self._lens_model.set_value(float(self.range[0])) def __on_lens_changed(self, model: ui.AbstractValueModel): # If current value still in current lens range, keep range no change value = self._values[self.current_index.as_int] if isinstance(value, int): if model.as_float == float(value): return elif float(value[0]) <= model.as_float and float(value[1]) >= model.as_float: return self.current_index.set_value(self._get_current_index_by_value(self.display)) class CameraLens(AbstractCameraSetting): def __init__(self, model: USDAttributeModel, enabled: bool = True): self._lens_model = _CameraLensModel(model) self._sub = self._lens_model.subscribe_item_changed_fn(self._on_lens_changed) super().__init__(model, enabled=enabled) def destroy(self): self._lens_model.destroy() self._sub = None def _build_ui(self) -> List[ui.MenuDelegate]: self._lens_delegate = ComboBoxMenuDelegate( model=self._lens_model, height=26, icon_height=26, enabled=self._enabled, text=False, icon_name="Lens", tooltip="Camera Lens", use_in_menubar=True, ) ui.MenuItem("Lens", delegate=self._lens_delegate, identifier="viewport.camera.lens") self._separator = ui.MenuItem("", delegate=SeparatorDelegate()) self._zoom_delegate = SliderMenuDelegate(model=self._property_model, width=0, enabled=self._enabled, tooltip="Camera Zoom") self._zoom_menu = ui.MenuItem("Zoom", delegate=self._zoom_delegate, enabled=self._enabled, identifier="viewport.camera.zoom") async def __delay_init(): await omni.kit.app.get_app().next_update_async() self._on_lens_changed(self._lens_model, None) asyncio.ensure_future(__delay_init()) return [self._lens_delegate, self._zoom_delegate] def _on_lens_changed(self, model: _CameraLensModel, item: ComboBoxItem): range = self._lens_model.range if range[0] == range[1]: self._zoom_delegate.visible = False self._separator.visible = False else: self._zoom_delegate.visible = True self._separator.visible = True self._zoom_delegate.set_range(range[0], range[1])
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/fstop.py
from pxr import Usd, Sdf from typing import List import omni.ui as ui from omni.ui import constant as fl from .camera_setting import AbstractCameraSetting from omni.kit.viewport.menubar.core import SpinnerMenuDelegate, USDAttributeModel __all__ = ["CameraFStop"] class CameraFStop(AbstractCameraSetting): def __init__(self, model: USDAttributeModel, enabled: bool = True): super().__init__(model, enabled=enabled) def destroy(self): pass def _build_ui(self) -> List[ui.MenuDelegate]: self._fstop_delegate = SpinnerMenuDelegate( model=self._property_model, min=0.0, max=22.0, step=0.1, height=26, enabled=self._enabled, text=False, icon_name="FStop", tooltip="Camera F Stop", icon_height=26, use_in_menubar=True, ) ui.MenuItem("F Stop", delegate=self._fstop_delegate, identifier="viewport.camera.f_stop") return [self._fstop_delegate]
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/auto_exposure.py
from pxr import Usd, Sdf from typing import List import omni.ui as ui from omni.ui import constant as fl from .camera_setting import AbstractCameraSetting from omni.kit.viewport.menubar.core import ( CheckboxMenuDelegate, SpinnerMenuDelegate, SliderMenuDelegate, USDAttributeModel, SettingModel, ) SETTING_AUTO_EXPOSURE = "/rtx/post/histogram/enabled" SETTING_ISO = "/rtx/post/tonemap/filmIso" SETTING_WHITE_SCALE = "/rtx/post/histogram/whiteScale" __all__ = ["CameraAutoExposure", "SETTING_AUTOEXPOSURE", "SETTING_ISO", "SETTING_WHITE_SCALE"] class CameraAutoExposure(AbstractCameraSetting): def __init__(self, model: USDAttributeModel, enabled: bool = True): self._auto_exposure_model = SettingModel(SETTING_AUTO_EXPOSURE) self._white_scale_model = SettingModel(SETTING_WHITE_SCALE) self._iso_model = SettingModel(SETTING_ISO) self._sub = self._auto_exposure_model.subscribe_value_changed_fn(self._on_auto_exposure_changed) super().__init__(model, enabled=enabled) def destroy(self): self._sub = None def _build_ui(self) -> List[ui.MenuDelegate]: self._auto_exposure_delegate = CheckboxMenuDelegate( model=self._auto_exposure_model, width=0, height=26, enabled=self._enabled, use_in_menubar=True ) ui.MenuItem("AE", delegate=self._auto_exposure_delegate, identifier="viewport.camera.auto_exposure") self._white_scale_item = ui.MenuItem( "", delegate=SliderMenuDelegate(model=self._white_scale_model, min=00, max=20, width=0), visible=self._auto_exposure_model.as_bool, ) self._iso_item = ui.MenuItem( "ISO", delegate=SpinnerMenuDelegate( model=self._iso_model, min=50, max=1600, height=26, use_in_menubar=True, ), visible=not self._auto_exposure_model.as_bool, identifier="viewport.camera.iso", ) return [self._auto_exposure_delegate, self._white_scale_item.delegate, self._iso_item.delegate] def _on_auto_exposure_changed(self, model: ui.AbstractValueModel) -> None: self._white_scale_item.visible = model.as_bool self._iso_item.visible = not model.as_bool
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/camera_setting.py
import abc from pxr import Usd, Sdf from typing import List import omni.ui as ui from omni.kit.viewport.menubar.core import USDAttributeModel __all__ = ["AbstractCameraSetting"] class AbstractCameraSetting: def __init__(self, model: USDAttributeModel, enabled: bool = True): self._property_model = model self._enabled = enabled self._delegates = self._build_ui() @property def enabled(self) -> bool: return self._enabled @enabled.setter def enabled(self, value: bool) -> None: self._enabled = value for delegate in self._delegates: delegate.enabled = value @abc.abstractclassmethod def _build_ui(self) -> List[ui.MenuDelegate]: return []
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/focal_distance.py
from .camera_setting import AbstractCameraSetting import omni.usd import omni.ui as ui from omni.ui import scene as sc from omni.ui import constant as fl import omni.kit.undo import omni.kit.app import omni.kit.commands from omni.kit.viewport.menubar.core import SpinnerMenuDelegate, IconMenuDelegate, USDAttributeModel import carb from pxr import Usd, Sdf, Gf import asyncio import weakref import math from typing import List __all__ = ["CamFocalData", "FocusClickGesture", "FocusDragGesture", "PreventOthers", "ViewportClickManipulator", "FocalPickerScene", "CameraFocalDistance"] class CamFocalData: def __init__(self, cam_focal: "CameraFocalDistance", viewport_api): self.__main_cursor = None self.__cam_focal = cam_focal self.viewport_api = viewport_api self.__undo = False self.__auto_destruct = False try: import omni.kit.window.cursor self.__main_cursor = omni.kit.window.cursor.get_main_window_cursor() if self.__main_cursor: self.__main_cursor.override_cursor_shape(carb.windowing.CursorStandardShape.CROSSHAIR) except ImportError: pass def __del__(self): self.destroy() def destroy(self): if self.__undo: self.__undo = False omni.kit.undo.end_group() if self.__main_cursor: self.__main_cursor.clear_overridden_cursor_shape() self.__main_cursor = None if self.__cam_focal: self.__cam_focal._destroy_scene() self.__cam_focal = False self.viewport_api = None def focus_query_completed(self, prim_path: str, world_space_pos, *args): try: viewport_api = self.viewport_api if prim_path and world_space_pos and viewport_api: cam_path = viewport_api.camera_path cam_prim = viewport_api.stage.GetPrimAtPath(cam_path) if not cam_prim: carb.log_error(f'Could not get camera prim at "{cam_path}"') return # Compute world-space camera position to get distance world_space_camera = viewport_api.transform.Transform(Gf.Vec3d(0, 0, 0)) distance = (Gf.Vec3d(*world_space_pos) - world_space_camera).GetLength() if math.isfinite(distance): # Set to the focusDistance attribute on the Camera focus_attr = cam_prim.GetAttribute('focusDistance') # Start an undo-group in case of a drag if not self.__undo: self.__undo = True omni.kit.undo.begin_group() omni.kit.commands.execute('ChangeProperty', prop_path=focus_attr.GetPath(), value=distance, prev=focus_attr.Get() if focus_attr else None) # XXX: Setting to change center of interest TOO ? except Exception: pass finally: if self.__auto_destruct: self.__auto_destruct = None self.destroy() def set_focus_position(self, ndc_mouse, auto_destruct: bool = True): mouse, viewport_api = self.viewport_api.map_ndc_to_texture_pixel(ndc_mouse) if mouse and viewport_api: self.__auto_destruct = auto_destruct viewport_api.request_query(mouse, self.focus_query_completed, query_name='omni.kit.viewport.menubar.camera.FocusQuery') elif auto_destruct: self.destroy() class FocusClickGesture(sc.ClickGesture): def __init__(self, cam_focal_data: CamFocalData, *args, **kwargs): super().__init__(*args, **kwargs) self.__cam_focal_data = cam_focal_data def on_ended(self, *args, **kwargs): if self.state != sc.GestureState.CANCELED: self.__cam_focal_data.set_focus_position(self.sender.gesture_payload.mouse) class FocusDragGesture(sc.DragGesture): def __init__(self, cam_focal_data: CamFocalData, *args, **kwargs): super().__init__(*args, **kwargs) self.__cam_focal_data = cam_focal_data def on_changed(self, *args, **kwargs): self.__cam_focal_data.set_focus_position(self.sender.gesture_payload.mouse, False) def on_ended(self, *args, **kwargs): if self.state != sc.GestureState.CANCELED: self.__cam_focal_data.set_focus_position(self.sender.gesture_payload.mouse) class PreventOthers(sc.GestureManager): '''Class to prevent any gestures (like selection) from interfering with the focus pick''' def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if isinstance(gesture, FocusDragGesture): return False if isinstance(gesture, FocusClickGesture): return False return True class ViewportClickManipulator(sc.Manipulator): def __init__(self, cam_focal_data: CamFocalData, mouse_button: int = 0, *args, **kwargs): super().__init__(*args, **kwargs) self.__gestures = [FocusDragGesture(cam_focal_data, mouse_button=mouse_button, manager=PreventOthers()), FocusClickGesture(cam_focal_data, mouse_button=mouse_button, manager=PreventOthers())] self.__transform = None def __del__(self): self.destroy() def on_build(self): # Need to hold a reference to this or the sc.Screen would be destroyed when out of scope self.__transform = sc.Transform() with self.__transform: self.__screen = sc.Screen(gestures=self.__gestures) def destroy(self): self.__gestures = None self.__screen = None if self.__transform: self.__transform.clear() self.__transform = None class FocalPickerScene: def __init__(self, cam_focal_data: CamFocalData, ui_frame): self.__ui_frame = ui_frame self.__manip = None self.__scene = None with ui_frame: # Need to insert a stack to get content_clipping and block events from going below us self.__container = ui.VStack(content_clipping=True) with self.__container: self.__scene = sc.SceneView() with self.__scene.scene: self.__manip = ViewportClickManipulator(cam_focal_data) def __del__(self): self.destroy() def destroy(self): manip, self.__manip = self.__manip, None if manip: manip.destroy() scene, self.__scene = self.__scene, None if scene: scene.destroy() container, self.__container = self.__container, None if container: container.clear() container.destroy() # Clear ui.Frame, but kep it alive for next click ui_frame, self.__ui_frame = self.__ui_frame, None if ui_frame: ui_frame.clear() class CameraFocalDistance(AbstractCameraSetting): def __init__(self, model: USDAttributeModel, viewport_context, enabled: bool = True): self.__registered_scene = None self.__viewport_api = viewport_context.get("viewport_api") self.__ui_get_frame = viewport_context.get("layer_provider") super().__init__(model, enabled=enabled) def destroy(self): self.__viewport_api = None self.__ui_get_frame = None self._destroy_scene() def _build_ui(self) -> List[ui.MenuDelegate]: self._focal_delegate = SpinnerMenuDelegate( model=self._property_model, height=26, enabled=self._enabled, text=False, icon_name="FocalDistance", tooltip="Camera Focal Distance", icon_height=26, use_in_menubar=True, ) ui.MenuItem("Focal Distance", delegate=self._focal_delegate, identifier="viewport.camera.focal_distance") self._sample_delegate = IconMenuDelegate(name="Sample", height=26, has_triangle=False, enabled=self._enabled, tooltip="Sample Focal Distance") ui.MenuItem("Sample", delegate=self._sample_delegate, triggered_fn=self._sample, enabled=self._enabled, identifier="viewport.camera.sample") return [self._focal_delegate, self._sample_delegate] def _sample(self): if self.__registered_scene: # stop sample self._destroy_scene() elif self._enabled: # start sample asyncio.ensure_future(self.__create_focus_picker_scene()) async def __create_focus_picker_scene(self): await omni.kit.app.get_app().next_update_async() self.__destroy_scene_sync() self.__registered_scene = FocalPickerScene(CamFocalData(weakref.proxy(self), self.__viewport_api), self.__ui_get_frame.get_frame("omni.kit.viewport.menubar.camera.FocalPickerScene")) def __destroy_scene_sync(self): if self.__registered_scene: self.__registered_scene.destroy() self.__registered_scene = None def _destroy_scene(self): # Destroy on next event async def ui_async_destroy(): await omni.kit.app.get_app().next_update_async() self.__destroy_scene_sync() asyncio.ensure_future(ui_async_destroy())
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/expand_menu_item.py
from typing import Dict, Optional import omni.ui as ui from omni.ui import constant as fl class _ExpandButtonDelegate(ui.MenuDelegate): """Simple button with left arrow""" def __init__(self, expanded: bool, **kwargs): self._expanded = expanded self.__icon: Optional[ui.Widget] = None super().__init__(**kwargs) def build_item(self, item: ui.MenuHelper): icon_type = "Menu.Item.Icon" self.__icon = ui.ImageWithProvider( style_type_name_override=icon_type, name="Expand", checked=self._expanded, width=20, height=30, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, ) @property def checked(self) -> bool: return self._expanded @checked.setter def checked(self, value: bool): self._expanded = value if self.__icon: self.__icon.checked = value class ExpandMenuItem(ui.MenuItem): def __init__(self, expand_model): self.__model = expand_model super().__init__( "Expand", delegate=_ExpandButtonDelegate(self.__model.as_bool), triggered_fn=lambda: self.__model.set_value(not self.__model.as_bool), identifier="viewport.camera.expand", ) @property def checked(self): return self.delegate.checked @checked.setter def checked(self, value: bool): self.delegate.checked = value
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/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.camera import get_instance as _get_menubar_extension from omni.kit.viewport.menubar.camera import SingleCameraMenuItem as _SingleCameraMenuItem from omni.kit.viewport.menubar.camera import SingleCameraMenuItemBase as _SingleCameraMenuItemBase from omni.kit.viewport.menubar.camera.camera_menu_container import CameraMenuContainer as _CameraMenuContainer 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_camera_menu_item(*args, **kwargs): class SingleCameraMenuItem(_SingleCameraMenuItemBase): pass return SingleCameraMenuItem(*args, **kwargs) extension = _get_menubar_extension() self.assertIsNotNone(extension) try: with patch.object(_CameraMenuContainer, "set_menu_item_type") as set_menu_item_type_mock: fn = functools.partial(_single_camera_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_camera_menu_item(*args, **kwargs): return _SingleCameraMenuItem(*args, **kwargs) extension = _get_menubar_extension() self.assertIsNotNone(extension) try: with patch.object(_CameraMenuContainer, "set_menu_item_type") as set_menu_item_type_mock: fn = functools.partial(_single_camera_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)
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/__init__.py
from .test_api import * from .test_commands import * from .test_ui import * from .test_focal_distance import *
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_ui.py
from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.menubar.camera import get_instance as _get_menubar_extension from omni.kit.viewport.menubar.camera import SingleCameraMenuItemBase from omni.kit.viewport.utility import get_active_viewport, get_active_viewport_window import omni.usd import omni.kit.app import functools import omni.kit.test import omni.appwindow import carb.input from pathlib import Path import omni.ui as ui import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 import unittest from pxr import Sdf, Usd, UsdGeom CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 850, 300 class ToggleExpansionState(): def __init__(self): self.__settings = carb.settings.get_settings() self.__key = "/persistent/exts/omni.kit.viewport.menubar.camera/expand" self.__restore_value = self.__settings.get(self.__key) def set(self, value: bool): self.__settings.set(self.__key, value) def __del__(self): self.__settings.set(self.__key, self.__restore_value) class TestCameraMenuWindow(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() context = omni.usd.get_context() # Create a new stage to show camera parameters await context.new_stage_async() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def test_general(self): await self.finalize_test(golden_img_name="menubar_camera.png") async def test_lock(self): viewport = get_active_viewport() viewport.camera_path = UsdGeom.Camera.Define(viewport.stage, '/NewCamera').GetPath() path = Sdf.Path(viewport.camera_path).AppendProperty("omni:kit:cameraLock") omni.kit.commands.execute('ChangePropertyCommand', prop_path=path, value=True, prev=False, timecode=Usd.TimeCode.Default(), type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool) try: await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_name="menubar_camera_locked.png") finally: omni.kit.commands.execute('ChangePropertyCommand', prop_path=path, value=False, prev=False, timecode=Usd.TimeCode.Default(), type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool) async def test_collapsed(self): """Test collapse/expand functionality of additional camera properties""" settings = carb.settings.get_settings() expand_state = ToggleExpansionState() try: expand_state.set(False) await self.finalize_test(golden_img_name="menubar_camera_collpased.png") expand_state.set(True) await self.finalize_test(golden_img_name="menubar_camera_expanded.png") finally: del expand_state await self.wait_n_updates() async def test_resize_4_in_1(self): restore_width = self._viewport_window.width expand_state = ToggleExpansionState() expand_state.set(True) await self.wait_n_updates(2) try: # resize 1: contract settings self._viewport_window.width = 200 await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_contract_settings.png") # resize 2: contract text self._viewport_window.width = 60 await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_contract_text.png") # resize 3 : expand text self._viewport_window.width = 200 await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_expand_text.png") # resize 4 : expand settings self._viewport_window.width = restore_width await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_expand_settings.png") finally: del expand_state self._viewport_window.width = restore_width await self.wait_n_updates() async def test_user_menu_item(self): def __create_first(viewport_context, root): ui.MenuItem("This is first custom menu item") def __create_second(viewport_context, root): ui.MenuItem("This is second custom menu item") expand_state = ToggleExpansionState() instance = omni.kit.viewport.menubar.camera.get_instance() try: instance.register_menu_item(__create_second, order=20) instance.register_menu_item(__create_first, order=10) expand_state.set(True) await self.__click_root_menu_item() await self.finalize_test(golden_img_name="menubar_camera_custom.png") await ui_test.emulate_mouse_click() expand_state.set(False) await self.__click_root_menu_item() await self.finalize_test(golden_img_name="menubar_camera_custom_collapsed.png") finally: await ui_test.emulate_mouse_click() instance.deregister_menu_item(__create_first) instance.deregister_menu_item(__create_second) del expand_state await self.wait_n_updates() async def __click_root_menu_item(self): # 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(Vec2(40, 40)) await ui_test.emulate_mouse_click() await self.wait_n_updates() async def test_camera_menu_with_custom_type(self): menu_option_clicked = 0 def _single_camera_menu_item(*args, **kwargs): class SingleCameraMenuItem(SingleCameraMenuItemBase): def _option_clicked(self): nonlocal menu_option_clicked menu_option_clicked += 1 return SingleCameraMenuItem(*args, **kwargs) await self.__click_root_menu_item() self.assertEqual(0, menu_option_clicked) await ui_test.emulate_mouse_move(Vec2(140, 110)) await ui_test.emulate_mouse_click() await self.wait_n_updates() self.assertEqual(0, menu_option_clicked) extension = _get_menubar_extension() try: extension.register_menu_item_type( functools.partial(_single_camera_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) # Call it again to hide popup menu window await self.__click_root_menu_item() async def test_external_cam_change(self): # Get the Viewport and change the active camera viewport = get_active_viewport() orig_cam_path = viewport.camera_path new_cam_path = Sdf.Path('/OmniverseKit_Top') self.assertNotEqual(orig_cam_path, new_cam_path) try: viewport.camera_path = new_cam_path # Change should be reflected in UI await self.wait_n_updates(10) await self.finalize_test(golden_img_name="menubar_camera_external_cam_change.png") finally: viewport.camera_path = orig_cam_path class TestCameraMenuHideStageCameras(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() context = omni.usd.get_context() carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showStageCameras", False) # Create a new stage to show camera parameters await context.new_stage_async() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showStageCameras", True) await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def __click_root_menu_item(self): # 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(Vec2(40, 40)) await ui_test.emulate_mouse_click() await self.wait_n_updates() async def test_hide_stage_cameras(self): """Test hide functionality of stage cameras properties""" await self.__click_root_menu_item() try: await self.finalize_test(golden_img_name="menubar_hide_stage_cameras.png") finally: await self.wait_n_updates() await self.__click_root_menu_item() class TestCameraMenuHideManualExposure(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() context = omni.usd.get_context() carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showManualExposure", False) # Create a new stage to show camera parameters await context.new_stage_async() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showManualExposure", True) await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def test_hide_manual_exposure(self): """Test hiding of manual exposure camera properties""" try: await self.finalize_test(golden_img_name="menubar_hide_manual_exposure.png") finally: await self.wait_n_updates()
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_focal_distance.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 carb.input from omni.ui.tests.test_base import OmniUiTest import omni.usd from pxr import Gf, UsdGeom import omni.kit.ui_test as ui_test from omni.kit.viewport.utility import get_active_viewport_window from omni.kit.ui_test import Vec2 TEST_WIDTH, TEST_HEIGHT = 850, 300 class TestFocalDistance(OmniUiTest): async def setUp(self): self.usd_context_name = '' self.usd_context = omni.usd.get_context(self.usd_context_name) await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() self.stage.SetDefaultPrim(UsdGeom.Xform.Define(self.stage, '/World').GetPrim()) await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): self.usd_context = None self.stage = None async def test_cam_sample_focal_distance(self): # create a test camera cam_path = '/World/TestCamera' cam_prim = UsdGeom.Camera.Define(self.stage, cam_path).GetPrim() omni.kit.commands.execute("TransformPrimSRTCommand", path=cam_path, new_translation=Gf.Vec3d(0, 0, 15)) focus_dist_attr = cam_prim.GetAttribute('focusDistance') focus_dist_attr.Set(400) # create a cube as the sample sample_path = '/World/Cube' UsdGeom.Cube.Define(self.stage, sample_path) await self.wait_n_updates(300) # set the test cam to be the viewport cam app_window = omni.appwindow.get_default_app_window() app_window.set_input_blocking_state(carb.input.DeviceType.MOUSE, None) # open camera list await ui_test.emulate_mouse_move(Vec2(40, 40)) await ui_test.emulate_mouse_click() await self.wait_n_updates() # cameras await ui_test.emulate_mouse_move(Vec2(40, 75)) await ui_test.emulate_mouse_click() await self.wait_n_updates() # choose test camera await ui_test.emulate_mouse_move(Vec2(200, 75)) await ui_test.emulate_mouse_click() await self.wait_n_updates() # decrease the focal distance by 3 await ui_test.emulate_mouse_move(Vec2(340, 50)) for _ in range(3): await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates() self.assertEqual(focus_dist_attr.Get(), 397) # click focal sample button to enable sample picker await ui_test.emulate_mouse_move(Vec2(370, 40)) await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates() # click the sample object (cube) to reset the focal distance await ui_test.emulate_mouse_move(Vec2(420, 150)) await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates(10) self.assertAlmostEqual(focus_dist_attr.Get(), 14, places=2)
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_commands.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__ = ['TestCommands'] import omni.kit.test from omni.kit.test import AsyncTestCase import omni.usd from pxr import Gf, Sdf, UsdGeom import omni.kit.undo import carb # Test that the Viewport-level commands reach the proper methods class TestViewportAPI: def __init__(self, usd_context_name, cam_path: str = None): self.usd_context_name = usd_context_name self.usd_context = omni.usd.get_context() self.stage = self.usd_context.get_stage() self.__camera_path = cam_path @property def camera_path(self): return self.__camera_path @camera_path.setter def camera_path(self, cam_path): self.__camera_path = cam_path class TestCommands(AsyncTestCase): async def setUp(self): self.usd_context_name = '' self.usd_context = omni.usd.get_context(self.usd_context_name) await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() self.stage.SetDefaultPrim(UsdGeom.Xform.Define(self.stage, '/World').GetPrim()) async def tearDown(self): self.usd_context = None self.stage = None async def test_duplicate_camera(self): def get_num_xform_ops(cam: UsdGeom.Camera): xform_ops = cam.GetOrderedXformOps() return len(xform_ops) if xform_ops else 0 cam_path = '/World/TestCamera' new_camera = UsdGeom.Camera.Define(self.stage, '/World/TestCamera') # This camera has no xformOps self.assertEqual(0, get_num_xform_ops(new_camera)) omni.kit.commands.execute("DuplicateCameraCommand", camera_path=cam_path) # Should have duplicated to '/World/Camera' dup_camera_path = '/World/Camera' dup_camera = UsdGeom.Camera(self.stage.GetPrimAtPath(dup_camera_path)) # Validate the new camera self.assertIsNotNone(dup_camera) self.assertTrue(bool(dup_camera)) # Should have 3 xformOps, in order to honor the defaut camera roation order self.assertEqual(3, get_num_xform_ops(dup_camera)) # Test duplication of implicit camera omni.kit.commands.execute("DuplicateCameraCommand", camera_path='/OmniverseKit_Persp') # Test both of these meta-data entries are true for an implicit Camera self.assertTrue(omni.usd.editor.is_hide_in_stage_window(self.stage.GetPrimAtPath('/OmniverseKit_Persp'))) self.assertTrue(omni.usd.editor.is_no_delete(self.stage.GetPrimAtPath('/OmniverseKit_Persp'))) num_xfops_1 = get_num_xform_ops(new_camera) # Should have duplicated to '/World/Camera_1' dup_camera_path = '/World/Camera_01' dup_camera = UsdGeom.Camera(self.stage.GetPrimAtPath(cam_path)) # Validate the new camera self.assertIsNotNone(dup_camera) self.assertTrue(bool(dup_camera)) # Should have same number of xformOps now self.assertEqual(num_xfops_1, get_num_xform_ops(dup_camera)) # Test both of these meta-data entries are false after duplicating an implicit Camera self.assertFalse(omni.usd.editor.is_hide_in_stage_window(dup_camera.GetPrim())) self.assertFalse(omni.usd.editor.is_no_delete(dup_camera.GetPrim())) async def test_duplicate_camera_unlocked(self): cam_path = '/World/TestCamera' cam_lock = 'omni:kit:cameraLock' usd_camera = UsdGeom.Camera.Define(self.stage, '/World/TestCamera') prop = usd_camera.GetPrim().CreateAttribute(cam_lock, Sdf.ValueTypeNames.Bool, True) prop.Set(True) # Make sure the lock attribute is present and set to true self.assertTrue(usd_camera.GetPrim().GetAttribute(cam_lock).Get()) omni.kit.commands.execute("DuplicateCameraCommand", camera_path=cam_path) cam_path = '/World/Camera' # Should have duplicated to '/World/Camera' new_camera = UsdGeom.Camera(self.stage.GetPrimAtPath(cam_path)) # Validate the new camera self.assertIsNotNone(new_camera) self.assertTrue(bool(new_camera)) # Make sure the lock attribute wasn't copied over self.assertFalse(new_camera.GetPrim().GetAttribute(cam_lock).IsValid()) # Nothing should have affected the original self.assertTrue(usd_camera.GetPrim().GetAttribute(cam_lock).Get()) async def test_duplicate_camera_with_name(self): cam_path = '/World/TestCamera' UsdGeom.Camera.Define(self.stage, '/World/TestCamera') new_cam_path = '/World/TestDuplicatedCamera' omni.kit.commands.execute("DuplicateCameraCommand", camera_path=cam_path, new_camera_path=new_cam_path) # Should have duplicated to '/World/TestDuplicatedCamera' camera = UsdGeom.Camera(self.stage.GetPrimAtPath(new_cam_path)) # Validate the new camera self.assertIsNotNone(camera) self.assertTrue(bool(camera)) # Undo the command omni.kit.undo.undo() # Camera should no longer be valid (its been deleted) self.assertFalse(bool(camera)) async def test_duplicate_viewport_camera(self): cam_path = '/World/TestCamera' UsdGeom.Camera.Define(self.stage, cam_path) viewport_api = TestViewportAPI(self.usd_context_name, cam_path) omni.kit.commands.execute("DuplicateViewportCameraCommand", viewport_api=viewport_api) # Should have duplicated to '/World/Camera' new_cam_path = '/World/Camera' camera = UsdGeom.Camera(self.stage.GetPrimAtPath(new_cam_path)) # Validate the new camera self.assertIsNotNone(camera) self.assertTrue(bool(camera)) self.assertEqual(viewport_api.camera_path, new_cam_path) # Undo the command omni.kit.undo.undo() # Viewport should have been reset self.assertEqual(viewport_api.camera_path, cam_path) # Camera should no longer be valid (its been deleted) self.assertFalse(bool(camera)) async def __test_duplicate_viewport_camera_hierarchy(self, rot_order: str = None): settings = carb.settings.get_settings() try: default_prim = self.stage.GetDefaultPrim() root_path = default_prim.GetPath().pathString if default_prim else '' parent_paths = (f'{root_path}/Xform0', f'{root_path}/Xform0/Xform1') cam_path = f'{parent_paths[1]}/TestCamera' UsdGeom.Xform.Define(self.stage, parent_paths[0]) omni.kit.commands.execute("TransformPrimSRTCommand", path=parent_paths[0], new_translation=Gf.Vec3d(10, 10, 10)) UsdGeom.Xform.Define(self.stage, parent_paths[1]) omni.kit.commands.execute("TransformPrimSRTCommand", path=parent_paths[1], new_translation=Gf.Vec3d(10, 10, 10), new_rotation_euler=Gf.Vec3d(90, 0, 0)) UsdGeom.Camera.Define(self.stage, cam_path) omni.kit.commands.execute("TransformPrimSRTCommand", path=cam_path, new_translation=Gf.Vec3d(10, 10, 10), new_rotation_euler=Gf.Vec3d(90, 0, 0)) # Set the rotation order now to test that moving from an existing order to a new one works if rot_order: settings.set('/persistent/app/primCreation/DefaultCameraRotationOrder', rot_order) viewport_api = TestViewportAPI(self.usd_context_name, cam_path) omni.kit.commands.execute("DuplicateViewportCameraCommand", viewport_api=viewport_api) # Should have duplicated to '/World/Camera' new_cam_path = f'{root_path}/Camera' camera = UsdGeom.Camera(self.stage.GetPrimAtPath(new_cam_path)) # Validate the new camera self.assertIsNotNone(camera) self.assertTrue(bool(camera)) self.assertEqual(viewport_api.camera_path, new_cam_path) src_xform = omni.usd.get_world_transform_matrix(self.stage.GetPrimAtPath(cam_path)) dst_xform = omni.usd.get_world_transform_matrix(self.stage.GetPrimAtPath(new_cam_path)) self.assertTrue(Gf.IsClose(src_xform, dst_xform, 1.0e-5)) if rot_order: self.assertTrue(f'xformOp:rotate{rot_order}' in camera.GetXformOpOrderAttr().Get()) finally: if rot_order: settings.destroy_item('/persistent/app/primCreation/DefaultCameraRotationOrder') async def test_duplicate_viewport_camera_hierarchy(self): await self.__test_duplicate_viewport_camera_hierarchy() async def test_duplicate_viewport_camera_hierarchy_with_order(self): '''Test duplictaing a camera that is nested in a transformed honors default camera rotation order''' await self.__test_duplicate_viewport_camera_hierarchy('XYZ') # Test again with a different order and also without a default prim await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() await self.__test_duplicate_viewport_camera_hierarchy('ZYX') async def test_set_viewport_camera(self): cam_path = '/World/TestCamera' cam_path2 = '/World/TestCamera2' UsdGeom.Camera.Define(self.stage, cam_path) UsdGeom.Camera.Define(self.stage, cam_path) viewport_api = TestViewportAPI(self.usd_context_name, cam_path) omni.kit.commands.execute("SetViewportCameraCommand", camera_path=cam_path2, viewport_api=viewport_api) # Should now be set to cam_path2 self.assertEqual(viewport_api.camera_path, cam_path2) # Undo the command omni.kit.undo.undo() # Should now be set to cam_path self.assertEqual(viewport_api.camera_path, cam_path)
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/docs/index.rst
omni.kit.viewport.menubar.camera ################################# Camera Setting in Viewport MenuBar .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule:: omni.kit.viewport.menubar.camera :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members:
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/PACKAGE-LICENSES/omni.kit.viewport.legacy_gizmos-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/config/extension.toml
[package] version = "1.0.10" title = "Legacy Viewport Gizmo drawing" description = "Deprecated API to draw gizmos in the viewport." authors = ["NVIDIA"] category = "Viewport" repository = "" readme = "docs/README.md" keywords = ["kit", "viewport", "gizmo"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [[native.plugin]] path = "bin/*.plugin" recursive = false [dependencies] "omni.usd" = {} [[python.module]] name = "omni.kit.viewport.legacy_gizmos" [settings] # Whether the Viewprt grid is enabled/visible or not app.viewport.grid.enabled = true # Whether to automatically update the grid-plane based on UsdContext and active camera app.viewport.grid.trackCamera = false [[test]] # RTX may need to build the shader-cache, so give it some time timeout = 900 dependencies = [ # FIXME: omni.ui provides carb.Format conversions required "omni.ui", "omni.hydra.rtx", "omni.kit.hydra_texture", "omni.kit.renderer.capture", "omni.kit.test_helpers_gfx" ] args = [ "--/renderer/enabled=rtx", "--/app/asyncRendering=false", "--/omni.kit.plugin/syncUsdLoads=true", "--/rtx/hydra/materialSyncLoads=true", "--/rtx/materialDb/syncLoads=true", "--/rtx/post/aa/op=0", "--/rtx/reflections/enabled=0", "--/rtx-defaults/post/aa/op=0", "--/rtx-defaults/reflections/enabled=0", "--no-window" ] unreliable = true # OM-49114 [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/omni/kit/viewport/legacy_gizmos/__init__.py
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/omni/kit/viewport/legacy_gizmos/tests/test_legacy_gizmos.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 pathlib import asyncio import carb import omni.kit.app import omni.kit.test import omni.hydratexture import omni.renderer_capture from omni.kit.test_helpers_gfx.compare_utils import finalize_capture_and_compare, ComparisonMetric import omni.usd from pxr import Usd, Gf # FIXME: omni.ui.ImageProvider holds the carb.Format conversion routine import omni.ui EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TEST_DATA_DIR = EXTENSION_FOLDER_PATH.joinpath('data', 'tests') KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve('${kit}')).parent.parent.parent OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path()) from sys import platform if platform.find('linux') == 0: IMAGE_PLATFORM='linux' elif platform == 'darwin': IMAGE_PLATFORM='macos' elif platform == 'win32': IMAGE_PLATFORM='windows' class TestLegacyGizmos(omni.kit.test.AsyncTestCase): async def setUp(self): self._settings = carb.settings.acquire_settings_interface() self._hydra_texture_factory = omni.hydratexture.acquire_hydra_texture_factory_interface() self._render_capture = omni.renderer_capture.acquire_renderer_capture_interface() self._usd_context_name = 'test_context' self._usd_context = omni.usd.create_context(self._usd_context_name) async def tearDown(self): omni.usd.release_all_hydra_engines(self._usd_context) omni.usd.destroy_context(self._usd_context_name) self._hydra_texture_factory = None self._settings = None self._render_capture = None async def _create_hydra_texture_test(self, filename: str = None): wait_iterations = 15 try: if 'rtx' not in self._usd_context.get_attached_hydra_engine_names(): omni.usd.add_hydra_engine('rtx', self._usd_context) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async() if filename: test_usd_asset = TEST_DATA_DIR.joinpath(filename) self._usd_context.open_stage_with_callback(str(test_usd_asset), None) else: self._usd_context.new_stage_with_callback(None) hydra_texture = self._hydra_texture_factory.create_hydra_texture( 'test_viewport', 320, 320, self._usd_context_name, '/OmniverseKit_Persp', 'rtx', is_async=False ) return hydra_texture finally: for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async() async def _capture_hydra_texture(self, hydra_texture, test_name: str, converge: int = 5, platform_image: bool = False): drawable_result = asyncio.Future() if platform_image: global IMAGE_PLATFORM image_name = f'{test_name}_{IMAGE_PLATFORM}.png' else: image_name = f'{test_name}.png' filepath = OUTPUTS_DIR.joinpath(image_name).absolute() def on_drawable_changed(event: carb.events.IEvent): if event.type != omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED: carb.log_error('Wrong event captured for DRAWABLE_CHANGED') return result_handle = event.payload['result_handle'] self.assertIsNotNone(result_handle) ldr_info = hydra_texture.get_aov_info(result_handle, 'LdrColor', include_texture=True) self.assertEqual(len(ldr_info), 1) self.assertEqual(ldr_info[0]['name'], 'LdrColor') ldr_tex = ldr_info[0]['texture'] self.assertIsNotNone(ldr_tex) ldr_rsrc = ldr_tex['rp_resource'] self.assertIsNotNone(ldr_rsrc) nonlocal converge converge = converge - 1 if converge <= 0 and not drawable_result.done(): self._render_capture.capture_next_frame_rp_resource(str(filepath), ldr_rsrc) drawable_result.set_result(True) drawable_change_sub = hydra_texture.get_event_stream().create_subscription_to_push_by_type( omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED, on_drawable_changed, name="_capture_hydra_texture", ) result = await drawable_result drawable_change_sub = None self.assertTrue(result) return image_name async def capture_and_compare(self, image_name: str, threshold: float = 1e-4): # self._render_capture.wait_async_capture() diff = finalize_capture_and_compare(image_name, threshold=threshold, output_img_dir=OUTPUTS_DIR, golden_img_dir=TEST_DATA_DIR, metric=ComparisonMetric.MEAN_ERROR_SQUARED) if diff > threshold: carb.log_error(f'The generated image {image_name} has a difference of {diff}, but max difference is {threshold}') async def test_light_gizmos(self): hydra_texture = await self._create_hydra_texture_test('gizmos.usda') self.assertIsNotNone(hydra_texture) # >> test_sphere_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 1) self._settings.set('/persistent/app/viewport/gizmo/scale', 1) self._usd_context.get_selection().set_selected_prim_paths(['/World/SphereLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_sphere_light', platform_image=True) await self.capture_and_compare(image) # << test_sphere_light # >> test_cylinder_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 2) self._settings.set('/persistent/app/viewport/gizmo/scale', 2) self._usd_context.get_selection().set_selected_prim_paths(['/World/CylinderLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_cylinder_light', platform_image=True) await self.capture_and_compare(image) # << test_cylinder_light # >> test_disk_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 10) self._settings.set('/persistent/app/viewport/gizmo/scale', 10) self._usd_context.get_selection().set_selected_prim_paths(['/World/DiskLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_disk_light', platform_image=True) await self.capture_and_compare(image) # << test_disk_light # >> test_rect_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 20) self._settings.set('/persistent/app/viewport/gizmo/scale', 20) self._usd_context.get_selection().set_selected_prim_paths(['/World/RectLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_rect_light', platform_image=True) await self.capture_and_compare(image) # << test_rect_light async def test_grid_drawing(self): hydra_texture = await self._create_hydra_texture_test('empty.usda') self.assertIsNotNone(hydra_texture) # >> test_grid_drawing self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/persistent/app/viewport/grid/lineWidth', 1) self._settings.set('/persistent/app/viewport/grid/scale', 100) # Need to wait for slightly more frames on Linux to avoid writing black imge / failure image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing', converge=20) await self.capture_and_compare(image) # << test_grid_drawing # >> test_grid_drawing_yz self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/app/viewport/grid/plane', 'YZ') self._settings.set('/persistent/app/viewport/grid/lineWidth', 10) self._settings.set('/persistent/app/viewport/grid/scale', 150) image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing_yz') await self.capture_and_compare(image) # << test_grid_drawing_yz # >> test_grid_drawing_xy self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/app/viewport/grid/plane', 'XY') self._settings.set('/persistent/app/viewport/grid/lineWidth', 4) self._settings.set('/persistent/app/viewport/grid/scale', 200) image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing_xy') await self.capture_and_compare(image) # << test_grid_drawing_xy # >> test_grid_drawing_xz self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/app/viewport/grid/plane', 'XZ') self._settings.set('/persistent/app/viewport/grid/lineWidth', 6) self._settings.set('/persistent/app/viewport/grid/scale', 250) image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing_xz') await self.capture_and_compare(image) # << test_grid_drawing_xz async def test_camera_gizmos(self): hydra_texture = await self._create_hydra_texture_test('cameras.usda') self.assertIsNotNone(hydra_texture) wait_iterations = 5 try: self._settings.set('/app/viewport/show/camera', True) self._settings.set('/persistent/app/viewport/gizmo/constantScaleCamera', False) self._settings.set('/persistent/app/viewport/gizmo/constantScaleEnabled', False) self._settings.set('/persistent/app/viewport/gizmo/constantScale', 10.0) self._settings.set('/persistent/app/viewport/gizmo/scale', 2.0) self._settings.set('/app/viewport/grid/enabled', False) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async(); image = await self._capture_hydra_texture(hydra_texture, 'test_camera_drawing_0') await self.capture_and_compare(image) stage = self._usd_context.get_stage() camera_prim = stage.GetPrimAtPath('/World/Camera') camera_prim.GetAttribute('xformOp:translate').Set(Gf.Vec3d(0, 0, -250)) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async(); image = await self._capture_hydra_texture(hydra_texture, 'test_camera_drawing_1') await self.capture_and_compare(image) self._settings.set('/persistent/app/viewport/gizmo/constantScale', 50.0) self._settings.set('/persistent/app/viewport/gizmo/constantScaleEnabled', True) self._settings.set('/persistent/app/viewport/gizmo/constantScaleCamera', True) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async(); image = await self._capture_hydra_texture(hydra_texture, 'test_camera_drawing_2') await self.capture_and_compare(image) finally: self._settings.set('/app/viewport/show/camera', False) self._settings.set('/persistent/app/viewport/gizmo/scale', 1.0) self._settings.set('/persistent/app/viewport/gizmo/constantScale', 10.0) self._settings.set('/persistent/app/viewport/gizmo/constantScaleEnabled', True) self._settings.set('/persistent/app/viewport/gizmo/constantScaleCamera', False)
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/omni/kit/viewport/legacy_gizmos/tests/__init__.py
from .test_legacy_gizmos import TestLegacyGizmos
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.10] - 2023-01-31 ### Added - /app/viewport/grid/offset setting to control grid placement in relation to origin. - Ability to disable bounding box updates during user intraction. ## [1.0.9] - 2023-01-25 ### Added - /app/viewport/grid/trackCamera setting to automatically update grid based on camera. ## [1.0.8] - 2022-12-09 ### Fixed - Issue with slow billboard updates during camera movement. ## [1.0.7] - 2022-10-24 ### Fixed - Clearing of gizmo prims when exiting live session. ## [1.0.6] - 2022-08-22 ### Fixed - Acquire Usd read lock in draw call. ## [1.0.5] - 2022-08-22 ### Fixed - Support latest UsdContext r/w lock pattern. ## [1.0.4] - 2022-08-08 ### Fixed - Performance issues when updating many USD scene representation cameras. ## [1.0.3] - 2022-08-05 ### Added - Remove camera gizmo if camera prim is removed or camera visibility turns off. ## [1.0.2] - 2022-07-26 ### Added - Honor camera scale independent of gizmo constant scale enabled state. - Ability to create and update legacy USD camera mesh representations. - Push values to /app/viewport/boundingBoxes/enabled as legacy Viewport did. ## [1.0.1] - 2022-02-03 - Added tests. ## [1.0.0] - 2021-10-15 - Initial version
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/docs/index.rst
omni.kit.viewport.legacy_gizmos ################################################################################# API Reference ============== .. automodule:: omni.kit.viewport.legacy_gizmos :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members:
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/docs/Overview.md
# Overview
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/data/tests/gizmos.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { string boundCamera = "/OmniverseKit_Persp" } } defaultPrim = "World" metersPerUnit = 0.01 upAxis = "Y" ) def Xform "World" { def DistantLight "defaultLight" ( apiSchemas = ["ShapingAPI"] ) { float angle = 1 float intensity = 3000 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file double3 xformOp:rotateXYZ = (315, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def SphereLight "SphereLight" ( apiSchemas = ["ShapingAPI"] ) { float intensity = 30000 float radius = 50 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (-250, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def RectLight "RectLight" ( apiSchemas = ["ShapingAPI"] ) { float height = 100 float intensity = 15000 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file float width = 100 double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, -250) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def DiskLight "DiskLight" ( apiSchemas = ["ShapingAPI"] ) { float intensity = 60000 float radius = 50 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 250) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def CylinderLight "CylinderLight" ( apiSchemas = ["ShapingAPI"] ) { float intensity = 30000 float length = 100 float radius = 5 float shaping:cone:angle = 180 float shaping:cone:softness float shaping:focus color3f shaping:focusTint asset shaping:ies:file double3 xformOp:rotateXYZ = (0, 0, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (250, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } } def Camera "OmniverseKit_Persp" ( hide_in_stage_window = true kind = "component" no_delete = true ) { float4[] clippingPlanes = [] float2 clippingRange = (1, 10000000) float focalLength = 30 float focusDistance = 0 float fStop = 0 float horizontalAperture = 20.955 float horizontalApertureOffset = 0 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -866.0254037844386) token projection = "perspective" float verticalAperture = 15.2908 float verticalApertureOffset = 0 double3 xformOp:rotateXYZ = (-35, 45.00000000000003, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (500, 500, 500) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Camera "OmniverseKit_Front" { float4[] clippingPlanes = [] float2 clippingRange = (20000, 10000000) float focalLength = 50 float focusDistance = 0 float fStop = 0 float horizontalAperture = 10000 float horizontalApertureOffset = 0 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -50000) token projection = "orthographic" float verticalAperture = 3648.4849 float verticalApertureOffset = 0 double3 xformOp:translate = (0, 0, 50000) uniform token[] xformOpOrder = ["xformOp:translate"] } def Camera "OmniverseKit_Top" { float4[] clippingPlanes = [] float2 clippingRange = (20000, 10000000) float focalLength = 50 float focusDistance = 0 float fStop = 0 float horizontalAperture = 10000 float horizontalApertureOffset = 0 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -50000) token projection = "orthographic" float verticalAperture = 3648.4849 float verticalApertureOffset = 0 double3 xformOp:rotateXYZ = (90, 0, -180) double3 xformOp:translate = (0, 50000, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"] } def Camera "OmniverseKit_Right" { float4[] clippingPlanes = [] float2 clippingRange = (20000, 10000000) float focalLength = 50 float focusDistance = 0 float fStop = 0 float horizontalAperture = 10000 float horizontalApertureOffset = 0 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -50000) token projection = "orthographic" float verticalAperture = 3648.4849 float verticalApertureOffset = 0 double3 xformOp:rotateXYZ = (0, -90, -0) double3 xformOp:translate = (-50000, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"] }
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/data/tests/cameras.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { dictionary Perspective = { double3 position = (500, 500, 500) double3 target = (0, 0, 0) } dictionary Front = { double3 position = (0, 0, 150) } dictionary Right = { double3 position = (-150, 0, 0) } dictionary Top = { double3 position = (0, 150, 0) } string boundCamera = "/OmniverseKit_Persp" } dictionary omni_layer = { dictionary muteness = { } } dictionary renderSettings = { bool "rtx:pathtracing:nrc:canRun" = 0 } } defaultPrim = "World" endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" { def Camera "Camera" { double3 xformOp:translate = (0, 0, 250) uniform token[] xformOpOrder = ["xformOp:translate"] } } def Camera "OmniverseKit_Persp" ( hide_in_stage_window = true no_delete = true ) { float focalLength = 18.147562 float horizontalAperture = 20.955 float verticalAperture = 15.2908 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -866.0254037844387) float3 xformOp:rotateXYZ = (-35.26439, 45, 0) float3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (500, 500, 500) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Camera "OmniverseKit_Front" ( hide_in_stage_window = true no_delete = true ) { float horizontalAperture = 1500 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -150) token projection = "orthographic" float verticalAperture = 1500 float3 xformOp:rotateXYZ = (-0, 0, -0) float3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 0, 150) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Camera "OmniverseKit_Top" ( hide_in_stage_window = true no_delete = true ) { float horizontalAperture = 1500 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -150) token projection = "orthographic" float verticalAperture = 1500 float3 xformOp:rotateXYZ = (90, -4.961563e-15, 180) float3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (0, 150, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Camera "OmniverseKit_Right" ( hide_in_stage_window = true no_delete = true ) { float horizontalAperture = 1500 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -150) token projection = "orthographic" float verticalAperture = 1500 float3 xformOp:rotateXYZ = (0, -90, -0) float3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (-150, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] }
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/data/tests/empty.usda
#usda 1.0 ( customLayerData = { dictionary cameraSettings = { string boundCamera = "/OmniverseKit_Persp" } } defaultPrim = "World" metersPerUnit = 0.01 upAxis = "Y" ) def Xform "World" { } def Camera "OmniverseKit_Persp" ( hide_in_stage_window = true kind = "component" no_delete = true ) { float4[] clippingPlanes = [] float2 clippingRange = (1, 10000000) float focalLength = 30 float focusDistance = 0 float fStop = 0 float horizontalAperture = 20.955 float horizontalApertureOffset = 0 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -866.0254037844386) token projection = "perspective" float verticalAperture = 15.2908 float verticalApertureOffset = 0 double3 xformOp:rotateXYZ = (-35, 45.00000000000003, 0) double3 xformOp:scale = (1, 1, 1) double3 xformOp:translate = (500, 500, 500) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } def Camera "OmniverseKit_Front" { float4[] clippingPlanes = [] float2 clippingRange = (20000, 10000000) float focalLength = 50 float focusDistance = 0 float fStop = 0 float horizontalAperture = 10000 float horizontalApertureOffset = 0 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -50000) token projection = "orthographic" float verticalAperture = 3648.4849 float verticalApertureOffset = 0 double3 xformOp:translate = (0, 0, 50000) uniform token[] xformOpOrder = ["xformOp:translate"] } def Camera "OmniverseKit_Top" { float4[] clippingPlanes = [] float2 clippingRange = (20000, 10000000) float focalLength = 50 float focusDistance = 0 float fStop = 0 float horizontalAperture = 10000 float horizontalApertureOffset = 0 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -50000) token projection = "orthographic" float verticalAperture = 3648.4849 float verticalApertureOffset = 0 double3 xformOp:rotateXYZ = (90, 0, -180) double3 xformOp:translate = (0, 50000, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"] } def Camera "OmniverseKit_Right" { float4[] clippingPlanes = [] float2 clippingRange = (20000, 10000000) float focalLength = 50 float focusDistance = 0 float fStop = 0 float horizontalAperture = 10000 float horizontalApertureOffset = 0 custom uniform vector3d omni:kit:centerOfInterest = (0, 0, -50000) token projection = "orthographic" float verticalAperture = 3648.4849 float verticalApertureOffset = 0 double3 xformOp:rotateXYZ = (0, -90, -0) double3 xformOp:translate = (-50000, 0, 0) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"] }
omniverse-code/kit/exts/omni.kit.notification_manager/PACKAGE-LICENSES/omni.kit.notification_manager-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.notification_manager/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.5" category = "Internal" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Notification Manager" description="Extension that provides interface to post notifications." # URL of the extension source repository. repository = "" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Keywords for the extension keywords = ["kit", "notification"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" [dependencies] "omni.ui" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.kit.notification_manager" [[test]] args = [ "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.commands", "omni.kit.renderer.capture", "omni.kit.mainwindow" ] unreliable = true # OM-48628
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/notification_info.py
class NotificationStatus: WARNING = 0 INFO = 1 class NotificationButtonInfo: def __init__(self, text, on_complete=None): """ Constructor for notification button. text (str): The button text. on_complete (Callable[]): The handler to handle button click. """ self._text = text self._on_complete = on_complete @property def text(self): return self._text @property def handler(self): return self._on_complete class NotificationInfo: def __init__( self, text, hide_after_timeout=True, duration=3, status=NotificationStatus.INFO, button_infos=[]): self._text = text self._hide_after_timeout = hide_after_timeout self._duration = duration self._status = status if not button_infos and not hide_after_timeout: button_info = NotificationButtonInfo("Dismiss", None) self._button_infos = [button_info] else: self._button_infos = button_infos @property def text(self): return self._text @property def hide_after_timeout(self): return self._hide_after_timeout @property def duration(self): return self._duration @property def status(self): return self._status @property def button_infos(self): return self._button_infos
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/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. # import asyncio import os import weakref import omni.ext from functools import partial from .manager import NotificationManager from .notification_info import NotificationInfo, NotificationStatus _global_instance = None def post_notification( text, hide_after_timeout=True, duration=3, status=NotificationStatus.INFO, button_infos=[] ): """ Post notification. If viewport is visible, it will be docked to the right-button of viewport. Otherwise, it will be docked to main window. Args: text (str): The notification text. hide_after_timeout (bool): If the notification will hide after duration. If it's False, and button_details are not provided, it will display a default dismiss button. duration (int): The duration (in seconds) after which the notification will be hidden. This duration only works if hide_after_timeout is True. status (NotificationStatus): The notification type. button_infos ([NotificationButtonInfo]): Array of buttons. Returns: Notification handler. Examples: >>> import omni.kit.notification_manager as nm >>> >>> ok_button = nm.NotificationButtonInfo("OK", on_complete=None) >>> cancel_button = nm.NotificationButtonInfo("CANCEL", on_complete=None) >>> notification = nm.post_notification( "Notification Example", hide_after_timeout=False, duration=0, status=nm.NotificationStatus.WARNING, button_infos=[ok_button, cancel_button]) """ global _global_instance if _global_instance and _global_instance(): ni = NotificationInfo(text, hide_after_timeout, duration, status, button_infos) return _global_instance().post_notification(ni) return None class NotificationManagerExtension(omni.ext.IExt): def on_startup(self): global _global_instance _global_instance = weakref.ref(self) self._notification_manager = NotificationManager() self._notification_manager.on_startup() def on_shutdown(self): global _global_instance _global_instance = None self._notification_manager.on_shutdown() self._notification_manager = None def post_notification(self, notification_info: NotificationInfo): return self._notification_manager.post_notification(notification_info)
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/__init__.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. # from .extension import * from .notification_info import NotificationButtonInfo, NotificationStatus
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/manager.py
import asyncio import carb import omni.kit.app import omni.ui as ui from typing import List from .notification_info import NotificationInfo, NotificationStatus from .prompt import Prompt SETTINGS_DISABLE_NOTIFICATIONS = "/exts/omni.kit.notification_manager/disable_notifications" class Notification: """Handler of notification""" def __init__(self, notification_info: NotificationInfo, notification_manager): """Internal constructor""" self._prompt = None self._notification_info = notification_info self._time_passed = 0 self._notification_mananger = notification_manager self._is_warming = True def destroy(self): self._is_warming = False self._notification_info = None if self._prompt: self._prompt.destroy() self._prompt = None if self._notification_mananger: self._notification_mananger.remove_notification(self) self._notification_mananger = None def _step_and_check(self, dt): if not self._prompt: return True if self._notification_info.hide_after_timeout: if self._time_passed >= self._notification_info.duration: return True self._time_passed += dt return False async def _docking_to(self, window_x, window_y, window_width, window_height, offset_y=0): if self._prompt: await self._prompt.docking_to(window_x, window_y, window_width, window_height, offset_y) def _hide(self): if self._prompt: self._prompt.hide() async def _pre_warming(self): self._prompt = Prompt(self._notification_info) # Set it to a corner pos self._prompt.position_x = 100000 self._prompt.position_y = 100000 # FIXME: After creation, the notification window still # does not have the correct width/height. It needs to # show and wait for the first draw to get correct width/height. # The following code shows it and all notification will # be transparent at the start. After getting correct widht/height, # it will be positioned to correct position later. self._prompt.show() self._is_warming = False async def _warming(): while not self._notification_mananger._shutdown and (self._prompt.width == 0.0 or self._prompt.height == 0.0): await omni.kit.app.get_app().next_update_async() self._hide() if not self._notification_mananger._shutdown: self._notification_mananger._pending_notifications.append(self) await _warming() @property def _dismissed(self): return self._prompt is None or not self._prompt.visible @property def _hovered(self): return self._prompt and self._prompt.hovered @property def info(self): return self._notification_info def dismiss(self): self.destroy() @property def dismissed(self): return not self._is_warming and self._prompt is None class NotificationManager: def on_startup(self): self._max_showed_notifications = 5 self._max_throttle_notifications = self._max_showed_notifications + 2 self._pre_warming_notifications: List[Notification] = [] self._pending_notifications: List[Notification] = [] self._notifications: List[Notification] = [] self._timer_task = None self._shutdown = False self._docking_window_width = 0 self._docking_window_height = 0 self._docking_window_pos_x = 0 self._docking_window_pos_y = 0 async def timer_fn(): while not self._shutdown: """ For each notification, it has 3 stages: 1. When it's created, it will be put in the pre-warming queue. Pre-warming is a WA to calculate the real size of prompt before it's positioning. 2. After pre-warming, it will be put to pending queue and waits to be displayed there. 3. If there is vacancy (determined by _max_showed_notifications), it will be displayed to viewport finally. """ showed_notifications = len(self._pending_notifications) + len(self._notifications) new_notifications = max(self._max_throttle_notifications - showed_notifications, 0) new_notifications = min(len(self._pre_warming_notifications), new_notifications) for _ in range(new_notifications): notification = self._pre_warming_notifications.pop(0) await notification._pre_warming() # To avoid flooding notification queue, all others will be flushed to console. for notification in self._pre_warming_notifications: if notification.info.status == NotificationStatus.INFO: carb.log_info(notification.info.text) else: carb.log_warn(notification.info.text) notification.destroy() self._pre_warming_notifications.clear() changed = self._on_docking_window_changed() pending_to_remove = [] for notification in self._notifications: if ( (notification._step_and_check(0.5) and not notification._hovered) or notification._dismissed ): pending_to_remove.append(notification) if len(pending_to_remove): changed = True for item in pending_to_remove: item.destroy() num_current_notifications = len(self._notifications) if num_current_notifications < self._max_showed_notifications: new_added = self._max_showed_notifications - num_current_notifications else: new_added = 0 num_pending_notifications = len(self._pending_notifications) new_added = min(new_added, num_pending_notifications) for i in range(new_added): notification = self._pending_notifications.pop(0) self._notifications.append(notification) if new_added > 0: changed = True if changed: offset_y = 0 for notification in self._notifications: await notification._docking_to(self._docking_window_pos_x, self._docking_window_pos_y, self._docking_window_width, self._docking_window_height, offset_y) offset_y += notification._prompt.height + 5 # Step 1s await asyncio.sleep(0.5) self._timer_task = asyncio.ensure_future(timer_fn()) def on_shutdown(self): self._shutdown = True if self._timer_task: self._timer_task.cancel() self._timer_task = None for notification in self._notifications: notification.destroy() for notification in self._pending_notifications: notification.destroy() for notification in self._pre_warming_notifications: notification.destroy() self._notifications.clear() self._pending_notifications.clear() self._pre_warming_notifications.clear() def post_notification(self, notification_info: NotificationInfo): notification = Notification(notification_info, self) # OM-87367: options to disable all notifications. settings = carb.settings.get_settings() disable_all_notifications = settings.get(SETTINGS_DISABLE_NOTIFICATIONS) if disable_all_notifications: if notification.info.status == NotificationStatus.INFO: carb.log_info(notification.info.text) else: carb.log_warn(notification.info.text) notification.destroy() else: self._pre_warming_notifications.append(notification) # Still returns the handle of notification. return notification def remove_notification(self, notification: Notification): try: if notification in self._notifications: self._notifications.remove(notification) if notification in self._pending_notifications: self._pending_notifications.remove(notification) if notification in self._pre_warming_notifications: self._pre_warming_notifications.remove(notification) except ValueError: pass def _on_docking_window_changed(self): viewport = ui.Workspace.get_window("Viewport") if viewport and viewport.visible: window_position_x = viewport.position_x window_position_y = viewport.position_y window_width = viewport.width window_height = viewport.height else: window_position_x = 0 window_position_y = 0 window_width = ui.Workspace.get_main_window_width() window_height = ui.Workspace.get_main_window_height() if ((self._docking_window_pos_x != window_position_x) or (self._docking_window_pos_y != window_position_y) or (self._docking_window_width != window_width) or (self._docking_window_height != window_height)): self._docking_window_pos_x = window_position_x self._docking_window_pos_y = window_position_y self._docking_window_width = window_width self._docking_window_height = window_height return True return False
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/prompt.py
import weakref import omni.ui as ui import omni.kit.app import uuid from .notification_info import NotificationStatus, NotificationButtonInfo, NotificationInfo from .icons import Icons HOVER_AREA_TRANSPARENT_STYLE = { "background_color": 0x0, "background_gradient_color": 0x0, "background_selected_color": 0x0, "border_color": 0x0, "color": 0x0, "selected_color": 0x0, "secondary_color": 0x0, "secondary_selected_color": 0x0, "debug_color": 0x0 } HOVER_AREA_DEFAULT_STYLE = { "Rectangle::hover_area_info": {"background_color": 0xFFE2B170, "border_radius": 10}, "Rectangle::hover_area_warning": {"background_color": 0xFF5EC7E8, "border_radius": 10}, "Label::text": {"font_size": 14, "color": 0xFF000000}, "Image::status_warning": {"image_url": Icons().get("warning"), "color": 0xFF000000}, "Image::status_info": {"image_url": Icons().get("info"), "color": 0xFF000000}, "Button:hovered": {"background_color": 0xFF9E9E9E}, } class Prompt: def __init__(self, notification_info: NotificationInfo): self._notification_info = notification_info self._build_ui( notification_info.text, notification_info.status, notification_info.button_infos ) self._docking_window_x = 0 self._docking_window_y = 0 self._docking_window_width = 0 self._docking_window_height = 0 self._hovered = False def destroy(self): self._notification_info = None self._window.destroy() self._window = None def __enter__(self): self._window.show() return self def __exit__(self, type, value, trace): self._window.hide() def show(self): self._window.visible = True def hide(self): self._window.visible = False @property def hovered(self): return self._hovered @property def visible(self): return self._window.visible @visible.setter def visible(self, value): self._window.visible = value @property def position_x(self): return self._window.position_x @position_x.setter def position_x(self, value): self._window.position_x = value @property def position_y(self): return self._window.position @position_y.setter def position_y(self, value): self._window.position_y = value @property def width(self): return self._window.width @property def height(self): return self._window.height async def docking_to(self, window_x, window_y, window_width, window_height, offset_y=0): self._docking_window_x = window_x self._docking_window_y = window_y self._docking_window_width = window_width self._docking_window_height = window_height self._window.visible = True # FIXME: No idea why this works. It needs to wait for the width/height to be stabalized. await omni.kit.app.get_app().next_update_async() position_x = self._docking_window_x + self._docking_window_width - self._window.width - 16 position_y = self._docking_window_y + self._docking_window_height - self._window.height - 16 - offset_y self._window.position_x = position_x if position_x > 0 else 0 self._window.position_y = position_y if position_y > 0 else 0 if self._notification_info.status == NotificationStatus.INFO: self._window.frame.set_style({"Window": {"background_color": 0xFF75542A, "border_radius": 10}}) else: self._window.frame.set_style({"Window": {"background_color": 0xFF2D5CA1, "border_radius": 10}}) self._layout.set_style(HOVER_AREA_DEFAULT_STYLE) def _build_ui(self, text, status, button_details): self._window = ui.Window(str(uuid.uuid1()), visible=False, height=0, dockPreference=ui.DockPreference.DISABLED) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_CLOSE | ui.WINDOW_FLAGS_NO_FOCUS_ON_APPEARING ) def _button_handler(handler): self.hide() if handler: handler() weak_self = weakref.ref(self) def _on_hovered(hovered): if not weak_self(): return weak_self()._hovered = hovered self._window.frame.style = HOVER_AREA_TRANSPARENT_STYLE with self._window.frame: self._layout = ui.ZStack(style=HOVER_AREA_DEFAULT_STYLE, height=0) with self._layout: if status == NotificationStatus.INFO: hover_area = ui.Rectangle(name="hover_area_info") else: hover_area = ui.Rectangle(name="hover_area_warning") hover_area.set_mouse_hovered_fn(_on_hovered) with ui.VStack(height=0): ui.Spacer(height=5) with ui.HStack(height=0): if status == NotificationStatus.INFO: name = "status_info" else: name = "status_warning" ui.Spacer(width=5) ui.Image(width=20, alignment=ui.Alignment.CENTER, name=name) ui.Spacer(width=10) ui.Label( text, name="text", word_wrap=True, width=self._window.width - 44, height=0, alignment=ui.Alignment.LEFT ) ui.Spacer() if button_details: button_width = 60 if len(button_details) >=3 else 120 ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer() button = ui.Button(button_details[0].text, width=button_width, height=0) button.set_clicked_fn(lambda a=button_details[0].handler: _button_handler(a)) for i in range(len(button_details) - 1): ui.Spacer(width=5) button_info = button_details[i + 1] button = ui.Button(button_info.text, width=button_width, height=0) button.set_clicked_fn(lambda a=button_info.handler: _button_handler(a)) ui.Spacer() ui.Spacer(height=5)
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/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. # from pathlib import Path from .singleton import Singleton @Singleton class Icons: """A singleton that scans the icon folder and returns the icon depending on the type""" def __init__(self): self._current_path = Path(__file__).parent self._icon_path = self._current_path.parent.parent.parent.joinpath("icons") # Read all the svg files in the directory self._icons = {icon.stem: icon for icon in self._icon_path.glob("*.svg")} def get(self, name, default=None): """Checks the icon cache and returns the icon if exists""" found = self._icons.get(name) if not found and default: found = self._icons.get(default) if found: return str(found)
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/singleton.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. # def Singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance