file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/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 .stage_window_test import TestStageWindow
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/tests/stage_window_test.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 from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import carb import omni.kit.app import omni.ui as ui import omni.usd import omni.kit.commands from omni.kit import ui_test from unittest.mock import Mock, patch, ANY from ..stage_window import StageWindow CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data") class TestStageWindow(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") self._w = ui.Workspace.get_window("Stage") self._usd_context = omni.usd.get_context() # After running each test async def tearDown(self): self._w = None self._golden_img_dir = None await super().tearDown() async def test_general(self): # New stage with a sphere await self._usd_context.new_stage_async() omni.kit.commands.execute("CreatePrim", prim_path="/Sphere", prim_type="Sphere", select_new_prim=False) # Loading icon takes time. # TODO: We need a mode that blocks UI until icons are loaded await self.wait(10) await self.docked_test_window( window=self._w, width=450, height=100, restore_window=ui.Workspace.get_window("Layer"), restore_position=ui.DockPosition.SAME, ) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_multi_visibility_change(self): """Testing visibility of StageWidget""" await self.docked_test_window( window=self._w, width=450, height=200, ) # New stage with three prims await self._usd_context.new_stage_async() omni.kit.commands.execute("CreatePrim", prim_path="/A", prim_type="Sphere", select_new_prim=False) omni.kit.commands.execute("CreatePrim", prim_path="/B", prim_type="Sphere", select_new_prim=False) omni.kit.commands.execute("CreatePrim", prim_path="/C", prim_type="Sphere", select_new_prim=False) await ui_test.wait_n_updates(5) # select both A and C self._usd_context.get_selection().set_selected_prim_paths(["/A", "/C"], True) # make A invisible await ui_test.wait_n_updates(5) stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") eye_icon = stage_widget.find_all("**/ToolButton[*]")[0] await eye_icon.click() await ui_test.wait_n_updates(5) # check C will also be invisible await self.finalize_test(golden_img_dir=self._golden_img_dir) async def wait(self, n=100): for i in range(n): await omni.kit.app.get_app().next_update_async() async def test_header_columns(self): from omni.kit import ui_test await ui_test.find("Stage").focus() stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") name_column = stage_widget.find("**/Label[*].text=='Name (Old to New)'") self.assertTrue(name_column) await ui_test.emulate_mouse_move(name_column.center) await name_column.right_click() with self.assertRaises(Exception): await ui_test.select_context_menu("Create") await self.wait() await name_column.click() await self.wait() name_column = stage_widget.find("**/Label[*].text=='Name (A to Z)'") self.assertTrue(name_column) await name_column.click() await self.wait() name_column = stage_widget.find("**/Label[*].text=='Name (Z to A)'") self.assertTrue(name_column) await name_column.click() await self.wait() name_column = stage_widget.find("**/Label[*].text=='Name (New to Old)'") self.assertTrue(name_column) await name_column.click() await self.wait() name_column = stage_widget.find("**/Label[*].text=='Name (Old to New)'") self.assertTrue(name_column) await self.finalize_test_no_image() async def test_rename_with_context_menu(self): from omni.kit import ui_test await ui_test.find("Stage").focus() stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") # New stage with three prims await self._usd_context.new_stage_async() stage = omni.usd.get_context().get_stage() stage.GetRootLayer().Clear() await ui_test.wait_n_updates(5) prim = stage.DefinePrim("/test", "Xform") await ui_test.wait_n_updates(5) prim_item = stage_widget.find("**/Label[*].text=='test'") self.assertTrue(prim_item) prim_name_field = stage_widget.find("**/StringField[*].identifier=='rename_field'") self.assertTrue(prim_name_field) await prim_item.double_click() self.assertTrue(prim_name_field.widget.selected) prim_name_field.model.set_value("") await prim_name_field.input("test2") await ui_test.input.emulate_keyboard_press(carb.input.KeyboardInput.ENTER) await ui_test.wait_n_updates(5) old_prim = stage.GetPrimAtPath("/test") self.assertFalse(old_prim) new_prim = stage.GetPrimAtPath("/test2") self.assertTrue(new_prim) # Rename with context menu prim_item = stage_widget.find("**/Label[*].text=='test2'") self.assertTrue(prim_item) prim_name_field = stage_widget.find("**/StringField[*].identifier=='rename_field'") self.assertTrue(prim_name_field) await prim_item.right_click() await ui_test.select_context_menu("Rename") self.assertTrue(prim_name_field.widget.selected) await prim_name_field.input("test3") await ui_test.input.emulate_keyboard_press(carb.input.KeyboardInput.ENTER) await ui_test.wait_n_updates(5) old_prim = stage.GetPrimAtPath("/test") self.assertFalse(old_prim) new_prim = stage.GetPrimAtPath("/test2test3") self.assertTrue(new_prim) await self.finalize_test_no_image() async def test_window_destroyed_when_hidden(self): """Test that hiding stage window destroys it, and showing creates a new instance.""" ui.Workspace.show_window("Stage") self.assertTrue(ui.Workspace.get_window("Stage").visible) with patch.object(StageWindow, "destroy", autospec=True) as mock_destroy_dialog: ui.Workspace.show_window("Stage", False) await ui_test.wait_n_updates(5) mock_destroy_dialog.assert_called() self.assertFalse(ui.Workspace.get_window("Stage").visible) await self.finalize_test_no_image()
omniverse-code/kit/exts/omni.kit.window.stage/docs/CHANGELOG.md
# Changelog ## [2.3.12] - 2023-01-11 ### Added - Move SelectionWatch into omni.kit.widget.stage to provide default implementation. ## [2.3.11] - 2022-11-29 ### Added - Unitests for header of name column. ## [2.3.10] - 2022-11-01 ### Added - Test for renaming prim. ## [2.3.9] - 2022-09-30 ### Fixed - Set the menu checkbox when the window is appearing ## [2.3.8] - 2022-08-04 ### Added - Test for toggling visibility for multiple prims ## [2.3.7] - 2022-05-24 ### Changed - Optimize selection of stage window by reducing allocations of Sdf.Path. ## [2.3.6] - 2022-03-03 ### Changed - Use command for selection in widget so it can be undoable. ## [2.3.5] - 2021-10-20 ### Changed - External drag/drop doesn't use windows slashes ## [2.3.4] - 2021-05-25 ### Fixed - Bug when hide and show the Stage window ## [2.3.3] - 2021-04-27 ## Removed - `omni.stageupdate` is deprecated and doesn't work well with multiple usd contexts ## [2.3.2] - 2020-11-19 ### Changed - Refusing selection of grayed prims in search mode ## [2.3.1] - 2020-10-22 ### Added - Dependency on omni.kit.widget.stage_icons ## [2.3.0] - 2020-09-16 ### Changed - Split to two parts: omni.kit.widget.stage and omni.kit.window.stage ## [2.2.0] - 2020-09-15 ### Changed - Detached from Editor and using UsdNotice for notifications
omniverse-code/kit/exts/omni.kit.procedural.mesh/ogn/nodes.json
{ "nodes": { "omni.kit.procedural.mesh.CreateMeshCapsule": { "description": "If necessary, create a new mesh representing a capsule", "version": 1, "extension": "omni.kit.procedural.mesh", "language": "C++" }, "omni.kit.procedural.mesh.CreateMeshCone": { "description": "If necessary, create a new mesh representing a Cone", "version": 1, "extension": "omni.kit.procedural.mesh", "language": "C++" }, "omni.kit.procedural.mesh.CreateMeshCube": { "description": "If necessary, create a new mesh representing a cube", "version": 1, "extension": "omni.kit.procedural.mesh", "language": "C++" }, "omni.kit.procedural.mesh.CreateMeshCylinder": { "description": "If necessary, create a new mesh representing a cylinder", "version": 1, "extension": "omni.kit.procedural.mesh", "language": "C++" }, "omni.kit.procedural.mesh.CreateMeshDisk": { "description": "If necessary, create a new mesh representing a disk", "version": 1, "extension": "omni.kit.procedural.mesh", "language": "C++" }, "omni.kit.procedural.mesh.CreateMeshPlane": { "description": "If necessary, create a new mesh representing a plane", "version": 1, "extension": "omni.kit.procedural.mesh", "language": "C++" }, "omni.kit.procedural.mesh.CreateMeshSphere": { "description": "If necessary, create a new mesh representing a shpere", "version": 1, "extension": "omni.kit.procedural.mesh", "language": "C++" }, "omni.kit.procedural.mesh.CreateMeshTorus": { "description": "If necessary, create a new mesh representing a torus", "version": 1, "extension": "omni.kit.procedural.mesh", "language": "C++" } } }
omniverse-code/kit/exts/omni.kit.procedural.mesh/PACKAGE-LICENSES/omni.kit.procedural.mesh-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.procedural.mesh/config/extension.toml
[package] version = "0.1.0" title = "Procedural Mesh" category = "Internal" # Main module of the python interface [[python.module]] name = "omni.kit.procedural.mesh" # Watch the .ogn files for hot reloading (only works for Python files) [fswatcher.patterns] include = ["*.ogn", "*.py"] exclude = ["Ogn*Database.py"] # Other extensions that must be loaded before this one [dependencies] "omni.usd" = {} "omni.ui" = {} "omni.graph" = {} "omni.graph.tools" = {} "omni.kit.menu.utils" = {} [[native.plugin]] path = "bin/*.plugin" recursive = false
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/__init__.py
from .scripts.extension import * from .scripts.command import *
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshSphereDatabase.py
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshSphere If necessary, create a new mesh representing a shpere """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnProceduralMeshSphereDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshSphere Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.diameter inputs.latitudeResolution inputs.longitudeResolution inputs.parameterCheck Outputs: outputs.extent outputs.faceVertexCounts outputs.faceVertexIndices outputs.parameterCheck outputs.points outputs.stIndices outputs.sts """ # 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:diameter', 'float', 0, None, 'Sphere diameter', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:latitudeResolution', 'int', 0, None, 'Sphere Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:longitudeResolution', 'int', 0, None, 'Sphere Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''), ('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''), ('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''), ('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''), ('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''), ('outputs:stIndices', 'int[]', 0, None, 'Texture coordinate indices of faces', {}, True, None, False, ''), ('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"diameter", "latitudeResolution", "longitudeResolution", "parameterCheck", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.diameter, self._attributes.latitudeResolution, self._attributes.longitudeResolution, self._attributes.parameterCheck] self._batchedReadValues = [100, 10, 10, -1] @property def diameter(self): return self._batchedReadValues[0] @diameter.setter def diameter(self, value): self._batchedReadValues[0] = value @property def latitudeResolution(self): return self._batchedReadValues[1] @latitudeResolution.setter def latitudeResolution(self, value): self._batchedReadValues[1] = value @property def longitudeResolution(self): return self._batchedReadValues[2] @longitudeResolution.setter def longitudeResolution(self, value): self._batchedReadValues[2] = value @property def parameterCheck(self): return self._batchedReadValues[3] @parameterCheck.setter def parameterCheck(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.extent_size = None self.faceVertexCounts_size = None self.faceVertexIndices_size = None self.points_size = None self.stIndices_size = None self.sts_size = None self._batchedWriteValues = { } @property def extent(self): data_view = og.AttributeValueHelper(self._attributes.extent) return data_view.get(reserved_element_count=self.extent_size) @extent.setter def extent(self, value): data_view = og.AttributeValueHelper(self._attributes.extent) data_view.set(value) self.extent_size = data_view.get_array_size() @property def faceVertexCounts(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) return data_view.get(reserved_element_count=self.faceVertexCounts_size) @faceVertexCounts.setter def faceVertexCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) data_view.set(value) self.faceVertexCounts_size = data_view.get_array_size() @property def faceVertexIndices(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) return data_view.get(reserved_element_count=self.faceVertexIndices_size) @faceVertexIndices.setter def faceVertexIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) data_view.set(value) self.faceVertexIndices_size = data_view.get_array_size() @property def points(self): data_view = og.AttributeValueHelper(self._attributes.points) return data_view.get(reserved_element_count=self.points_size) @points.setter def points(self, value): data_view = og.AttributeValueHelper(self._attributes.points) data_view.set(value) self.points_size = data_view.get_array_size() @property def stIndices(self): data_view = og.AttributeValueHelper(self._attributes.stIndices) return data_view.get(reserved_element_count=self.stIndices_size) @stIndices.setter def stIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.stIndices) data_view.set(value) self.stIndices_size = data_view.get_array_size() @property def sts(self): data_view = og.AttributeValueHelper(self._attributes.sts) return data_view.get(reserved_element_count=self.sts_size) @sts.setter def sts(self, value): data_view = og.AttributeValueHelper(self._attributes.sts) data_view.set(value) self.sts_size = data_view.get_array_size() @property def parameterCheck(self): value = self._batchedWriteValues.get(self._attributes.parameterCheck) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.parameterCheck) return data_view.get() @parameterCheck.setter def parameterCheck(self, value): self._batchedWriteValues[self._attributes.parameterCheck] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnProceduralMeshSphereDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnProceduralMeshSphereDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnProceduralMeshSphereDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshCubeDatabase.py
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshCube If necessary, create a new mesh representing a cube """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnProceduralMeshCubeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshCube Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.parameterCheck inputs.xLength inputs.xResolution inputs.yLength inputs.yResolution inputs.zLength inputs.zResolution Outputs: outputs.creaseIndices outputs.creaseLengths outputs.creaseSharpnesses outputs.extent outputs.faceVertexCounts outputs.faceVertexIndices outputs.normalIndices outputs.normals outputs.parameterCheck outputs.points outputs.stIndices outputs.sts """ # 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:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('inputs:xLength', 'float', 0, None, 'Cube x extent', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:xResolution', 'int', 0, None, 'Cube Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:yLength', 'float', 0, None, 'Cube y extent', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:yResolution', 'int', 0, None, 'Cube Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:zLength', 'float', 0, None, 'Cube z extent', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:zResolution', 'int', 0, None, 'Cube Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('outputs:creaseIndices', 'int[]', 0, None, "Crease vertices's indices, one crease after another", {}, True, None, False, ''), ('outputs:creaseLengths', 'int[]', 0, None, 'Number of vertices of creases', {}, True, None, False, ''), ('outputs:creaseSharpnesses', 'float[]', 0, None, 'Sharpness of creases', {}, True, None, False, ''), ('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''), ('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''), ('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''), ('outputs:normalIndices', 'int[]', 0, None, 'Normal indices of faces', {}, True, None, False, ''), ('outputs:normals', 'float3[]', 0, None, 'Normal of vertices', {}, True, None, False, ''), ('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''), ('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''), ('outputs:stIndices', 'int[]', 0, None, 'Texture coordinate indices of faces', {}, True, None, False, ''), ('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "xLength", "xResolution", "yLength", "yResolution", "zLength", "zResolution", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.parameterCheck, self._attributes.xLength, self._attributes.xResolution, self._attributes.yLength, self._attributes.yResolution, self._attributes.zLength, self._attributes.zResolution] self._batchedReadValues = [-1, 100, 10, 100, 10, 100, 10] @property def parameterCheck(self): return self._batchedReadValues[0] @parameterCheck.setter def parameterCheck(self, value): self._batchedReadValues[0] = value @property def xLength(self): return self._batchedReadValues[1] @xLength.setter def xLength(self, value): self._batchedReadValues[1] = value @property def xResolution(self): return self._batchedReadValues[2] @xResolution.setter def xResolution(self, value): self._batchedReadValues[2] = value @property def yLength(self): return self._batchedReadValues[3] @yLength.setter def yLength(self, value): self._batchedReadValues[3] = value @property def yResolution(self): return self._batchedReadValues[4] @yResolution.setter def yResolution(self, value): self._batchedReadValues[4] = value @property def zLength(self): return self._batchedReadValues[5] @zLength.setter def zLength(self, value): self._batchedReadValues[5] = value @property def zResolution(self): return self._batchedReadValues[6] @zResolution.setter def zResolution(self, value): self._batchedReadValues[6] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.creaseIndices_size = None self.creaseLengths_size = None self.creaseSharpnesses_size = None self.extent_size = None self.faceVertexCounts_size = None self.faceVertexIndices_size = None self.normalIndices_size = None self.normals_size = None self.points_size = None self.stIndices_size = None self.sts_size = None self._batchedWriteValues = { } @property def creaseIndices(self): data_view = og.AttributeValueHelper(self._attributes.creaseIndices) return data_view.get(reserved_element_count=self.creaseIndices_size) @creaseIndices.setter def creaseIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.creaseIndices) data_view.set(value) self.creaseIndices_size = data_view.get_array_size() @property def creaseLengths(self): data_view = og.AttributeValueHelper(self._attributes.creaseLengths) return data_view.get(reserved_element_count=self.creaseLengths_size) @creaseLengths.setter def creaseLengths(self, value): data_view = og.AttributeValueHelper(self._attributes.creaseLengths) data_view.set(value) self.creaseLengths_size = data_view.get_array_size() @property def creaseSharpnesses(self): data_view = og.AttributeValueHelper(self._attributes.creaseSharpnesses) return data_view.get(reserved_element_count=self.creaseSharpnesses_size) @creaseSharpnesses.setter def creaseSharpnesses(self, value): data_view = og.AttributeValueHelper(self._attributes.creaseSharpnesses) data_view.set(value) self.creaseSharpnesses_size = data_view.get_array_size() @property def extent(self): data_view = og.AttributeValueHelper(self._attributes.extent) return data_view.get(reserved_element_count=self.extent_size) @extent.setter def extent(self, value): data_view = og.AttributeValueHelper(self._attributes.extent) data_view.set(value) self.extent_size = data_view.get_array_size() @property def faceVertexCounts(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) return data_view.get(reserved_element_count=self.faceVertexCounts_size) @faceVertexCounts.setter def faceVertexCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) data_view.set(value) self.faceVertexCounts_size = data_view.get_array_size() @property def faceVertexIndices(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) return data_view.get(reserved_element_count=self.faceVertexIndices_size) @faceVertexIndices.setter def faceVertexIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) data_view.set(value) self.faceVertexIndices_size = data_view.get_array_size() @property def normalIndices(self): data_view = og.AttributeValueHelper(self._attributes.normalIndices) return data_view.get(reserved_element_count=self.normalIndices_size) @normalIndices.setter def normalIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.normalIndices) data_view.set(value) self.normalIndices_size = data_view.get_array_size() @property def normals(self): data_view = og.AttributeValueHelper(self._attributes.normals) return data_view.get(reserved_element_count=self.normals_size) @normals.setter def normals(self, value): data_view = og.AttributeValueHelper(self._attributes.normals) data_view.set(value) self.normals_size = data_view.get_array_size() @property def points(self): data_view = og.AttributeValueHelper(self._attributes.points) return data_view.get(reserved_element_count=self.points_size) @points.setter def points(self, value): data_view = og.AttributeValueHelper(self._attributes.points) data_view.set(value) self.points_size = data_view.get_array_size() @property def stIndices(self): data_view = og.AttributeValueHelper(self._attributes.stIndices) return data_view.get(reserved_element_count=self.stIndices_size) @stIndices.setter def stIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.stIndices) data_view.set(value) self.stIndices_size = data_view.get_array_size() @property def sts(self): data_view = og.AttributeValueHelper(self._attributes.sts) return data_view.get(reserved_element_count=self.sts_size) @sts.setter def sts(self, value): data_view = og.AttributeValueHelper(self._attributes.sts) data_view.set(value) self.sts_size = data_view.get_array_size() @property def parameterCheck(self): value = self._batchedWriteValues.get(self._attributes.parameterCheck) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.parameterCheck) return data_view.get() @parameterCheck.setter def parameterCheck(self, value): self._batchedWriteValues[self._attributes.parameterCheck] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnProceduralMeshCubeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnProceduralMeshCubeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnProceduralMeshCubeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshPlaneDatabase.py
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshPlane If necessary, create a new mesh representing a plane """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnProceduralMeshPlaneDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshPlane Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.parameterCheck inputs.xLength inputs.xResolution inputs.zLength inputs.zResolution Outputs: outputs.extent outputs.faceVertexCounts outputs.faceVertexIndices outputs.parameterCheck outputs.points outputs.sts """ # 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:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('inputs:xLength', 'float', 0, None, 'Plane x extent', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:xResolution', 'int', 0, None, 'Plane Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:zLength', 'float', 0, None, 'Plane z extent', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:zResolution', 'int', 0, None, 'Plane Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('outputs:extent', 'point3f[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''), ('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''), ('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''), ('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''), ('outputs:points', 'point3f[]', 0, None, 'Points', {}, True, None, False, ''), ('outputs:sts', 'texCoord2f[]', 0, None, 'Texture coordinate of vertices', {}, 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.outputs.extent = og.Database.ROLE_POINT role_data.outputs.points = og.Database.ROLE_POINT role_data.outputs.sts = og.Database.ROLE_TEXCOORD return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "xLength", "xResolution", "zLength", "zResolution", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.parameterCheck, self._attributes.xLength, self._attributes.xResolution, self._attributes.zLength, self._attributes.zResolution] self._batchedReadValues = [-1, 100, 10, 100, 10] @property def parameterCheck(self): return self._batchedReadValues[0] @parameterCheck.setter def parameterCheck(self, value): self._batchedReadValues[0] = value @property def xLength(self): return self._batchedReadValues[1] @xLength.setter def xLength(self, value): self._batchedReadValues[1] = value @property def xResolution(self): return self._batchedReadValues[2] @xResolution.setter def xResolution(self, value): self._batchedReadValues[2] = value @property def zLength(self): return self._batchedReadValues[3] @zLength.setter def zLength(self, value): self._batchedReadValues[3] = value @property def zResolution(self): return self._batchedReadValues[4] @zResolution.setter def zResolution(self, value): self._batchedReadValues[4] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.extent_size = None self.faceVertexCounts_size = None self.faceVertexIndices_size = None self.points_size = None self.sts_size = None self._batchedWriteValues = { } @property def extent(self): data_view = og.AttributeValueHelper(self._attributes.extent) return data_view.get(reserved_element_count=self.extent_size) @extent.setter def extent(self, value): data_view = og.AttributeValueHelper(self._attributes.extent) data_view.set(value) self.extent_size = data_view.get_array_size() @property def faceVertexCounts(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) return data_view.get(reserved_element_count=self.faceVertexCounts_size) @faceVertexCounts.setter def faceVertexCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) data_view.set(value) self.faceVertexCounts_size = data_view.get_array_size() @property def faceVertexIndices(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) return data_view.get(reserved_element_count=self.faceVertexIndices_size) @faceVertexIndices.setter def faceVertexIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) data_view.set(value) self.faceVertexIndices_size = data_view.get_array_size() @property def points(self): data_view = og.AttributeValueHelper(self._attributes.points) return data_view.get(reserved_element_count=self.points_size) @points.setter def points(self, value): data_view = og.AttributeValueHelper(self._attributes.points) data_view.set(value) self.points_size = data_view.get_array_size() @property def sts(self): data_view = og.AttributeValueHelper(self._attributes.sts) return data_view.get(reserved_element_count=self.sts_size) @sts.setter def sts(self, value): data_view = og.AttributeValueHelper(self._attributes.sts) data_view.set(value) self.sts_size = data_view.get_array_size() @property def parameterCheck(self): value = self._batchedWriteValues.get(self._attributes.parameterCheck) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.parameterCheck) return data_view.get() @parameterCheck.setter def parameterCheck(self, value): self._batchedWriteValues[self._attributes.parameterCheck] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnProceduralMeshPlaneDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnProceduralMeshPlaneDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnProceduralMeshPlaneDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshConeDatabase.py
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshCone If necessary, create a new mesh representing a Cone """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnProceduralMeshConeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshCone Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.capResolution inputs.diameter inputs.height inputs.latitudeResolution inputs.longitudeResolution inputs.parameterCheck Outputs: outputs.cornerIndices outputs.cornerSharpnesses outputs.creaseIndices outputs.creaseLengths outputs.creaseSharpnesses outputs.extent outputs.faceVertexCounts outputs.faceVertexIndices outputs.normalIndices outputs.normals outputs.parameterCheck outputs.points outputs.stIndices outputs.sts """ # 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:capResolution', 'int', 0, None, 'Cone Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:diameter', 'float', 0, None, 'Cone diameter', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:height', 'float', 0, None, 'Cone height', {ogn.MetadataKeys.DEFAULT: '200'}, True, 200, False, ''), ('inputs:latitudeResolution', 'int', 0, None, 'Cone Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:longitudeResolution', 'int', 0, None, 'Cone Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('outputs:cornerIndices', 'int[]', 0, None, "Corner vertices's indices", {}, True, None, False, ''), ('outputs:cornerSharpnesses', 'float[]', 0, None, "Corner vertices's sharpness values", {}, True, None, False, ''), ('outputs:creaseIndices', 'int[]', 0, None, "Crease vertices's indices, one crease after another", {}, True, None, False, ''), ('outputs:creaseLengths', 'int[]', 0, None, 'Number of vertices of creases', {}, True, None, False, ''), ('outputs:creaseSharpnesses', 'float[]', 0, None, 'Sharpness of creases', {}, True, None, False, ''), ('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''), ('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''), ('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''), ('outputs:normalIndices', 'int[]', 0, None, 'Normal indices of faces', {}, True, None, False, ''), ('outputs:normals', 'float3[]', 0, None, 'Normal of vertices', {}, True, None, False, ''), ('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''), ('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''), ('outputs:stIndices', 'int[]', 0, None, 'Texture coordinate indices of faces', {}, True, None, False, ''), ('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"capResolution", "diameter", "height", "latitudeResolution", "longitudeResolution", "parameterCheck", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.capResolution, self._attributes.diameter, self._attributes.height, self._attributes.latitudeResolution, self._attributes.longitudeResolution, self._attributes.parameterCheck] self._batchedReadValues = [10, 100, 200, 10, 10, -1] @property def capResolution(self): return self._batchedReadValues[0] @capResolution.setter def capResolution(self, value): self._batchedReadValues[0] = value @property def diameter(self): return self._batchedReadValues[1] @diameter.setter def diameter(self, value): self._batchedReadValues[1] = value @property def height(self): return self._batchedReadValues[2] @height.setter def height(self, value): self._batchedReadValues[2] = value @property def latitudeResolution(self): return self._batchedReadValues[3] @latitudeResolution.setter def latitudeResolution(self, value): self._batchedReadValues[3] = value @property def longitudeResolution(self): return self._batchedReadValues[4] @longitudeResolution.setter def longitudeResolution(self, value): self._batchedReadValues[4] = value @property def parameterCheck(self): return self._batchedReadValues[5] @parameterCheck.setter def parameterCheck(self, value): self._batchedReadValues[5] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.cornerIndices_size = None self.cornerSharpnesses_size = None self.creaseIndices_size = None self.creaseLengths_size = None self.creaseSharpnesses_size = None self.extent_size = None self.faceVertexCounts_size = None self.faceVertexIndices_size = None self.normalIndices_size = None self.normals_size = None self.points_size = None self.stIndices_size = None self.sts_size = None self._batchedWriteValues = { } @property def cornerIndices(self): data_view = og.AttributeValueHelper(self._attributes.cornerIndices) return data_view.get(reserved_element_count=self.cornerIndices_size) @cornerIndices.setter def cornerIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.cornerIndices) data_view.set(value) self.cornerIndices_size = data_view.get_array_size() @property def cornerSharpnesses(self): data_view = og.AttributeValueHelper(self._attributes.cornerSharpnesses) return data_view.get(reserved_element_count=self.cornerSharpnesses_size) @cornerSharpnesses.setter def cornerSharpnesses(self, value): data_view = og.AttributeValueHelper(self._attributes.cornerSharpnesses) data_view.set(value) self.cornerSharpnesses_size = data_view.get_array_size() @property def creaseIndices(self): data_view = og.AttributeValueHelper(self._attributes.creaseIndices) return data_view.get(reserved_element_count=self.creaseIndices_size) @creaseIndices.setter def creaseIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.creaseIndices) data_view.set(value) self.creaseIndices_size = data_view.get_array_size() @property def creaseLengths(self): data_view = og.AttributeValueHelper(self._attributes.creaseLengths) return data_view.get(reserved_element_count=self.creaseLengths_size) @creaseLengths.setter def creaseLengths(self, value): data_view = og.AttributeValueHelper(self._attributes.creaseLengths) data_view.set(value) self.creaseLengths_size = data_view.get_array_size() @property def creaseSharpnesses(self): data_view = og.AttributeValueHelper(self._attributes.creaseSharpnesses) return data_view.get(reserved_element_count=self.creaseSharpnesses_size) @creaseSharpnesses.setter def creaseSharpnesses(self, value): data_view = og.AttributeValueHelper(self._attributes.creaseSharpnesses) data_view.set(value) self.creaseSharpnesses_size = data_view.get_array_size() @property def extent(self): data_view = og.AttributeValueHelper(self._attributes.extent) return data_view.get(reserved_element_count=self.extent_size) @extent.setter def extent(self, value): data_view = og.AttributeValueHelper(self._attributes.extent) data_view.set(value) self.extent_size = data_view.get_array_size() @property def faceVertexCounts(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) return data_view.get(reserved_element_count=self.faceVertexCounts_size) @faceVertexCounts.setter def faceVertexCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) data_view.set(value) self.faceVertexCounts_size = data_view.get_array_size() @property def faceVertexIndices(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) return data_view.get(reserved_element_count=self.faceVertexIndices_size) @faceVertexIndices.setter def faceVertexIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) data_view.set(value) self.faceVertexIndices_size = data_view.get_array_size() @property def normalIndices(self): data_view = og.AttributeValueHelper(self._attributes.normalIndices) return data_view.get(reserved_element_count=self.normalIndices_size) @normalIndices.setter def normalIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.normalIndices) data_view.set(value) self.normalIndices_size = data_view.get_array_size() @property def normals(self): data_view = og.AttributeValueHelper(self._attributes.normals) return data_view.get(reserved_element_count=self.normals_size) @normals.setter def normals(self, value): data_view = og.AttributeValueHelper(self._attributes.normals) data_view.set(value) self.normals_size = data_view.get_array_size() @property def points(self): data_view = og.AttributeValueHelper(self._attributes.points) return data_view.get(reserved_element_count=self.points_size) @points.setter def points(self, value): data_view = og.AttributeValueHelper(self._attributes.points) data_view.set(value) self.points_size = data_view.get_array_size() @property def stIndices(self): data_view = og.AttributeValueHelper(self._attributes.stIndices) return data_view.get(reserved_element_count=self.stIndices_size) @stIndices.setter def stIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.stIndices) data_view.set(value) self.stIndices_size = data_view.get_array_size() @property def sts(self): data_view = og.AttributeValueHelper(self._attributes.sts) return data_view.get(reserved_element_count=self.sts_size) @sts.setter def sts(self, value): data_view = og.AttributeValueHelper(self._attributes.sts) data_view.set(value) self.sts_size = data_view.get_array_size() @property def parameterCheck(self): value = self._batchedWriteValues.get(self._attributes.parameterCheck) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.parameterCheck) return data_view.get() @parameterCheck.setter def parameterCheck(self, value): self._batchedWriteValues[self._attributes.parameterCheck] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnProceduralMeshConeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnProceduralMeshConeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnProceduralMeshConeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshDiskDatabase.py
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshDisk If necessary, create a new mesh representing a disk """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnProceduralMeshDiskDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshDisk Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.capResolution inputs.diameter inputs.longitudeResolution inputs.parameterCheck Outputs: outputs.extent outputs.faceVertexCounts outputs.faceVertexIndices outputs.parameterCheck outputs.points outputs.sts """ # 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:capResolution', 'int', 0, None, 'Disk Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:diameter', 'float', 0, None, 'Disk diameter', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:longitudeResolution', 'int', 0, None, 'Disk Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''), ('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''), ('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''), ('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''), ('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''), ('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"capResolution", "diameter", "longitudeResolution", "parameterCheck", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.capResolution, self._attributes.diameter, self._attributes.longitudeResolution, self._attributes.parameterCheck] self._batchedReadValues = [10, 100, 10, -1] @property def capResolution(self): return self._batchedReadValues[0] @capResolution.setter def capResolution(self, value): self._batchedReadValues[0] = value @property def diameter(self): return self._batchedReadValues[1] @diameter.setter def diameter(self, value): self._batchedReadValues[1] = value @property def longitudeResolution(self): return self._batchedReadValues[2] @longitudeResolution.setter def longitudeResolution(self, value): self._batchedReadValues[2] = value @property def parameterCheck(self): return self._batchedReadValues[3] @parameterCheck.setter def parameterCheck(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.extent_size = None self.faceVertexCounts_size = None self.faceVertexIndices_size = None self.points_size = None self.sts_size = None self._batchedWriteValues = { } @property def extent(self): data_view = og.AttributeValueHelper(self._attributes.extent) return data_view.get(reserved_element_count=self.extent_size) @extent.setter def extent(self, value): data_view = og.AttributeValueHelper(self._attributes.extent) data_view.set(value) self.extent_size = data_view.get_array_size() @property def faceVertexCounts(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) return data_view.get(reserved_element_count=self.faceVertexCounts_size) @faceVertexCounts.setter def faceVertexCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) data_view.set(value) self.faceVertexCounts_size = data_view.get_array_size() @property def faceVertexIndices(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) return data_view.get(reserved_element_count=self.faceVertexIndices_size) @faceVertexIndices.setter def faceVertexIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) data_view.set(value) self.faceVertexIndices_size = data_view.get_array_size() @property def points(self): data_view = og.AttributeValueHelper(self._attributes.points) return data_view.get(reserved_element_count=self.points_size) @points.setter def points(self, value): data_view = og.AttributeValueHelper(self._attributes.points) data_view.set(value) self.points_size = data_view.get_array_size() @property def sts(self): data_view = og.AttributeValueHelper(self._attributes.sts) return data_view.get(reserved_element_count=self.sts_size) @sts.setter def sts(self, value): data_view = og.AttributeValueHelper(self._attributes.sts) data_view.set(value) self.sts_size = data_view.get_array_size() @property def parameterCheck(self): value = self._batchedWriteValues.get(self._attributes.parameterCheck) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.parameterCheck) return data_view.get() @parameterCheck.setter def parameterCheck(self, value): self._batchedWriteValues[self._attributes.parameterCheck] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnProceduralMeshDiskDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnProceduralMeshDiskDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnProceduralMeshDiskDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshCapsuleDatabase.py
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshCapsule If necessary, create a new mesh representing a capsule """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnProceduralMeshCapsuleDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshCapsule Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.diameter inputs.hemisphereLatitudeResolution inputs.longitudeResolution inputs.middleLatitudeResolution inputs.parameterCheck inputs.yLength Outputs: outputs.extent outputs.faceVertexCounts outputs.faceVertexIndices outputs.parameterCheck outputs.points outputs.stIndices outputs.sts """ # 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:diameter', 'float', 0, None, 'Capsule diameter', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:hemisphereLatitudeResolution', 'int', 0, None, 'Capsule Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:longitudeResolution', 'int', 0, None, 'Capsule Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:middleLatitudeResolution', 'int', 0, None, 'Capsule Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('inputs:yLength', 'float', 0, None, 'Capsule y extent', {ogn.MetadataKeys.DEFAULT: '200'}, True, 200, False, ''), ('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''), ('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''), ('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''), ('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''), ('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''), ('outputs:stIndices', 'int[]', 0, None, 'Texture coordinate indices of faces', {}, True, None, False, ''), ('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"diameter", "hemisphereLatitudeResolution", "longitudeResolution", "middleLatitudeResolution", "parameterCheck", "yLength", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.diameter, self._attributes.hemisphereLatitudeResolution, self._attributes.longitudeResolution, self._attributes.middleLatitudeResolution, self._attributes.parameterCheck, self._attributes.yLength] self._batchedReadValues = [100, 10, 10, 10, -1, 200] @property def diameter(self): return self._batchedReadValues[0] @diameter.setter def diameter(self, value): self._batchedReadValues[0] = value @property def hemisphereLatitudeResolution(self): return self._batchedReadValues[1] @hemisphereLatitudeResolution.setter def hemisphereLatitudeResolution(self, value): self._batchedReadValues[1] = value @property def longitudeResolution(self): return self._batchedReadValues[2] @longitudeResolution.setter def longitudeResolution(self, value): self._batchedReadValues[2] = value @property def middleLatitudeResolution(self): return self._batchedReadValues[3] @middleLatitudeResolution.setter def middleLatitudeResolution(self, value): self._batchedReadValues[3] = value @property def parameterCheck(self): return self._batchedReadValues[4] @parameterCheck.setter def parameterCheck(self, value): self._batchedReadValues[4] = value @property def yLength(self): return self._batchedReadValues[5] @yLength.setter def yLength(self, value): self._batchedReadValues[5] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.extent_size = None self.faceVertexCounts_size = None self.faceVertexIndices_size = None self.points_size = None self.stIndices_size = None self.sts_size = None self._batchedWriteValues = { } @property def extent(self): data_view = og.AttributeValueHelper(self._attributes.extent) return data_view.get(reserved_element_count=self.extent_size) @extent.setter def extent(self, value): data_view = og.AttributeValueHelper(self._attributes.extent) data_view.set(value) self.extent_size = data_view.get_array_size() @property def faceVertexCounts(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) return data_view.get(reserved_element_count=self.faceVertexCounts_size) @faceVertexCounts.setter def faceVertexCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) data_view.set(value) self.faceVertexCounts_size = data_view.get_array_size() @property def faceVertexIndices(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) return data_view.get(reserved_element_count=self.faceVertexIndices_size) @faceVertexIndices.setter def faceVertexIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) data_view.set(value) self.faceVertexIndices_size = data_view.get_array_size() @property def points(self): data_view = og.AttributeValueHelper(self._attributes.points) return data_view.get(reserved_element_count=self.points_size) @points.setter def points(self, value): data_view = og.AttributeValueHelper(self._attributes.points) data_view.set(value) self.points_size = data_view.get_array_size() @property def stIndices(self): data_view = og.AttributeValueHelper(self._attributes.stIndices) return data_view.get(reserved_element_count=self.stIndices_size) @stIndices.setter def stIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.stIndices) data_view.set(value) self.stIndices_size = data_view.get_array_size() @property def sts(self): data_view = og.AttributeValueHelper(self._attributes.sts) return data_view.get(reserved_element_count=self.sts_size) @sts.setter def sts(self, value): data_view = og.AttributeValueHelper(self._attributes.sts) data_view.set(value) self.sts_size = data_view.get_array_size() @property def parameterCheck(self): value = self._batchedWriteValues.get(self._attributes.parameterCheck) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.parameterCheck) return data_view.get() @parameterCheck.setter def parameterCheck(self, value): self._batchedWriteValues[self._attributes.parameterCheck] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnProceduralMeshCapsuleDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnProceduralMeshCapsuleDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnProceduralMeshCapsuleDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshTorusDatabase.py
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshTorus If necessary, create a new mesh representing a torus """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnProceduralMeshTorusDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshTorus Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.diameter inputs.loopResolution inputs.parameterCheck inputs.sectionDiameter inputs.sectionResolution inputs.sectionTwist Outputs: outputs.extent outputs.faceVertexCounts outputs.faceVertexIndices outputs.parameterCheck outputs.points outputs.stIndices outputs.sts """ # 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:diameter', 'float', 0, None, 'Torus diameter', {ogn.MetadataKeys.DEFAULT: '200'}, True, 200, False, ''), ('inputs:loopResolution', 'int', 0, None, 'Torus Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('inputs:sectionDiameter', 'float', 0, None, 'Torus section diameter', {ogn.MetadataKeys.DEFAULT: '50'}, True, 50, False, ''), ('inputs:sectionResolution', 'int', 0, None, 'Torus Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:sectionTwist', 'float', 0, None, 'Torus section twist radian', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''), ('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''), ('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''), ('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''), ('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''), ('outputs:stIndices', 'int[]', 0, None, 'Texture coordinate indices of faces', {}, True, None, False, ''), ('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"diameter", "loopResolution", "parameterCheck", "sectionDiameter", "sectionResolution", "sectionTwist", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.diameter, self._attributes.loopResolution, self._attributes.parameterCheck, self._attributes.sectionDiameter, self._attributes.sectionResolution, self._attributes.sectionTwist] self._batchedReadValues = [200, 10, -1, 50, 10, 0] @property def diameter(self): return self._batchedReadValues[0] @diameter.setter def diameter(self, value): self._batchedReadValues[0] = value @property def loopResolution(self): return self._batchedReadValues[1] @loopResolution.setter def loopResolution(self, value): self._batchedReadValues[1] = value @property def parameterCheck(self): return self._batchedReadValues[2] @parameterCheck.setter def parameterCheck(self, value): self._batchedReadValues[2] = value @property def sectionDiameter(self): return self._batchedReadValues[3] @sectionDiameter.setter def sectionDiameter(self, value): self._batchedReadValues[3] = value @property def sectionResolution(self): return self._batchedReadValues[4] @sectionResolution.setter def sectionResolution(self, value): self._batchedReadValues[4] = value @property def sectionTwist(self): return self._batchedReadValues[5] @sectionTwist.setter def sectionTwist(self, value): self._batchedReadValues[5] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.extent_size = None self.faceVertexCounts_size = None self.faceVertexIndices_size = None self.points_size = None self.stIndices_size = None self.sts_size = None self._batchedWriteValues = { } @property def extent(self): data_view = og.AttributeValueHelper(self._attributes.extent) return data_view.get(reserved_element_count=self.extent_size) @extent.setter def extent(self, value): data_view = og.AttributeValueHelper(self._attributes.extent) data_view.set(value) self.extent_size = data_view.get_array_size() @property def faceVertexCounts(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) return data_view.get(reserved_element_count=self.faceVertexCounts_size) @faceVertexCounts.setter def faceVertexCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) data_view.set(value) self.faceVertexCounts_size = data_view.get_array_size() @property def faceVertexIndices(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) return data_view.get(reserved_element_count=self.faceVertexIndices_size) @faceVertexIndices.setter def faceVertexIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) data_view.set(value) self.faceVertexIndices_size = data_view.get_array_size() @property def points(self): data_view = og.AttributeValueHelper(self._attributes.points) return data_view.get(reserved_element_count=self.points_size) @points.setter def points(self, value): data_view = og.AttributeValueHelper(self._attributes.points) data_view.set(value) self.points_size = data_view.get_array_size() @property def stIndices(self): data_view = og.AttributeValueHelper(self._attributes.stIndices) return data_view.get(reserved_element_count=self.stIndices_size) @stIndices.setter def stIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.stIndices) data_view.set(value) self.stIndices_size = data_view.get_array_size() @property def sts(self): data_view = og.AttributeValueHelper(self._attributes.sts) return data_view.get(reserved_element_count=self.sts_size) @sts.setter def sts(self, value): data_view = og.AttributeValueHelper(self._attributes.sts) data_view.set(value) self.sts_size = data_view.get_array_size() @property def parameterCheck(self): value = self._batchedWriteValues.get(self._attributes.parameterCheck) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.parameterCheck) return data_view.get() @parameterCheck.setter def parameterCheck(self, value): self._batchedWriteValues[self._attributes.parameterCheck] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnProceduralMeshTorusDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnProceduralMeshTorusDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnProceduralMeshTorusDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshCylinderDatabase.py
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshCylinder If necessary, create a new mesh representing a cylinder """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnProceduralMeshCylinderDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshCylinder Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.capResolution inputs.diameter inputs.height inputs.latitudeResolution inputs.longitudeResolution inputs.parameterCheck Outputs: outputs.creaseIndices outputs.creaseLengths outputs.creaseSharpnesses outputs.extent outputs.faceVertexCounts outputs.faceVertexIndices outputs.normalIndices outputs.normals outputs.parameterCheck outputs.points outputs.stIndices outputs.sts """ # 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:capResolution', 'int', 0, None, 'Cylinder Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:diameter', 'float', 0, None, 'Cylinder diameter', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:height', 'float', 0, None, 'Cylinder height', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:latitudeResolution', 'int', 0, None, 'Cylinder Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:longitudeResolution', 'int', 0, None, 'Cylinder Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('outputs:creaseIndices', 'int[]', 0, None, "Crease vertices's indices, one crease after another", {}, True, None, False, ''), ('outputs:creaseLengths', 'int[]', 0, None, 'Number of vertices of creases', {}, True, None, False, ''), ('outputs:creaseSharpnesses', 'float[]', 0, None, 'Sharpness of creases', {}, True, None, False, ''), ('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''), ('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''), ('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''), ('outputs:normalIndices', 'int[]', 0, None, 'Normal indices of faces', {}, True, None, False, ''), ('outputs:normals', 'float3[]', 0, None, 'Normal of vertices', {}, True, None, False, ''), ('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''), ('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''), ('outputs:stIndices', 'int[]', 0, None, 'Texture coordinate indices of faces', {}, True, None, False, ''), ('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"capResolution", "diameter", "height", "latitudeResolution", "longitudeResolution", "parameterCheck", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.capResolution, self._attributes.diameter, self._attributes.height, self._attributes.latitudeResolution, self._attributes.longitudeResolution, self._attributes.parameterCheck] self._batchedReadValues = [10, 100, 100, 10, 10, -1] @property def capResolution(self): return self._batchedReadValues[0] @capResolution.setter def capResolution(self, value): self._batchedReadValues[0] = value @property def diameter(self): return self._batchedReadValues[1] @diameter.setter def diameter(self, value): self._batchedReadValues[1] = value @property def height(self): return self._batchedReadValues[2] @height.setter def height(self, value): self._batchedReadValues[2] = value @property def latitudeResolution(self): return self._batchedReadValues[3] @latitudeResolution.setter def latitudeResolution(self, value): self._batchedReadValues[3] = value @property def longitudeResolution(self): return self._batchedReadValues[4] @longitudeResolution.setter def longitudeResolution(self, value): self._batchedReadValues[4] = value @property def parameterCheck(self): return self._batchedReadValues[5] @parameterCheck.setter def parameterCheck(self, value): self._batchedReadValues[5] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.creaseIndices_size = None self.creaseLengths_size = None self.creaseSharpnesses_size = None self.extent_size = None self.faceVertexCounts_size = None self.faceVertexIndices_size = None self.normalIndices_size = None self.normals_size = None self.points_size = None self.stIndices_size = None self.sts_size = None self._batchedWriteValues = { } @property def creaseIndices(self): data_view = og.AttributeValueHelper(self._attributes.creaseIndices) return data_view.get(reserved_element_count=self.creaseIndices_size) @creaseIndices.setter def creaseIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.creaseIndices) data_view.set(value) self.creaseIndices_size = data_view.get_array_size() @property def creaseLengths(self): data_view = og.AttributeValueHelper(self._attributes.creaseLengths) return data_view.get(reserved_element_count=self.creaseLengths_size) @creaseLengths.setter def creaseLengths(self, value): data_view = og.AttributeValueHelper(self._attributes.creaseLengths) data_view.set(value) self.creaseLengths_size = data_view.get_array_size() @property def creaseSharpnesses(self): data_view = og.AttributeValueHelper(self._attributes.creaseSharpnesses) return data_view.get(reserved_element_count=self.creaseSharpnesses_size) @creaseSharpnesses.setter def creaseSharpnesses(self, value): data_view = og.AttributeValueHelper(self._attributes.creaseSharpnesses) data_view.set(value) self.creaseSharpnesses_size = data_view.get_array_size() @property def extent(self): data_view = og.AttributeValueHelper(self._attributes.extent) return data_view.get(reserved_element_count=self.extent_size) @extent.setter def extent(self, value): data_view = og.AttributeValueHelper(self._attributes.extent) data_view.set(value) self.extent_size = data_view.get_array_size() @property def faceVertexCounts(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) return data_view.get(reserved_element_count=self.faceVertexCounts_size) @faceVertexCounts.setter def faceVertexCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) data_view.set(value) self.faceVertexCounts_size = data_view.get_array_size() @property def faceVertexIndices(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) return data_view.get(reserved_element_count=self.faceVertexIndices_size) @faceVertexIndices.setter def faceVertexIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) data_view.set(value) self.faceVertexIndices_size = data_view.get_array_size() @property def normalIndices(self): data_view = og.AttributeValueHelper(self._attributes.normalIndices) return data_view.get(reserved_element_count=self.normalIndices_size) @normalIndices.setter def normalIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.normalIndices) data_view.set(value) self.normalIndices_size = data_view.get_array_size() @property def normals(self): data_view = og.AttributeValueHelper(self._attributes.normals) return data_view.get(reserved_element_count=self.normals_size) @normals.setter def normals(self, value): data_view = og.AttributeValueHelper(self._attributes.normals) data_view.set(value) self.normals_size = data_view.get_array_size() @property def points(self): data_view = og.AttributeValueHelper(self._attributes.points) return data_view.get(reserved_element_count=self.points_size) @points.setter def points(self, value): data_view = og.AttributeValueHelper(self._attributes.points) data_view.set(value) self.points_size = data_view.get_array_size() @property def stIndices(self): data_view = og.AttributeValueHelper(self._attributes.stIndices) return data_view.get(reserved_element_count=self.stIndices_size) @stIndices.setter def stIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.stIndices) data_view.set(value) self.stIndices_size = data_view.get_array_size() @property def sts(self): data_view = og.AttributeValueHelper(self._attributes.sts) return data_view.get(reserved_element_count=self.sts_size) @sts.setter def sts(self, value): data_view = og.AttributeValueHelper(self._attributes.sts) data_view.set(value) self.sts_size = data_view.get_array_size() @property def parameterCheck(self): value = self._batchedWriteValues.get(self._attributes.parameterCheck) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.parameterCheck) return data_view.get() @parameterCheck.setter def parameterCheck(self, value): self._batchedWriteValues[self._attributes.parameterCheck] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnProceduralMeshCylinderDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnProceduralMeshCylinderDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnProceduralMeshCylinderDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshSphere.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshSphereDatabase import OgnProceduralMeshSphereDatabase test_file_name = "OgnProceduralMeshSphereTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_kit_procedural_mesh_CreateMeshSphere") database = OgnProceduralMeshSphereDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:diameter")) attribute = test_node.get_attribute("inputs:diameter") db_value = database.inputs.diameter expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:latitudeResolution")) attribute = test_node.get_attribute("inputs:latitudeResolution") db_value = database.inputs.latitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:longitudeResolution")) attribute = test_node.get_attribute("inputs:longitudeResolution") db_value = database.inputs.longitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:stIndices")) attribute = test_node.get_attribute("outputs:stIndices") db_value = database.outputs.stIndices self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshCapsule.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshCapsuleDatabase import OgnProceduralMeshCapsuleDatabase test_file_name = "OgnProceduralMeshCapsuleTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_kit_procedural_mesh_CreateMeshCapsule") database = OgnProceduralMeshCapsuleDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:diameter")) attribute = test_node.get_attribute("inputs:diameter") db_value = database.inputs.diameter expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:hemisphereLatitudeResolution")) attribute = test_node.get_attribute("inputs:hemisphereLatitudeResolution") db_value = database.inputs.hemisphereLatitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:longitudeResolution")) attribute = test_node.get_attribute("inputs:longitudeResolution") db_value = database.inputs.longitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:middleLatitudeResolution")) attribute = test_node.get_attribute("inputs:middleLatitudeResolution") db_value = database.inputs.middleLatitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:yLength")) attribute = test_node.get_attribute("inputs:yLength") db_value = database.inputs.yLength expected_value = 200 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:stIndices")) attribute = test_node.get_attribute("outputs:stIndices") db_value = database.outputs.stIndices self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshCone.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshConeDatabase import OgnProceduralMeshConeDatabase test_file_name = "OgnProceduralMeshConeTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_kit_procedural_mesh_CreateMeshCone") database = OgnProceduralMeshConeDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:capResolution")) attribute = test_node.get_attribute("inputs:capResolution") db_value = database.inputs.capResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:diameter")) attribute = test_node.get_attribute("inputs:diameter") db_value = database.inputs.diameter expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:height")) attribute = test_node.get_attribute("inputs:height") db_value = database.inputs.height expected_value = 200 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:latitudeResolution")) attribute = test_node.get_attribute("inputs:latitudeResolution") db_value = database.inputs.latitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:longitudeResolution")) attribute = test_node.get_attribute("inputs:longitudeResolution") db_value = database.inputs.longitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:cornerIndices")) attribute = test_node.get_attribute("outputs:cornerIndices") db_value = database.outputs.cornerIndices self.assertTrue(test_node.get_attribute_exists("outputs:cornerSharpnesses")) attribute = test_node.get_attribute("outputs:cornerSharpnesses") db_value = database.outputs.cornerSharpnesses self.assertTrue(test_node.get_attribute_exists("outputs:creaseIndices")) attribute = test_node.get_attribute("outputs:creaseIndices") db_value = database.outputs.creaseIndices self.assertTrue(test_node.get_attribute_exists("outputs:creaseLengths")) attribute = test_node.get_attribute("outputs:creaseLengths") db_value = database.outputs.creaseLengths self.assertTrue(test_node.get_attribute_exists("outputs:creaseSharpnesses")) attribute = test_node.get_attribute("outputs:creaseSharpnesses") db_value = database.outputs.creaseSharpnesses self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:normalIndices")) attribute = test_node.get_attribute("outputs:normalIndices") db_value = database.outputs.normalIndices self.assertTrue(test_node.get_attribute_exists("outputs:normals")) attribute = test_node.get_attribute("outputs:normals") db_value = database.outputs.normals self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:stIndices")) attribute = test_node.get_attribute("outputs:stIndices") db_value = database.outputs.stIndices self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshTorus.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshTorusDatabase import OgnProceduralMeshTorusDatabase test_file_name = "OgnProceduralMeshTorusTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_kit_procedural_mesh_CreateMeshTorus") database = OgnProceduralMeshTorusDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:diameter")) attribute = test_node.get_attribute("inputs:diameter") db_value = database.inputs.diameter expected_value = 200 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:loopResolution")) attribute = test_node.get_attribute("inputs:loopResolution") db_value = database.inputs.loopResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:sectionDiameter")) attribute = test_node.get_attribute("inputs:sectionDiameter") db_value = database.inputs.sectionDiameter expected_value = 50 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:sectionResolution")) attribute = test_node.get_attribute("inputs:sectionResolution") db_value = database.inputs.sectionResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:sectionTwist")) attribute = test_node.get_attribute("inputs:sectionTwist") db_value = database.inputs.sectionTwist expected_value = 0 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:stIndices")) attribute = test_node.get_attribute("outputs:stIndices") db_value = database.outputs.stIndices self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/__init__.py
"""====== GENERATED BY omni.graph.tools - DO NOT EDIT ======""" import omni.graph.tools as ogt ogt.import_tests_in_directory(__file__, __name__)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshPlane.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshPlaneDatabase import OgnProceduralMeshPlaneDatabase test_file_name = "OgnProceduralMeshPlaneTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_kit_procedural_mesh_CreateMeshPlane") database = OgnProceduralMeshPlaneDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:xLength")) attribute = test_node.get_attribute("inputs:xLength") db_value = database.inputs.xLength expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:xResolution")) attribute = test_node.get_attribute("inputs:xResolution") db_value = database.inputs.xResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:zLength")) attribute = test_node.get_attribute("inputs:zLength") db_value = database.inputs.zLength expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:zResolution")) attribute = test_node.get_attribute("inputs:zResolution") db_value = database.inputs.zResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshCylinder.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshCylinderDatabase import OgnProceduralMeshCylinderDatabase test_file_name = "OgnProceduralMeshCylinderTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_kit_procedural_mesh_CreateMeshCylinder") database = OgnProceduralMeshCylinderDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:capResolution")) attribute = test_node.get_attribute("inputs:capResolution") db_value = database.inputs.capResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:diameter")) attribute = test_node.get_attribute("inputs:diameter") db_value = database.inputs.diameter expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:height")) attribute = test_node.get_attribute("inputs:height") db_value = database.inputs.height expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:latitudeResolution")) attribute = test_node.get_attribute("inputs:latitudeResolution") db_value = database.inputs.latitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:longitudeResolution")) attribute = test_node.get_attribute("inputs:longitudeResolution") db_value = database.inputs.longitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:creaseIndices")) attribute = test_node.get_attribute("outputs:creaseIndices") db_value = database.outputs.creaseIndices self.assertTrue(test_node.get_attribute_exists("outputs:creaseLengths")) attribute = test_node.get_attribute("outputs:creaseLengths") db_value = database.outputs.creaseLengths self.assertTrue(test_node.get_attribute_exists("outputs:creaseSharpnesses")) attribute = test_node.get_attribute("outputs:creaseSharpnesses") db_value = database.outputs.creaseSharpnesses self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:normalIndices")) attribute = test_node.get_attribute("outputs:normalIndices") db_value = database.outputs.normalIndices self.assertTrue(test_node.get_attribute_exists("outputs:normals")) attribute = test_node.get_attribute("outputs:normals") db_value = database.outputs.normals self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:stIndices")) attribute = test_node.get_attribute("outputs:stIndices") db_value = database.outputs.stIndices self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshCube.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshCubeDatabase import OgnProceduralMeshCubeDatabase test_file_name = "OgnProceduralMeshCubeTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_kit_procedural_mesh_CreateMeshCube") database = OgnProceduralMeshCubeDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:xLength")) attribute = test_node.get_attribute("inputs:xLength") db_value = database.inputs.xLength expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:xResolution")) attribute = test_node.get_attribute("inputs:xResolution") db_value = database.inputs.xResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:yLength")) attribute = test_node.get_attribute("inputs:yLength") db_value = database.inputs.yLength expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:yResolution")) attribute = test_node.get_attribute("inputs:yResolution") db_value = database.inputs.yResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:zLength")) attribute = test_node.get_attribute("inputs:zLength") db_value = database.inputs.zLength expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:zResolution")) attribute = test_node.get_attribute("inputs:zResolution") db_value = database.inputs.zResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:creaseIndices")) attribute = test_node.get_attribute("outputs:creaseIndices") db_value = database.outputs.creaseIndices self.assertTrue(test_node.get_attribute_exists("outputs:creaseLengths")) attribute = test_node.get_attribute("outputs:creaseLengths") db_value = database.outputs.creaseLengths self.assertTrue(test_node.get_attribute_exists("outputs:creaseSharpnesses")) attribute = test_node.get_attribute("outputs:creaseSharpnesses") db_value = database.outputs.creaseSharpnesses self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:normalIndices")) attribute = test_node.get_attribute("outputs:normalIndices") db_value = database.outputs.normalIndices self.assertTrue(test_node.get_attribute_exists("outputs:normals")) attribute = test_node.get_attribute("outputs:normals") db_value = database.outputs.normals self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:stIndices")) attribute = test_node.get_attribute("outputs:stIndices") db_value = database.outputs.stIndices self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/TestOgnProceduralMeshDisk.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.kit.procedural.mesh.ogn.OgnProceduralMeshDiskDatabase import OgnProceduralMeshDiskDatabase test_file_name = "OgnProceduralMeshDiskTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_kit_procedural_mesh_CreateMeshDisk") database = OgnProceduralMeshDiskDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error" self.assertTrue(test_node.get_attribute_exists("inputs:capResolution")) attribute = test_node.get_attribute("inputs:capResolution") db_value = database.inputs.capResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:diameter")) attribute = test_node.get_attribute("inputs:diameter") db_value = database.inputs.diameter expected_value = 100 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:longitudeResolution")) attribute = test_node.get_attribute("inputs:longitudeResolution") db_value = database.inputs.longitudeResolution expected_value = 10 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("inputs:parameterCheck")) attribute = test_node.get_attribute("inputs:parameterCheck") db_value = database.inputs.parameterCheck expected_value = -1 actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:extent")) attribute = test_node.get_attribute("outputs:extent") db_value = database.outputs.extent self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexCounts")) attribute = test_node.get_attribute("outputs:faceVertexCounts") db_value = database.outputs.faceVertexCounts self.assertTrue(test_node.get_attribute_exists("outputs:faceVertexIndices")) attribute = test_node.get_attribute("outputs:faceVertexIndices") db_value = database.outputs.faceVertexIndices self.assertTrue(test_node.get_attribute_exists("outputs:parameterCheck")) attribute = test_node.get_attribute("outputs:parameterCheck") db_value = database.outputs.parameterCheck self.assertTrue(test_node.get_attribute_exists("outputs:points")) attribute = test_node.get_attribute("outputs:points") db_value = database.outputs.points self.assertTrue(test_node.get_attribute_exists("outputs:sts")) attribute = test_node.get_attribute("outputs:sts") db_value = database.outputs.sts
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/usd/OgnProceduralMeshConeTemplate.usda
#usda 1.0 ( doc ="""Generated from node description file OgnProceduralMeshCone.ogn Contains templates for node types found in that file.""" ) def OmniGraph "TestGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 3) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Template_omni_kit_procedural_mesh_CreateMeshCone" ( docs="""If necessary, create a new mesh representing a Cone""" ) { token node:type = "omni.kit.procedural.mesh.CreateMeshCone" int node:typeVersion = 1 # 6 attributes custom int inputs:capResolution = 10 ( docs="""Cone Resolution""" ) custom float inputs:diameter = 100 ( docs="""Cone diameter""" ) custom float inputs:height = 200 ( docs="""Cone height""" ) custom int inputs:latitudeResolution = 10 ( docs="""Cone Resolution""" ) custom int inputs:longitudeResolution = 10 ( docs="""Cone Resolution""" ) custom int inputs:parameterCheck = -1 ( docs="""Previous crc value""" ) # 14 attributes custom int[] outputs:cornerIndices ( docs="""Corner vertices's indices""" ) custom float[] outputs:cornerSharpnesses ( docs="""Corner vertices's sharpness values""" ) custom int[] outputs:creaseIndices ( docs="""Crease vertices's indices, one crease after another""" ) custom int[] outputs:creaseLengths ( docs="""Number of vertices of creases""" ) custom float[] outputs:creaseSharpnesses ( docs="""Sharpness of creases""" ) custom float3[] outputs:extent ( docs="""Extent of the mesh""" ) custom int[] outputs:faceVertexCounts ( docs="""Vertex count of faces""" ) custom int[] outputs:faceVertexIndices ( docs="""Vertex indices of faces""" ) custom int[] outputs:normalIndices ( docs="""Normal indices of faces""" ) custom float3[] outputs:normals ( docs="""Normal of vertices""" ) custom int outputs:parameterCheck ( docs="""Current crc value""" ) custom float3[] outputs:points ( docs="""Points""" ) custom int[] outputs:stIndices ( docs="""Texture coordinate indices of faces""" ) custom float2[] outputs:sts ( docs="""Texture coordinate of vertices""" ) } }
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/usd/OgnProceduralMeshTorusTemplate.usda
#usda 1.0 ( doc ="""Generated from node description file OgnProceduralMeshTorus.ogn Contains templates for node types found in that file.""" ) def OmniGraph "TestGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 3) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Template_omni_kit_procedural_mesh_CreateMeshTorus" ( docs="""If necessary, create a new mesh representing a torus""" ) { token node:type = "omni.kit.procedural.mesh.CreateMeshTorus" int node:typeVersion = 1 # 6 attributes custom float inputs:diameter = 200 ( docs="""Torus diameter""" ) custom int inputs:loopResolution = 10 ( docs="""Torus Resolution""" ) custom int inputs:parameterCheck = -1 ( docs="""Previous crc value""" ) custom float inputs:sectionDiameter = 50 ( docs="""Torus section diameter""" ) custom int inputs:sectionResolution = 10 ( docs="""Torus Resolution""" ) custom float inputs:sectionTwist = 0 ( docs="""Torus section twist radian""" ) # 7 attributes custom float3[] outputs:extent ( docs="""Extent of the mesh""" ) custom int[] outputs:faceVertexCounts ( docs="""Vertex count of faces""" ) custom int[] outputs:faceVertexIndices ( docs="""Vertex indices of faces""" ) custom int outputs:parameterCheck ( docs="""Current crc value""" ) custom float3[] outputs:points ( docs="""Points""" ) custom int[] outputs:stIndices ( docs="""Texture coordinate indices of faces""" ) custom float2[] outputs:sts ( docs="""Texture coordinate of vertices""" ) } }
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/usd/OgnProceduralMeshSphereTemplate.usda
#usda 1.0 ( doc ="""Generated from node description file OgnProceduralMeshSphere.ogn Contains templates for node types found in that file.""" ) def OmniGraph "TestGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 3) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Template_omni_kit_procedural_mesh_CreateMeshSphere" ( docs="""If necessary, create a new mesh representing a shpere""" ) { token node:type = "omni.kit.procedural.mesh.CreateMeshSphere" int node:typeVersion = 1 # 4 attributes custom float inputs:diameter = 100 ( docs="""Sphere diameter""" ) custom int inputs:latitudeResolution = 10 ( docs="""Sphere Resolution""" ) custom int inputs:longitudeResolution = 10 ( docs="""Sphere Resolution""" ) custom int inputs:parameterCheck = -1 ( docs="""Previous crc value""" ) # 7 attributes custom float3[] outputs:extent ( docs="""Extent of the mesh""" ) custom int[] outputs:faceVertexCounts ( docs="""Vertex count of faces""" ) custom int[] outputs:faceVertexIndices ( docs="""Vertex indices of faces""" ) custom int outputs:parameterCheck ( docs="""Current crc value""" ) custom float3[] outputs:points ( docs="""Points""" ) custom int[] outputs:stIndices ( docs="""Texture coordinate indices of faces""" ) custom float2[] outputs:sts ( docs="""Texture coordinate of vertices""" ) } }
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/usd/OgnProceduralMeshCapsuleTemplate.usda
#usda 1.0 ( doc ="""Generated from node description file OgnProceduralMeshCapsule.ogn Contains templates for node types found in that file.""" ) def OmniGraph "TestGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 3) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Template_omni_kit_procedural_mesh_CreateMeshCapsule" ( docs="""If necessary, create a new mesh representing a capsule""" ) { token node:type = "omni.kit.procedural.mesh.CreateMeshCapsule" int node:typeVersion = 1 # 6 attributes custom float inputs:diameter = 100 ( docs="""Capsule diameter""" ) custom int inputs:hemisphereLatitudeResolution = 10 ( docs="""Capsule Resolution""" ) custom int inputs:longitudeResolution = 10 ( docs="""Capsule Resolution""" ) custom int inputs:middleLatitudeResolution = 10 ( docs="""Capsule Resolution""" ) custom int inputs:parameterCheck = -1 ( docs="""Previous crc value""" ) custom float inputs:yLength = 200 ( docs="""Capsule y extent""" ) # 7 attributes custom float3[] outputs:extent ( docs="""Extent of the mesh""" ) custom int[] outputs:faceVertexCounts ( docs="""Vertex count of faces""" ) custom int[] outputs:faceVertexIndices ( docs="""Vertex indices of faces""" ) custom int outputs:parameterCheck ( docs="""Current crc value""" ) custom float3[] outputs:points ( docs="""Points""" ) custom int[] outputs:stIndices ( docs="""Texture coordinate indices of faces""" ) custom float2[] outputs:sts ( docs="""Texture coordinate of vertices""" ) } }
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/usd/OgnProceduralMeshCylinderTemplate.usda
#usda 1.0 ( doc ="""Generated from node description file OgnProceduralMeshCylinder.ogn Contains templates for node types found in that file.""" ) def OmniGraph "TestGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 3) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Template_omni_kit_procedural_mesh_CreateMeshCylinder" ( docs="""If necessary, create a new mesh representing a cylinder""" ) { token node:type = "omni.kit.procedural.mesh.CreateMeshCylinder" int node:typeVersion = 1 # 6 attributes custom int inputs:capResolution = 10 ( docs="""Cylinder Resolution""" ) custom float inputs:diameter = 100 ( docs="""Cylinder diameter""" ) custom float inputs:height = 100 ( docs="""Cylinder height""" ) custom int inputs:latitudeResolution = 10 ( docs="""Cylinder Resolution""" ) custom int inputs:longitudeResolution = 10 ( docs="""Cylinder Resolution""" ) custom int inputs:parameterCheck = -1 ( docs="""Previous crc value""" ) # 12 attributes custom int[] outputs:creaseIndices ( docs="""Crease vertices's indices, one crease after another""" ) custom int[] outputs:creaseLengths ( docs="""Number of vertices of creases""" ) custom float[] outputs:creaseSharpnesses ( docs="""Sharpness of creases""" ) custom float3[] outputs:extent ( docs="""Extent of the mesh""" ) custom int[] outputs:faceVertexCounts ( docs="""Vertex count of faces""" ) custom int[] outputs:faceVertexIndices ( docs="""Vertex indices of faces""" ) custom int[] outputs:normalIndices ( docs="""Normal indices of faces""" ) custom float3[] outputs:normals ( docs="""Normal of vertices""" ) custom int outputs:parameterCheck ( docs="""Current crc value""" ) custom float3[] outputs:points ( docs="""Points""" ) custom int[] outputs:stIndices ( docs="""Texture coordinate indices of faces""" ) custom float2[] outputs:sts ( docs="""Texture coordinate of vertices""" ) } }
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/usd/OgnProceduralMeshCubeTemplate.usda
#usda 1.0 ( doc ="""Generated from node description file OgnProceduralMeshCube.ogn Contains templates for node types found in that file.""" ) def OmniGraph "TestGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 3) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Template_omni_kit_procedural_mesh_CreateMeshCube" ( docs="""If necessary, create a new mesh representing a cube""" ) { token node:type = "omni.kit.procedural.mesh.CreateMeshCube" int node:typeVersion = 1 # 7 attributes custom int inputs:parameterCheck = -1 ( docs="""Previous crc value""" ) custom float inputs:xLength = 100 ( docs="""Cube x extent""" ) custom int inputs:xResolution = 10 ( docs="""Cube Resolution""" ) custom float inputs:yLength = 100 ( docs="""Cube y extent""" ) custom int inputs:yResolution = 10 ( docs="""Cube Resolution""" ) custom float inputs:zLength = 100 ( docs="""Cube z extent""" ) custom int inputs:zResolution = 10 ( docs="""Cube Resolution""" ) # 12 attributes custom int[] outputs:creaseIndices ( docs="""Crease vertices's indices, one crease after another""" ) custom int[] outputs:creaseLengths ( docs="""Number of vertices of creases""" ) custom float[] outputs:creaseSharpnesses ( docs="""Sharpness of creases""" ) custom float3[] outputs:extent ( docs="""Extent of the mesh""" ) custom int[] outputs:faceVertexCounts ( docs="""Vertex count of faces""" ) custom int[] outputs:faceVertexIndices ( docs="""Vertex indices of faces""" ) custom int[] outputs:normalIndices ( docs="""Normal indices of faces""" ) custom float3[] outputs:normals ( docs="""Normal of vertices""" ) custom int outputs:parameterCheck ( docs="""Current crc value""" ) custom float3[] outputs:points ( docs="""Points""" ) custom int[] outputs:stIndices ( docs="""Texture coordinate indices of faces""" ) custom float2[] outputs:sts ( docs="""Texture coordinate of vertices""" ) } }
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/usd/OgnProceduralMeshDiskTemplate.usda
#usda 1.0 ( doc ="""Generated from node description file OgnProceduralMeshDisk.ogn Contains templates for node types found in that file.""" ) def OmniGraph "TestGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 3) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Template_omni_kit_procedural_mesh_CreateMeshDisk" ( docs="""If necessary, create a new mesh representing a disk""" ) { token node:type = "omni.kit.procedural.mesh.CreateMeshDisk" int node:typeVersion = 1 # 4 attributes custom int inputs:capResolution = 10 ( docs="""Disk Resolution""" ) custom float inputs:diameter = 100 ( docs="""Disk diameter""" ) custom int inputs:longitudeResolution = 10 ( docs="""Disk Resolution""" ) custom int inputs:parameterCheck = -1 ( docs="""Previous crc value""" ) # 6 attributes custom float3[] outputs:extent ( docs="""Extent of the mesh""" ) custom int[] outputs:faceVertexCounts ( docs="""Vertex count of faces""" ) custom int[] outputs:faceVertexIndices ( docs="""Vertex indices of faces""" ) custom int outputs:parameterCheck ( docs="""Current crc value""" ) custom float3[] outputs:points ( docs="""Points""" ) custom float2[] outputs:sts ( docs="""Texture coordinate of vertices""" ) } }
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/tests/usd/OgnProceduralMeshPlaneTemplate.usda
#usda 1.0 ( doc ="""Generated from node description file OgnProceduralMeshPlane.ogn Contains templates for node types found in that file.""" ) def OmniGraph "TestGraph" { token evaluator:type = "push" int2 fileFormatVersion = (1, 3) token flatCacheBacking = "Shared" token pipelineStage = "pipelineStageSimulation" def OmniGraphNode "Template_omni_kit_procedural_mesh_CreateMeshPlane" ( docs="""If necessary, create a new mesh representing a plane""" ) { token node:type = "omni.kit.procedural.mesh.CreateMeshPlane" int node:typeVersion = 1 # 5 attributes custom int inputs:parameterCheck = -1 ( docs="""Previous crc value""" ) custom float inputs:xLength = 100 ( docs="""Plane x extent""" ) custom int inputs:xResolution = 10 ( docs="""Plane Resolution""" ) custom float inputs:zLength = 100 ( docs="""Plane z extent""" ) custom int inputs:zResolution = 10 ( docs="""Plane Resolution""" ) # 6 attributes custom point3f[] outputs:extent ( docs="""Extent of the mesh""" ) custom int[] outputs:faceVertexCounts ( docs="""Vertex count of faces""" ) custom int[] outputs:faceVertexIndices ( docs="""Vertex indices of faces""" ) custom int outputs:parameterCheck ( docs="""Current crc value""" ) custom point3f[] outputs:points ( docs="""Points""" ) custom texCoord2f[] outputs:sts ( docs="""Texture coordinate of vertices""" ) } }
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/extension.py
import omni.ext from ..bindings._omni_kit_procedural_mesh import * from .menu import * class PublicExtension(omni.ext.IExt): def on_startup(self): self._interface = acquire_interface() self._menu = Menu() def on_shutdown(self): self._menu.on_shutdown() self._menu = None release_interface(self._interface)
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/procedural_mesh_omnigraph_utils.py
""" A set of utilities """ import omni.kit.app import omni.usd from pxr import Sdf, UsdGeom import omni.graph.core as og def get_parent(stage, parentPath): if parentPath: parentPrim = stage.GetPrimAtPath(parentPath) if parentPrim: return parentPrim, False # fallback to default behavior (creating a parent xform prim) omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type="Xform", prim_path=omni.usd.get_stage_next_free_path(stage, "/" + "ProceduralMeshXform", True), select_new_prim=True, create_default_xform=False, ) paths = omni.usd.get_context().get_selection().get_selected_prim_paths() for path in paths: parentPrim = stage.GetPrimAtPath(path) return parentPrim, True def create_mesh_computer(stage, prim_name: str, evaluator_name: str, node_type: str, parentPath=None): parentPrim, isParentOwned = get_parent(stage, parentPath) omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type="Mesh", prim_path=omni.usd.get_stage_next_free_path( stage, str(parentPrim.GetPath().AppendElementString(prim_name)), False ), select_new_prim=True, create_default_xform=False, ) paths = omni.usd.get_context().get_selection().get_selected_prim_paths() for path in paths: mesh = stage.GetPrimAtPath(path) helper = og.OmniGraphHelper() computer = helper.create_node(str(mesh.GetPath().AppendElementString(evaluator_name)), node_type) if isParentOwned: return parentPrim, mesh, computer else: return mesh, mesh, computer def init_common_attributes(prim): # parameter check # sschirm parameterCheckAttr = prim.CreateAttribute("proceduralMesh:parameterCheck", Sdf.ValueTypeNames.Int) parameterCheckAttr.Set(0) # basic attributes pointsAttr = prim.GetAttribute("points") faceVertexCountsAttr = prim.GetAttribute("faceVertexCounts") faceVertexIndicesAttr = prim.GetAttribute("faceVertexIndices") # extent extentAttr = prim.GetAttribute("extent") def connect_common_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect parameterCheck attribute as in and output helper.connect(ognPrim, "proceduralMesh:parameterCheck", computer, "inputs:parameterCheck") helper.connect(computer, "outputs:parameterCheck", ognPrim, "proceduralMesh:parameterCheck") # connect basic attributes helper.connect(computer, "outputs:points", ognPrim, "points") helper.connect(computer, "outputs:faceVertexCounts", ognPrim, "faceVertexCounts") helper.connect(computer, "outputs:faceVertexIndices", ognPrim, "faceVertexIndices") # connect to extent helper.connect(computer, "outputs:extent", ognPrim, "extent") def init_crease_attributes(prim): creaseIndicesAttr = prim.GetAttribute("creaseIndices") creaseLengthsAttr = prim.GetAttribute("creaseLengths") creaseSharpnessesAttr = prim.GetAttribute("creaseSharpnesses") def connect_crease_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect smooth group related attributes helper.connect(computer, "outputs:creaseIndices", ognPrim, "creaseIndices") helper.connect(computer, "outputs:creaseLengths", ognPrim, "creaseLengths") helper.connect(computer, "outputs:creaseSharpnesses", ognPrim, "creaseSharpnesses") def init_corner_attributes(prim): cornerIndicesAttr = prim.GetAttribute("cornerIndices") cornerSharpnessesAttr = prim.GetAttribute("cornerSharpnesses") def connect_corner_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect smooth group related attributes helper.connect(computer, "outputs:cornerIndices", ognPrim, "cornerIndices") helper.connect(computer, "outputs:cornerSharpnesses", ognPrim, "cornerSharpnesses") def init_normals_facevarying_attributes(prim): mesh = UsdGeom.Mesh(prim) # authored normals only works when subdivision is none mesh.CreateSubdivisionSchemeAttr("none") normalsVar = mesh.CreatePrimvar("normals", Sdf.ValueTypeNames.Normal3fArray) normalsAttr = prim.GetAttribute("primvars:normals") normalIndicesAttr = prim.CreateAttribute("primvars:normals:indices", Sdf.ValueTypeNames.IntArray, False) normalsVar.SetInterpolation("faceVarying") def connect_normals_facevarying_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect normal related attributes helper.connect(computer, "outputs:normals", ognPrim, "primvars:normals") helper.connect(computer, "outputs:normalIndices", ognPrim, "primvars:normals:indices") def init_texture_coords_facevarying_attributes(prim): mesh = UsdGeom.Mesh(prim) # st related attributes stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying) stsAttr = prim.GetAttribute("primvars:st") stIndicesAttr = prim.CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False) def connect_texture_coords_facevarying_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect st related attributes helper.connect(computer, "outputs:sts", ognPrim, "primvars:st") helper.connect(computer, "outputs:stIndices", ognPrim, "primvars:st:indices") def init_texture_coords_attributes(prim): mesh = UsdGeom.Mesh(prim) # st related attributes stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex) stsAttr = prim.GetAttribute("primvars:st") def connect_texture_coords_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect st related attributes helper.connect(computer, "outputs:sts", ognPrim, "primvars:st") def create_procedural_mesh_cube( stage, parentPath=None, xLength=100, yLength=100, zLength=100, xResolution=10, yResolution=10, zResolution=10 ): root, cube, computer = create_mesh_computer( stage, "ProceduralMeshCube", "CubeEvaluator", "omni.kit.procedural.mesh.CreateMeshCube", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:xLength", xLength], ["inputs:yLength", yLength], ["inputs:zLength", zLength], ["inputs:xResolution", xResolution], ["inputs:yResolution", xResolution], ["inputs:zResolution", zResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(cube) init_crease_attributes(cube) init_normals_facevarying_attributes(cube) init_texture_coords_facevarying_attributes(cube) connect_common_attributes(cube, computer) connect_crease_attributes(cube, computer) connect_normals_facevarying_attributes(cube, computer) connect_texture_coords_facevarying_attributes(cube, computer) return root, cube def create_procedural_mesh_sphere(stage, parentPath=None, diameter=100, longitudeResolution=10, latitudeResolution=10): root, sphere, computer = create_mesh_computer( stage, "ProceduralMeshSphere", "SphereEvaluator", "omni.kit.procedural.mesh.CreateMeshSphere", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:longitudeResolution", longitudeResolution], ["inputs:latitudeResolution", latitudeResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(sphere) init_texture_coords_facevarying_attributes(sphere) connect_common_attributes(sphere, computer) connect_texture_coords_facevarying_attributes(sphere, computer) return root, sphere def create_procedural_mesh_capsule( stage, parentPath=None, diameter=100, yLength=200, longitudeResolution=10, hemisphereLatitudeResolution=10, middleLatitudeResolution=10, ): root, capsule, computer = create_mesh_computer( stage, "ProceduralMeshCapsule", "CapsuleEvaluator", "omni.kit.procedural.mesh.CreateMeshCapsule", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:yLength", yLength], ["inputs:longitudeResolution", longitudeResolution], ["inputs:hemisphereLatitudeResolution", hemisphereLatitudeResolution], ["inputs:middleLatitudeResolution", middleLatitudeResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(capsule) init_texture_coords_facevarying_attributes(capsule) connect_common_attributes(capsule, computer) connect_texture_coords_facevarying_attributes(capsule, computer) return root, capsule def create_procedural_mesh_cylinder( stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10 ): root, cylinder, computer = create_mesh_computer( stage, "ProceduralMeshCylinder", "CylinderEvaluator", "omni.kit.procedural.mesh.CreateMeshCylinder", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:height", height], ["inputs:longitudeResolution", longitudeResolution], ["inputs:latitudeResolution", latitudeResolution], ["inputs:capResolution", capResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(cylinder) init_crease_attributes(cylinder) init_normals_facevarying_attributes(cylinder) init_texture_coords_facevarying_attributes(cylinder) connect_common_attributes(cylinder, computer) connect_crease_attributes(cylinder, computer) connect_normals_facevarying_attributes(cylinder, computer) connect_texture_coords_facevarying_attributes(cylinder, computer) return root, cylinder def create_procedural_mesh_cone( stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10 ): root, cone, computer = create_mesh_computer( stage, "ProceduralMeshCone", "ConeEvaluator", "omni.kit.procedural.mesh.CreateMeshCone", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:height", height], ["inputs:longitudeResolution", longitudeResolution], ["inputs:latitudeResolution", latitudeResolution], ["inputs:capResolution", capResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(cone) init_crease_attributes(cone) init_corner_attributes(cone) init_normals_facevarying_attributes(cone) init_texture_coords_facevarying_attributes(cone) connect_common_attributes(cone, computer) connect_crease_attributes(cone, computer) connect_corner_attributes(cone, computer) connect_normals_facevarying_attributes(cone, computer) connect_texture_coords_facevarying_attributes(cone, computer) return root, cone def create_procedural_mesh_torus( stage, parentPath=None, diameter=200, sectionDiameter=50, sectionTwist=0, loopResolution=10, sectionResolution=10 ): root, torus, computer = create_mesh_computer( stage, "ProceduralMeshTorus", "TorusEvaluator", "omni.kit.procedural.mesh.CreateMeshTorus", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:sectionDiameter", sectionDiameter], ["inputs:sectionTwist", sectionTwist], ["inputs:loopResolution", loopResolution], ["inputs:sectionResolution", sectionResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(torus) init_texture_coords_facevarying_attributes(torus) connect_common_attributes(torus, computer) connect_texture_coords_facevarying_attributes(torus, computer) return root, torus def create_procedural_mesh_disk(stage, parentPath=None, diameter=100, longitudeResolution=10, capResolution=10): root, disk, computer = create_mesh_computer( stage, "ProceduralMeshDisk", "DiskEvaluator", "omni.kit.procedural.mesh.CreateMeshDisk", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:longitudeResolution", longitudeResolution], ["inputs:capResolution", capResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(disk) init_texture_coords_attributes(disk) connect_common_attributes(disk, computer) connect_texture_coords_attributes(disk, computer) return root, disk def create_procedural_mesh_plane(stage, parentPath=None, xLength=100, zLength=100, xResolution=10, zResolution=10): root, plane, computer = create_mesh_computer( stage, "ProceduralMeshPlane", "PlaneEvaluator", "omni.kit.procedural.mesh.CreateMeshPlane", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:xLength", xLength], ["inputs:zLength", zLength], ["inputs:xResolution", xResolution], ["inputs:zResolution", zResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(plane) init_texture_coords_attributes(plane) connect_common_attributes(plane, computer) connect_texture_coords_attributes(plane, computer) return root, plane
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/menu.py
import omni.kit.ui import omni.usd # ====================================================================== MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cube' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Sphere' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Capsule' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cylinder' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cone' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Torus' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Plane' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Disk' ) class Menu: def __init__(self): self.on_startup() def on_startup(self): self.menus = [] editor_menu = omni.kit.ui.get_editor_menu() self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK, self._on_menu_click)) def _on_menu_click(self, menu_item, value): if menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE: omni.kit.commands.execute("CreateProceduralMeshCube") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE: omni.kit.commands.execute("CreateProceduralMeshSphere") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE: omni.kit.commands.execute("CreateProceduralMeshCapsule") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER: omni.kit.commands.execute("CreateProceduralMeshCylinder") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE: omni.kit.commands.execute("CreateProceduralMeshCone") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS: omni.kit.commands.execute("CreateProceduralMeshTorus") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE: omni.kit.commands.execute("CreateProceduralMeshPlane") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK: omni.kit.commands.execute("CreateProceduralMeshDisk") def on_shutdown(self): self.menus = []
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/command.py
import omni from pxr import UsdGeom, Usd, Vt, Kind, Sdf from .procedural_mesh_omnigraph_utils import ( create_procedural_mesh_cube, create_procedural_mesh_sphere, create_procedural_mesh_capsule, create_procedural_mesh_cylinder, create_procedural_mesh_cone, create_procedural_mesh_torus, create_procedural_mesh_plane, create_procedural_mesh_disk, ) class CreateProceduralMeshCommand(omni.kit.commands.Command): def __init__(self): self._create = None self._stage = omni.usd.get_context().get_stage() self._selection = omni.usd.get_context().get_selection() def do(self): xForm, mesh = self._create(self._stage) self._prim_path = xForm.GetPath() # set the new prim as the active selection self._selection.set_prim_path_selected(self._prim_path.pathString, True, False, True, True) return xForm def undo(self): prim = self._stage.GetPrimAtPath(self._prim_path) if prim: self._stage.RemovePrim(self._prim_path) class CreateProceduralMeshCubeCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_cube class CreateProceduralMeshSphereCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_sphere class CreateProceduralMeshCapsuleCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_capsule class CreateProceduralMeshCylinderCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_cylinder class CreateProceduralMeshConeCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_cone class CreateProceduralMeshTorusCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_torus class CreateProceduralMeshPlaneCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_plane class CreateProceduralMeshDiskCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_disk omni.kit.commands.register(CreateProceduralMeshCubeCommand) omni.kit.commands.register(CreateProceduralMeshSphereCommand) omni.kit.commands.register(CreateProceduralMeshCapsuleCommand) omni.kit.commands.register(CreateProceduralMeshCylinderCommand) omni.kit.commands.register(CreateProceduralMeshConeCommand) omni.kit.commands.register(CreateProceduralMeshTorusCommand) omni.kit.commands.register(CreateProceduralMeshPlaneCommand) omni.kit.commands.register(CreateProceduralMeshDiskCommand)
omniverse-code/kit/exts/omni.kit.gfn/PACKAGE-LICENSES/omni.kit.gfn-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.gfn/config/extension.toml
[package] title = "NVIDIA GFN Integration" category = "Streaming" # Semantic Versioning is used: https://semver.org/ version = "1.1.0" [dependencies] #"omni.usd" = {} [[python.module]] name = "omni.kit.gfn" [[native.plugin]] path = "bin/*.plugin" recursive = false [settings] #exts."omni.kit.gfn".enable = false [[test]] waiver = "Tests are in omni.gfn.autoload"
omniverse-code/kit/exts/omni.kit.gfn/omni/kit/gfn/__init__.py
from ._kit_gfn import * # Cached interface instance pointer def get_geforcenow_interface() -> IGeForceNow: """Returns cached :class:`omni.kit.gfn.IGeForceNow` interface""" if not hasattr(get_geforcenow_interface, "geforcenow"): get_geforcenow_interface.geforcenow = acquire_geforcenow_interface() return get_geforcenow_interface.geforcenow
omniverse-code/kit/exts/omni.kit.gfn/omni/kit/gfn/_kit_gfn.pyi
"""pybind11 omni.kit.gfn bindings""" from __future__ import annotations import omni.kit.gfn._kit_gfn import typing __all__ = [ "IGeForceNow", "acquire_geforcenow_interface", "release_geforcenow_interface" ] class IGeForceNow(): def get_partner_secure_data(self) -> str: ... def shutdown(self) -> None: ... def startup(self, sdk_library_path: str = '') -> None: ... pass def acquire_geforcenow_interface(plugin_name: str = None, library_path: str = None) -> IGeForceNow: pass def release_geforcenow_interface(arg0: IGeForceNow) -> None: pass
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/thumbnail_grid.py
from functools import partial from typing import Callable, Dict, List, Optional import omni.ui as ui from omni.ui import constant as fl from .style import ICON_PATH class ThumbnailItem(ui.AbstractItem): """ Data item for a thumbnail. Args: thumbnail (str): Url to thumbnail. url (str): Url to item. text (str): Display text for this item. Default use file name of url. """ def __init__(self, thumbnail: str, url: str, text: Optional[str] = None): self.thumbnail = thumbnail self.url = url self.text = text if text else url.split("/")[-1] super().__init__() def execute(self): pass class ThumbnailModel(ui.AbstractItemModel): """ Data model for thumbnail items. Args: items (List[ThumbnailItem]): List of thumbnail items """ def __init__(self, items: List[ThumbnailItem]): super().__init__() self._items = items def get_item_children(self, item: Optional[ThumbnailItem] = None) -> List[ThumbnailItem]: return self._items class ThumbnailGrid: """ Widget to show a grid (thumbnail + label). Args: model (ThumbnailModel): Data model. label_height (int): Height for item label. Default 30. thumbnail_width (int): Thumbnail width. Default 128. thumbnail_height (int): Thumbnail height. Default 128. thumbnail_padding_x (int): X padding between different thumbnail items. Default 2. thumbnail_padding_y (int): Y padding between different thumbnail items. Default 4. """ def __init__( self, model: ThumbnailModel, on_selection_changed: Callable[[Optional[ThumbnailItem]], None] = None, label_height:int=fl._find("welcome_open_lable_size"), thumbnail_width: int=fl._find("welcome_open_thumbnail_size"), thumbnail_height: int=fl._find("welcome_open_thumbnail_size"), thumbnail_padding_x: int=2, thumbnail_padding_y: int=4, ): self._model = model self._on_selection_changed = on_selection_changed self._label_height = label_height self._thumbnail_width = thumbnail_width self._thumbnail_height = thumbnail_height self._thumbnail_padding_x = thumbnail_padding_x self._thumbnail_padding_y = thumbnail_padding_y self._column_width = self._thumbnail_width + 2 * self._thumbnail_padding_x self._row_height = self._thumbnail_height + 2 * self._thumbnail_padding_y + self._label_height self.__selected_thumbnail: Optional[ThumbnailItem] = None self.__frames: Dict[ThumbnailItem, ui.Frame] = {} self._build_ui() @property def selected(self) -> Optional[ThumbnailItem]: return self.__selected_thumbnail @selected.setter def selected(self, item: Optional[ThumbnailItem]) -> None: self.select_item(item) def _build_ui(self): self._container = ui.ScrollingFrame( style_type_name_override="ThumbnailGrid.Frame", vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ) self._refresh() self._sub_model = self._model.subscribe_item_changed_fn(lambda m, i: self._refresh()) def _refresh(self): self._container.clear() with self._container: self._grid = ui.VGrid( column_width=self._column_width, row_hegiht=self._row_height, content_clipping=True, ) with self._grid: children = self._model.get_item_children() if not children: return for item in children: with ui.VStack(): ui.Spacer(height=self._thumbnail_padding_y) with ui.HStack(): ui.Spacer(width=self._thumbnail_padding_x) self.__frames[item] = ui.Frame( build_fn=lambda i=item: self._build_thumbnail_item(i), mouse_double_clicked_fn=lambda x, y, a, f, i=item: i.execute(), mouse_pressed_fn=lambda x, y, a, f, i=item: self.select_item(i), ) ui.Spacer(width=self._thumbnail_padding_x) ui.Spacer(height=self._thumbnail_padding_y) self._grid.set_mouse_pressed_fn(lambda x, y, btn, flag: self.select_item(None)) def _build_thumbnail_item(self, item: ThumbnailItem) -> None: with ui.ZStack(): with ui.VStack(): self.build_thumbnail(item) self.build_label(item) ui.Rectangle(style_type_name_override="ThumbnailGrid.Selection") def build_thumbnail(self, item: ThumbnailItem) -> None: def on_image_progress(default_image: ui.Image, thumbnail_image: ui.Image, progress: float): """Called when the image loading progress is changed.""" if progress != 1.0: # We only need to catch the moment when the image is loaded. return # Hide the default_image at the back. default_image.visible = False # Remove the callback to avoid circular references. thumbnail_image.set_progress_changed_fn(None) with ui.ZStack(width=self._thumbnail_width, height=self._thumbnail_height): # Default image for thumbnail not defined or invalid thumbnail url or download in progress # Hidden when actually thumbnail downloaded default_image = ui.Image(f"{ICON_PATH}/usd_stage_256.png", style_type_name_override="ThumbnailGrid.Image") if item.thumbnail: thumbnail_image = ui.Image(item.thumbnail, style_type_name_override="ThumbnailGrid.Image") thumbnail_image.set_progress_changed_fn(partial(on_image_progress, default_image, thumbnail_image)) def build_label(self, item: ThumbnailItem) -> None: with ui.ZStack(): ui.Rectangle(style_type_name_override="ThumbnailGrid.Item.Background") ui.Label( item.text, height=self._label_height, word_wrap=True, elided_text=True, skip_draw_when_clipped=True, alignment=ui.Alignment.CENTER, style_type_name_override="ThumbnailGrid.Item", ) def select_item(self, item: Optional[ThumbnailItem]) -> None: if self.__selected_thumbnail: self.__frames[self.__selected_thumbnail].selected = False if item: self.__frames[item].selected = True self.__selected_thumbnail = item if self._on_selection_changed: self._on_selection_changed(item) def find_item(self, url: str) -> Optional[ThumbnailItem]: for item in self._model.get_item_children(None): if item.url == url: return item return None def select_url(self, url: str) -> None: if url: item = self.find_item(url) self.select_item(item) else: self.select_item(None)
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/stage_tab.py
from typing import Optional import carb import omni.ui as ui from omni.ui import constant as fl from omni.kit.welcome.window import show_window as show_welcome_window from .recent_widget import RecentWidget from .template_grid import TemplateGrid from .thumbnail_grid import ThumbnailItem SETTING_SHOW_TEMPLATES = "/exts/omni.kit.welcome.open/show_templates" class StageTab: """ Tab to show stage content. """ def __init__(self): self._checkpoint_combobox = None self._build_ui() def destroy(self): self._recent_widget.destroy() def _build_ui(self): with ui.VStack(): # Templates if carb.settings.get_settings().get_as_bool(SETTING_SHOW_TEMPLATES): with ui.HStack(height=0): ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.VStack(): ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator") ui.Label("NEW", height=0, style_type_name_override="ThumbnailGrid.Title") ui.Spacer(height=10) ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.HStack(height=fl._find("welcome_open_thumbnail_size") + fl._find("welcome_open_lable_size") + 60): ui.Spacer(width=8) self._template_grid = TemplateGrid(on_selection_changed=self.__on_template_selected) ui.Spacer(width=8) # Recent files with ui.HStack(height=0): ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.VStack(): ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator") with ui.HStack(height=20): ui.Label("RECENT", width=0, style_type_name_override="ThumbnailGrid.Title") ui.Spacer() self._mode_image = ui.Image(name="grid", width=20, style_type_name_override="ThumbnailGrid.Mode", mouse_pressed_fn=lambda x, y, b,a: self.__toggle_thumbnail_model()) ui.Spacer(height=10) ui.Spacer(width=fl._find("welcome_content_padding_x")) self._recent_widget = RecentWidget(self.__on_recent_selected, self.__on_grid_mode) # Open widgets with ui.ZStack(height=26): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(spacing=2): self._checkpoint_blank = ui.Rectangle(style_type_name_override="Stage.Blank") self._checkpoint_frame = ui.Frame(build_fn=self.__build_checkpoints, visible=False) # Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_file()) ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False)) def __toggle_thumbnail_model(self): if self._mode_image.name == "grid": self._mode_image.name = "table" self._recent_widget.show_grid(False) else: self._mode_image.name = "grid" self._recent_widget.show_grid(True) def __build_checkpoints(self): try: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.widget.versioning", True) from omni.kit.widget.versioning import CheckpointCombobox with ui.HStack(spacing=2): with ui.ZStack(content_clipping=True, width=0): ui.Rectangle(style_type_name_override="Stage.Blank") ui.Label("Checkpoints", width=0, style_type_name_override="Stage.Label") self._checkpoint_combobox = CheckpointCombobox( self._recent_widget.selected_url if self._recent_widget.selected_url else "", None, width=ui.Fraction(1), has_pre_spacer=False, popup_width=0, modal=True ) except Exception as e: carb.log_warn(f"Failed to create checkpoint combobox: {e}") self._checkpoint_combobox = None def __on_template_selected(self, item: Optional[ThumbnailItem]): if item: # Clear selection in recents self._recent_widget.selected_url = None # Hide checkpoint combobox self._checkpoint_frame.visible = False self._checkpoint_blank.visible = True def __on_recent_selected(self, item: Optional[ui.AbstractItem]): if item: # Clear selection in templates self._template_grid.selected = None if isinstance(item, ThumbnailItem): # Show checkpoint combobox if selected in recent grid self._checkpoint_frame.visible = bool(item) self._checkpoint_blank.visible = not bool(item) if item and self._checkpoint_combobox: self._checkpoint_combobox.url = item.url def __on_grid_mode(self, grid_mode: bool) -> None: # Show checkpoint combobox in grid mode and recent file selected if grid_mode: show_checkpoint = bool(self._recent_widget.selected_url) self._checkpoint_frame.visible = show_checkpoint self._checkpoint_blank.visible = not show_checkpoint else: self._checkpoint_frame.visible = False self._checkpoint_blank.visible = True def __open_file(self) -> None: selected = self._template_grid.selected if selected: carb.log_info(f"Open template: {selected.url}") selected.execute() else: self._recent_widget.open_selected(self._checkpoint_combobox.url if self._checkpoint_combobox else None)
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/style.py
from pathlib import Path import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons") fl.welcome_open_thumbnail_size = 145 fl.welcome_open_lable_size = 30 cl.welcome_open_item_selected = cl.shade(cl("#77878A")) cl.welcome_open_label = cl.shade(cl("#9E9E9E")) OPEN_PAGE_STYLE = { "RadioButton": {"background_color": cl.transparent, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "padding": 0, "margin": 0}, "RadioButton.Label": {"font_size": fl.welcome_title_font_size, "color": cl.welcome_label, "alignment": ui.Alignment.LEFT_CENTER}, "RadioButton.Label:checked": {"color": cl.welcome_label_selected}, "RadioButton:checked": {"background_color": cl.transparent}, "RadioButton:hovered": {"background_color": cl.transparent}, "RadioButton:pressed": {"background_color": cl.transparent}, "RadioButton.Image::STAGE": {"image_url": f"{ICON_PATH}/USD.svg"}, "RadioButton.Image::SAMPLES": {"image_url": f"{ICON_PATH}/image.svg"}, "RadioButton.Image::FILE": {"image_url": f"{ICON_PATH}/hdd.svg"}, "RadioButton.Image": {"color": cl.welcome_label, "alignment": ui.Alignment.RIGHT_CENTER}, "RadioButton.Image:checked": {"color": cl.welcome_label_selected}, "ThumbnailGrid.Separator": {"color": cl.welcome_window_background, "border_width": 1.5}, "ThumbnailGrid.Title": {"color": 0xFFCCCCCC, "font_size": fl.welcome_title_font_size}, "ThumbnailGrid.Mode": {"margin": 2}, "ThumbnailGrid.Mode::grid": {"image_url": f"{ICON_PATH}/thumbnail.svg"}, "ThumbnailGrid.Mode::table": {"image_url": f"{ICON_PATH}/list.svg"}, "ThumbnailGrid.Frame": { "background_color": cl.transparent, "secondary_color": 0xFF808080, "border_radius": 0, "scrollbar_size": 10, }, "ThumbnailGrid.Selection": { "background_color": cl.transparent, }, "ThumbnailGrid.Selection:selected": { "border_width": 1, "border_color": cl.welcome_open_item_selected, "border_radius": 0, }, "ThumbnailGrid.Item.Background": { "background_color": cl.transparent, }, "ThumbnailGrid.Item.Background:selected": { "background_color": 0xFF525252, }, "ThumbnailGrid.Item": { "margin_width": 2, "color": cl.welcome_label, }, "Template.Add": {"color": 0xFFFFFFFF}, "Template.Add:hovered": {"color": cl.welcome_label_selected}, "Template.Add:pressed": {"color": cl.welcome_label_selected}, "Template.Add:selected": {"color": cl.welcome_label_selected}, "Stage.Label": {"color": cl.welcome_open_label, "margin_width": 6}, "Stage.Button": { "background_color": 0xFF23211F, "selected_color": 0xFF8A8777, "color": cl.welcome_open_label, "margin": 0, "padding": 0 }, "Stage.Button:hovered": {"background_color": 0xFF3A3A3A}, "Stage.Button.Label": {"color": cl.welcome_open_label}, "Stage.Button.Label:disabled": {"color": 0xFF3A3A3A}, "Stage.Separator": {"background_color": cl.welcome_window_background}, "Stage.Blank": {"background_color": cl.welcome_content_background}, }
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/extension.py
from typing import Optional import omni.ext import omni.ui as ui from omni.kit.welcome.window import register_page from .open_widget import OpenWidget class OpenPageExtension(omni.ext.IExt): def on_startup(self, ext_id): self._widget: Optional[OpenWidget] = None self.__ext_name = omni.ext.get_extension_name(ext_id) register_page(self.__ext_name, self.build_ui) def on_shutdown(self): if self._widget: self._widget.destroy() self._widget = None def build_ui(self) -> None: self._widget = OpenWidget()
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/__init__.py
from .extension import *
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_widget.py
import asyncio import os from typing import Callable, List, Optional import carb.settings import omni.ui as ui from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel SETTING_RECENT_FILES = "/persistent/app/file/recentFiles" class RecentItem(ThumbnailItem): """ Data item for recent file. """ def __init__(self, url: str): super().__init__(self.__get_thumbnail(url), url) def __get_thumbnail(self, url: str): file_name = os.path.basename(url) path = os.path.dirname(url) # Do not check if thumbnail image exists here, leave it to ThumbnailGrid return f"{path}/.thumbs/256x256/{file_name}.png" def execute(self, url: Optional[str] = None): from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", url if url else self.url) class RecentModel(ThumbnailModel): """ Data model for recent files. """ def __init__(self, recent_files: List[str]): super().__init__([]) self.refresh(recent_files) def refresh(self, recent_files: List[str]) -> None: self._items = [RecentItem(recent) for recent in recent_files] if recent_files else [] self._item_changed(None) class RecentWidget: """ Show recents grid and open widgets. """ def __init__(self, on_recent_changed_fn: Callable[[Optional[ui.AbstractItem]], None], on_grid_mode_fn: Callable[[bool], None]): self._settings = carb.settings.get_settings() self.__get_recent_history() self._grid_model = RecentModel(self.__recent_files) self._recent_table: Optional[RecentTable] = None self.__on_recent_selected_fn = on_recent_changed_fn self.__on_grid_mode_fn = on_grid_mode_fn self._build_ui() def destroy(self): self._subscription = None self._event_sub = None @property def selected_url(self) -> str: if self._grid_frame.visible: return self._recent_grid.selected.url if self._recent_grid.selected else "" else: return self._recent_table.selected @selected_url.setter def selected_url(self, url: str) -> None: if self._grid_frame.visible: self._recent_grid.select_url(url) else: self._recent_table.selected = url def clear_selection(self): if self._grid_frame.visible: self._recent_grid.selected = None else: self._recent_table.selected = None def show_grid(self, grid: bool) -> None: self._grid_frame.visible = grid self._table_frame.visible = not grid if grid: # Set grid selection from table if self._recent_table: self._recent_grid.select_url(self._recent_table.selected) else: # Set table selection from grid if self._recent_table: if self._recent_grid.selected: self._recent_table.selected = self._recent_grid.selected.url else: # Wait for widget create and set selection async def __delay_select(): await omni.kit.app.get_app().next_update_async() if self._recent_grid.selected: self._recent_table.selected = self._recent_grid.selected.url asyncio.ensure_future(__delay_select()) self.__on_grid_mode_fn(grid) def open_selected(self, checkpoint_url: Optional[str]) -> None: def __open_file(url): carb.log_info(f"Open recent file: {url}") from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", url) if self.selected_url: if self._grid_frame.visible: __open_file(checkpoint_url or self.selected_url) else: __open_file(self._recent_table.get_filename()) def _build_ui(self): with ui.ZStack(): self._grid_frame = ui.Frame(build_fn=self._build_grid_ui) self._table_frame = ui.Frame(build_fn=self._build_table_ui, visible=False) def _build_table_ui(self): try: from .recent_table import RecentTable self._recent_table = RecentTable(self.__recent_files, on_selection_changed_fn=self.__on_recent_selected_fn) except Exception as e: self._recent_table = None carb.log_error(f"Failed to create recent table: {e}") def _build_grid_ui(self): with ui.VStack(): # Recent grid with ui.HStack(): ui.Spacer(width=8) self._recent_grid = ThumbnailGrid(self._grid_model, on_selection_changed=self.__on_recent_selected_fn) ui.Spacer(width=8) def _on_change(self, item, event_type): if event_type == carb.settings.ChangeEventType.CHANGED: self.__recent_files = self._settings.get(SETTING_RECENT_FILES) self.__rebuild_recents() def __rebuild_recents_from_event(self) -> None: from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD) if self._recent_table: self._recent_table.refresh(self.__recent_files) self._grid_model.refresh(self.__recent_files) def __get_recent_history(self): load_recents_from_event = self._settings.get("/exts/omni.kit.welcome.open/load_recent_from_event") if load_recents_from_event: self.__get_recent_from_event() else: self.__recent_files = self._settings.get(SETTING_RECENT_FILES) # If recent files changed, refresh self._subscription = omni.kit.app.SettingChangeSubscription(SETTING_RECENT_FILES, self._on_change) def __get_recent_from_event(self) -> None: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.helper.file_utils", True) from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types, FILE_EVENT_QUEUE_UPDATED self._max_recent_files = self._settings.get("exts/omni.kit.menu.file/maxRecentFiles") or 10 self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD) event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._event_sub = event_stream.create_subscription_to_pop_by_type(FILE_EVENT_QUEUE_UPDATED, lambda _: self.__rebuild_recents_from_event())
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_action.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__ = ["run_open_action"] import asyncio def run_open_action(extension_id: str, action_id: str, *args, **kwargs): import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() # Setup the viewport (and UI first) action_registry.execute_action("omni.app.setup", "enable_viewport_rendering") # Finally hide the Welcome window from omni.kit.welcome.window import show_window as show_welcome_window show_welcome_window(visible=False, stage_opened=True) # Run the action which will open or create a Usd.Stage async def __execute_action(): import omni.kit.app # OM-90720: sometimes open stage will popup a prompt to ask if save current stage # But the prompt is a popup window which will hide immediately if the welcome window (modal) still there # As a result, the required stage will not be opened # So here wait a few frames to make sure welcome window is really closed for _ in range(4): await omni.kit.app.get_app().next_update_async() action_registry.execute_action(extension_id, action_id, *args, **kwargs) asyncio.ensure_future(__execute_action())
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_widget.py
from typing import Dict, Optional import carb import omni.ui as ui from omni.kit.welcome.window import show_window as show_welcome_window from omni.ui import constant as fl from .stage_tab import StageTab from .style import OPEN_PAGE_STYLE class OpenWidget: """ Widget for open page. """ def __init__(self): self.__tabs: Dict[str, callable] = { "STAGE": self.__build_stage, "SAMPLES": self.__build_sample, "FILE": self.__build_file, } self.__tab_frames: Dict[str, ui.Frame] = {} self.__stage_tab: Optional[StageTab] = None self._build_ui() def destroy(self): if self.__stage_tab: self.__stage_tab.destroy() self.__stage_tab = None def _build_ui(self): self._collection = ui.RadioCollection() with ui.ZStack(style=OPEN_PAGE_STYLE): # Background ui.Rectangle(style_type_name_override="Content") with ui.VStack(): # Tab buttons with ui.VStack(height=fl._find("welcome_page_title_height")): ui.Spacer() with ui.HStack(height=0): ui.Spacer() with ui.HStack(spacing=30): for tab in self.__tabs.keys(): ui.RadioButton(text=tab, width=0, spacing=8, image_width=24, image_height=24, name=tab, radio_collection=self._collection, clicked_fn=lambda t=tab: self._show_tab(t)) ui.Spacer() ui.Spacer() # Tab frames with ui.ZStack(): for tab in self.__tabs.keys(): self.__tab_frames[tab] = ui.Frame(build_fn=lambda t=tab: self.__tabs[t](), visible=tab == "STAGE") def _show_tab(self, name: str) -> None: for tab in self.__tabs.keys(): if tab == name: self.__tab_frames[name].visible = True else: self.__tab_frames[tab].visible = False def __build_stage(self): self.__stage_tab = StageTab() def __build_sample(self): try: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.browser.sample", True) from omni.kit.browser.sample import get_instance as get_sample_instance from omni.kit.browser.sample.browser_widget import SampleTreeFolderBrowserWidget from omni.kit.browser.core import BrowserSearchBar # Remove options button class SampleWidget(SampleTreeFolderBrowserWidget): def _build_search_bar(self): self._search_bar = BrowserSearchBar(options_menu=None) # Hack to close welcome window after sample opened def __open_sample(item): from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", item.url) model = get_sample_instance().get_model() model.execute = __open_sample # Sample widget with ui.ZStack(): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=2) self.__sample_widget = SampleWidget(model) # Open widgets with ui.ZStack(height=26): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(spacing=2): ui.Rectangle(style_type_name_override="Stage.Blank") # Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_sample()) ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False)) except Exception as e: carb.log_error(f"Failed to import sample browser widget: {e}") def __build_file(self): try: from omni.kit.window.filepicker import FilePickerWidget def __open_file(file_name, dir_name): from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", dir_name + file_name) with ui.ZStack(): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(): ui.Spacer(width=2) FilePickerWidget( "Welcome", enable_checkpoints=True, apply_button_label="Open File", cancel_button_label="Close", click_apply_handler=__open_file, click_cancel_handler=lambda f, d: show_welcome_window(visible=False), modal=True, ) except Exception as e: carb.log_error(f"Failed to import file picker widget: {e}") def __open_sample(self): selections = self.__sample_widget.detail_selection if selections: self.__sample_widget._browser_model.execute(selections[0]) show_welcome_window(visible=False)
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_table.py
import os from typing import List, Optional import omni.client import omni.ui as ui from omni.kit.widget.filebrowser import LAYOUT_SINGLE_PANE_LIST, LISTVIEW_PANE, FileBrowserItem, FileBrowserModel from omni.kit.widget.filebrowser.model import FileBrowserItemFields from omni.kit.window.filepicker import FilePickerWidget class RecentTableModel(FileBrowserModel): def __init__(self, recent_files: List[str]): super().__init__() self.refresh(recent_files) def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]: return self._items def refresh(self, recent_files: List[str]): if recent_files: self._items = [self.__create_file_item(url) for url in recent_files] else: self._items = [] self._item_changed(None) def __create_file_item(self, url: str) -> Optional[FileBrowserItem]: file_name = os.path.basename(url) result, entry = omni.client.stat(url) if result == omni.client.Result.OK: item = FileBrowserItem(url, FileBrowserItemFields(file_name, entry.modified_time, 0, 0), is_folder=False) item._models = (ui.SimpleStringModel(item.name), entry.modified_time, ui.SimpleStringModel("")) return item else: return None class RecentTable: def __init__(self, recent_files: List[str], on_selection_changed_fn: callable): self.__recent_files = recent_files self.__picker: Optional[FilePickerWidget] = None self.__on_selection_changed_fn = on_selection_changed_fn self._build_ui() @property def selected(self) -> str: if self.__picker: selections = self.__picker._view.get_selections(pane=LISTVIEW_PANE) if selections: return selections[0].path else: return "" else: return "" @selected.setter def selected(self, url: str) -> None: if self.__picker: if url: for item in self._model.get_item_children(None): if item.path == url: selections = [item] else: selections = [] self.__picker._view.set_selections(selections, pane=LISTVIEW_PANE) def refresh(self, recent_files: List[str]): self._model.refresh(recent_files) def get_filename(self) -> str: return self.__picker._api.get_filename() if self.__picker else "" def _build_ui(self): with ui.ZStack(): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(): self.__picker = FilePickerWidget( "Welcome", enable_tool_bar=False, layout=LAYOUT_SINGLE_PANE_LIST, show_grid_view=False, save_grid_view=False, enable_checkpoints=True, enable_zoombar=False, enable_file_bar=False, selection_changed_fn=self.__on_selection_changed_fn, ) self._model = RecentTableModel(self.__recent_files) self.__picker._view.show_model(self._model)
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/render_loading.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__ = ["start_render_loading_ui"] def start_render_loading_ui(ext_manager, renderer: str): import carb import time time_begin = time.time() carb.settings.get_settings().set("/exts/omni.kit.viewport.ready/startup/enabled", False) ext_manager.set_extension_enabled_immediate("omni.kit.viewport.ready", True) from omni.kit.viewport.ready.viewport_ready import ViewportReady, ViewportReadyDelegate class TimerDelegate(ViewportReadyDelegate): def __init__(self, time_begin): super().__init__() self.__timer_start = time.time() self.__vp_ready_cost = self.__timer_start - time_begin @property def font_size(self) -> float: return 48 @property def message(self) -> str: rtx_mode = { "RaytracedLighting": "Real-Time", "PathTracing": "Interactive (Path Tracing)", "LightspeedAperture": "Aperture (Game Path Tracer)" }.get(carb.settings.get_settings().get("/rtx/rendermode"), "Real-Time") renderer_label = { "rtx": f"RTX - {rtx_mode}", "iray": "RTX - Accurate (Iray)", "pxr": "Pixar Storm", "index": "RTX - Scientific (IndeX)" }.get(renderer, renderer) return f"Waiting for {renderer_label} to start" def on_complete(self): rtx_load_time = time.time() - self.__timer_start super().on_complete() print(f"Time until pixel: {rtx_load_time}") print(f"ViewportReady cost: {self.__vp_ready_cost}") return ViewportReady(TimerDelegate(time_begin))
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/template_grid.py
import functools import locale from typing import List import omni.kit.stage_templates import omni.ui as ui from omni.kit.welcome.window import show_window from .style import ICON_PATH from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel import asyncio class TemplateItem(ThumbnailItem): """ Data item for template. """ def __init__(self, template: list): # TODO: how to get template thumbnail? stage_name = template[0] super().__init__("", stage_name) def execute(self): from .open_action import run_open_action run_open_action("omni.kit.stage.templates", self.__get_action_name()) def __get_action_name(self): return "create_new_stage_" + self.url.lower().replace('-', '_').replace(' ', '_') class TemplateModel(ThumbnailModel): """ Data model for templates. """ def __init__(self): stage_templates = omni.kit.stage_templates.get_stage_template_list() template_items: List[ThumbnailItem] = [] def sort_cmp(template1, template2): return locale.strcoll(template1[0], template2[0]) for template_list in stage_templates: for template in sorted(template_list.items(), key=functools.cmp_to_key(sort_cmp)): template_items.append(TemplateItem(template)) super().__init__(template_items) class TemplateGrid(ThumbnailGrid): """ Template grid. """ def __init__(self, **kwargs): self._model = TemplateModel() super().__init__(self._model, **kwargs) def build_thumbnail(self, item: ThumbnailItem): padding = 5 with ui.ZStack(): super().build_thumbnail(item) with ui.VStack(): ui.Spacer() with ui.HStack(height=20): ui.Spacer() ui.Image( f"{ICON_PATH}/add_dark.svg", width=20, style_type_name_override="Template.Add", mouse_pressed_fn=lambda x, y, a, f, i=item: i.execute() ) ui.Spacer(width=padding) ui.Spacer(height=padding)
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/tests/test_page.py
import asyncio from pathlib import Path import omni.kit.app from omni.ui.tests.test_base import OmniUiTest from ..extension import OpenPageExtension CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") class TestPage(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() # After running each test async def tearDown(self): await super().tearDown() async def test_page(self): window = await self.create_test_window(width=800, height=800) with window.frame: ext = OpenPageExtension() ext.on_startup("omni.kit.welcome.open-1.1.0") ext.build_ui() await omni.kit.app.get_app().next_update_async() # OM-92413: Wait for icons loaded await asyncio.sleep(8) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="page.png")
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/tests/__init__.py
from .test_page import *
omniverse-code/kit/exts/omni.kit.welcome.open/docs/index.rst
omni.kit.welcome.open ########################### .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.kit.selection/PACKAGE-LICENSES/omni.kit.selection-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.selection/config/extension.toml
[package] version = "0.1.0" category = "Internal" [dependencies] "omni.kit.commands" = {} "omni.ui" = {} "omni.usd" = {} [[python.module]] name = "omni.kit.selection"
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection_actions.py
import omni.kit.actions.core def register_actions(extension_id): import omni.kit.commands action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "Selection Actions" action_registry.register_action( extension_id, "all", lambda: omni.kit.commands.execute("SelectAll"), display_name="Select->All", description="Select all prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "none", lambda: omni.kit.commands.execute("SelectNone"), display_name="Select->None", description="Deselect all prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "invert", lambda: omni.kit.commands.execute("SelectInvert"), display_name="Select->Invert", description="Deselect all currently unselected prims, and select all currently unselected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "parent", lambda: omni.kit.commands.execute("SelectParentCommand"), display_name="Select->Parent", description="Select the parents of all currently selected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "leaf", lambda: omni.kit.commands.execute("SelectLeafCommand"), display_name="Select->Leaf", description="Select the leafs of all currently selected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "hierarchy", lambda: omni.kit.commands.execute("SelectHierarchyCommand"), display_name="Select->Hierarchy", description="Select the hierachies of all currently selected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "similar", lambda: omni.kit.commands.execute("SelectSimilarCommand"), display_name="Select->Similar", description="Select prims of the same type as any currently selected prim.", tag=actions_tag, ) action_registry.register_action( extension_id, "HideUnselected", lambda: omni.kit.commands.execute("HideUnselected"), display_name="Select->Hide Unselected", description="Hide Unselected Prims", tag=actions_tag, ) action_registry.register_action( extension_id, "UnhideAllPrims", lambda: omni.kit.commands.execute("UnhideAllPrims"), display_name="Select->Unhide All Prims", description="Unhide All Prims", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/__init__.py
from .selection import *
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection.py
import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, Trace, Kind from .selection_actions import register_actions, deregister_actions class SelectionExtension(omni.ext.IExt): def on_startup(self, ext_id): self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name) def on_shutdown(self): deregister_actions(self._ext_name) class SelectAllCommand(omni.kit.commands.Command): """ Select all prims. Args: type (Union[str, None]): Specific type name. If it's None, it will select all prims. If it has type str with value "", it will select all prims without any type. Otherwise, it will select prims with that type. """ def __init__(self, type=None): self._type = type self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() @Trace.TraceFunction def do(self): omni.usd.get_context().get_selection().select_all_prims(self._type) def undo(self): if self._prev_selection: omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) else: omni.usd.get_context().get_selection().clear_selected_prim_paths() class SelectNoneCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def do(self): omni.usd.get_context().get_selection().clear_selected_prim_paths() def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectInvertCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() @Trace.TraceFunction def do(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) omni.usd.get_context().get_selection().select_inverted_prims() def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class HideUnselectedCommand(omni.kit.commands.Command): def get_parent_prims(self, stage, prim): parent_prims = set([]) while prim.GetParent(): parent_prims.add(prim.GetParent().GetPath()) prim = prim.GetParent() if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: break return parent_prims def get_all_children(self, prim): children_list = set([]) queue = [prim] while len(queue) > 0: child_prim = queue.pop() for child in child_prim.GetAllChildren(): children_list.add(child.GetPath()) queue.append(child) return children_list def __init__(self): stage = omni.usd.get_context().get_stage() selection = omni.usd.get_context().get_selection().get_selected_prim_paths() # if selected path as children and none of the children are selected, then all the children are selected.. selected_prims = set([]) for prim_path in selection: sdf_prim_path = Sdf.Path(prim_path) prim = stage.GetPrimAtPath(sdf_prim_path) if prim: selected_prims.add(sdf_prim_path) selected_prims.update(self.get_all_children(prim)) ## exclude parent prims as visabillity is inherited all_parent_prims = set([]) for prim_path in selected_prims: prim = stage.GetPrimAtPath(prim_path) if prim: all_parent_prims.update(self.get_parent_prims(stage, prim)) selected_prims.update(all_parent_prims) all_prims = set([]) children_iterator = iter(stage.TraverseAll()) for prim in children_iterator: if omni.usd.is_hidden_type(prim): children_iterator.PruneChildren() continue all_prims.add(prim.GetPath()) self._invert_prims = [item for item in all_prims if item not in selected_prims] self._prev_visabillity = [] for prim_path in self._invert_prims: prim = stage.GetPrimAtPath(prim_path) if prim: if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: continue imageable = UsdGeom.Imageable(prim) if imageable: self._prev_visabillity.append([prim, imageable.ComputeVisibility()]) @Trace.TraceFunction def do(self): stage = omni.usd.get_context().get_stage() for prim_path in self._invert_prims: prim = stage.GetPrimAtPath(prim_path) if prim: if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: continue imageable = UsdGeom.Imageable(prim) if imageable: imageable.MakeInvisible() def undo(self): for prim, state in self._prev_visabillity: imageable = UsdGeom.Imageable(prim) if imageable: if state == UsdGeom.Tokens.invisible: imageable.MakeInvisible() else: imageable.MakeVisible() class SelectParentCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def do(self): stage = omni.usd.get_context().get_stage() parent_prims = set() for prim_path in self._prev_selection: prim = stage.GetPrimAtPath(prim_path) if prim and prim.GetParent() is not None: parent_prims.add(prim.GetParent().GetPath().pathString) omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(parent_prims)), True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectLeafCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def collect_leafs(self, prim, leaf_set): prim_children = prim.GetChildren() if not prim_children: leaf_set.add(prim.GetPath().pathString) else: for child in prim_children: self.collect_leafs(child, leaf_set) def do(self): stage = omni.usd.get_context().get_stage() leaf_prims = set() for prim_path in self._prev_selection: prim = stage.GetPrimAtPath(prim_path) self.collect_leafs(prim, leaf_prims) omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(leaf_prims)), True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectHierarchyCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def collect_hierarchy(self, prim, hierarchy_set): hierarchy_set.add(prim.GetPath().pathString) prim_children = prim.GetChildren() for child in prim_children: self.collect_hierarchy(child, hierarchy_set) def do(self): stage = omni.usd.get_context().get_stage() heirarchy_prims = set() for prim_path in self._prev_selection: prim = stage.GetPrimAtPath(prim_path) self.collect_hierarchy(prim, heirarchy_prims) omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(heirarchy_prims)), True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectSimilarCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def do(self): stage = omni.usd.get_context().get_stage() similar_prim_types = set() for prim_path in self._prev_selection: prim_type = stage.GetPrimAtPath(prim_path).GetTypeName() similar_prim_types.add(prim_type) omni.usd.get_context().get_selection().select_all_prims(sorted(list(similar_prim_types))) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectListCommand(omni.kit.commands.Command): def __init__(self, **kwargs): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() self._new_selection = [] if 'selection' in kwargs: self._new_selection = kwargs['selection'] def do(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._new_selection, True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectKindCommand(omni.kit.commands.Command): def __init__(self, **kwargs): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() self._kind = "" if 'kind' in kwargs: self._kind = kwargs['kind'] @Trace.TraceFunction def do(self): selection = [] for prim in omni.usd.get_context().get_stage().TraverseAll(): model_api = Usd.ModelAPI(prim) if Kind.Registry.IsA(model_api.GetKind(), self._kind): selection.append(str(prim.GetPath())) omni.usd.get_context().get_selection().set_selected_prim_paths(selection, True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/create_prims.py
import os import carb import carb.settings import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux def create_test_stage(): settings = carb.settings.get_settings() default_prim_name = settings.get("/persistent/app/stage/defaultPrimName") rootname = f"/{default_prim_name}" stage = omni.usd.get_context().get_stage() kit_folder = carb.tokens.get_tokens_interface().resolve("${kit}") omni_pbr_mtl = os.path.normpath(kit_folder + "/mdl/core/Base/OmniPBR.mdl") # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=False ) # create GroundMat material mtl_name = "GroundMat" mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=mtl_path ) ground_mat_prim = stage.GetPrimAtPath(mtl_path) shader = UsdShade.Material(ground_mat_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "specular_level", 0.25, Sdf.ValueTypeNames.Float) omni.usd.create_material_input( ground_mat_prim, "diffuse_color_constant", Gf.Vec3f(0.08, 0.08, 0.08), Sdf.ValueTypeNames.Color3f ) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "metallic_constant", 0.0, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) # create BackSideMat mtl_name = "BackSideMat" backside_mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=backside_mtl_path ) backside_mtl_prim = stage.GetPrimAtPath(backside_mtl_path) shader = UsdShade.Material(backside_mtl_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input( backside_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0.11814344, 0.118142255, 0.118142255), Sdf.ValueTypeNames.Color3f, ) omni.usd.create_material_input(backside_mtl_prim, "reflection_roughness_constant", 0.27, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(backside_mtl_prim, "specular_level", 0.163, Sdf.ValueTypeNames.Float) # create EmissiveMat mtl_name = "EmissiveMat" emissive_mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=emissive_mtl_path ) emissive_mtl_prim = stage.GetPrimAtPath(emissive_mtl_path) shader = UsdShade.Material(emissive_mtl_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input( emissive_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0, 0, 0), Sdf.ValueTypeNames.Color3f ) omni.usd.create_material_input(emissive_mtl_prim, "reflection_roughness_constant", 1, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(emissive_mtl_prim, "specular_level", 0, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(emissive_mtl_prim, "enable_emission", True, Sdf.ValueTypeNames.Bool) omni.usd.create_material_input(emissive_mtl_prim, "emissive_color", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(emissive_mtl_prim, "emissive_intensity", 15000, Sdf.ValueTypeNames.Float) # create studiohemisphere hemisphere_path = omni.usd.get_stage_next_free_path(stage, "{}/studiohemisphere".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_path, prim_type="Xform", select_new_prim=False, attributes={} ) hemisphere_prim = stage.GetPrimAtPath(hemisphere_path) UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) Usd.ModelAPI(hemisphere_prim).SetKind("group") # create sphere hemisphere_sphere_path = omni.usd.get_stage_next_free_path( stage, "{}/studiohemisphere/Sphere".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_sphere_path, prim_type="Sphere", select_new_prim=False, attributes={UsdGeom.Tokens.radius: 100}, ) hemisphere_prim = stage.GetPrimAtPath(hemisphere_sphere_path) Usd.ModelAPI(hemisphere_prim).SetKind("assembly") # set transform hemisphere_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(2500, 2500, 2500)) hemisphere_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=hemisphere_sphere_path, material_path=mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create floor hemisphere_floor_path = omni.usd.get_stage_next_free_path( stage, "{}/studiohemisphere/Floor".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_floor_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100}, ) hemisphere_floor_prim = stage.GetPrimAtPath(hemisphere_floor_path) # set transform hemisphere_floor_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(2500, 0.1, 2500) ) hemisphere_floor_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) UsdGeom.PrimvarsAPI(hemisphere_floor_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=hemisphere_floor_path, material_path=mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create LightPivot_01 light_pivot1_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_01".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot1_prim = stage.GetPrimAtPath(light_pivot1_path) UsdGeom.PrimvarsAPI(light_pivot1_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot1_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot1_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(-30.453436397207547, 16.954190666353664, 9.728788165428536) ) light_pivot1_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0.9999999445969171, 1.000000574567198, 0.9999995086845976) ) light_pivot1_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight light_pivot1_al_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_al_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot1_al_prim = stage.GetPrimAtPath(light_pivot1_al_path) UsdGeom.PrimvarsAPI(light_pivot1_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot1_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 800) ) light_pivot1_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot1_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(4.5, 4.5, 4.5) ) light_pivot1_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight RectLight light_pivot1_alrl_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/RectLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_alrl_path, prim_type="RectLight", select_new_prim=False, attributes={}, ) light_pivot1_alrl_prim = stage.GetPrimAtPath(light_pivot1_alrl_path) # set values # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 # https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4 if hasattr(UsdLux.Tokens, 'inputsIntensity'): light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(15000) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) else: light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(15000) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) # create AreaLight Backside backside_albs_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/Backside".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_albs_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_albs_prim = stage.GetPrimAtPath(backside_albs_path) # set values backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1)) backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_albs_path, material_path=backside_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create AreaLight EmissiveSurface backside_ales_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/EmissiveSurface".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_ales_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_ales_prim = stage.GetPrimAtPath(backside_ales_path) # set values backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 0.002) ) backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_ales_path, material_path=emissive_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create LightPivot_02 light_pivot2_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_02".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot2_prim = stage.GetPrimAtPath(light_pivot2_path) UsdGeom.PrimvarsAPI(light_pivot2_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot2_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot2_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(-149.8694695859529, 35.87684189578612, -18.78499937937383) ) light_pivot2_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0.9999999347425043, 0.9999995656418647, 1.0000001493100235) ) light_pivot2_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight light_pivot2_al_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_al_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot2_al_prim = stage.GetPrimAtPath(light_pivot2_al_path) UsdGeom.PrimvarsAPI(light_pivot2_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot2_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 800) ) light_pivot2_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot2_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(1.5, 1.5, 1.5) ) light_pivot2_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight RectLight light_pivot2_alrl_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/RectLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_alrl_path, prim_type="RectLight", select_new_prim=False, attributes={}, ) light_pivot2_alrl_prim = stage.GetPrimAtPath(light_pivot2_alrl_path) # set values # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 # https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4 if hasattr(UsdLux.Tokens, 'inputsIntensity'): light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(55000) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) else: light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(55000) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) # create AreaLight Backside backside_albs_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/Backside".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_albs_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_albs_prim = stage.GetPrimAtPath(backside_albs_path) # set values backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1)) backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_albs_path, material_path=backside_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create AreaLight EmissiveSurface backside_ales_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/EmissiveSurface".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_ales_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_ales_prim = stage.GetPrimAtPath(backside_ales_path) # set values backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 0.002) ) backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_ales_path, material_path=emissive_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, )
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/__init__.py
from .test_commands import * from .create_prims import *
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/test_commands.py
import random import omni.kit.test import omni.kit.commands import omni.kit.undo from pxr import Usd, UsdGeom, Kind class TestCommands(omni.kit.test.AsyncTestCase): def check_visibillity(self, visible_set, invisible_set): context = omni.usd.get_context() stage = context.get_stage() for prim in stage.TraverseAll(): if prim and not prim.GetMetadata("hide_in_stage_window"): if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: continue imageable = UsdGeom.Imageable(prim) if imageable: if imageable.ComputeVisibility() == UsdGeom.Tokens.invisible: self.assertTrue((prim.GetPath().pathString in invisible_set)) else: self.assertTrue((prim.GetPath().pathString in visible_set)) def get_parent_prims(self, prim): stage = omni.usd.get_context().get_stage() parent_prims = [] while prim.GetParent(): parent_prims.append(prim.GetParent().GetPath().pathString) prim = prim.GetParent() if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: break return parent_prims def get_all_children(self, prim, child_list): for child in prim.GetAllChildren(): child_list.append(child.GetPath().pathString) self.get_all_children(child, child_list) def get_all_prims(self): all_prims = [] stage = omni.usd.get_context().get_stage() for prim in stage.TraverseAll(): if not prim.GetMetadata("hide_in_stage_window"): all_prims.append(prim.GetPath().pathString) return all_prims async def setUp(self): # Disable logging for the time of tests to avoid spewing errors await omni.usd.get_context().new_stage_async() omni.kit.selection.tests.create_test_stage() async def tearDown(self): pass async def test_command_select_all(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_root_prims = [] all_prims = [] material_prims = [] cube_prims = [] sphere_prims = [] children_iterator = iter(stage.TraverseAll()) for prim in children_iterator: all_root_prims.append(prim.GetPath().pathString) children_iterator.PruneChildren() for prim in stage.TraverseAll(): if prim.GetMetadata("hide_in_stage_window"): continue all_prims.append(prim.GetPath().pathString) if prim.GetTypeName() == "Material": material_prims.append(prim.GetPath().pathString) if prim.GetTypeName() == "Cube": cube_prims.append(prim.GetPath().pathString) if prim.GetTypeName() == "Sphere": sphere_prims.append(prim.GetPath().pathString) subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) # SelectAllCommand Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll") self.assertListEqual(selection.get_selected_prim_paths(), all_root_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectAllCommand "Material" Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll", type="Material") self.assertListEqual(selection.get_selected_prim_paths(), material_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectAllCommand "Cube" Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll", type="Cube") self.assertListEqual(selection.get_selected_prim_paths(), cube_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectAllCommand "Sphere" Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll", type="Sphere") self.assertListEqual(selection.get_selected_prim_paths(), sphere_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectSimilarCommand: "Sphere" and "Cube" prim_paths = [sphere_prims[0], cube_prims[0]] selection.set_selected_prim_paths(prim_paths, True) omni.kit.commands.execute("SelectSimilar") all_prims = sphere_prims.copy() all_prims.extend(cube_prims) self.assertListEqual(selection.get_selected_prim_paths(), all_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), prim_paths) async def test_command_select_none(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = self.get_all_prims() subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) inverse_prims = [item for item in all_prims if item not in subset_prims] # SelectNoneCommand Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectNone") self.assertListEqual(selection.get_selected_prim_paths(), []) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_select_invert(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = [] for prim in stage.TraverseAll(): if not prim.GetMetadata("hide_in_stage_window") and stage.HasDefaultPrim() and not stage.GetDefaultPrim() == prim: all_prims.append(prim.GetPath().pathString) # if selected path as children and none of the children are selected, then all the children are selected.. subset_count = int(len(all_prims) >> 1) subset_prims = [] for prim_path in sorted(random.sample(all_prims, subset_count), reverse=True): prim = stage.GetPrimAtPath(prim_path) if prim: subset_prims.append(prim_path) child_list = [] self.get_all_children(prim, child_list) if not set(subset_prims).intersection(set(child_list)): subset_prims += child_list # SelectInvertCommand Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectInvert") self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_hide_unselected(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = self.get_all_prims() # if selected path as children and none of the children are selected, then all the children are selected.. subset_prims = set() for prim_path in sorted(random.sample(all_prims, 3), reverse=True): # we need to remove "/World" from the sampled result since it is the parent of all prims if prim_path == '/World': continue prim = stage.GetPrimAtPath(prim_path) if prim: subset_prims.add(prim_path) child_list = [] self.get_all_children(prim, child_list) subset_prims.update(child_list) # HideUnselectedCommand Execute and undo visible_prims = set() for prim_path in subset_prims: prim = stage.GetPrimAtPath(prim_path) if prim: visible_prims.add(prim.GetPath().pathString) visible_prims.update(self.get_parent_prims(prim)) invisible_prims = set([item for item in all_prims if item not in visible_prims]) selection.set_selected_prim_paths(list(subset_prims), True) omni.kit.commands.execute("HideUnselected") self.check_visibillity(visible_prims, invisible_prims) omni.kit.undo.undo() self.check_visibillity(all_prims, []) async def test_command_select_parent(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = self.get_all_prims() subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) parent_prims = set() for prim_path in subset_prims: prim = stage.GetPrimAtPath(prim_path) if prim and prim.GetParent() is not None: parent_prims.add(prim.GetParent().GetPath().pathString) parent_prims = list(parent_prims) selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectParent") self.assertListEqual(selection.get_selected_prim_paths(), sorted(parent_prims)) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_select_kind(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = [] group_prims = [] for prim in stage.TraverseAll(): if Kind.Registry.IsA(Usd.ModelAPI(prim).GetKind(), "group"): group_prims.append(prim.GetPath().pathString) if not prim.GetMetadata("hide_in_stage_window"): all_prims.append(prim.GetPath().pathString) subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectKind", kind="group") self.assertListEqual(selection.get_selected_prim_paths(), sorted(group_prims)) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_select_hierarchy(self): context = omni.usd.get_context() selection = context.get_selection() selection.set_selected_prim_paths(['/World'], True) omni.kit.commands.execute("SelectHierarchy") self.assertListEqual(selection.get_selected_prim_paths(), sorted(self.get_all_prims())) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) async def test_command_select_list(self): context = omni.usd.get_context() selection = context.get_selection() all_prims = self.get_all_prims() subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) selection.set_selected_prim_paths(['/World'], True) self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) # with no kwargs it should clear the selection omni.kit.commands.execute("SelectList") self.assertListEqual(selection.get_selected_prim_paths(), []) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) # with kwarg it should swap the selection to the new list omni.kit.commands.execute("SelectList", selection=subset_prims) self.assertListEqual(sorted(selection.get_selected_prim_paths()), sorted(subset_prims)) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) async def test_command_select_leaf(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() selection.set_selected_prim_paths(['/World'], True) omni.kit.commands.execute("SelectLeaf") selected = selection.get_selected_prim_paths() for leaf in selected: self.assertFalse(stage.GetPrimAtPath(leaf).GetChildren()) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
omniverse-code/kit/exts/omni.kit.selection/docs/index.rst
omni.kit.selection ########################### Commands for selection of prims
omniverse-code/kit/exts/omni.mdl.distill_and_bake/docs/index.rst
omni.mdl.distill_and_bake ########################### .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.kit.widget.toolbar/PACKAGE-LICENSES/omni.kit.widget.toolbar-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.toolbar/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.4.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI description = "Extension to create toolbar widget. It also comes with builtin tools for transform manipulation and animation playing." title = "Toolbar Widget Extension" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Internal" # Keywords for the extension keywords = ["kit", "toolbar", "widget"] # Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content # of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.actions.core" = {} "omni.kit.commands" = {} "omni.kit.context_menu" = {} "omni.kit.menu.utils" = {} "omni.timeline" = {} "omni.ui" = {} "omni.usd" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.kit.widget.toolbar" [[test]] args = [ "--/app/window/width=480", "--/app/window/height=480", "--/app/renderer/resolution/width=480", "--/app/renderer/resolution/height=480", "--/app/window/scaleToMonitor=false", "--no-window", ] dependencies = [ "omni.kit.uiapp", "omni.kit.renderer.capture", ] stdoutFailPatterns.exclude = [ "*Failed to acquire interface*while unloading all plugins*", ] [settings] exts."omni.kit.widget.toolbar".Grab.enabled = true exts."omni.kit.widget.toolbar".legacySnapButton.enabled = true exts."omni.kit.widget.toolbar".PlayButton.enabled = true exts."omni.kit.widget.toolbar".SelectionButton.enabled = true exts."omni.kit.widget.toolbar".SelectionButton.SelectMode.enabled = true exts."omni.kit.widget.toolbar".TransformButton.enabled = true
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/simple_tool_button.py
# 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. # import omni.ui import weakref from .hotkey import Hotkey from .widget_group import WidgetGroup class SimpleToolButton(WidgetGroup): """ A helper class to create simple WidgetGroup that contains only one ToolButton. Args: name: Name of the ToolButton. tooltip: Tooltip of the ToolButton. icon_path: The icon to be used when button is not checked. icon_checked_path: The icon to be used when button is checked. hotkey: HotKey to toggle the button (optional). toggled_fn: Callback function when button is toggled. Signature: on_toggled(checked) (optional). model: Model for the ToolButton (optional). additional_style: Additional styling to apply to the ToolButton (optional). """ def __init__( self, name, tooltip, icon_path, icon_checked_path, hotkey=None, toggled_fn=None, model=None, additional_style=None, ): super().__init__() self._name = name self._tooltip = tooltip self._icon_path = icon_path self._icon_checked_path = icon_checked_path self._hotkey = hotkey self._toggled_fn = toggled_fn self._model = model self._additional_style = additional_style self._hotkey = None if hotkey: def on_hotkey_changed(hotkey: str): self._tool_button.tooltip = f"{self._tooltip} ({hotkey})" self._select_hotkey = Hotkey( f"{name}::hotkey", hotkey, lambda: self._on_hotkey(), lambda: self._tool_button.enabled and self._is_in_context(), on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey), ) def clean(self): super().clean() self._value_sub = None self._tool_button = None if self._select_hotkey: self._select_hotkey.clean() self._select_hotkey = None def get_style(self): style = { f"Button.Image::{self._name}": {"image_url": self._icon_path}, f"Button.Image::{self._name}:checked": {"image_url": self._icon_checked_path}, } if self._additional_style: style.update(self._additional_style) return style def create(self, default_size): def on_value_changed(model, widget): widget = widget() if widget is not None: if model.get_value_as_bool(): self._acquire_toolbar_context() else: self._release_toolbar_context() widget._toggled_fn(model.get_value_as_bool()) self._tool_button = omni.ui.ToolButton( name=self._name, model=self._model, tooltip=self._tooltip, width=default_size, height=default_size ) if self._toggled_fn is not None: self._value_sub = self._tool_button.model.subscribe_value_changed_fn( lambda model, widget=weakref.ref(self): on_value_changed(model, widget) ) # return a dictionary of name -> widget if you want to expose it to other widget_group return {self._name: self._tool_button} def get_tool_button(self): return self._tool_button def _on_hotkey(self): self._tool_button.model.set_value(not self._tool_button.model.get_value_as_bool())
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/widget_group.py
# 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. # import asyncio from abc import abstractmethod import omni.kit.widget.toolbar import omni.kit.app import omni.ui as ui from .context_menu import ContextMenuEvent class WidgetGroup: """ Base class to create a group of widgets on Toolbar """ def __init__(self): self._context = "" self._context_token = None self._show_menu_task = None self._toolbar_ext_path = ( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar") ) @abstractmethod def clean(self): """ Clean up function to be called before destorying the object. """ if self._context_token: self._release_toolbar_context() self._context_token = None self._context = "" if self._show_menu_task: # pragma: no cover self._show_menu_task.cancel() self._show_menu_task = None @abstractmethod def get_style(self) -> dict: """ Gets the style of all widgets defined in this Widgets group. """ pass # pragma: no cover (Abstract) @abstractmethod def create(self, default_size): """ Main function to creates widget. If you want to export widgets and allow external code to fetch and manipulate them, return a Dict[str, Widget] mapping from name to instance at the end of the function. """ pass # pragma: no cover (Abstract) def on_toolbar_context_changed(self, context: str): """ Called when toolbar's effective context has changed. Args: context: new toolbar context. """ pass def on_added(self, context): """ Called when widget is added to toolbar when calling Toolbar.add_widget Args: context: the context used to add widget when calling Toolbar.add_widget. """ self._context = context def on_removed(self): """ Called when widget is removed from toolbar when calling Toolbar.remove_widget """ pass def _acquire_toolbar_context(self): """ Request toolbar to switch to current widget's context. """ self._context_token = omni.kit.widget.toolbar.get_instance().acquire_toolbar_context(self._context) def _release_toolbar_context(self): """ Release the ownership of toolbar context and reset to default. If the ownership was preemptively taken by other owner, release does nothing. """ omni.kit.widget.toolbar.get_instance().release_toolbar_context(self._context_token) def _is_in_context(self): """ Checks if the Toolbar is in default context or owned by current widget's context. Override this function if you want to customize the behavior. Returns: True if toolbar is either in default context or owned by current widget. False otherwise. """ toolbar_context = omni.kit.widget.toolbar.get_instance().get_context() return toolbar_context == omni.kit.widget.toolbar.Toolbar.DEFAULT_CONTEXT or self._context == toolbar_context def _invoke_context_menu(self, button_id: str, min_menu_entries: int = 1): """ Function to invoke context menu. Args: button_id: button_id of the context menu to be invoked. min_menu_entries: minimal number of menu entries required for menu to be visible (default 1). """ event = ContextMenuEvent() event.payload["widget_name"] = button_id event.payload["min_menu_entries"] = min_menu_entries omni.kit.widget.toolbar.get_instance().context_menu.on_mouse_event(event) def _on_mouse_pressed(self, button, button_id: str, min_menu_entries: int = 2): """ Function to handle flyout menu. Either with LMB long press or RMB click. Args: button_id: button_id of the context menu to be invoked. min_menu_entries: minimal number of menu entries required for menu to be visible (default 1). """ self._acquire_toolbar_context() if button == 1: # Right click, show immediately self._invoke_context_menu(button_id, min_menu_entries) elif button == 0: # Schedule a task if hold LMB long enough self._show_menu_task = asyncio.ensure_future(self._schedule_show_menu(button_id)) def _on_mouse_released(self, button): if button == 0: if self._show_menu_task: self._show_menu_task.cancel() async def _schedule_show_menu(self, button_id: str, min_menu_entries: int = 2): await asyncio.sleep(0.3) self._invoke_context_menu(button_id, min_menu_entries) self._show_menu_task = None def _build_flyout_indicator( self, width, height, index: str, extension_id: str = "omni.kit.widget.toolbar", padding=7, min_menu_count=2 ): import carb import omni.kit.context_menu indicator_size = 3 with ui.Placer(offset_x=width - indicator_size - padding, offset_y=height - indicator_size - padding): indicator = ui.Image( f"{self._toolbar_ext_path}/data/icon/flyout_indicator_dark.svg", width=indicator_size, height=indicator_size, ) def on_menu_changed(evt: carb.events.IEvent): try: menu_list = omni.kit.context_menu.get_menu_dict(index, extension_id) # because we moved separated the widget from the window extension, we need to still grab the menu from # the window extension menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(index, "omni.kit.window.toolbar") if menu_list_backward_compatible and evt.payload.get("extension_id", None) == "omni.kit.window.toolbar": # pragma: no cover omni.kit.app.log_deprecation( 'Adding menu using "add_menu(menu, index, "omni.kit.window.toolbar")" is deprecated. ' 'Please use "add_menu(menu, index, "omni.kit.widget.toolbar")"' ) # TODO check the actual menu entry visibility with show_fn indicator.visible = len(menu_list + menu_list_backward_compatible) >= min_menu_count except AttributeError as exc: # pragma: no cover carb.log_warn(f"on_menu_changed error {exc}") # Check initial state on_menu_changed(None) event_stream = omni.kit.context_menu.get_menu_event_stream() return event_stream.create_subscription_to_pop(on_menu_changed)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/commands.py
# 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. # import omni.timeline import omni.kit.commands class ToolbarPlayButtonClickedCommand(omni.kit.commands.Command): """ On clicked toolbar play button **Command**. """ def do(self): omni.timeline.get_timeline_interface().play() class ToolbarPauseButtonClickedCommand(omni.kit.commands.Command): """ On clicked toolbar pause button **Command**. """ def do(self): omni.timeline.get_timeline_interface().pause() class ToolbarStopButtonClickedCommand(omni.kit.commands.Command): """ On clicked toolbar stop button **Command**. """ def do(self): omni.timeline.get_timeline_interface().stop() class ToolbarPlayFilterCheckedCommand(omni.kit.commands.Command): """ Change settings depending on the status of play filter checkboxes **Command**. Args: path: Path to the setting to change. enabled: New value to change to. """ def __init__(self, setting_path, enabled): self._setting_path = setting_path self._enabled = enabled def do(self): omni.kit.commands.execute("ChangeSetting", path=self._setting_path, value=self._enabled) def undo(self): pass # pragma: no cover class ToolbarPlayFilterSelectAllCommand(omni.kit.commands.Command): # pragma: no cover """ Sets all play filter settings to True **Command**. Args: settings: Paths to the settings. """ def __init__(self, settings): self._settings = settings def do(self): for setting in self._settings: omni.kit.commands.execute("ChangeSetting", path=setting, value=True) def undo(self): pass omni.kit.commands.register_all_commands_in_module(__name__)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/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 import omni.ext from functools import lru_cache from pathlib import Path from .toolbar import Toolbar _toolbar_instance = None @lru_cache() def get_data_path() -> Path: manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path_by_module("omni.kit.widget.toolbar") return Path(extension_path).joinpath("data") def get_instance(): return _toolbar_instance class WidgetToolBarExtension(omni.ext.IExt): """omni.kit.widget.toolbar ext""" def on_startup(self, ext_id): global _toolbar_instance carb.log_info("[omni.kit.widget.toolbar] Startup") _toolbar_instance = Toolbar() def on_shutdown(self): carb.log_info("[omni.kit.widget.toolbar] Shutdown") global _toolbar_instance if _toolbar_instance: _toolbar_instance.destroy() _toolbar_instance = None
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/__init__.py
from .extension import * from .toolbar import * from omni.kit.widget.toolbar.simple_tool_button import * # backward compatible from .widget_group import * # backward compatible
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/context_menu.py
# 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. # import carb import omni.kit.context_menu from omni import ui class ContextMenuEvent: """The object comatible with ContextMenu""" def __init__(self): self.type = 0 self.payload = {} class ContextMenu: def on_mouse_event(self, event): # check its expected event if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): # pragma: no cover return # get context menu core functionality & check its enabled context_menu = omni.kit.context_menu.get_instance() if context_menu is None: # pragma: no cover carb.log_error("context_menu is disabled!") return # setup objects, this is passed to all functions objects = {} objects.update(event.payload) widget_name = objects.get("widget_name", None) menu_list = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.widget.toolbar") # because we moved separated the widget from the window extension, we need to still grab the menu from # the window extension menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.window.toolbar") for menu_list_backward in menu_list_backward_compatible: # pragma: no cover if menu_list_backward not in menu_list: menu_list.append(menu_list_backward) # For some tool buttons, the context menu only shows if additional (>1) menu entries are added. min_menu_entries = event.payload.get("min_menu_entries", 0) # show menu context_menu.show_context_menu("toolbar", objects, menu_list, min_menu_entries, delegate=ui.MenuDelegate())
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/toolbar.py
# 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. # import asyncio import carb import carb.settings import omni.kit.app import omni.ui as ui import omni.usd from omni.ui import color as cl from typing import Callable from .builtin_tools.builtin_tools import BuiltinTools from .commands import * from .context_menu import * from .widget_group import WidgetGroup # backward compatible import typing if typing.TYPE_CHECKING: # pragma: no cover import weakref GRAB_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/Grab/enabled" # 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 Toolbar: WINDOW_NAME = "Main ToolBar" DEFAULT_CONTEXT = "" DEFAULT_CONTEXT_TOKEN = 0 DEFAULT_SIZE = 38 # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def __init__(self): self._settings = carb.settings.get_settings() self.__root_frame = None self._toolbar_widget_groups = [] self._toolbar_widgets = {} self._toolbar_dirty = False self._axis = ui.ToolBarAxis.X self._rebuild_task = None self._grab_stack = None self._context_menu = ContextMenu() self._context_token_pool = 1 self._context = Toolbar.DEFAULT_CONTEXT self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN self._context_token_owner_count = 0 self.__init_shades() self._builtin_tools = BuiltinTools(self) def __init_shades(self): """Style colors""" cl.toolbar_button_background = cl.shade(0x0) cl.toolbar_button_background_checked = cl.shade(0xFF1F2123) cl.toolbar_button_background_pressed = cl.shade(0xFF4B4B4B) cl.toolbar_button_background_hovered = cl.shade(0xFF383838) @property def context_menu(self): return self._context_menu def destroy(self): if self._rebuild_task is not None: # pragma: no cover self._rebuild_task.cancel() self._toolbar_widgets = {} if self._builtin_tools: self._builtin_tools.destroy() self._builtin_tools = None self._toolbar_widget_groups = [] def add_widget(self, widget_group: "WidgetGroup", priority: int, context: str = ""): self._toolbar_widget_groups.append((priority, widget_group)) widget_group.on_added(context) self._set_toolbar_dirty() def remove_widget(self, widget_group: "WidgetGroup"): for widget in self._toolbar_widget_groups: if widget[1] == widget_group: self._toolbar_widget_groups.remove(widget) widget_group.on_removed() self._set_toolbar_dirty() break def get_widget(self, name: str): return self._toolbar_widgets.get(name, None) def acquire_toolbar_context(self, context: str): """ Request toolbar to switch to given context. It takes the context preemptively even if previous context owner has not release the context. Args: context (str): Context to switch to. Returns: A token to be used to release_toolbar_context """ if self._context == context: self._context_token_owner_count += 1 return self._context_token # preemptively take current context, regardless of previous owner/count self._context = context if context == Toolbar.DEFAULT_CONTEXT: self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN else: self._context_token_pool += 1 self._context_token = self._context_token_pool self._context_token_owner_count = 1 for widget in self._toolbar_widget_groups: widget[1].on_toolbar_context_changed(context) return self._context_token def release_toolbar_context(self, token: int): """ Request toolbar to release context associated with token. If token is expired (already released or context ownership taken by others), this function does nothing. Args: token (int): Context token to release. """ if token == self._context_token: self._context_token_owner_count -= 1 else: carb.log_info("Releasing expired context token, ignoring") return if self._context_token_owner_count <= 0: self._context = Toolbar.DEFAULT_CONTEXT self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN self._context_token_owner_count = 0 for widget in self._toolbar_widget_groups: widget[1].on_toolbar_context_changed(self._context) def get_context(self): return self._context def _set_toolbar_dirty(self): self._toolbar_dirty = True if self._rebuild_task is None: self._rebuild_task = asyncio.ensure_future(self._delayed_rebuild()) def set_axis(self, axis): self._axis = axis # delay rebuild so widgets added within one frame are rebuilt together @omni.usd.handle_exception async def _delayed_rebuild(self): await omni.kit.app.get_app().next_update_async() if self._toolbar_dirty: self.rebuild_toolbar() self._toolbar_dirty = False self._rebuild_task = None def rebuild_toolbar(self, root_frame=None): if root_frame: self.__root_frame = root_frame if not self.__root_frame: carb.log_warn("No root frame specified. Please specify a root frame for this widget") return axis = self._axis self._toolbar_widgets = {} self._toolbar_widget_groups.sort(key=lambda x: x[0]) # sort by priority with self.__root_frame: stack = None style = { "Button": {"background_color": cl.toolbar_button_background, "border_radius": 4, "margin": 2, "padding": 3}, "Button:checked": {"background_color": cl.toolbar_button_background_checked}, "Button:pressed": {"background_color": cl.toolbar_button_background_pressed}, "Button:hovered": {"background_color": cl.toolbar_button_background_hovered}, "Button.Image::disabled": {"color": 0x608A8777}, "Line::grab": {"color": 0xFF2E2E2E, "border_width": 2, "margin": 2}, "Line::separator": {"color": 0xFF555555}, "Tooltip": { "background_color": 0xFFC7F5FC, "color": 0xFF4B493B, "border_width": 1, "margin_width": 2, "margin_height": 1, "padding": 1, }, } for widget in self._toolbar_widget_groups: style.update(widget[1].get_style()) default_size = self.DEFAULT_SIZE if axis == ui.ToolBarAxis.X: stack = ui.HStack(style=style, height=default_size, width=ui.Percent(100)) else: stack = ui.VStack(style=style, height=ui.Percent(100), width=default_size) with stack: if self._settings.get(GRAB_ENABLED_SETTING_PATH): self._create_grab(axis) ui.Spacer(width=3, height=3) last_priority = None for widget in self._toolbar_widget_groups: this_priority = widget[0] if last_priority is not None and this_priority - last_priority >= 10: self._create_separator(axis) public_widgets = widget[1].create(default_size=default_size) if public_widgets is not None: self._toolbar_widgets.update(public_widgets) last_priority = this_priority def _create_separator(self, axis): if axis == ui.ToolBarAxis.X: ui.Line(width=1, name="separator", alignment=ui.Alignment.LEFT) else: ui.Line(height=1, name="separator", alignment=ui.Alignment.TOP) def subscribe_grab_mouse_pressed(self, function: Callable[[int, "weakref.ref"], None]): if self._grab_stack: self._grab_stack.set_mouse_pressed_fn(function) def _create_grab(self, axis): grab_area_size = 20 if axis == ui.ToolBarAxis.X: self._grab_stack = ui.HStack(width=grab_area_size) else: self._grab_stack = ui.VStack(height=grab_area_size) with self._grab_stack: if axis == ui.ToolBarAxis.X: ui.Spacer(width=5) ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT) ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT) ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT) ui.Spacer(width=3) else: ui.Spacer(height=5) ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP) ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP) ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP) ui.Spacer(height=3) def add_custom_select_type(self, entry_name: str, selection_types: list): self._builtin_tools.add_custom_select_type(entry_name, selection_types) def remove_custom_select(self, entry_name): self._builtin_tools.remove_custom_select(entry_name)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/hotkey.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from __future__ import annotations from typing import Callable import carb.events import carb.input import omni.appwindow import omni.kit.actions.core import omni.kit.app class Hotkey: def __init__( self, action_name: str, hotkey: carb.input.KeyboardInput, on_action_fn: Callable[[], None], hotkey_enabled_fn: Callable[[], None], modifiers: int = 0, on_hotkey_changed_fn: Callable[[str], None] = None, ): self._action_registry = omni.kit.actions.core.get_action_registry() self._settings = carb.settings.get_settings() self._action_name = action_name self._hotkey = hotkey self._modifiers = modifiers self._on_hotkey_changed_fn = on_hotkey_changed_fn self._registered_hotkey = None self._manager = omni.kit.app.get_app().get_extension_manager() self._extension_name = omni.ext.get_extension_name(self._manager.get_extension_id_by_module(__name__)) def action_trigger(): if not hotkey_enabled_fn(): return if on_action_fn: on_action_fn() # Register a test action that invokes a Python function. self._action = self._action_registry.register_action( self._extension_name, action_name, lambda *_: action_trigger(), display_name=action_name, tag="Toolbar", ) self._hooks = self._manager.subscribe_to_extension_enable( lambda _: self._register_hotkey(), lambda _: self._unregister_hotkey(), ext_name="omni.kit.hotkeys.core", hook_name=f"toolbar hotkey {action_name} listener", ) def clean(self): self._unregister_hotkey() self._action_registry.deregister_action(self._action) self._hooks = None self._on_hotkey_changed_fn = None def get_as_string(self, default:str): if self._registered_hotkey: return self._registered_hotkey.key_text return default def _on_hotkey_changed(self, event: carb.events.IEvent): from omni.kit.hotkeys.core import KeyCombination if ( event.payload["hotkey_ext_id"] == self._extension_name and event.payload["action_ext_id"] == self._extension_name and event.payload["action_id"] == self._action_name ): new_key = event.payload["key"] # refresh _registered_hotkey with newly registered key? hotkey_combo = KeyCombination(new_key) self._registered_hotkey = self._hotkey_registry.get_hotkey(self._extension_name, hotkey_combo) if self._on_hotkey_changed_fn: self._on_hotkey_changed_fn(new_key) def _register_hotkey(self): try: from omni.kit.hotkeys.core import HOTKEY_CHANGED_EVENT, KeyCombination, get_hotkey_registry self._hotkey_registry = get_hotkey_registry() hotkey_combo = KeyCombination(self._hotkey, self._modifiers) self._registered_hotkey = self._hotkey_registry.register_hotkey( self._extension_name, hotkey_combo, self._extension_name, self._action_name ) event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._change_event_sub = event_stream.create_subscription_to_pop_by_type( HOTKEY_CHANGED_EVENT, self._on_hotkey_changed ) except ImportError: # pragma: no cover pass def _unregister_hotkey(self): if not self._registered_hotkey or not self._hotkey_registry: return try: self._hotkey_registry.deregister_hotkey(self._registered_hotkey) self._registered_hotkey = None self._change_event_sub = None except Exception: # pragma: no cover pass
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/play_button_group.py
# 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. # import carb.dictionary import carb.settings import omni.timeline import omni.ui as ui from carb.input import KeyboardInput as Key from omni.kit.commands import execute from omni.kit.widget.toolbar.hotkey import Hotkey from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.timeline_model import TimelinePlayPauseModel PLAY_TOOL_NAME = "Play" PAUSE_TOOL_NAME = "Pause" class PlayButtonGroup(WidgetGroup): PLAY_ANIMATIONS_SETTING = "/app/player/playAnimations" PLAY_AUDIO_SETTING = "/app/player/audio/enabled" PLAY_SIMULATIONS_SETTING = "/app/player/playSimulations" PLAY_COMPUTEGRAPH_SETTING = "/app/player/playComputegraph" all_settings_paths = [ PLAY_ANIMATIONS_SETTING, PLAY_AUDIO_SETTING, PLAY_SIMULATIONS_SETTING, PLAY_COMPUTEGRAPH_SETTING, ] def __init__(self): super().__init__() self._play_button = None self._play_hotkey = None self._stop_button = None self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._timeline_play_pause_model = TimelinePlayPauseModel() self._timeline = omni.timeline.get_timeline_interface() self._settings.set_default_bool(self.PLAY_ANIMATIONS_SETTING, True) self._settings.set_default_bool(self.PLAY_AUDIO_SETTING, True) self._settings.set_default_bool(self.PLAY_SIMULATIONS_SETTING, True) self._settings.set_default_bool(self.PLAY_COMPUTEGRAPH_SETTING, True) stream = self._timeline.get_timeline_event_stream() self._sub = stream.create_subscription_to_pop(self._on_timeline_event) self._register_context_menu() self._show_menu_task = None self._visible = True def clean(self): super().clean() self._sub = None if self._timeline_play_pause_model: self._timeline_play_pause_model.clean() self._timeline_play_pause_model = None self._play_button = None self._stop_button = None self._animations_menu = None self._audio_menu = None self._simulations_menu = None self._compute_graph_menu = None self._play_filter_menu = None self._filter_menu = None self._sep_menu = None self._sep_menu2 = None self._select_all_menu = None if self._show_menu_task: # pragma: no cover self._show_menu_task.cancel() self._show_menu_task = None if self._play_hotkey: self._play_hotkey.clean() self._play_hotkey = None self._visible = True def get_style(self): style = { "Button.Image::play": {"image_url": "${glyphs}/toolbar_play.svg"}, "Button.Image::play:checked": {"image_url": "${glyphs}/toolbar_pause.svg"}, "Button.Image::stop": {"image_url": "${glyphs}/toolbar_stop.svg"}, } return style def create(self, default_size): # Build Play button self._play_button = ui.ToolButton( model=self._timeline_play_pause_model, name="play", tooltip=f"{PLAY_TOOL_NAME} ('Space')", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "play"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), checked=self._timeline_play_pause_model.get_value_as_bool(), ) def on_play_hotkey_changed(hotkey: str): if self._play_button: self._play_button.tooltip = f"{PLAY_TOOL_NAME} ({hotkey})" # Assign Play button Hotkey self._play_hotkey = Hotkey( "toolbar::play", Key.SPACE, lambda: self._timeline_play_pause_model.set_value(not self._timeline_play_pause_model.get_value_as_bool()), lambda: self._play_button is not None and self._play_button.enabled and self._is_in_context(), on_hotkey_changed_fn=lambda hotkey: on_play_hotkey_changed(hotkey), ) self._visible = True def on_stop_clicked(*_): self._acquire_toolbar_context() execute("ToolbarStopButtonClicked") self._stop_button = ui.Button( name="stop", tooltip="Stop", width=default_size, height=default_size, visible=False, clicked_fn=on_stop_clicked, ) return {"play": self._play_button, "stop": self._stop_button} def _on_setting_changed(self, item, event_type, menu_item): # pragma: no cover menu_item.checked = self._dict.get(item) def _on_timeline_event(self, e): if e.type == int(omni.timeline.TimelineEventType.PLAY): if self._play_button: self._play_button.set_tooltip(f"{PAUSE_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})") if self._stop_button: self._stop_button.visible = self._visible if e.type == int(omni.timeline.TimelineEventType.PAUSE): if self._play_button: self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})") if e.type == int(omni.timeline.TimelineEventType.STOP): if self._stop_button: self._stop_button.visible = False if self._play_button: self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})") if hasattr(omni.timeline.TimelineEventType, 'DIRECTOR_CHANGED') and\ e.type == int(omni.timeline.TimelineEventType.DIRECTOR_CHANGED): # pragma: no cover self._visible = not e.payload['hasDirector'] if self._stop_button: self._stop_button.visible = self._visible if self._play_button: self._play_button.visible = self._visible def _on_filter_changed(self, filter_setting, enabled): # pragma: no cover execute("ToolbarPlayFilterChecked", setting_path=filter_setting, enabled=enabled) def _select_all(self): # pragma: no cover execute("ToolbarPlayFilterSelectAll", settings=self.all_settings_paths) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name def create_menu_entry(name, setting_path): menu = { "name": name, "show_fn": [lambda object: is_button(object, "play")], "onclick_fn": lambda object: self._on_filter_changed( setting_path, not self._settings.get(setting_path) ), "checked_fn": lambda object: self._settings.get(setting_path), } return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar") def create_seperator(name=""): menu = { "name": name, "show_fn": [lambda object: is_button(object, "play")], } return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar") if context_menu: menu = { "name": "Filter", "show_fn": [lambda object: is_button(object, "play")], "enabled_fn": lambda object: False, } self._filter_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar") self._sep_menu = create_seperator("sep/") self._animations_menu = create_menu_entry("Animation", self.PLAY_ANIMATIONS_SETTING) self._audio_menu = create_menu_entry("Audio", self.PLAY_AUDIO_SETTING) self._simulations_menu = create_menu_entry("Simulations", self.PLAY_SIMULATIONS_SETTING) self._compute_graph_menu = create_menu_entry("OmniGraph", self.PLAY_COMPUTEGRAPH_SETTING) self._sep_menu2 = create_seperator("sep2/") menu = { "name": "Select All", "show_fn": [lambda object: is_button(object, "play")], "onclick_fn": lambda object: self._select_all(), } self._select_all_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/builtin_tools.py
# 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. # import carb.dictionary import carb.settings from .select_button_group import SelectButtonGroup from .snap_button_group import LegacySnapButtonGroup from .transform_button_group import TransformButtonGroup from .play_button_group import PlayButtonGroup import typing if typing.TYPE_CHECKING: # pragma: no cover from ..toolbar import Toolbar SELECT_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/enabled" TRANSFORM_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/TransformButton/enabled" PLAY_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/PlayButton/enabled" LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW = "/exts/omni.kit.window.toolbar/legacySnapButton/enabled" LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET = "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled" class BuiltinTools: def __init__(self, toolbar: "Toolbar"): self._dict = carb.dictionary.get_dictionary() self._settings = carb.settings.get_settings() self._sub_window = self._settings.subscribe_to_node_change_events( LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, self._on_legacy_snap_setting_changed_window ) self._toolbar = toolbar self._select_button_group = None if self._settings.get(SELECT_BUTTON_ENABLED_SETTING_PATH): self._select_button_group = SelectButtonGroup() toolbar.add_widget(self._select_button_group, 0) self._transform_button_group = None if self._settings.get(TRANSFORM_BUTTON_ENABLED_SETTING_PATH): self._transform_button_group = TransformButtonGroup() toolbar.add_widget(self._transform_button_group, 1) self._snap_button_group = None if self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET): self._add_snap_button() self._play_button_group = None if self._settings.get(PLAY_BUTTON_ENABLED_SETTING_PATH): self._play_button_group = PlayButtonGroup() toolbar.add_widget(self._play_button_group, 21) self._sub_widget = self._settings.subscribe_to_node_change_events( LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, self._on_legacy_snap_setting_changed ) def destroy(self): if self._select_button_group: self._toolbar.remove_widget(self._select_button_group) self._select_button_group.clean() self._select_button_group = None if self._transform_button_group: self._toolbar.remove_widget(self._transform_button_group) self._transform_button_group.clean() self._transform_button_group = None if self._snap_button_group: self._remove_snap_button() if self._play_button_group: self._toolbar.remove_widget(self._play_button_group) self._play_button_group.clean() self._play_button_group = None if self._sub_window: self._settings.unsubscribe_to_change_events(self._sub_window) self._sub_window = None if self._sub_widget: self._settings.unsubscribe_to_change_events(self._sub_widget) self._sub_widget = None def __del__(self): self.destroy() def _add_snap_button(self): self._snap_button_group = LegacySnapButtonGroup() self._toolbar.add_widget(self._snap_button_group, 11) def _remove_snap_button(self): self._toolbar.remove_widget(self._snap_button_group) self._snap_button_group.clean() self._snap_button_group = None def _on_legacy_snap_setting_changed_window(self, *args, **kwargs): """ If the old setting is set, we forward it into the new settings. """ enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW) if enabled_legacy_snap is not None: carb.log_warn( 'Deprecated, please use "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled" setting' ) self._settings.set(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, enabled_legacy_snap) def _on_legacy_snap_setting_changed(self, *args, **kwargs): enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET) if self._snap_button_group is None and enabled_legacy_snap: self._add_snap_button() elif self._snap_button_group is not None and not enabled_legacy_snap: self._remove_snap_button() def add_custom_select_type(self, entry_name: str, selection_types: list): self._select_button_group.add_custom_select_type(entry_name, selection_types) def remove_custom_select(self, entry_name): self._select_button_group.remove_custom_select(entry_name)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/transform_button_group.py
# 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. # import carb.input import carb.dictionary import carb.settings import omni.kit.context_menu import omni.ui as ui from carb.input import KeyboardInput as Key from omni.kit.widget.toolbar.hotkey import Hotkey from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.transform_mode_model import LocalGlobalTransformModeModel, TransformModeModel MOVE_TOOL_NAME = "Move" ROTATE_TOOL_NAME = "Rotate" SCALE_TOOL_NAME = "Scale" class TransformButtonGroup(WidgetGroup): TRANSFORM_MOVE_MODE_SETTING = "/app/transform/moveMode" TRANSFORM_ROTATE_MODE_SETTING = "/app/transform/rotateMode" def __init__(self): super().__init__() self._input = carb.input.acquire_input_interface() self._settings = carb.settings.get_settings() self._settings.set_default_string(TransformModeModel.TRANSFORM_OP_SETTING, TransformModeModel.TRANSFORM_OP_MOVE) self._settings.set_default_string( self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ) self._settings.set_default_string( self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ) self._move_op_model = LocalGlobalTransformModeModel( op=TransformModeModel.TRANSFORM_OP_MOVE, op_space_setting_path=self.TRANSFORM_MOVE_MODE_SETTING ) self._rotate_op_model = LocalGlobalTransformModeModel( op=TransformModeModel.TRANSFORM_OP_ROTATE, op_space_setting_path=self.TRANSFORM_ROTATE_MODE_SETTING ) self._scale_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SCALE) def on_hotkey_changed(hotkey: str, button, tool_name: str): button.tooltip = f"{tool_name} ({hotkey})" self._move_hotkey = Hotkey( "toolbar::move", Key.W, lambda: self._move_op_model.set_value(not self._move_op_model.get_value_as_bool()), lambda: self._move_button.enabled and self._is_in_context() and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON) == 0, # when RMB is down, it's possible viewport WASD navigation is going on, and don't trigger it if W is pressed on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._move_button, MOVE_TOOL_NAME), ) self._rotate_hotkey = Hotkey( "toolbar::rotate", Key.E, lambda: self._rotate_op_model.set_value(not self._rotate_op_model.get_value_as_bool()), lambda: self._rotate_button.enabled and self._is_in_context() and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON) == 0, on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._rotate_button, ROTATE_TOOL_NAME), ) self._scale_hotkey = Hotkey( "toolbar::scale", Key.R, lambda: self._scale_op_model.set_value(True), lambda: self._scale_button.enabled and self._is_in_context(), on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._scale_button, SCALE_TOOL_NAME), ) self._register_context_menu() def get_style(self): style = { "Button.Image::move_op_global": {"image_url": "${glyphs}/toolbar_move_global.svg"}, "Button.Image::move_op_local": {"image_url": "${glyphs}/toolbar_move_local.svg"}, "Button.Image::rotate_op_global": {"image_url": "${glyphs}/toolbar_rotate_global.svg"}, "Button.Image::rotate_op_local": {"image_url": "${glyphs}/toolbar_rotate_local.svg"}, "Button.Image::scale_op": {"image_url": "${glyphs}/toolbar_scale.svg"}, } return style def create(self, default_size): self._sub_move, self._move_button = self._create_local_global_button( self._move_op_model, f"{MOVE_TOOL_NAME} ({self._move_hotkey.get_as_string('W')})", "move_op", self.TRANSFORM_MOVE_MODE_SETTING, "move_op_global", "move_op_local", default_size, ) self._sub_rotate, self._rotate_button = self._create_local_global_button( self._rotate_op_model, f"{ROTATE_TOOL_NAME} ({self._rotate_hotkey.get_as_string('E')})", "rotate_op", self.TRANSFORM_ROTATE_MODE_SETTING, "rotate_op_global", "rotate_op_local", default_size, ) self._scale_button = ui.ToolButton( model=self._scale_op_model, name="scale_op", tooltip=f"{SCALE_TOOL_NAME} ({self._scale_hotkey.get_as_string('R')})", width=default_size, height=default_size, mouse_pressed_fn=lambda *_: self._acquire_toolbar_context(), ) return {"move_op": self._move_button, "rotate_op": self._rotate_button, "scale_op": self._scale_button} def clean(self): super().clean() self._move_button = None self._rotate_button = None self._scale_button = None self._sub_move = None self._sub_rotate = None self._move_op_model.clean() self._move_op_model = None self._rotate_op_model.clean() self._rotate_op_model = None self._scale_op_model.clean() self._scale_op_model = None self._move_hotkey.clean() self._move_hotkey = None self._rotate_hotkey.clean() self._rotate_hotkey = None self._scale_hotkey.clean() self._scale_hotkey = None self._move_global_menu_entry = None self._move_local_menu_entry = None self._rotate_global_menu_entry = None self._rotate_local_menu_entry = None def _get_op_button_name(self, model, global_name, local_name): if model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL: return global_name else: # pragma: no cover return local_name def _create_local_global_button( self, op_model, tooltip, button_name, op_setting_path, global_name, local_name, default_size ): op_button = ui.ToolButton( name=self._get_op_button_name(op_model, global_name, local_name), model=op_model, tooltip=tooltip, width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, button_name), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), checked=op_model.get_value_as_bool(), ) def on_op_button_value_change(model): op_button.name = self._get_op_button_name(model, global_name, local_name) return op_model.subscribe_value_changed_fn(on_op_button_value_change), op_button def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name def on_mode(objects: dict, op_setting_path: str, desired_value): # pragma: no cover self._settings.set(op_setting_path, desired_value) def checked(objects: dict, op_setting_path: str, desired_value: str): # pragma: no cover return self._settings.get(op_setting_path) == desired_value if context_menu: menu = { "name": "Global (W)", "show_fn": [lambda object: is_button(object, "move_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), } self._move_global_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar") menu = { "name": "Local (W)", "show_fn": [lambda object: is_button(object, "move_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), } self._move_local_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar") menu = { "name": "Global (E)", "show_fn": [lambda object: is_button(object, "rotate_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), } self._rotate_global_menu_entry = omni.kit.context_menu.add_menu( menu, "rotate_op", "omni.kit.widget.toolbar" ) menu = { "name": "Local (E)", "show_fn": [lambda object: is_button(object, "rotate_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), } self._rotate_local_menu_entry = omni.kit.context_menu.add_menu(menu, "rotate_op", "omni.kit.widget.toolbar")
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/snap_button_group.py
# 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. # import carb.dictionary import carb.settings import omni.kit.context_menu import omni.ui as ui from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.setting_model import BoolSettingModel, FloatSettingModel class LegacySnapButtonGroup(WidgetGroup): SNAP_ENABLED_SETTING = "/app/viewport/snapEnabled" SNAP_MOVE_X_SETTING = "/persistent/app/viewport/stepMove/x" SNAP_MOVE_Y_SETTING = "/persistent/app/viewport/stepMove/y" SNAP_MOVE_Z_SETTING = "/persistent/app/viewport/stepMove/z" SNAP_ROTATE_SETTING = "/persistent/app/viewport/stepRotate" SNAP_SCALE_SETTING = "/persistent/app/viewport/stepScale" SNAP_TO_SURFACE_SETTING = "/persistent/app/viewport/snapToSurface" def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_bool(self.SNAP_ENABLED_SETTING, False) self._settings.set_default_float(self.SNAP_MOVE_X_SETTING, 50.0) self._settings.set_default_float(self.SNAP_MOVE_Y_SETTING, 50.0) self._settings.set_default_float(self.SNAP_MOVE_Z_SETTING, 50.0) self._settings.set_default_float(self.SNAP_ROTATE_SETTING, 1.0) self._settings.set_default_float(self.SNAP_SCALE_SETTING, 1.0) self._dict = carb.dictionary.get_dictionary() self._snap_setting_model = BoolSettingModel(self.SNAP_ENABLED_SETTING, False) self._snap_move_x_settings_model = FloatSettingModel(self.SNAP_MOVE_X_SETTING) self._snap_move_y_settings_model = FloatSettingModel(self.SNAP_MOVE_Y_SETTING) self._snap_move_z_settings_model = FloatSettingModel(self.SNAP_MOVE_Z_SETTING) self._snap_rotate_settings_model = FloatSettingModel(self.SNAP_ROTATE_SETTING) self._snap_scale_settings_model = FloatSettingModel(self.SNAP_SCALE_SETTING) self._create_snap_increment_setting_window() self._register_context_menu() self._show_menu_task = None self._button = None def clean(self): super().clean() self._snap_setting_model.clean() self._snap_setting_model = None # workaround delayed toolbar rebuild after group is destroyed and access null model if self._button: self._button.model = ui.SimpleBoolModel() self._button = None self._snap_move_x_settings_model.clean() self._snap_move_x_settings_model = None self._snap_move_y_settings_model.clean() self._snap_move_y_settings_model = None self._snap_move_z_settings_model.clean() self._snap_move_z_settings_model = None self._snap_rotate_settings_model.clean() self._snap_rotate_settings_model = None self._snap_scale_settings_model.clean() self._snap_scale_settings_model = None self._snap_increment_setting_window = None self._snap_setting_menu = None self._snap_settings = None self._snap_to_increment_menu = None self._snap_to_face_menu = None if self._show_menu_task: # pragma: no cover self._show_menu_task.cancel() self._show_menu_task = None self._snap_settings_menu_entry = None self._snap_to_increment_menu_entry = None self._snap_to_face_menu_entry = None def get_style(self): style = {"Button.Image::snap": {"image_url": "${glyphs}/toolbar_snap.svg"}} return style def create(self, default_size): self._button = ui.ToolButton( model=self._snap_setting_model, name="snap", tooltip="Snap", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "snap"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), checked=self._snap_setting_model.get_value_as_bool(), ) return {"snap": self._button} def _on_snap_on_off(self, model): # pragma: no cover (Never called anywhere it seems) self._snap_settings.enabled = self._snap_setting_model.get_value_as_bool() def _on_snap_setting_change(self, item, event_type): # pragma: no cover (Never called anywhere it seems) snap_to_face = self._dict.get(item) self._snap_to_increment_menu.checked = not snap_to_face self._snap_to_face_menu.checked = snap_to_face self._snap_settings.enabled = not snap_to_face def _on_snap_setting_menu_clicked(self, snap_to_face): # pragma: no cover self._settings.set(self.SNAP_TO_SURFACE_SETTING, snap_to_face) def _on_show_snap_increment_setting_window(self): # pragma: no cover self._snap_increment_setting_window.visible = True def _create_snap_increment_setting_window(self): self._snap_increment_setting_window = ui.Window( "Snap Increment Settings Menu", width=400, height=0, flags=ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR, visible=False, ) with self._snap_increment_setting_window.frame: with ui.VStack(spacing=8, height=0, name="frame_v_stack"): ui.Label("Snap Settings - Increments", enabled=False) ui.Separator() with ui.HStack(): with ui.HStack(width=120): ui.Label("Position", width=50) ui.Spacer() all_axis = ["X", "Y", "Z"] all_axis_model = { "X": self._snap_move_x_settings_model, "Y": self._snap_move_y_settings_model, "Z": self._snap_move_z_settings_model, } colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F} for axis in all_axis: with ui.HStack(): with ui.ZStack(width=15): ui.Rectangle( width=15, height=20, style={ "background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(axis, alignment=ui.Alignment.CENTER) ui.FloatDrag(model=all_axis_model[axis], min=0, max=1000000, step=0.01) ui.Circle(width=20, radius=3.5, size_policy=ui.CircleSizePolicy.FIXED) with ui.HStack(): with ui.HStack(width=120): ui.Label("Rotation", width=50) ui.Spacer() ui.FloatDrag(model=self._snap_rotate_settings_model, min=0, max=1000000, step=0.01) with ui.HStack(): with ui.HStack(width=120): ui.Label("Scale", width=50) ui.Spacer() ui.FloatDrag(model=self._snap_scale_settings_model, min=0, max=1000000, step=0.01) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name if context_menu: menu = { "name": f"Snap Settings {ui.get_custom_glyph_code('${glyphs}/cog.svg')}", "show_fn": [lambda object: is_button(object, "snap")], "onclick_fn": lambda object: self._on_show_snap_increment_setting_window(), "enabled_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING), } self._snap_settings_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar") menu = { "name": "Snap to Increment", "show_fn": [lambda object: is_button(object, "snap")], "onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=False), "checked_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING), } self._snap_to_increment_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar") menu = { "name": "Snap to Face", "show_fn": [lambda object: is_button(object, "snap")], "onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=True), "checked_fn": lambda object: self._settings.get(self.SNAP_TO_SURFACE_SETTING), } self._snap_to_face_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar")
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/select_button_group.py
# 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. # import carb.input import omni.kit.context_menu import omni.ui as ui import pathlib from pxr import Kind from carb.input import KeyboardInput as Key from omni.kit.widget.toolbar.hotkey import Hotkey from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.select_mode_model import SelectModeModel from .models.select_no_kinds_model import SelectNoKindsModel from .models.select_include_ref_model import SelectIncludeRefModel from .models.transform_mode_model import TransformModeModel SELECT_PRIM_MODE_TOOL_NAME = "Prim" SELECT_MODEL_MODE_TOOL_NAME = "Model" SELECT_TOOL_NAME = "Select" LIGHT_TYPES = "type:CylinderLight;type:DiskLight;type:DistantLight;type:DomeLight;type:GeometryLight;type:Light;type:RectLight;type:SphereLight" EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar") ) SELECT_MODE_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/SelectMode/enabled" class SelectButtonGroup(WidgetGroup): def __init__(self): super().__init__() self._input = carb.input.acquire_input_interface() self._select_mode_model = SelectModeModel() self._select_no_kinds_model = SelectNoKindsModel() self._select_include_ref_model = SelectIncludeRefModel() self._select_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SELECT) self._select_op_menu_entry = None self._custom_types = [] self._settings = carb.settings.get_settings() self._icon_path = str(EXTENSION_FOLDER_PATH / "data" / "icon") self._settings = carb.settings.get_settings() self._select_mode_button = None self._mode_hotkey = None if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH): def hotkey_change(): current_mode = self._select_mode_model.get_value_as_string() if current_mode == "models" or current_mode == "kind:model.ALL": self._select_mode_model.set_value("type:ALL") else: self._select_mode_model.set_value("kind:model.ALL") self._update_selection_mode_button() def on_select_mode_hotkey_changed(hotkey: str): self._select_mode_button.tooltip = self._get_select_mode_tooltip() self._mode_hotkey = Hotkey( "toolbar::select_mode", Key.T, hotkey_change, lambda: self._select_mode_button.enabled and self._is_in_context(), on_hotkey_changed_fn=on_select_mode_hotkey_changed, ) # only replace the tooltip part so that "Paint Select" registered from select brush can still have correct label def on_select_hotkey_changed(hotkey: str): self._select_op_button.tooltip = ( self._select_op_button.tooltip.rsplit("(", 1)[0] + f"({self._select_hotkey.get_as_string('Q')})" ) self._select_hotkey = Hotkey( "toolbar::select", Key.Q, lambda: self._select_op_button.model.set_value(True), lambda: self._select_op_button.enabled and self._is_in_context() and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON) == 0, on_hotkey_changed_fn=lambda hotkey: on_select_hotkey_changed(hotkey), ) self._sub_menu = [] self._register_context_menu() def get_style(self): style = { "Button.Image::select_mode": {"image_url": "${glyphs}/toolbar_select_prim.svg"}, "Button.Image::select_op_models": {"image_url": "${glyphs}/toolbar_select_models.svg"}, "Button.Image::select_op_prims": {"image_url": "${glyphs}/toolbar_select_prims.svg"}, "Button.Image::all_prim_types": {"image_url": f"{self._icon_path}/all_prim_types.svg"}, "Button.Image::meshes": {"image_url": f"{self._icon_path}/meshes.svg"}, "Button.Image::lights": {"image_url": f"{self._icon_path}/lights.svg"}, "Button.Image::cameras": {"image_url": f"{self._icon_path}/cameras.svg"}, "Button.Image::model_kinds": {"image_url": f"{self._icon_path}/model_kinds.svg"}, "Button.Image::assembly": {"image_url": f"{self._icon_path}/assembly.svg"}, "Button.Image::group": {"image_url": f"{self._icon_path}/group.svg"}, "Button.Image::component": {"image_url": f"{self._icon_path}/component.svg"}, "Button.Image::sub_component": {"image_url": f"{self._icon_path}/sub_component.svg"}, "Button.Image::payload_reference": {"image_url": f"{self._icon_path}/payload_reference.svg"}, "Button.Image::custom_kind": {"image_url": f"{self._icon_path}/custom_kind.svg"}, "Button.Image::custom_type": {"image_url": f"{self._icon_path}/custom_type.svg"}, } return style def create(self, default_size): def select_enabled(): # pragma: no cover (Unused, it's commened out below - I am just adding coverage! '^^) return True def on_select_mode_change(model): self._update_selection_mode_button() result = {} if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH): self._select_mode_button = ui.ToolButton( model=self._select_mode_model, name="select_mode", tooltip=self._get_select_mode_tooltip(), width=default_size, height=default_size, # checked=select_enabled, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_mode"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), ) self._model_changed_sub = self._select_mode_model.subscribe_value_changed_fn(on_select_mode_change) result["select_mode"] = self._select_mode_button with ui.ZStack(width=0, height=0): self._select_op_button = ui.ToolButton( model=self._select_op_model, name=self._get_select_op_button_name(self._select_mode_model), tooltip=self._get_select_tooltip(), width=default_size, height=default_size, checked=self._select_op_model.get_value_as_bool(), mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_op"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), ) # Follow the pattern here (ZStack + _build_flyout_indicator) for other buttons if they want dynamic flyout indicator self._select_op_menu_sub = self._build_flyout_indicator(default_size, default_size, "select_op") result["select_op"] = self._select_op_button self._update_selection_mode_button() return result def clean(self): super().clean() self._select_mode_button = None self._select_op_button = None self._select_mode_model.clean() self._select_mode_model = None self._select_no_kinds_model.clean() self._select_no_kinds_model = None self._select_include_ref_model.clean() self._select_include_ref_model = None self._select_op_model.clean() self._select_op_model = None self._model_changed_sub = None if self._mode_hotkey: self._mode_hotkey.clean() self._mode_hotkey = None self._select_hotkey.clean() self._select_hotkey = None self._select_mode_menu_entry.release() self._select_mode_menu_entry = None if self._select_op_menu_entry: self._select_op_menu_entry.release() self._select_op_menu_entry = None self._select_op_menu_sub = None for menu in self._sub_menu: menu.release() self._sub_menu = [] def _get_select_op_button_name(self, model): return "select_op_prims" if model.get_value_as_bool() else "select_op_models" def _get_select_tooltip(self): return f"{SELECT_TOOL_NAME} ({self._select_hotkey.get_as_string('Q')})" def _get_select_mode_button_name(self): mode_name = { "type:ALL": "all_prim_types", "type:Mesh": "meshes", LIGHT_TYPES: "lights", "type:Camera": "cameras", "kind:model.ALL": "model_kinds", "kind:assembly": "assembly", "kind:group": "group", "kind:component": "component", "kind:subcomponent": "sub_component", "ref:reference;ref:payload": "custom_type", } mode = self._select_mode_model.get_value_as_string() if mode in mode_name: return mode_name[mode] else: # pragma: no cover if mode[:4] == "kind": return "custom_kind" else: return "custom_type" def _get_select_mode_tooltip(self): mode_data = { "type:ALL": "All Prim Types", "type:Mesh": "Meshes", LIGHT_TYPES: "Lights", "type:Camera": "Camera", "kind:model.ALL": "All Model Kinds", "kind:assembly": "Assembly", "kind:group": "Group", "kind:component": "Component", "kind:subcomponent": "Subcomponent", "ref:reference;ref:payload": "Subcomponent", } mode = self._select_mode_model.get_value_as_string() if mode in mode_data: tooltip = mode_data[mode] else: # pragma: no cover if mode[:4] == "kind": tooltip = "Custom Kind" else: tooltip = "Custom type" return tooltip + f" ({self._mode_hotkey.get_as_string('T')})" def _usd_kinds(self): return ["model", "assembly", "group", "component", "subcomponent"] def _enable_no_kinds_option(self, b): # pragma: no cover mode = self._select_mode_model.get_value_as_string() return mode[:4] == "kind" def _usd_kinds_display(self): # pragma: no cover return self._usd_kinds()[1:] def _plugin_kinds(self): all_kinds = set(Kind.Registry.GetAllKinds()) return all_kinds - set(self._usd_kinds()) def _create_selection_list(self, selections): results = "" delimiter = ";" first_selection = True for s in selections: if not first_selection: # pragma: no cover (This seemingly can never happen, since first_selection is initialized with True oO) first_selection = True else: results += delimiter results += s return results def _update_selection_mode_button(self): if self._select_mode_button: self._select_mode_button.name = self._get_select_mode_button_name() self._select_mode_button.tooltip = self._get_select_mode_tooltip() if self._select_op_button: self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model) def _update_select_menu(self): for menu in self._sub_menu: menu.release() self._sub_menu = [] def create_menu_entry(name, value, add_hotkey=False): menu = { "name": name, "onclick_fn": lambda object: self._select_mode_model.set_value(value), "checked_fn": lambda object, name=name, value=value: self._select_mode_model.get_value_as_string() == value, "additional_kwargs": { "style": {"Menu.Item.CheckMark": {"image_url": omni.kit.context_menu.style.get_radio_mark_url()}} }, } if add_hotkey: menu["hotkey"] = (carb.input.KeyboardInput.T) return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar") def create_header(header=""): menu = { "header": header, "name": "", } return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar") self._sub_menu.append(create_header(header="Select by Type")) self._sub_menu.append(create_menu_entry("All Prim Types", "type:ALL", True)) self._sub_menu.append(create_menu_entry("Meshes", "type:Mesh")) self._sub_menu.append(create_menu_entry("Lights", LIGHT_TYPES)) self._sub_menu.append(create_menu_entry("Camera", "type:Camera")) if self._custom_types: for name, types in self._custom_types: self._sub_menu.append(create_menu_entry(name, types)) self._sub_menu.append(create_header(header="Select by Model Kind")) self._sub_menu.append(create_menu_entry("All Model Kinds", "kind:model.ALL")) self._sub_menu.append(create_menu_entry("Assembly", "kind:assembly")) self._sub_menu.append(create_menu_entry("Group", "kind:group")) self._sub_menu.append(create_menu_entry("Component", "kind:component")) self._sub_menu.append(create_menu_entry("Subcomponent", "kind:subcomponent")) plugin_kinds = self._plugin_kinds() if (len(plugin_kinds)) > 0: for k in plugin_kinds: # pragma: no cover self._sub_menu.append(create_menu_entry(str(k), str(key).capitalize(), f"kind:{k}")) self._sub_menu.append(create_header(header="")) menu = { "name": "Include Prims with no Kind", "onclick_fn": lambda object: self._select_no_kinds_model.set_value(not self._select_no_kinds_model.get_value_as_bool()), "checked_fn": lambda object: self._select_no_kinds_model.get_value_as_bool(), "enabled_fn": self._enable_no_kinds_option, } self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")) menu = { "name": "Include References and Payloads", "onclick_fn": lambda object: self._select_include_ref_model.set_value(not self._select_include_ref_model.get_value_as_bool()), "checked_fn": lambda object: self._select_include_ref_model.get_value_as_bool(), "enabled_fn": self._enable_no_kinds_option, } self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name if context_menu: def on_clicked_select(): # pragma: no cover self._select_op_model.set_value(True) self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model) self._select_op_button.set_tooltip(self._get_select_tooltip()) self._select_op_button.model = self._select_op_model menu = { "name": "Select", "show_fn": [lambda object: is_button(object, "select_op")], "onclick_fn": lambda object: on_clicked_select(), "checked_fn": lambda object: self._select_op_button.name == "select_op_prims" or self._select_op_button.name == "select_op_models", } self._select_mode_menu_entry = omni.kit.context_menu.add_menu(menu, "select_op", "omni.kit.widget.toolbar") if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH): menu = { "name": "Select Mode", "show_fn": [lambda object: is_button(object, "select_mode")], } self._select_op_menu_entry = omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar") self._update_select_menu() def add_custom_select_type(self, entry_name: str, selection_types: list): selection = [] for s in selection_types: selection.append(f"type:{s}") selection_string = self._create_selection_list(selection) self._custom_types.append((entry_name, selection_string)) self._update_select_menu() def remove_custom_select(self, entry_name): for index, (entry, selection_string) in enumerate(self._custom_types): if entry == entry_name: del self._custom_types[index] self._update_select_menu() return
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/transform_mode_model.py
# 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. # import omni.ui as ui import carb import carb.dictionary import carb.settings class TransformModeModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the prim select mode""" TRANSFORM_OP_SETTING = "/app/transform/operation" TRANSFORM_OP_SELECT = "select" TRANSFORM_OP_MOVE = "move" TRANSFORM_OP_ROTATE = "rotate" TRANSFORM_OP_SCALE = "scale" def __init__(self, op): super().__init__() self._op = op self._settings = carb.settings.get_settings() self._settings.set_default_string(self.TRANSFORM_OP_SETTING, self.TRANSFORM_OP_MOVE) self._dict = carb.dictionary.get_dictionary() self._op_sub = self._settings.subscribe_to_node_change_events(self.TRANSFORM_OP_SETTING, self._on_op_change) self._selected_op = self._settings.get(self.TRANSFORM_OP_SETTING) def clean(self): self._settings.unsubscribe_to_change_events(self._op_sub) def _on_op_change(self, item, event_type): self._selected_op = self._dict.get(item) self._value_changed() def _on_op_space_changed(self, item, event_type): # pragma: no cover (Seems to never be used, is overwritten in the inherited model where it is used.) self._op_space = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._selected_op == self._op def set_value(self, value): """Reimplemented set bool""" if value: self._settings.set(self.TRANSFORM_OP_SETTING, self._op) class LocalGlobalTransformModeModel(TransformModeModel): TRANSFORM_MODE_GLOBAL = "global" TRANSFORM_MODE_LOCAL = "local" def __init__(self, op, op_space_setting_path): super().__init__(op=op) self._setting_path = op_space_setting_path self._op_space_sub = self._settings.subscribe_to_node_change_events( self._setting_path, self._on_op_space_changed ) self._op_space = self._settings.get(self._setting_path) def clean(self): self._settings.unsubscribe_to_change_events(self._op_space_sub) super().clean() def _on_op_space_changed(self, item, event_type): self._op_space = self._dict.get(item) self._value_changed() def get_op_space_mode(self): return self._op_space def set_value(self, value): if not value: self._settings.set( self._setting_path, self.TRANSFORM_MODE_LOCAL if self._op_space == self.TRANSFORM_MODE_GLOBAL else self.TRANSFORM_MODE_GLOBAL, ) super().set_value(value)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/setting_model.py
# 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. # import omni.ui as ui import carb import carb.dictionary import carb.settings class BoolSettingModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch a bool setting path""" def __init__(self, setting_path, inverted): super().__init__() self._setting_path = setting_path self._inverted = inverted self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change) self._value = self._settings.get(self._setting_path) if self._inverted: self._value = not self._value def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._value = self._dict.get(item) if self._inverted: self._value = not self._value self._value_changed() def get_value_as_bool(self): return self._value def set_value(self, value): """Reimplemented set bool""" if self._inverted: value = not value self._settings.set(self._setting_path, value) if self._inverted: self._value = value class FloatSettingModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch a float setting path""" def __init__(self, setting_path): super().__init__() self._setting_path = setting_path self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change) self._value = self._settings.get(self._setting_path) def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._value = self._dict.get(item) self._value_changed() def get_value_as_float(self): return self._value def set_value(self, value): """Reimplemented set float""" self._settings.set(self._setting_path, value)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/timeline_model.py
# 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. # import omni.ui as ui import carb import omni.timeline from omni.kit.commands import execute class TimelinePlayPauseModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch a bool setting path""" def __init__(self): super().__init__() self._timeline = omni.timeline.get_timeline_interface() self._is_playing = self._timeline.is_playing() self._is_stopped = self._timeline.is_stopped() stream = self._timeline.get_timeline_event_stream() self._sub = stream.create_subscription_to_pop(self._on_timeline_event) def clean(self): self._sub = None def get_value_as_bool(self): return self._is_playing and not self._is_stopped def set_value(self, value): """Reimplemented set bool""" if value: execute("ToolbarPlayButtonClicked") else: execute("ToolbarPauseButtonClicked") def _on_timeline_event(self, e): is_playing = self._timeline.is_playing() is_stopped = self._timeline.is_stopped() if is_playing != self._is_playing or is_stopped != self._is_stopped: self._is_playing = self._timeline.is_playing() self._is_stopped = self._timeline.is_stopped() self._value_changed()
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_mode_model.py
# 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. # import omni.ui as ui import carb import carb.dictionary import carb.settings class SelectModeModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the prim select mode""" PICKING_MODE_SETTING = "/persistent/app/viewport/pickingMode" PICKING_MODE_MODELS = "kind:model.ALL" PICKING_MODE_PRIMS = "type:ALL" # new default PICKING_MODE_DEFAULT = PICKING_MODE_PRIMS def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_string(self.PICKING_MODE_SETTING, self.PICKING_MODE_DEFAULT) self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_SETTING, self._on_change) self.set_value(self._settings.get(self.PICKING_MODE_SETTING)) def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._mode = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._mode == self.PICKING_MODE_PRIMS def get_value_as_string(self): return self._mode def set_value(self, value): if isinstance(value, bool): if value: self._mode = self.PICKING_MODE_PRIMS else: self._mode = self.PICKING_MODE_MODELS else: self._mode = value self._settings.set(self.PICKING_MODE_SETTING, self._mode)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_no_kinds_model.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import carb import carb.dictionary import carb.settings class SelectNoKindsModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the prim select mode""" PICKING_MODE_NO_KINDS_SETTING = "/persistent/app/viewport/pickingModeNoKinds" # new default PICKING_MODE_NO_KINDS_DEFAULT = True def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_bool(self.PICKING_MODE_NO_KINDS_SETTING, self.PICKING_MODE_NO_KINDS_DEFAULT) self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_NO_KINDS_SETTING, self._on_change) self.set_value(self._settings.get(self.PICKING_MODE_NO_KINDS_SETTING)) def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._mode = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._mode def set_value(self, value): self._mode = value self._settings.set(self.PICKING_MODE_NO_KINDS_SETTING, self._mode)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_include_ref_model.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import carb import carb.dictionary import carb.settings class SelectIncludeRefModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the prim select mode""" PICKING_MODE_INCLUDE_REF_SETTING = "/persistent/app/viewport/pickingModeIncludeRef" # new default PICKING_MODE_INCLUDE_REF_DEFAULT = True def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_bool(self.PICKING_MODE_INCLUDE_REF_SETTING, self.PICKING_MODE_INCLUDE_REF_DEFAULT) self._dict = carb.dictionary.get_dictionary() self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_INCLUDE_REF_SETTING, self._on_change) self.set_value(self._settings.get(self.PICKING_MODE_INCLUDE_REF_SETTING)) def clean(self): self._settings.unsubscribe_to_change_events(self._subscription) def _on_change(self, item, event_type): self._mode = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._mode def set_value(self, value): self._mode = value self._settings.set(self.PICKING_MODE_INCLUDE_REF_SETTING, self._mode)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/helpers.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.settings def reset_toolbar_settings(): settings = carb.settings.get_settings() vals = { "/app/transform/operation": "move", "/persistent/app/viewport/pickingMode": "type:ALL", "/app/viewport/snapEnabled": False, } for key, val in vals.items(): settings.set(key, val)
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_api.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 import carb.settings import omni.appwindow import omni.kit.app import omni.kit.test import omni.timeline import omni.kit.ui_test as ui_test import omni.kit.widget.toolbar import omni.kit.context_menu import omni.kit.hotkeys.core import omni.ui as ui from carb.input import KeyboardInput as Key from carb.input import KEYBOARD_MODIFIER_FLAG_SHIFT from omni.kit.ui_test import Vec2 from omni.kit.widget.toolbar import Hotkey, SimpleToolButton, Toolbar, WidgetGroup, get_instance from .helpers import reset_toolbar_settings test_message_queue = [] class TestSimpleToolButton(SimpleToolButton): """ Test of how to use SimpleToolButton """ def __init__(self, icon_path): def on_toggled(c): test_message_queue.append(f"Test button toggled {c}") super().__init__( name="test_simple_tool_button", tooltip="Test Simple ToolButton", icon_path=f"{icon_path}/plus.svg", icon_checked_path=f"{icon_path}/plus.svg", hotkey=Key.U, toggled_fn=on_toggled, additional_style={"Button": { "color": 0xffffffff }} ) class TestToolButtonGroup(WidgetGroup): """ Test of how to create two ToolButton in one WidgetGroup """ def __init__(self, icon_path): super().__init__() self._icon_path = icon_path def clean(self): self._sub1 = None self._sub2 = None self._hotkey.clean() self._hotkey = None super().clean() def get_style(self): style = { "Button.Image::test1": {"image_url": f"{self._icon_path}/plus.svg"}, "Button.Image::test1:checked": {"image_url": f"{self._icon_path}/minus.svg"}, "Button.Image::test2": {"image_url": f"{self._icon_path}/minus.svg"}, "Button.Image::test2:checked": {"image_url": f"{self._icon_path}/plus.svg"}, } return style def create(self, default_size): def on_value_changed(index, model): if model.get_value_as_bool(): self._acquire_toolbar_context() else: self._release_toolbar_context() test_message_queue.append(f"Group button {index} clicked") self._menu1 = omni.kit.context_menu.add_menu({ "name": "Test 1", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar") self._menu2 = omni.kit.context_menu.add_menu({ "name": "Test 2", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar") button1 = ui.ToolButton( name="test1", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "test1"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), ) self._sub1 = button1.model.subscribe_value_changed_fn(lambda model, index=1: on_value_changed(index, model)) button2 = ui.ToolButton( name="test2", width=default_size, height=default_size, ) self._sub2 = button2.model.subscribe_value_changed_fn(lambda model, index=2: on_value_changed(index, model)) self._hotkey = Hotkey( "toolbar::test2", Key.K, lambda: button2.model.set_value(not button2.model.get_value_as_bool()), lambda: self._is_in_context(), ) # return a dictionary of name -> widget if you want to expose it to other widget_group return {"test1": button1, "test2": button2} _MAIN_WINDOW_INSTANCE = None class ToolbarApiTest(omni.kit.test.AsyncTestCase): WINDOW_NAME = "Main Toolbar Test" async def setUp(self): reset_toolbar_settings() self._icon_path = omni.kit.widget.toolbar.get_data_path().absolute().joinpath("icon").absolute() self._app = omni.kit.app.get_app() test_message_queue.clear() # If the instance doesn't exist, we need to create it for the test # Create a tmp window with the widget inside, Y axis because the tests are in the Y axis global _MAIN_WINDOW_INSTANCE if _MAIN_WINDOW_INSTANCE is None: _MAIN_WINDOW_INSTANCE = ui.ToolBar( self.WINDOW_NAME, noTabBar=False, padding_x=3, padding_y=3, margin=5, axis=ui.ToolBarAxis.Y ) self._widget = get_instance() self._widget.set_axis(ui.ToolBarAxis.Y) self._widget.rebuild_toolbar(root_frame=_MAIN_WINDOW_INSTANCE.frame) await self._app.next_update_async() await self._app.next_update_async() self._main_dockspace = ui.Workspace.get_window("DockSpace") self._toolbar_handle = ui.Workspace.get_window(self.WINDOW_NAME) self._toolbar_handle.undock() await self._app.next_update_async() self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.LEFT) await self._app.next_update_async() async def test_api(self): toolbar: Toolbar = omni.kit.widget.toolbar.get_instance() widget_simple = TestSimpleToolButton(self._icon_path) widget = TestToolButtonGroup(self._icon_path) toolbar.add_widget(widget, -100) toolbar.add_widget(widget_simple, -200) await self._app.next_update_async() self.assertIsNotNone(widget_simple.get_tool_button()) # Check widgets are added and can be fetched self.assertIsNotNone(toolbar.get_widget("test_simple_tool_button")) self.assertIsNotNone(toolbar.get_widget("test1")) self.assertIsNotNone(toolbar.get_widget("test2")) await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() manager = omni.kit.app.get_app().get_extension_manager() extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__)) hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry() hotkey = self._get_hotkey('test_simple_tool_button::hotkey') self.assertIsNotNone(hotkey) hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button") tool_test1_pos = self._get_widget_center(toolbar, "test1") tool_test2_pos = self._get_widget_center(toolbar, "test2") # Test click on first simple button await self._emulate_click(tool_test_simple_pos) await self._app.next_update_async() # Test hot key on first simple button await self._emulate_keyboard_press(Key.U, KEYBOARD_MODIFIER_FLAG_SHIFT) await self._app.next_update_async() # Test click on 1/2 group button await self._emulate_click(tool_test1_pos) await self._app.next_update_async() # Test click on 2/2 group button await self._emulate_click(tool_test2_pos) await self._app.next_update_async() # Test click on 2/2 group button again await self._emulate_click(tool_test2_pos) await self._app.next_update_async() self.assertIsNone(ui.Menu.get_current()) # Test right click on 1/2 group button await self._emulate_click(tool_test1_pos, right_click=True) await self._app.next_update_async() self.assertIsNotNone(ui.Menu.get_current()) # Test left click on 1/2 group button to close the menu await self._emulate_click(tool_test1_pos, right_click=False) await self._app.next_update_async() self.assertIsNone(ui.Menu.get_current()) # Test hold-left-click click on 1/2 group button await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.MOVE, Vec2(*tool_test1_pos)) await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_DOWN) await self._app.next_update_async() await asyncio.sleep(0.4) await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_UP) await self._app.next_update_async() self.assertIsNotNone(ui.Menu.get_current()) # Test left click on 1/2 group button to close the menu await self._emulate_click(tool_test1_pos) await self._app.next_update_async() self.assertIsNone(ui.Menu.get_current()) # Making sure all button are triggered by checking the message queue expected_messages = [ "Test button toggled True", "Test button toggled False", "Group button 1 clicked", "Group button 2 clicked", "Group button 2 clicked", ] self.assertEqual(expected_messages, test_message_queue) test_message_queue.clear() hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=0), None) toolbar.remove_widget(widget) toolbar.remove_widget(widget_simple) widget.clean() widget_simple.clean() await self._app.next_update_async() # Check widgets are cleared self.assertIsNone(toolbar.get_widget("test_simple_tool_button")) self.assertIsNone(toolbar.get_widget("test1")) self.assertIsNone(toolbar.get_widget("test2")) # Change the Hotkey for the Play button play_hotkey = self._get_hotkey('toolbar::play') self.assertIsNotNone(play_hotkey) hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) await self._app.next_update_async() tooltip_after_change = toolbar.get_widget('play').tooltip hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=0), None) await self._app.next_update_async() tooltip_after_revert = toolbar.get_widget('play').tooltip self.assertEqual(tooltip_after_change, "Play (SHIFT + SPACE)") self.assertEqual(tooltip_after_revert, "Play (SPACE)") # Change the Hotkey for the Select Mode button select_mode_hotkey = self._get_hotkey('toolbar::select_mode') self.assertIsNotNone(select_mode_hotkey) hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) await self._app.next_update_async() tooltip_after_change = toolbar.get_widget('select_mode').tooltip hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=0), None) await self._app.next_update_async() tooltip_after_revert = toolbar.get_widget('select_mode').tooltip self.assertEqual(tooltip_after_change, "All Prim Types (SHIFT + T)") self.assertEqual(tooltip_after_revert, "All Prim Types (T)") # Change the Hotkey for the Move button move_op_hotkey = self._get_hotkey('toolbar::move') self.assertIsNotNone(move_op_hotkey) hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) await self._app.next_update_async() tooltip_after_change = toolbar.get_widget('move_op').tooltip hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=0), None) await self._app.next_update_async() tooltip_after_revert = toolbar.get_widget('move_op').tooltip from ..builtin_tools.transform_button_group import MOVE_TOOL_NAME self.assertEqual(tooltip_after_change, f"{MOVE_TOOL_NAME} (SHIFT + W)") self.assertEqual(tooltip_after_revert, f"{MOVE_TOOL_NAME} (W)") # Test the Select Mode hotkey button settings = carb.settings.get_settings() from ..builtin_tools.models.select_mode_model import SelectModeModel self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS) await self._emulate_keyboard_press(Key.T) await self._app.next_update_async() self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_MODELS) await self._emulate_keyboard_press(Key.T) await self._app.next_update_async() self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS) # Test changing the Select hotkey select_hotkey = self._get_hotkey('toolbar::select') self.assertIsNotNone(select_hotkey) hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None) await self._app.next_update_async() hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=0), None) await self._app.next_update_async() async def test_context(self): toolbar = omni.kit.widget.toolbar.get_instance() widget_simple = TestSimpleToolButton(self._icon_path) widget = TestToolButtonGroup(self._icon_path) test_context = "test_context" toolbar.add_widget(widget, -100) toolbar.add_widget(widget_simple, -200, test_context) await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() await self._app.next_update_async() tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button") tool_test1_pos = self._get_widget_center(toolbar, "test1") # Test click on first simple button # Add "Test button toggled True" to queue await self._emulate_click(tool_test_simple_pos) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), test_context) # Test hot key on 2/2 group button # It should have no effect since it's not "in context" # Add nothing to queue await self._emulate_keyboard_press(Key.K) await self._app.next_update_async() # Test click on first simple button again, should exit context # Add "Test button toggled False" to queue await self._emulate_click(tool_test_simple_pos) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT) # Test hot key on 2/2 group button again # It should have effect because it's in default context # Add "Group button 2 clicked" to queue await self._emulate_keyboard_press(Key.K) await self._app.next_update_async() # Test click on first simple button again # Add "Test button toggled True" to queue await self._emulate_click(tool_test_simple_pos) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), test_context) # Test click on 1/2 group button so it takes context by force. # Add "Group button 1 clicked" to queue await self._emulate_click(tool_test1_pos) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT) # Test hot key on first simple button, it should still work on default context. # Releasing an expired context. # Add "Test button toggled False" to queue await self._emulate_keyboard_press(Key.U) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT) # Test hot key on first simple button, it should still work on default context. # Add "Test button toggled True" to queue await self._emulate_keyboard_press(Key.U) await self._app.next_update_async() self.assertEqual(toolbar.get_context(), test_context) expected_messages = [ "Test button toggled True", "Test button toggled False", "Group button 2 clicked", "Test button toggled True", "Group button 1 clicked", "Test button toggled False", "Test button toggled True", ] self.assertEqual(expected_messages, test_message_queue) toolbar.remove_widget(widget) toolbar.remove_widget(widget_simple) widget.clean() widget_simple.clean() await self._app.next_update_async() def _get_widget_center(self, toolbar, id: str): return ( toolbar.get_widget(id).screen_position_x + toolbar.get_widget(id).width / 2, toolbar.get_widget(id).screen_position_y + toolbar.get_widget(id).height / 2, ) def _get_hotkey(self, action_id: str): manager = omni.kit.app.get_app().get_extension_manager() extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__)) hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry() for hotkey in hotkey_registry.get_all_hotkeys_for_extension(extension_name): if hotkey.action_id == action_id: return hotkey async def _emulate_click(self, pos, right_click: bool = False): await ui_test.emulate_mouse_move_and_click(Vec2(*pos), right_click=right_click) async def _emulate_keyboard_press(self, key: Key, modifier: int = 0): await ui_test.emulate_keyboard_press(key, modifier) async def test_custom_select_types(self): toolbar: Toolbar = omni.kit.widget.toolbar.get_instance() entry_name = 'TestType' toolbar.add_custom_select_type(entry_name, ['test_type']) menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar") self.assertIn(entry_name, [item['name'] for item in menu_dict]) toolbar.remove_custom_select(entry_name) menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar") self.assertNotIn(entry_name, [item['name'] for item in menu_dict]) async def test_toolbar_methods(self): from ..context_menu import ContextMenu toolbar: Toolbar = omni.kit.widget.toolbar.get_instance() self.assertIsInstance(toolbar.context_menu, ContextMenu) toolbar.set_axis(ui.ToolBarAxis.X) toolbar.rebuild_toolbar() await ui_test.human_delay() toolbar.set_axis(ui.ToolBarAxis.Y) toolbar.rebuild_toolbar() await ui_test.human_delay() toolbar.subscribe_grab_mouse_pressed(None) async def test_toolbar_play_stop_button(self): toolbar: Toolbar = omni.kit.widget.toolbar.get_instance() timeline = omni.timeline.get_timeline_interface() # Click the stop button toolbar.get_widget("stop").call_clicked_fn() await ui_test.human_delay() self.assertTrue(timeline.is_stopped())
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/__init__.py
from .test_api import * from .test_models import *
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_models.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.app import omni.kit.test import omni.timeline import carb.settings import omni.kit.commands from omni.kit import ui_test class ToolbarTestModels(omni.kit.test.AsyncTestCase): async def test_setting_pass_through(self): from ..builtin_tools.builtin_tools import LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET settings = carb.settings.get_settings() orig_value = settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET) settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, True) self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET)) settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, False) self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET)) settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, orig_value) async def test_select_include_ref_model(self): from ..builtin_tools.models.select_include_ref_model import SelectIncludeRefModel model = SelectIncludeRefModel() orig_value = model.get_value_as_bool() model.set_value(not orig_value) self.assertEqual(model.get_value_as_bool(), not orig_value) model.set_value(orig_value) async def test_select_mode_model(self): from ..builtin_tools.models.select_mode_model import SelectModeModel model = SelectModeModel() orig_value = model.get_value_as_string() model.set_value(True) self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS) model.set_value(False) self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_MODELS) model.set_value(SelectModeModel.PICKING_MODE_PRIMS) self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS) model.set_value(orig_value) async def test_select_no_kinds_model(self): from ..builtin_tools.models.select_no_kinds_model import SelectNoKindsModel model = SelectNoKindsModel() orig_value = model.get_value_as_bool() model.set_value(not orig_value) self.assertEqual(model.get_value_as_bool(), not orig_value) model.set_value(orig_value) async def test_setting_model(self): from ..builtin_tools.models.setting_model import BoolSettingModel, FloatSettingModel settings = carb.settings.get_settings() bool_setting_path = '/exts/omni.kit.widget.toolbar/test/boolSetting' float_setting_path = '/exts/omni.kit.widget.toolbar/test/floatSetting' bool_model = BoolSettingModel(bool_setting_path, False) bool_model.set_value(True) self.assertEqual(bool_model.get_value_as_bool(), True) self.assertEqual(settings.get(bool_setting_path), True) bool_model.set_value(False) self.assertEqual(bool_model.get_value_as_bool(), False) self.assertEqual(settings.get(bool_setting_path), False) inverted_bool_model = BoolSettingModel(bool_setting_path, True) inverted_bool_model.set_value(True) self.assertEqual(inverted_bool_model.get_value_as_bool(), not True) self.assertEqual(settings.get(bool_setting_path), not True) inverted_bool_model.set_value(False) self.assertEqual(inverted_bool_model.get_value_as_bool(), not False) self.assertEqual(settings.get(bool_setting_path), not False) float_model = FloatSettingModel(float_setting_path) float_model.set_value(42.0) self.assertEqual(float_model.get_value_as_float(), 42.0) self.assertEqual(settings.get(float_setting_path), 42.0) float_model.set_value(21.0) self.assertEqual(float_model.get_value_as_float(), 21.0) self.assertEqual(settings.get(float_setting_path), 21.0) async def test_timeline_model(self): from ..builtin_tools.models.timeline_model import TimelinePlayPauseModel model = TimelinePlayPauseModel() model.set_value(True) await ui_test.human_delay() self.assertTrue(model.get_value_as_bool()) model.set_value(False) await ui_test.human_delay() self.assertFalse(model.get_value_as_bool()) async def test_transform_mode_model(self): from ..builtin_tools.models.transform_mode_model import TransformModeModel, LocalGlobalTransformModeModel model = TransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE) model.set_value(True) self.assertTrue(model.get_value_as_bool()) settings = carb.settings.get_settings() setting_path = '/exts/omni.kit.widget.toolbar/test/localGlobalTransformOp' settings.set(setting_path, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL) model = LocalGlobalTransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE, setting_path) model.set_value(False) self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL) model.set_value(False) self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL) async def test_play_pause_stop_commands(self): timeline = omni.timeline.get_timeline_interface() omni.kit.commands.execute("ToolbarPlayButtonClicked") await ui_test.human_delay() self.assertTrue(timeline.is_playing()) omni.kit.commands.execute("ToolbarPauseButtonClicked") await ui_test.human_delay() self.assertFalse(timeline.is_playing()) omni.kit.commands.execute("ToolbarStopButtonClicked") await ui_test.human_delay() self.assertTrue(timeline.is_stopped()) settings = carb.settings.get_settings() setting_path = '/exts/omni.kit.widget.toolbar/test/playFilter' omni.kit.commands.execute("ToolbarPlayFilterChecked", setting_path=setting_path, enabled=True) self.assertTrue(settings.get(setting_path))
omniverse-code/kit/exts/omni.kit.widget.toolbar/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.kit.window.toolbar`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [1.4.0] - 2022-11-28 ### Changed - Rename `omni.kit.window.toolbar` into `omni.kit.widget.toolbar` ## [1.3.3] - 2022-09-26 ### Changed - Updated to use `omni.kit.actions.core` and `omni.kit.hotkeys.core` for hotkeys. ## [1.3.2] - 2022-09-01 ### Changed - Context menu without compatibility mode. ## [1.3.1] - 2022-06-23 ### Changed - Change how hotkey `W` is skipped during possible camera manipulation. ## [1.3.0] - 2022-05-17 ### Changed - Changed Snap button to legacy button. New snap button will be registered by extension. ## [1.2.4] - 2022-04-19 ### Fixed - Slienced menu_changed error on create exit ## [1.2.3] - 2022-04-06 ### Fixed - Message "Failed to acquire interface while unloading all plugins" ## [1.2.1] - 2021-06-22 ### Added - Fixed height of increment settings window ## [1.2.0] - 2021-06-04 ### Added - Moved all built-in toolbutton's flyout menu to use omni.kit.context_menu, making it easier to add additional menu items to exiting button from external extension. ## [1.1.0] - 2021-04-16 ### Added - Added "Context" concept to toolbar that can be used to control the effective scope of tool buttons. ## [1.0.0] - 2021-03-04 ### Added - Started tracking changelog. Added tests.
omniverse-code/kit/exts/omni.kit.widget.toolbar/docs/index.rst
omni.kit.widget.toolbar ########################### Omniverse Kit Toolbar extension .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.kit.window.file/PACKAGE-LICENSES/omni.kit.window.file-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.window.file/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.3.32" category = "Internal" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "USD File UI" description="Provides utility functions to new/open/save/close USD files" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "usd", "ui"] # 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" [dependencies] "omni.client" = {} "omni.usd" = {} "omni.kit.stage_templates" = {} "omni.ui" = {} "omni.kit.pip_archive" = {} # Pull in pip_archive to make sure psutil is found and not installed "omni.kit.window.file_importer" = {} "omni.kit.window.file_exporter" = {} "omni.kit.widget.versioning" = {} "omni.kit.widget.nucleus_connector" = {} "omni.kit.actions.core" = {} [python.pipapi] requirements = ["psutil"] [[python.module]] name = "omni.kit.window.file" [settings] exts."omni.kit.window.file".enable_versioning = true [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/file/ignoreUnsavedOnExit=true", "--/persistent/app/omniverse/filepicker/options_menu/show_details=false", "--no-window" ] dependencies = [ "omni.hydra.pxr", "omni.physx.bundle", "omni.timeline", "omni.kit.mainwindow", "omni.kit.menu.file", "omni.kit.ui_test", "omni.kit.test_suite.helpers", ]
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/__init__.py
from .scripts import *
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/prompt_ui.py
import urllib import carb import carb.settings import omni.ui as ui from typing import List class Prompt: def __init__( self, title: str, text: str, button_text: list, button_fn: list, modal: bool = False, callback_addons: List = [], callback_destroy: List = [], decode_text: bool = True ): self._title = title self._text = urllib.parse.unquote(text) if decode_text else text self._button_list = [] self._modal = modal self._callback_addons = callback_addons self._callback_destroy = callback_destroy self._buttons = [] for name, fn in zip(button_text, button_fn): self._button_list.append((name, fn)) self._build_ui() def destroy(self): self._cancel_button_fn = None self._ok_button_fn = None self._button_list = [] if self._window: self._window.destroy() del self._window self._window = None for button in self._buttons: button.set_clicked_fn(None) self._buttons.clear() self._callback_addons = [] for callback in self._callback_destroy: if callback and callable(callback): callback() self._callback_destroy = [] def __del__(self): self.destroy() def __enter__(self): self.show() if self._modal: settings = carb.settings.get_settings() # Only use first word as a reason (e.g. "Creating, Openning"). URL won't work as a setting key. operation = self._text.split(" ")[0].lower() self._hang_detector_disable_key = "/app/hangDetector/disableReasons/{0}".format(operation) settings.set(self._hang_detector_disable_key, "1") settings.set("/crashreporter/data/appState", operation) return self def __exit__(self, type, value, trace): self.hide() if self._modal: settings = carb.settings.get_settings() settings.destroy_item(self._hang_detector_disable_key) settings.set("/crashreporter/data/appState", "started") def show(self): self._window.visible = True def hide(self): self._window.visible = False def is_visible(self): return self._window.visible def set_text(self, text): self._text_label.text = text def _build_ui(self): self._window = ui.Window( self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED, raster_policy=ui.RasterPolicy.NEVER ) 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_CLOSE ) if self._modal: self._window.flags |= ui.WINDOW_FLAGS_MODAL with self._window.frame: with ui.VStack(height=0): ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer(widht=10, height=0) self._text_label = ui.Label( self._text, width=ui.Percent(100), height=0, word_wrap=True, alignment=ui.Alignment.CENTER, ) ui.Spacer(widht=10, height=0) ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer(height=0) for name, fn in self._button_list: if name: button = ui.Button(name) if fn: button.set_clicked_fn(lambda on_fn=fn: (self.hide(), on_fn())) else: button.set_clicked_fn(lambda: self.hide()) self._buttons.append(button) ui.Spacer(height=0) ui.Spacer(width=0, height=10) for callback in self._callback_addons: if callback and callable(callback): callback()
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/share_window.py
import carb import omni.ui as ui class ShareWindow(ui.Window): def __init__(self, copy_button_text="Copy Path to Clipboard", copy_button_fn=None, modal=True, url=None): self._title = "Share Omniverse USD Path" self._copy_button_text = copy_button_text self._copy_button_fn = copy_button_fn self._status_text = "Copy and paste this path to another user to share the location of this USD file." self._stage_url = url self._stage_string_box = None super().__init__(self._title, visible=url is not None, width=600, height=140, dockPreference=ui.DockPreference.DISABLED) self.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE ) if modal: self.flags = self.flags | ui.WINDOW_FLAGS_MODAL self.frame.set_build_fn(self._build_ui) def _build_ui(self): with self.frame: with ui.VStack(): ui.Spacer(height=10) with ui.HStack(height=0): ui.Spacer() self._status_label = ui.Label(self._status_text, width=0) ui.Spacer() ui.Spacer(height=10) with ui.HStack(height=0): ui.Spacer() self._stage_string_box = ui.StringField(width=550) self._stage_string_box.model.set_value(self._stage_url) ui.Spacer() ui.Spacer(height=5) with ui.HStack(height=0): ui.Spacer() copy_button = ui.Button(self._copy_button_text, width=165) copy_button.set_clicked_fn(self._on_copy_button_fn) ui.Spacer() ui.Spacer(height=10) def _on_copy_button_fn(self): self.visible = False if self._stage_string_box: try: import omni.kit.clipboard # type: ignore try: omni.kit.clipboard.copy(self._stage_string_box.model.as_string) except: carb.log_warn("clipboard copy failed") except ImportError: carb.log_warn("Could not import omni.kit.clipboard. Cannot copy scene URL to the clipboard.") @property def url(self): return self._stage_url @url.setter def url(self, value: str) -> None: self._stage_url = value if self._stage_string_box: self._stage_string_box.model.set_value(value) self.visible = True
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/save_stage_ui.py
import asyncio import weakref import urllib import carb.settings import omni.client import omni.ui from omni.kit.widget.versioning import CheckpointHelper class CheckBoxStatus: def __init__(self, checkbox, layer_identifier, layer_is_writable): self.checkbox = checkbox self.layer_identifier = layer_identifier self.layer_is_writable = layer_is_writable self.is_checking = False class StageSaveDialog: WINDOW_WIDTH = 580 MAX_VISIBLE_LAYER_COUNT = 10 def __init__(self, on_save_fn=None, on_dont_save_fn=None, on_cancel_fn=None, enable_dont_save=False): self._usd_context = omni.usd.get_context() self._save_fn = on_save_fn self._dont_save_fn = on_dont_save_fn self._cancel_fn = on_cancel_fn self._checkboxes_status = [] self._select_all_checkbox_is_checking = False self._selected_layers = [] self._checkpoint_marks = {} flags = ( omni.ui.WINDOW_FLAGS_NO_COLLAPSE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_MODAL ) self._window = omni.ui.Window( "Select Files to Save##file.py", visible=False, width=0, height=0, flags=flags, auto_resize=True, padding_x=10, dockPreference=omni.ui.DockPreference.DISABLED, ) with self._window.frame: with omni.ui.VStack(height=0, width=StageSaveDialog.WINDOW_WIDTH): self._layers_scroll_frame = omni.ui.ScrollingFrame(height=160) omni.ui.Spacer(width=0, height=10) self._checkpoint_comment_frame = omni.ui.Frame() with self._checkpoint_comment_frame: with omni.ui.VStack(height=0, spacing=5): omni.ui.Label("*) File(s) that will be Checkpointed with a comment.") with omni.ui.ZStack(): self._description_field = omni.ui.StringField(multiline=True, height=60) self._description_field_hint_label = omni.ui.Label( " Description", alignment=omni.ui.Alignment.LEFT_TOP, style={"color": 0xFF3F3F3F} ) self._description_begin_edit_sub = self._description_field.model.subscribe_begin_edit_fn( self._on_description_begin_edit ) self._description_end_edit_sub = self._description_field.model.subscribe_end_edit_fn( self._on_description_end_edit ) self._checkpoint_comment_spacer = omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(height=0) self._save_selected_button = omni.ui.Button("Save Selected", width=0, height=0) self._save_selected_button.set_clicked_fn(self._on_save_fn) omni.ui.Spacer(width=5, height=0) if enable_dont_save: self._dont_save_button = omni.ui.Button("Don't Save", width=0, height=0) self._dont_save_button.set_clicked_fn(self._on_dont_save_fn) omni.ui.Spacer(width=5, height=0) self._cancel_button = omni.ui.Button("Cancel", width=0, height=0) self._cancel_button.set_clicked_fn(self._on_cancel_fn) omni.ui.Spacer(height=0) omni.ui.Spacer(height=5) def destroy(self): self._usd_context = None self._save_fn = None self._dont_save_fn = None self._cancel_fn = None self._checkboxes_status = None self._selected_layers = None self._checkpoint_marks = None if self._window: del self._window self._window = None def __del__(self): self.destroy() def _on_save_fn(self): if self._save_fn: self._save_fn( self._selected_layers, comment=self._description_field.model.get_value_as_string() if self._checkpoint_comment_frame.visible else "", ) self._window.visible = False self._selected_layers = [] def _on_dont_save_fn(self): if self._dont_save_fn: self._dont_save_fn(self._description_field.model.get_value_as_string()) self._window.visible = False self._selected_layers = [] def _on_cancel_fn(self): if self._cancel_fn: self._cancel_fn(self._description_field.model.get_value_as_string()) self._window.visible = False self._selected_layers = [] def _on_select_all_fn(self, model): if self._select_all_checkbox_is_checking: return self._select_all_checkbox_is_checking = True if model.get_value_as_bool(): for checkbox_status in self._checkboxes_status: checkbox_status.checkbox.model.set_value(True) else: for checkbox_status in self._checkboxes_status: checkbox_status.checkbox.model.set_value(False) self._select_all_checkbox_is_checking = False def _check_and_select_all(self, select_all_check_box): select_all = True for checkbox_status in self._checkboxes_status: if checkbox_status.layer_is_writable and not checkbox_status.checkbox.model.get_value_as_bool(): select_all = False break if select_all: self._select_all_checkbox_is_checking = True select_all_check_box.model.set_value(True) self._select_all_checkbox_is_checking = False def _on_checkbox_fn(self, model, check_box_index, select_all_check_box): check_box_status = self._checkboxes_status[check_box_index] if check_box_status.is_checking: return check_box_status.is_checking = True if not check_box_status.layer_is_writable: model.set_value(False) elif model.get_value_as_bool(): self._selected_layers.append(check_box_status.layer_identifier) self._check_and_select_all(select_all_check_box) else: self._selected_layers.remove(check_box_status.layer_identifier) self._select_all_checkbox_is_checking = True select_all_check_box.model.set_value(False) self._select_all_checkbox_is_checking = False check_box_status.is_checking = False def show(self, layer_identifiers=None): self._layers_scroll_frame.clear() self._checkpoint_marks.clear() self._checkpoint_comment_frame.visible = False self._checkpoint_comment_spacer.visible = False settings = carb.settings.get_settings() enable_versioning = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False # make a copy self._selected_layers.extend(layer_identifiers) self._checkboxes_status = [] #build layers_scroll_frame self._first_item_stack = None with self._layers_scroll_frame: with omni.ui.VStack(height=0): omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(width=20, height=0) self._select_all_checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16}) self._select_all_checkbox.model.set_value(True) omni.ui.Label("File Name", alignment=omni.ui.Alignment.LEFT) omni.ui.Spacer(width=20, height=0) omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(width=20, height=0) omni.ui.Separator(height=0, style={"color": 0xFF808080}) omni.ui.Spacer(width=20, height=0) omni.ui.Spacer(width=0, height=5) for i in range(len(layer_identifiers)): layer_identifier = layer_identifiers[i] # TODO Move version related code if enable_versioning: # Check if the server support checkpoint self._check_checkpoint_enabled(layer_identifier) style = {} layer_is_writable = omni.usd.is_layer_writable(layer_identifier) layer_is_locked = omni.usd.is_layer_locked(self._usd_context, layer_identifier) if not layer_is_writable or layer_is_locked: self._selected_layers.remove(layer_identifier) style = {"background_color": 0xFF808080, "color": 0xFF808080} label_text = urllib.parse.unquote(layer_identifier).replace("\\", "/") if not layer_is_writable or layer_is_locked: label_text += " (Read-Only)" omni.ui.Spacer(width=0, height=5) stack = omni.ui.HStack(height=0, style=style) if self._first_item_stack is None: self._first_item_stack = stack with stack: omni.ui.Spacer(width=20, height=0) checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16}) checkbox.model.set_value(True) omni.ui.Label(label_text, word_wrap=False, elided_text=True, alignment=omni.ui.Alignment.LEFT) check_point_label = omni.ui.Label("*", width=3, alignment=omni.ui.Alignment.LEFT, visible=False) omni.ui.Spacer(width=20, height=0) self._checkpoint_marks[layer_identifier] = check_point_label checkbox.model.add_value_changed_fn( lambda a, b=i, c=self._select_all_checkbox: self._on_checkbox_fn(a, b, c) ) self._checkboxes_status.append(CheckBoxStatus(checkbox, layer_identifier, layer_is_writable)) self._select_all_checkbox.model.add_value_changed_fn(lambda a: self._on_select_all_fn(a)) self._window.visible = True async def __delay_adjust_window_size(weak_self): await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() __self = weak_self() if not __self: return y0 = __self._layers_scroll_frame.screen_position_y y1 = __self._first_item_stack.screen_position_y fixed_height = y1 - y0 + 5 item_height = __self._first_item_stack.computed_content_height + 5 count = min(StageSaveDialog.MAX_VISIBLE_LAYER_COUNT, len(__self._checkpoint_marks)) scroll_frame_new_height = fixed_height + count * item_height __self._layers_scroll_frame.height = omni.ui.Pixel(scroll_frame_new_height) if len(layer_identifiers) > 0: asyncio.ensure_future(__delay_adjust_window_size(weakref.ref(self))) def is_visible(self): return self._window.visible def _on_description_begin_edit(self, model): self._description_field_hint_label.visible = False def _on_description_end_edit(self, model): if len(model.get_value_as_string()) == 0: self._description_field_hint_label.visible = True def _check_checkpoint_enabled(self, url): async def check_server_support(weak_self, url): _self = weak_self() if not _self: return if await CheckpointHelper.is_checkpoint_enabled_async(url): _self._checkpoint_comment_frame.visible = True _self._checkpoint_comment_spacer.visible = True label = _self._checkpoint_marks.get(url, None) if label: label.visible = True asyncio.ensure_future(check_server_support(weakref.ref(self), url))
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/style.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 import omni.ui as ui try: THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") except Exception: THEME = None finally: THEME = THEME or "NvidiaDark" def get_style(): if THEME == "NvidiaLight": # pragma: no cover BACKGROUND_COLOR = 0xFF535354 BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E FIELD_BACKGROUND_COLOR = 0xFF1F2124 SECONDARY_COLOR = 0xFFE0E0E0 BORDER_COLOR = 0xFF707070 TITLE_COLOR = 0xFF707070 TEXT_COLOR = 0xFF8D760D TEXT_HINT_COLOR = 0xFFD6D6D6 else: BACKGROUND_COLOR = 0xFF23211F BACKGROUND_SELECTED_COLOR = 0xFF8A8777 BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A SECONDARY_COLOR = 0xFF9E9E9E BORDER_COLOR = 0xFF8A8777 TITLE_COLOR = 0xFFCECECE TEXT_COLOR = 0xFF9E9E9E TEXT_HINT_COLOR = 0xFF7A7A7A style = { "Button": { "background_color": BACKGROUND_COLOR, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "margin": 0, "padding": 0 }, "Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR}, "Button.Label": {"color": TEXT_COLOR}, "Field": {"background_color": BACKGROUND_COLOR, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER}, "Field.Hint": {"background_color": 0x0, "color": TEXT_HINT_COLOR, "margin_width": 4}, "Label": {"background_color": 0x0, "color": TEXT_COLOR}, "CheckBox": {"alignment": ui.Alignment.CENTER}, } return style
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/__init__.py
from .file_window import *
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/file_actions.py
import omni.kit.actions.core from .app_ui import AppUI, DialogOptions def register_actions(extension_id): import omni.kit.window.file action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "File Actions" action_registry.register_action( extension_id, "new", omni.kit.window.file.new, display_name="File->New", description="Create a new USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "open", omni.kit.window.file.open, display_name="File->Open", description="Open an existing USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "open_stage", omni.kit.window.file.open_stage, display_name="File->Open Stage", description="Open an named USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "reopen", omni.kit.window.file.reopen, display_name="File->Reopen", description="Reopen the currently opened USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "open_with_new_edit_layer", omni.kit.window.file.open_with_new_edit_layer, display_name="File->Open With New Edit Layer", description="Open an existing USD stage with a new edit layer.", tag=actions_tag, ) action_registry.register_action( extension_id, "share", omni.kit.window.file.share, display_name="File->Share", description="Share the currently open USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "save", lambda: omni.kit.window.file.save(dialog_options=DialogOptions.HIDE), display_name="File->Save", description="Save the currently opened USD stage to file.", tag=actions_tag, ) action_registry.register_action( extension_id, "save_with_options", lambda: omni.kit.window.file.save(dialog_options=DialogOptions.NONE), display_name="File->Save With Options", description="Save the currently opened USD stage to file.", tag=actions_tag, ) action_registry.register_action( extension_id, "save_as", lambda: omni.kit.window.file.save_as(False), display_name="File->Save As", description="Save the currently opened USD stage to a new file.", tag=actions_tag, ) action_registry.register_action( extension_id, "save_as_flattened", lambda: omni.kit.window.file.save_as(True), display_name="File->Save As Flattened", description="Save the currently opened USD stage to a new flattened file.", tag=actions_tag, ) action_registry.register_action( extension_id, "add_reference", lambda: omni.kit.window.file.add_reference(is_payload=False), display_name="File->Add Reference", description="Add a reference to a file.", tag=actions_tag, ) action_registry.register_action( extension_id, "add_payload", lambda: omni.kit.window.file.add_reference(is_payload=True), display_name="File->Add Payload", description="Add a payload to a file.", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)