file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/types.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # class PeerUser: """Information of peer user that's joined to the same channel.""" def __init__(self, user_id: str, user_name: str, from_app: str) -> None: """ Constructor. Internal only. Args: user_id (str): Unique user id. user_name (str): Readable user name. from_app (str): Which app this users join from. """ self._user_id = user_id self._user_name = user_name self._from_app = from_app @property def user_id(self): """Property. Unique user id.""" return self._user_id @property def user_name(self): """Property. Readable user name.""" return self._user_name @property def from_app(self): """Property. Readable app name, like 'Kit', 'Maya', etc.""" return self._from_app class MessageType: JOIN = "JOIN" # User is joined. Client should respond HELLO if it receives JOIN from new user. HELLO = "HELLO" # Someone said hello to me. Normally, client sends HELLO when it receives GET_USERS = "GET_USERS" # User does not join this channel, but wants to find who are inside this channel. # Clients receive this message should respond with HELLO to broadcast its existence. # Clients implement this command does not need to send JOIN firstly, and no LEFT sent # also before quitting channel. LEFT = "LEFT" # User left this channel. MESSAGE = "MESSAGE" # Normal message after JOIN. class Message: def __init__(self, from_user: PeerUser, message_type: MessageType, content: dict) -> None: """ Constructor. Internal only. Args: from_user (PeerUser): User that message sent from. message_type (MessageType): Message type. content (dict): Message content in dict. """ self._from_user = from_user self._message_type = message_type self._content = content @property def from_user(self) -> PeerUser: """Property. User that message sent from.""" return self._from_user @property def message_type(self) -> MessageType: """Property. Message type.""" return self._message_type @property def content(self) -> dict: """Property. Message content in dictionary.""" return self._content def __str__(self) -> str: return f"from: {self.from_user.user_name}, message_type: {self.message_type}, content: {self.content}"
3,048
Python
32.505494
113
0.613517
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/__init__.py
from .channel_manager_tests import TestChannelManager
54
Python
26.499987
53
0.87037
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/channel_manager_tests.py
import unittest import omni.client import omni.kit.test import omni.kit.app import omni.kit.collaboration.channel_manager as cm from omni.kit.collaboration.channel_manager.manager import _build_message_in_bytes from .test_base import enable_server_tests class TestChannelManager(omni.kit.test.AsyncTestCase): # pragma: no cover BASE_URL = "omniverse://localhost/Projects/tests/omni.kit.collaboration.channel_manger/" # Before running each test async def setUp(self): self.app = omni.kit.app.get_app() self.current_message = None async def tearDown(self): pass async def _wait(self, frames=10): for i in range(frames): await self.app.next_update_async() async def test_join_invalid_omniverse_url(self): channel = await cm.join_channel_async("file://c/invalid_url.channel") self.assertFalse(channel) channel = await cm.join_channel_async("omniverse://invalid-server/invalid_url.channel") self.assertFalse(channel) async def test_peer_user_and_message_api(self): peer_user = cm.PeerUser("test_id", "test", "Create") self.assertEqual(peer_user.user_id, "test_id") self.assertEqual(peer_user.user_name, "test") self.assertEqual(peer_user.from_app, "Create") content = {"key" : "value"} message = cm.Message(peer_user, cm.MessageType.HELLO, content=content) self.assertEqual(message.from_user, peer_user) self.assertEqual(message.message_type, cm.MessageType.HELLO) self.assertEqual(message.content, content) @unittest.skipIf(not enable_server_tests(), "") async def test_api(self): test_url = self.BASE_URL + "test.channel" def subscriber(message: cm.Message): self.current_message = message channel = await cm.join_channel_async(test_url) handle = channel.add_subscriber(subscriber) self.assertTrue(channel is not None, f"Failed to connect channel.") self.assertTrue(channel.url is not None) self.assertTrue(channel.logged_user_name is not None) self.assertTrue(channel.logged_user_id is not None) self.assertTrue(channel.stopped is False) # Send empty message result = await channel.send_message_async({}) self.assertTrue(result == omni.client.Result.OK) # Send more result = await channel.send_message_async({"test": "message_content"}) self.assertTrue(result == omni.client.Result.OK) # Simulates multi-users user_id = 0 for message_type in [cm.MessageType.JOIN, cm.MessageType.HELLO, cm.MessageType.LEFT]: self.current_message = None content = _build_message_in_bytes("test", message_type, {}) channel._handler()._handle_message(omni.client.ChannelEvent.MESSAGE, str(user_id), content) self.assertTrue(self.current_message is not None) self.assertEqual(self.current_message.message_type, message_type) self.assertEqual(self.current_message.from_user.user_id, str(user_id)) self.assertEqual(self.current_message.from_user.user_name, "test") # Don't increment user id for LEFT message as LEFT message will not be handled if user is not logged. if message_type == cm.MessageType.JOIN: user_id += 1 # Simulates customized message self.current_message = None content = {"test_key": "content"} message = _build_message_in_bytes("test", cm.MessageType.MESSAGE, content) channel._handler()._handle_message(omni.client.ChannelEvent.MESSAGE, str(user_id), message) self.assertTrue(self.current_message) self.assertEqual(self.current_message.message_type, cm.MessageType.MESSAGE) self.assertEqual(self.current_message.content, content) # Channel's LEFT message will be treated as left too. self.current_message = None channel._handler()._handle_message(omni.client.ChannelEvent.LEFT, str(user_id), None) self.assertEqual(self.current_message.message_type, cm.MessageType.LEFT) handle.unsubscribe() @unittest.skipIf(not enable_server_tests(), "") async def test_synchronization(self): test_url = self.BASE_URL + "test.channel" for i in range(20): channel = await cm.join_channel_async(test_url) self.assertTrue(not not channel)
4,456
Python
40.654205
113
0.665619
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/test_base.py
import carb.settings def enable_server_tests(): settings = carb.settings.get_settings() enabled = settings.get_as_bool("/exts/omni.kit.collaboration.channel_manager/enable_server_tests") return enabled
218
Python
20.899998
102
0.738532
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/docs/CHANGELOG.md
# Changelog ## [1.0.9] - 2021-11-02 ### Changed - Support to fetch connection id for logged user. ## [1.0.8] - 2021-09-22 ### Changed - More tests coverage. ## [1.0.7] - 2021-08-21 ### Changed - More tests coverage. ## [1.0.6] - 2021-08-08 ### Changed - Exclude code to improve test coverage. ## [1.0.5] - 2021-07-25 ### Changed - Don't send LEFT message for getting users only. ## [1.0.4] - 2021-07-08 ### Changed - Use real app name for live session. ## [1.0.3] - 2021-06-07 ### Changed - Don't send hello if user is joined already. ## [1.0.2] - 2021-03-15 ### Changed - Improve extension and add tests. ## [1.0.0] - 2021-03-09 ### Changed - Initial extension.
681
Markdown
16.947368
49
0.615272
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/docs/README.md
# Channel Manager [omni.kit.collaboration.channel_manager] This extension provides interfaces create/manage Omniverse Channel without caring about state management but only message exchange between clients.
207
Markdown
68.333311
147
0.850242
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/docs/index.rst
omni.kit.collaboration.channel_manager ###################################### Channel Manager Introduction ============ This extension provides interfaces create/manage Omniverse Channel without caring about state management but only message exchange between clients.
270
reStructuredText
26.099997
121
0.696296
omniverse-code/kit/exts/omni.debugdraw/PACKAGE-LICENSES/omni.debugdraw-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.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.debugdraw/config/extension.toml
[package] title = "debug draw" category = "Rendering" version = "0.1.1" [dependencies] "omni.usd" = {} "omni.hydra.rtx" = {optional=true} [[python.module]] name = "omni.debugdraw" [[native.plugin]] path = "bin/*.plugin" [[test]] timeout = 600 args = [ "--/app/asyncRendering=false", # OM-49867 random test crashes without this flag "--/renderer/enabled=rtx", "--/renderer/active=rtx", "--/rtx/post/aa/op=0", "--/rtx/post/tonemap/op=1", "--/app/file/ignoreUnsavedOnExit=true", "--/persistent/app/viewport/displayOptions=0", "--/app/viewport/forceHideFps=true", "--/app/viewport/grid/enabled=false", "--/app/viewport/show/lights=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/window/width=800", "--/app/window/height=600", "--no-window" ] dependencies = [ "omni.ui", "omni.kit.ui_test", "omni.hydra.rtx", "omni.kit.test_helpers_gfx", "omni.kit.viewport.utility", "omni.kit.window.viewport" ]
1,025
TOML
21.8
83
0.623415
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/_debugDraw.pyi
"""pybind11 omni.debugdraw bindings""" from __future__ import annotations import omni.debugdraw._debugDraw import typing import carb._carb __all__ = [ "IDebugDraw", "SimplexPoint", "acquire_debug_draw_interface", "release_debug_draw_interface" ] class IDebugDraw(): def draw_box(self, box_pos: carb._carb.Float3, box_rotation: carb._carb.Float4, box_size: carb._carb.Float3, color: int, line_width: float = 1.0) -> None: ... @typing.overload def draw_line(self, start_pos: carb._carb.Float3, start_color: int, start_width: float, end_pos: carb._carb.Float3, end_color: int, end_width: float) -> None: ... @typing.overload def draw_line(self, start_pos: carb._carb.Float3, start_color: int, end_pos: carb._carb.Float3, end_color: int) -> None: ... def draw_lines(self, lines_list: list) -> None: ... def draw_point(self, pos: carb._carb.Float3, color: int, width: float = 1.0) -> None: ... def draw_points(self, points_list: list) -> None: ... def draw_sphere(self, sphere_pos: carb._carb.Float3, sphere_radius: float, color: int, line_width: float = 1.0, tesselation: int = 32) -> None: ... pass class SimplexPoint(): """ SimplexPoint structure. """ def __init__(self) -> None: ... @property def color(self) -> int: """ :type: int """ @color.setter def color(self, arg0: int) -> None: pass @property def position(self) -> carb._carb.Float3: """ :type: carb._carb.Float3 """ @position.setter def position(self, arg0: carb._carb.Float3) -> None: pass @property def width(self) -> float: """ :type: float """ @width.setter def width(self, arg0: float) -> None: pass pass def acquire_debug_draw_interface(plugin_name: str = None, library_path: str = None) -> IDebugDraw: pass def release_debug_draw_interface(arg0: IDebugDraw) -> None: pass
1,968
unknown
31.816666
166
0.609756
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/__init__.py
from ._debugDraw import IDebugDraw from ._debugDraw import acquire_debug_draw_interface, release_debug_draw_interface def _get_interface(func, acq): if not hasattr(func, "iface"): func.iface = acq() return func.iface def get_debug_draw_interface() -> IDebugDraw: return _get_interface(get_debug_draw_interface, acquire_debug_draw_interface) from .scripts.extension import *
397
Python
29.615382
82
0.735516
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/scripts/extension.py
import omni.ext from .. import get_debug_draw_interface class DebugDrawExtension(omni.ext.IExt): def on_startup(self): get_debug_draw_interface() def on_shutdown(self): pass
201
Python
17.363635
40
0.676617
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/tests/visualtests.py
import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from omni.debugdraw import get_debug_draw_interface from omni.debugdraw._debugDraw import SimplexPoint import carb from pathlib import Path import inspect from omni.kit.viewport.utility import get_active_viewport_window, next_viewport_frame_async from omni.kit.viewport.utility.camera_state import ViewportCameraState from omni.kit.viewport.utility.tests import setup_viewport_test_window, capture_viewport_and_compare EXTENSION_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${omni.debugdraw}")).resolve().absolute() GOLDEN_IMAGES = EXTENSION_ROOT.joinpath("data", "tests") OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()) COLOR_RED = 0xffff0000 class DebugDrawVisualTest(OmniUiTest): def set_camera(self): camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world((10, 0, 0), False) camera_state.set_target_world((0, 0, 0), True) async def setup_viewport(self, resolution_x: int = 800, resolution_y: int = 600): await self.create_test_area(resolution_x, resolution_y) return await setup_viewport_test_window(resolution_x, resolution_y) async def base(self, fn): viewport_window = await self.setup_viewport() viewport = viewport_window.viewport_api await omni.usd.get_context().new_stage_async() self.set_camera() # Wait until the Viewport has delivered some frames await next_viewport_frame_async(viewport, 2) # Draw for 20 frames (TC: Windows requires ~5 Linux requires ~20) for _ in range(20): fn() await omni.kit.app.get_app().next_update_async() # Capture and compare the image test_caller = inspect.stack()[1][3] image_name = f"{test_caller}.png" passed, fail_msg = await capture_viewport_and_compare(image_name=image_name, output_img_dir=OUTPUTS_DIR, golden_img_dir=GOLDEN_IMAGES, viewport=viewport) self.assertTrue(passed, msg=fail_msg) def get_point(self, pos, width=2): p = SimplexPoint() p.position = pos p.color = COLOR_RED p.width = width return p async def setUp(self): await super().setUp() self._iface = get_debug_draw_interface() async def test_debugdraw_visual_sphere(self): await self.base(lambda: self._iface.draw_sphere(carb.Float3(0.0, 0.0, 0.0), 2, COLOR_RED)) async def test_debugdraw_visual_line(self): await self.base(lambda: self._iface.draw_line( carb.Float3(0.0, 0.0, 0.0), COLOR_RED, 2, carb.Float3(0.0, 2.0, 0.0), COLOR_RED, 2 )) async def test_debugdraw_visual_line_list(self): line_list = [ self.get_point(carb.Float3(0.0, 0.0, 0.0)), self.get_point(carb.Float3(0.0, -2.0, 0.0)), self.get_point(carb.Float3(0.0, 0.0, 0.0)), self.get_point(carb.Float3(0.0, 2.0, 0.0)), ] await self.base(lambda: self._iface.draw_lines(line_list)) async def test_debugdraw_visual_point(self): await self.base(lambda: self._iface.draw_point(carb.Float3(0.0, 0.0, 0.0), COLOR_RED, 10)) async def test_debugdraw_visual_box(self): await self.base(lambda: self._iface.draw_box( carb.Float3(0.0, 0.0, 0.0), carb.Float4(0.3535534, 0.3535534, 0.1464466, 0.8535534), carb.Float3(2, 2, 2), COLOR_RED )) async def test_debugdraw_visual_points(self): point_list = [ self.get_point(carb.Float3(0.0, 0.0, 0.0), 10), self.get_point(carb.Float3(0.0, -2.0, 0.0), 10), self.get_point(carb.Float3(0.0, 2.0, 0.0), 10), ] await self.base(lambda: self._iface.draw_points(point_list))
3,833
Python
38.122449
161
0.639969
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/tests/__init__.py
from .visualtests import *
27
Python
12.999994
26
0.777778
omniverse-code/kit/exts/omni.kit.test_app_compat/omni/kit/test_app_compat/__init__.py
from .app_dev_test import *
28
Python
13.499993
27
0.714286
omniverse-code/kit/exts/omni.kit.test_app_compat/omni/kit/test_app_compat/app_dev_test.py
import os import sys import inspect import pathlib import importlib import carb import carb.settings import carb.tokens import omni.kit.app import omni.kit.test import omni.usd #import omni.kit.test_helpers_gfx import omni.kit.renderer.bind from omni.kit.test.teamcity import teamcity_publish_image_artifact OUTPUTS_DIR = omni.kit.test.get_test_output_path() USE_TUPLES = True EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) DATA_DIR = EXTENSION_FOLDER_PATH.joinpath("data/tests") class AppDevCompatTest(omni.kit.test.AsyncTestCase): async def setUp(self): self._settings = carb.settings.acquire_settings_interface() self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface() self._renderer = omni.kit.renderer.bind.acquire_renderer_interface() self._module_test_helpers_gfx = importlib.import_module('omni.kit.test_helpers_gfx') self._captured_buffer = [] self._captured_buffer_w = 0 self._captured_buffer_h = 0 self._captured_buffer_fmt = 0 def __test_name(self) -> str: return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" async def tearDown(self): self._renderer = None self._app_window_factory = None self._settings = None def _capture_callback(self, buf, buf_size, w, h, fmt): if USE_TUPLES: self._captured_buffer = omni.renderer_capture.convert_raw_bytes_to_rgba_tuples(buf, buf_size, w, h, fmt) else: self._captured_buffer = omni.renderer_capture.convert_raw_bytes_to_list(buf, buf_size, w, h, fmt) self._captured_buffer_w = w self._captured_buffer_h = h self._captured_buffer_fmt = fmt async def test_1_capture_variance(self): test_name = self.__test_name() import omni.renderer_capture app_window = self._app_window_factory.get_default_window() self._usd_context_name = '' self._usd_context = omni.usd.get_context(self._usd_context_name) test_usd_asset = DATA_DIR.joinpath("simple_cubes_mat.usda") print("Opening '%s'" % (test_usd_asset)) await self._usd_context.open_stage_async(str(test_usd_asset)) # We can wait for omni.usd.StageEventType.ASSETS_LOADED here, but it may fail if MDL materials happen to be # already loaded. We need some way to wait only if there is something to wait. for _ in range (3): await omni.kit.app.get_app().next_update_async() capture_interface = omni.renderer_capture.acquire_renderer_capture_interface() capture_interface.capture_next_frame_swapchain_callback(self._capture_callback, app_window) await omni.kit.app.get_app().next_update_async() capture_interface.wait_async_capture(app_window) if "PIL" not in sys.modules.keys(): # Checking if we have Pillow imported try: from PIL import Image except ImportError: # Install Pillow if it's not installed import omni.kit.pipapi omni.kit.pipapi.install("Pillow", module="PIL") from PIL import Image from PIL import ImageStat image = Image.new('RGBA', [self._captured_buffer_w, self._captured_buffer_h]) if USE_TUPLES: image.putdata(self._captured_buffer) else: buf_channel_it = iter(self._captured_buffer) captured_buffer_tuples = list(zip(buf_channel_it, buf_channel_it, buf_channel_it, buf_channel_it)) image.putdata(captured_buffer_tuples) # Only compare the standard deviation, since the test failing because of the UI elements shifting around is # no good. Generally, it is enough to test that: # 1. the test doesn't crash on iGPUs, # 2. the test produces anything other than the black screen (the std dev of which is 0.0) image_stats = ImageStat.Stat(image) avg_std_dev = sum(image_stats.stddev) / 3.0 # Save image for user verification test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") image.save(TEST_IMG_PATH) # The full app.dev has a std dev ~30.0, and the version with broken layout has a std dev of ~18.0 STD_DEV_THRESHOLD = 10.0 if avg_std_dev < STD_DEV_THRESHOLD: teamcity_publish_image_artifact(TEST_IMG_PATH, "results", "Generated") carb.log_error("Standard deviation of the produced image is lower than the threshold!") self.assertTrue(False)
4,698
Python
37.203252
123
0.647935
omniverse-code/kit/exts/omni.kit.test_app_compat/docs/index.rst
omni.kit.test_app_compat ########################### Test app.dev in compatibility mode.
91
reStructuredText
14.333331
35
0.538462
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/__init__.py
from ._app_snippets import *
29
Python
13.999993
28
0.724138
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/_app_snippets.pyi
from __future__ import annotations import omni.kit.app_snippets._app_snippets import typing __all__ = [ "IAppSnippets", "acquire_app_snippets_interface", "release_app_snippets_interface" ] class IAppSnippets(): def execute(self) -> int: ... def shutdown(self) -> None: ... def startup(self) -> None: ... pass def acquire_app_snippets_interface(plugin_name: str = None, library_path: str = None) -> IAppSnippets: pass def release_app_snippets_interface(arg0: IAppSnippets) -> None: pass
525
unknown
24.047618
102
0.672381
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/tests/__init__.py
from .test_app_snippets import *
33
Python
15.999992
32
0.757576
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/tests/test_app_snippets.py
import inspect import carb import carb.settings import omni.kit.app import omni.kit.test import omni.kit.app_snippets class RendererTest(omni.kit.test.AsyncTestCase): async def setUp(self): self._settings = carb.settings.acquire_settings_interface() self._app_snippets = omni.kit.app_snippets.acquire_app_snippets_interface() self._app_snippets.startup() def __test_name(self) -> str: return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" async def tearDown(self): self._app_snippets.shutdown() self._app_snippets = None self._settings = None async def test_0_cpp_snippets(self): carb.log_warn("\n\n\ntest 0!!\n\n") failed_test_count = self._app_snippets.execute() carb.log_warn("failed test count: %d" % (failed_test_count)) self.assertEqual(0, failed_test_count)
902
Python
27.218749
85
0.648559
omniverse-code/kit/exts/omni.graph.scriptnode/ogn/docs/OgnScriptNode.rst
.. _omni_graph_scriptnode_ScriptNode_2: .. _omni_graph_scriptnode_ScriptNode: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Script Node :keywords: lang-en omnigraph node script WriteOnly scriptnode script-node Script Node =========== .. <description> This script node allows you to execute arbitrary Python code. `import` statements, function/class definitions, and global variables may be placed outside of the callbacks, and variables may be added to the ``db.internal_state`` state object The following callback functions may be defined in the script - ``setup(db)`` is called before compute the first time, or after reset is pressed - ``compute(db)`` is called every time the node computes (should always be defined) - ``cleanup(db)`` is called when the node is deleted or the reset button is pressed Predefined Variables - ``db (og.Database)`` is the node interface, attributes are exposed like ``db.inputs.foo``. Use ``db.log_error``, ``db.log_warning`` to report problems - ``og``: is the `omni.graph.core` module .. </description> Installation ------------ To use this node enable :ref:`omni.graph.scriptnode<ext_omni_graph_scriptnode>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:execIn", "``execution``", "The input execution", "None" "Inline Script (*inputs:script*)", "``string``", "A string containing a Python script that may define code to be executed when the script node computes. See the default and example scripts for more info.", "None" "Script File Path (*inputs:scriptPath*)", "``token``", "The path of a file containing a Python script that may define code to be executed when the script node computes. See the default and example scripts for more info.", "None" "", "*uiType*", "filePath", "" "", "*fileExts*", "Python Scripts (\\*.py)", "" "Use Script File (*inputs:usePath*)", "``bool``", "When true, the python script is read from the file specified in 'Script File Path', instead of the string in 'Inline Script'", "False" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:execOut", "``execution``", "The output execution", "None" State ----- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "state:omni_initialized", "``bool``", "State attribute used to control when the script should be reloaded. This should be set to False to trigger a reload of the script.", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.scriptnode.ScriptNode" "Version", "2" "Extension", "omni.graph.scriptnode" "Icon", "ogn/icons/omni.graph.scriptnode.ScriptNode.svg" "Has State?", "True" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Script Node" "Categories", "script" "Generated Class Name", "OgnScriptNodeDatabase" "Python Module", "omni.graph.scriptnode"
3,366
reStructuredText
34.072916
232
0.635472
omniverse-code/kit/exts/omni.graph.scriptnode/PACKAGE-LICENSES/omni.graph.scriptnode-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.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.graph.scriptnode/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.10.0" authors = ["NVIDIA"] title = "Script Node" description="Python Node for OmniGraph" readme = "docs/README.md" repository = "" category = "graph" keywords = ["script"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" # Watch the .ogn files for hot reloading (only works for Python files) [fswatcher.patterns] include = ["*.ogn", "*.py"] exclude = ["Ogn*Database.py"] [dependencies] "omni.graph" = {} "omni.graph.tools" = {} "omni.kit.widget.text_editor" = { optional = true } # Note: omni.kit.widget.text_editor is brought in by omni.graph.ui "omni.graph.ui" = { optional = true } "omni.kit.widget.searchfield" = { optional = true } "omni.kit.property.usd" = { optional = true } "omni.kit.window.popup_dialog" = { optional = true } "omni.kit.window.property" = { optional = true } # Main python module this extension provides, it will be publicly available as "import omni.graph.scriptnode". [[python.module]] name = "omni.graph.scriptnode" [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
1,142
TOML
26.878048
118
0.691769
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/__init__.py
"""The public API """ __all__ = [] from ._impl.extension import _PublicExtension # noqa: F401
96
Python
18.399996
59
0.635417
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/ogn/OgnScriptNodeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.scriptnode.ScriptNode This script node allows you to execute arbitrary Python code. `import` statements, function/class definitions, and global variables may be placed outside of the callbacks, and variables may be added to the ``db.internal_state`` state object The following callback functions may be defined in the script - ``setup(db)`` is called before compute the first time, or after reset is pressed - ``compute(db)`` is called every time the node computes (should always be defined) - ``cleanup(db)`` is called when the node is deleted or the reset button is pressed Predefined Variables - ``db (og.Database)`` is the node interface, attributes are exposed like ``db.inputs.foo``. Use ``db.log_error``, ``db.log_warning`` to report problems - ``og``: is the `omni.graph.core` module """ import carb import sys import traceback import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnScriptNodeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.scriptnode.ScriptNode Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.script inputs.scriptPath inputs.usePath Outputs: outputs.execOut State: state.omni_initialized """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:execIn', 'execution', 0, None, 'The input execution', {}, True, None, False, ''), ('inputs:script', 'string', 0, 'Inline Script', 'A string containing a Python script that may define code to be executed when the script node computes.\nSee the default and example scripts for more info.', {}, False, None, False, ''), ('inputs:scriptPath', 'token', 0, 'Script File Path', 'The path of a file containing a Python script that may define code to be executed when the script node computes.\nSee the default and example scripts for more info.', {ogn.MetadataKeys.UI_TYPE: 'filePath', 'fileExts': 'Python Scripts (*.py)'}, False, None, False, ''), ('inputs:usePath', 'bool', 0, 'Use Script File', "When true, the python script is read from the file specified in 'Script File Path', instead of the string in 'Inline Script'", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('outputs:execOut', 'execution', 0, None, 'The output execution', {}, True, None, False, ''), ('state:omni_initialized', 'bool', 0, None, 'State attribute used to control when the script should be reloaded.\nThis should be set to False to trigger a reload of the script.', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.execIn = og.AttributeRole.EXECUTION role_data.inputs.script = og.AttributeRole.TEXT role_data.outputs.execOut = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execIn", "script", "scriptPath", "usePath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.execIn, self._attributes.script, self._attributes.scriptPath, self._attributes.usePath] self._batchedReadValues = [None, None, None, False] @property def execIn(self): return self._batchedReadValues[0] @execIn.setter def execIn(self, value): self._batchedReadValues[0] = value @property def script(self): return self._batchedReadValues[1] @script.setter def script(self, value): self._batchedReadValues[1] = value @property def scriptPath(self): return self._batchedReadValues[2] @scriptPath.setter def scriptPath(self, value): self._batchedReadValues[2] = value @property def usePath(self): return self._batchedReadValues[3] @usePath.setter def usePath(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 = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) @property def omni_initialized(self): data_view = og.AttributeValueHelper(self._attributes.omni_initialized) return data_view.get() @omni_initialized.setter def omni_initialized(self, value): data_view = og.AttributeValueHelper(self._attributes.omni_initialized) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnScriptNodeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnScriptNodeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnScriptNodeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.scriptnode.ScriptNode' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnScriptNodeDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnScriptNodeDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnScriptNodeDatabase(node) try: compute_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnScriptNodeDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnScriptNodeDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnScriptNodeDatabase.PER_NODE_DATA[node.node_id()] def on_connection_or_disconnection(*args): per_node_data['_db'] = None node.register_on_connected_callback(on_connection_or_disconnection) node.register_on_disconnected_callback(on_connection_or_disconnection) @staticmethod def release(node): release_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnScriptNodeDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnScriptNodeDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.scriptnode") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Script Node") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "script") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This script node allows you to execute arbitrary Python code.\n `import` statements, function/class definitions, and global variables may be placed\n outside of the callbacks, and variables may be added to the ``db.internal_state`` state object\n \n The following callback functions may be defined in the script\n - ``setup(db)`` is called before compute the first time, or after reset is pressed\n - ``compute(db)`` is called every time the node computes (should always be defined)\n - ``cleanup(db)`` is called when the node is deleted or the reset button is pressed\n \n Predefined Variables\n - ``db (og.Database)`` is the node interface, attributes are exposed like ``db.inputs.foo``. Use ``db.log_error``, ``db.log_warning`` to report problems\n - ``og``: is the `omni.graph.core` module\n \n") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.scriptnode}") icon_path = icon_path + '/' + "ogn/icons/omni.graph.scriptnode.ScriptNode.svg" node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path) __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.set_data_access(og.eAccessLocation.E_USD, og.eAccessType.E_WRITE) OgnScriptNodeDatabase.INTERFACE.add_to_node_type(node_type) node_type.set_has_state(True) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None @staticmethod def register(node_type_class): OgnScriptNodeDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnScriptNodeDatabase.abi, 2) @staticmethod def deregister(): og.deregister_node_type("omni.graph.scriptnode.ScriptNode")
15,498
Python
47.586207
890
0.639115
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/ogn/python/nodes/OgnScriptNode.py
import inspect import os import tempfile import traceback import omni.client import omni.graph.core as og import omni.graph.tools.ogn as ogn import omni.usd from omni.graph.scriptnode.ogn.OgnScriptNodeDatabase import OgnScriptNodeDatabase # A hacky context manager that captures local variable name declarations and saves them in a dict class ScriptContextSaver: def __init__(self, script_context: dict): self.script_context = script_context self.local_names = None def __enter__(self): caller_frame = inspect.currentframe().f_back self.local_names = set(caller_frame.f_locals) return self def __exit__(self, exc_type, exc_val, exc_tb): caller_frame = inspect.currentframe().f_back caller_locals = caller_frame.f_locals for name in caller_locals: if name not in self.local_names: self.script_context[name] = caller_locals[name] class UserCode: """The cached data associated with a user script""" def __init__(self): self.code_object = None # The compiled code object self.setup_fn = None # setup() self.cleanup_fn = None # cleanup() self.compute_fn = None # compute() self.script_context = {} # namespace for the executed code class OgnScriptNodeState: def __init__(self): self.code = UserCode() # The cached code data self.tempfile_path: str = None # Name of the temporary file for storing the script self.script_path: str = None # The last value of inputs:scriptPath self.script: str = None # The last value of inputs:script self.use_path: bool = None # The last value of inputs:usePath self.node_initialized: bool = False # Flag used to check if the per-instance node state is initialized. class OgnScriptNode: @staticmethod def internal_state(): return OgnScriptNodeState() @staticmethod def _is_initialized(node: og.Node) -> bool: return og.Controller.get(og.Controller.attribute("state:omni_initialized", node)) @staticmethod def _set_initialized(node: og.Node, init: bool): return og.Controller.set(og.Controller.attribute("state:omni_initialized", node), init) @staticmethod def initialize(context, node: og.Node): state = OgnScriptNodeDatabase.per_node_internal_state(node) state.node_initialized = True # Create a temporary file for storing the script with tempfile.NamedTemporaryFile(suffix=".py", delete=False) as tf: state.tempfile_path = tf.name OgnScriptNode._set_initialized(node, False) @staticmethod def release(node: og.Node): state = OgnScriptNodeDatabase.per_node_internal_state(node) # Same logic as when the reset button is pressed OgnScriptNode.try_cleanup(node) # Delete the temporary file for storing the script if os.path.exists(state.tempfile_path): os.remove(state.tempfile_path) @staticmethod def try_cleanup(node: og.Node): # Skip if not setup in the fist place if not OgnScriptNode._is_initialized(node): return state = OgnScriptNodeDatabase.per_node_internal_state(node) # Call the user-defined cleanup function if state.code.cleanup_fn is not None: # Get the database object per_node_data = OgnScriptNodeDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get("_db") try: db.inputs._setting_locked = True # noqa: PLW0212 state.code.cleanup_fn(db) db.inputs._setting_locked = False # noqa: PLW0212 except Exception: # pylint: disable=broad-except OgnScriptNode._print_stacktrace(db) OgnScriptNode._set_initialized(node, False) @staticmethod def _print_stacktrace(db: OgnScriptNodeDatabase): stacktrace = traceback.format_exc().splitlines(keepends=True) stacktrace_iter = iter(stacktrace) stacktrace_output = "" for stacktrace_line in stacktrace_iter: if "OgnScriptNode.py" in stacktrace_line: # The stack trace shows that the exception originates from this file # Removing this useless information from the stack trace next(stacktrace_iter, None) else: stacktrace_output += stacktrace_line db.log_error(stacktrace_output) @staticmethod def _read_script_file(file_path: str) -> str: """Reads the given file and returns the contents""" # Get the absolute path from the possibly relative path in inputs:scriptPath with the edit layer edit_layer = omni.usd.get_context().get_stage().GetEditTarget().GetLayer() if not edit_layer.anonymous: file_path = omni.client.combine_urls(edit_layer.realPath, file_path).replace("\\", "/") del edit_layer # Try to read the script at the specified path result, _, content = omni.client.read_file(file_path) if result != omni.client.Result.OK: raise RuntimeError(f"Could not open/read the script at '{file_path}': error code: {result}") script_bytes = memoryview(content).tobytes() if len(script_bytes) < 2: return "" cur_script = script_bytes.decode("utf-8") return cur_script @staticmethod def _legacy_compute(db: OgnScriptNodeDatabase): # Legacy compute we just exec the whole script every compute with ScriptContextSaver(db.internal_state.code.script_context): exec(db.internal_state.code.code_object) # noqa: PLW0122 @staticmethod def compute(db) -> bool: # Note that we initialize this node's OgnScriptNodeState in the OgnScriptNode initialize # method. While this works for non-instanced workflows, if we try to instance an OmniGraph # that contains a ScriptNode we run into issues, mainly because the instanced ScriptNode # will NOT have an initialized OgnScriptNodeState (since the instanced node's initialize() # method was never actually executed). To account for this, in the compute method we'll # simply call the OgnScriptNode initialize() if said method was never called. if not db.internal_state.node_initialized: OgnScriptNode.initialize(db.abi_context, db.abi_node) use_path = db.inputs.usePath cur_script: str = "" # The script contents tempfile_path = db.internal_state.tempfile_path # The path to the script file to be compiled/executed initialized = db.state.omni_initialized if use_path: script_path = db.inputs.scriptPath if not script_path: return True else: # Use inputs:script for the script and the temporary file for the script path cur_script = db.inputs.script if not cur_script: return True if use_path != db.internal_state.use_path: initialized = False db.internal_state.use_path = use_path try: # Compile / Execute the script if necessary if not initialized: db.state.omni_initialized = True db.internal_state.code = UserCode() db.internal_state.script = None try: if use_path: cur_script = OgnScriptNode._read_script_file(script_path) db.internal_state.script_path = script_path # If the script content has changed we need to re-compile if db.internal_state.script != cur_script: with open(tempfile_path, "w", encoding="utf-8") as tf: tf.write(cur_script) db.internal_state.code.code_object = compile(cur_script, tempfile_path, "exec") db.internal_state.script = cur_script except Exception as ex: # pylint: disable=broad-except # No need for a callstack for an i/o or compilation error db.log_error(str(ex)) return False # Execute the script inside a context manager that captures the names defined in it with ScriptContextSaver(db.internal_state.code.script_context): exec(db.internal_state.code.code_object) # noqa: PLW0122 # Extract the user-defined setup, compute, and cleanup functions db.internal_state.code.compute_fn = db.internal_state.code.script_context.get("compute") if not callable(db.internal_state.code.compute_fn): db.internal_state.code.compute_fn = None if db.internal_state.code.compute_fn is None: # Assume the script is legacy, so execute on every compute db.log_warning("compute(db) not defined in user script, running in legacy mode") db.internal_state.code.compute_fn = OgnScriptNode._legacy_compute return True db.internal_state.code.setup_fn = db.internal_state.code.script_context.get("setup") if not callable(db.internal_state.code.setup_fn): db.internal_state.code.setup_fn = None db.internal_state.code.cleanup_fn = db.internal_state.code.script_context.get("cleanup") if not callable(db.internal_state.code.cleanup_fn): db.internal_state.code.cleanup_fn = None # Inject script-global names into the function globals if db.internal_state.code.compute_fn is not None: db.internal_state.code.compute_fn.__globals__.update(db.internal_state.code.script_context) if db.internal_state.code.setup_fn is not None: db.internal_state.code.setup_fn.__globals__.update(db.internal_state.code.script_context) if db.internal_state.code.cleanup_fn is not None: db.internal_state.code.cleanup_fn.__globals__.update(db.internal_state.code.script_context) # Call the user-defined setup function if db.internal_state.code.setup_fn is not None: db.internal_state.code.setup_fn(db) # ------------------------------------------------------------------------------------ # Call the user-defined compute function if db.internal_state.code.compute_fn is not None: db.internal_state.code.compute_fn(db) # Set outputs:execOut if not hidden if db.node.get_attribute("outputs:execOut").get_metadata(ogn.MetadataKeys.HIDDEN) != "1": db.outputs.execOut = og.ExecutionAttributeState.ENABLED except Exception: # pylint: disable=broad-except OgnScriptNode._print_stacktrace(db) return False return True
11,103
Python
43.594377
112
0.618752
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/ogn/tests/TestOgnScriptNode.py
import os import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts from omni.graph.core.tests.omnigraph_test_utils import _TestGraphAndNode from omni.graph.core.tests.omnigraph_test_utils import _test_clear_scene from omni.graph.core.tests.omnigraph_test_utils import _test_setup_scene from omni.graph.core.tests.omnigraph_test_utils import _test_verify_scene class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.scriptnode.ogn.OgnScriptNodeDatabase import OgnScriptNodeDatabase test_file_name = "OgnScriptNodeTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_scriptnode_ScriptNode") database = OgnScriptNodeDatabase(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), 2) 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:execIn")) attribute = test_node.get_attribute("inputs:execIn") db_value = database.inputs.execIn self.assertTrue(test_node.get_attribute_exists("inputs:usePath")) attribute = test_node.get_attribute("inputs:usePath") db_value = database.inputs.usePath expected_value = False actual_value = og.Controller.get(attribute) ogts.verify_values(expected_value, actual_value, _attr_error(attribute, True)) ogts.verify_values(expected_value, db_value, _attr_error(attribute, False)) self.assertTrue(test_node.get_attribute_exists("outputs:execOut")) attribute = test_node.get_attribute("outputs:execOut") db_value = database.outputs.execOut self.assertTrue(test_node.get_attribute_exists("state:omni_initialized")) attribute = test_node.get_attribute("state:omni_initialized") db_value = database.state.omni_initialized
2,500
Python
48.039215
94
0.6988
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/ogn/tests/__init__.py
"""====== GENERATED BY omni.graph.tools - DO NOT EDIT ======""" import omni.graph.tools._internal as ogi ogi.import_tests_in_directory(__file__, __name__)
155
Python
37.999991
63
0.645161
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/_impl/extension.py
"""Support required by the Carbonite extension loader""" import asyncio from contextlib import suppress from typing import List import carb import carb.dictionary import omni.ext import omni.graph.core as og from omni.kit.app import get_app SCRIPTNODE_OPT_IN_SETTING = "/app/omni.graph.scriptnode/opt_in" SCRIPTNODE_ENABLE_OPT_IN_SETTING = "/app/omni.graph.scriptnode/enable_opt_in" OMNIGRAPH_STAGEUPDATE_ORDER = 100 # We want our attach() to run after OG so that nodes have been instantiated # ============================================================================================================== def set_all_graphs_enabled(enable: bool): """Set the enabled state of all OmniGraphs""" graphs = og.get_all_graphs() if graphs and not isinstance(graphs, list): graphs = [graphs] for graph in graphs: graph.set_disabled(not enable) def is_check_enabled(): """Returns True if scriptnode opt-in is enabled""" settings = carb.settings.get_settings() if not settings.is_accessible_as(carb.dictionary.ItemType.BOOL, SCRIPTNODE_ENABLE_OPT_IN_SETTING): # The enable-setting is not present, we enable the check return True if not settings.get(SCRIPTNODE_ENABLE_OPT_IN_SETTING): # The enable-setting is present and False, disable the check return False # the enable-setting is present and True, enable the check return True def on_opt_in_change(item: carb.dictionary.Item, change_type: carb.settings.ChangeEventType): """Update the local cache of the setting value""" if change_type != carb.settings.ChangeEventType.CHANGED: return settings = carb.settings.get_settings() should_run = bool(settings.get(SCRIPTNODE_OPT_IN_SETTING)) if should_run: set_all_graphs_enabled(True) def verify_scriptnode_load(script_nodes: List[og.Node]): """ Get verification from the user that they want to run scriptnodes. This opt-in applies to the current session only. Args: script_nodes: The list of script nodes on the stage that have been disabled. """ from omni.kit.window.popup_dialog import MessageDialog def on_cancel(dialog: MessageDialog): settings = carb.settings.get_settings() settings.set(SCRIPTNODE_OPT_IN_SETTING, False) dialog.hide() def on_ok(dialog: MessageDialog): settings = carb.settings.get_settings() settings.set(SCRIPTNODE_OPT_IN_SETTING, True) dialog.hide() message = """ This stage contains scriptnodes. There is currently no limitation on what code can be executed by this node. This means that graphs that contain these nodes should only be used when the author of the graph is trusted. Do you want to enable the scriptnode functionality for this session? """ dialog = MessageDialog( title="Warning", width=400, message=message, cancel_handler=on_cancel, ok_handler=on_ok, ok_label="Yes", cancel_label="No", ) async def show_async(): # wait a few frames to allow the app ui to finish loading await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() dialog.show() asyncio.ensure_future(show_async()) def check_for_scriptnodes(): """ Check for presence of omni.graph.scriptnode instances and confirm user wants to enable them. """ # If the check is not enabled then we are good if not is_check_enabled(): return # Check is enabled - see if they already opted-in settings = carb.settings.get_settings() scriptnode_opt_in = settings.get(SCRIPTNODE_OPT_IN_SETTING) if scriptnode_opt_in: # The check is enabled, and they opted-in return # The check is enabled but they opted out, or haven't been prompted yet try: import omni.kit.window.popup_dialog # noqa except ImportError: # Don't prompt in headless mode return script_nodes = [] graphs = og.get_all_graphs() if graphs and not isinstance(graphs, list): graphs = [graphs] for graph in graphs: for node in graph.get_nodes(): node_type = node.get_node_type() if node_type.get_node_type() == "omni.graph.scriptnode.ScriptNode": # Found one script_nodes.append(node) if not script_nodes: # No script nodes means we can leave them enabled return # Disable them until we get the opt-in via the async dialog set_all_graphs_enabled(False) verify_scriptnode_load(script_nodes) def on_attach(ext_id: int, _): """Called when USD stage is attached""" check_for_scriptnodes() # ============================================================================================================== class _PublicExtension(omni.ext.IExt): """Object that tracks the lifetime of the Python part of the extension loading""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__stage_subscription = None self.__opt_in_setting_sub = None with suppress(ImportError): manager = get_app().get_extension_manager() # This is a bit of a hack to make the template directory visible to the OmniGraph UI extension # if it happens to already be enabled. The "hack" part is that this logic really should be in # omni.graph.ui, but it would be much more complicated there, requiring management of extensions # that both do and do not have dependencies on omni.graph.ui. if manager.is_extension_enabled("omni.graph.ui"): import omni.graph.ui as ogui # noqa: PLW0621 ogui.ComputeNodeWidget.get_instance().add_template_path(__file__) def on_startup(self): stage_update = omni.stageupdate.get_stage_update_interface() self.__stage_subscription = stage_update.create_stage_update_node("OmniGraphAttach", on_attach_fn=on_attach) assert self.__stage_subscription nodes = stage_update.get_stage_update_nodes() stage_update.set_stage_update_node_order(len(nodes) - 1, OMNIGRAPH_STAGEUPDATE_ORDER + 1) self.__opt_in_setting_sub = omni.kit.app.SettingChangeSubscription(SCRIPTNODE_OPT_IN_SETTING, on_opt_in_change) assert self.__opt_in_setting_sub def on_shutdown(self): self.__stage_subscription = None self.__opt_in_setting_sub = None
6,536
Python
35.316666
184
0.643666
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/_impl/scriptnode_example_scripts.py
# This file contains the set of example scripts for the script node. # User can click on the Code Snippets button in the UI to display these scripts. # To add new example scripts to the script node, # simply add the delimiter to the bottom of this file, followed by the new script. # Declare og to suppress linter warnings about undefined variables og = None # # # DELIMITER # # # Title = "Default Script" # This script is executed the first time the script node computes, or the next time it computes after this script # is modified or the 'Reset' button is pressed. # The following callback functions may be defined in this script: # setup(db): Called immediately after this script is executed # compute(db): Called every time the node computes (should always be defined) # cleanup(db): Called when the node is deleted or the reset button is pressed (if setup(db) was called before) # Defining setup(db) and cleanup(db) is optional, but if compute(db) is not defined then this script node will run # in legacy mode, where the entire script is executed on every compute and the callback functions above are ignored. # Available variables: # db: og.Database The node interface, attributes are db.inputs.data, db.outputs.data. # Use db.log_error, db.log_warning to report problems. # Note that this is available outside of the callbacks only to support legacy mode. # og: The OmniGraph module # Import statements, function/class definitions, and global variables may be placed outside of the callbacks. # Variables may also be added to the db.internal_state state object. # Example code snippet: import math UNITS = "cm" def calculate_circumfrence(radius): return 2 * math.pi * radius def setup(db): state = db.internal_state state.radius = 1 def compute(db): state = db.internal_state circumfrence = calculate_circumfrence(state.radius) print(f"{circumfrence} {UNITS}") state.radius += 1 # To see more examples, click on the Code Snippets button below. # # # DELIMITER # # # Title = "Compute Count" # In this example, we retrieve the number of times this script node has been computed # and assign it to Output Data so that downstream nodes can use this information. def compute(db): compute_count = db.node.get_compute_count() db.outputs.my_output_attribute = compute_count # # # DELIMITER # # # Title = "Fibonacci" # In this example, we produce the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21... # Each time this node is evaluated, the next Fibonacci number will be set as the output value. # This illustrates how variables declared in the setup script can be used to keep persistent information. # Remember to add an output attribute of type 'int' named my_output_attribute first. def setup(db): state = db.internal_state state.num1 = 0 state.num2 = 1 def compute(db): state = db.internal_state total = state.num1 + state.num2 state.num1 = state.num2 state.num2 = total db.outputs.my_output_attribute = state.num1 # # # DELIMITER # # # Title = "Controller" # In this example, we use omni.graph.core.Controller to create cube prims. # Each time this node is evaluated, it will create a new cube prim on the scene. # When the 'Reset' button is pressed or the node is deleted, the created cube prims will be deleted. import omni.kit.commands def setup(db): state = db.internal_state state.cube_count = 0 def compute(db): state = db.internal_state state.cube_count += 1 og.Controller.edit( db.node.get_graph(), {og.Controller.Keys.CREATE_PRIMS: [(f"/World/Cube{state.cube_count}", "Cube")]} ) def cleanup(db): state = db.internal_state omni.kit.commands.execute("DeletePrims", paths=[f"/World/Cube{i}" for i in range(1, state.cube_count + 1)]) # # # DELIMITER # # # Title = "Random Vectors with Warp" # In this example, we compute the lengths of random 3D vectors using Warp import numpy as np import warp as wp wp.init() NUM_POINTS = 1024 DEVICE = "cuda" @wp.kernel def length(points: wp.array(dtype=wp.vec3), lengths: wp.array(dtype=float)): # thread index tid = wp.tid() # compute distance of each point from origin lengths[tid] = wp.length(points[tid]) def compute(db): # allocate an array of 3d points points = wp.array(np.random.rand(NUM_POINTS, 3), dtype=wp.vec3, device=DEVICE) lengths = wp.zeros(NUM_POINTS, dtype=float, device=DEVICE) # launch kernel wp.launch(kernel=length, dim=len(points), inputs=[points, lengths], device=DEVICE) print(lengths) # # # DELIMITER # # # Title = "Value Changed Callbacks" # In this example, we register a value changed callback function for inputs:my_input_attribute. # The callback is called when the value of inputs:my_input_attribute is changed from the property panel. # Remember to add an input attribute named my_input_attribute first. def on_my_input_attribute_changed(attr): print(f"inputs:my_input_attribute = {attr.get_attribute_data().get()}") def setup(db): attr = db.node.get_attribute("inputs:my_input_attribute") attr.register_value_changed_callback(on_my_input_attribute_changed) def compute(db): pass
5,239
Python
30.190476
116
0.712541
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/_impl/templates/template_omni.graph.scriptnode.ScriptNode.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import shutil import subprocess from functools import partial from pathlib import Path import carb.settings import omni.client import omni.graph.core as og import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn import omni.ui as ui from omni.graph.scriptnode.ogn.OgnScriptNodeDatabase import OgnScriptNodeDatabase from omni.graph.ui import OmniGraphAttributeModel from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder from omni.kit.widget.text_editor import TextEditor EXT_PATH = Path(__file__).absolute().parent.parent.parent.parent.parent.parent ICONS_PATH = EXT_PATH.joinpath("icons") FONTS_PATH = EXT_PATH.joinpath("fonts") class ComboBoxOption(ui.AbstractItem): """Provide a conversion from simple text to a StringModel to be used in ComboBox options""" def __init__(self, text: str): super().__init__() self.model = ui.SimpleStringModel(text) def destroy(self): self.model = None class ComboBoxModel(ui.AbstractItemModel): """The underlying model of a combo box""" def __init__(self, option_names, option_values, current_value, on_value_changed_callback): super().__init__() self.option_names = option_names self.option_values = option_values self.on_value_changed_callback = on_value_changed_callback self._current_index = ui.SimpleIntModel(self.option_values.index(current_value)) self._current_index.add_value_changed_fn(self._on_index_changed) self._items = [ComboBoxOption(option) for option in self.option_names] def destroy(self): ogt.destroy_property(self, "_current_index") ogt.destroy_property(self, "_items") def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id: int): if item is None: return self._current_index # combo box expects index model on item == None return item.model def _on_index_changed(self, new_index: ui.SimpleIntModel): new_value = self.option_values[new_index.as_int] self.on_value_changed_callback(new_value) self._item_changed(None) class CreateAttributePopupDialog: """The popup dialog for creating new dynamic attribute on the script node""" def __init__(self, create_new_attribute_callback, **kwargs): self.create_new_attribute_callback = create_new_attribute_callback self.all_supported_types = [] self.all_displayed_types = [] self.window = None self.attribute_name_field = None self.port_type_radio_collection = None self.input_port_button = None self.output_port_button = None self.state_port_button = None self.scrolling_frame = None self.selected_type_button = None self.selected_memory_type = None self.selected_cuda_pointers = None self.error_message_label = None self.get_all_supported_types() self.build_popup_dialog() def get_all_supported_types(self): """Get a list of types that can be added to the script node""" # "any" types need to be manually resolved by script writers, # "transform" types are marked for deprecation in USD, so we don't want to support them self.all_supported_types = [ attr_type for attr_type in ogn.supported_attribute_type_names() if attr_type != "any" and attr_type[:9] != "transform" ] self.all_displayed_types = self.all_supported_types def build_scrolling_frame(self): """Build the scrolling frame underneath the search bar""" def _on_type_selected(button): if self.selected_type_button is not None: self.selected_type_button.checked = False self.selected_type_button = button self.selected_type_button.checked = True self.scrolling_frame.clear() with self.scrolling_frame: with ui.VStack(): for displayed_type in self.all_displayed_types: button = ui.Button(displayed_type, height=20) button.set_clicked_fn(partial(_on_type_selected, button)) def build_popup_dialog(self): def filter_types_by_prefix(text): """Callback executed when the user presses enter in the search bar""" if text is None: self.all_displayed_types = self.all_supported_types else: text = text[0] self.all_displayed_types = [ displayed_type for displayed_type in self.all_supported_types if displayed_type[: len(text)] == text ] self.build_scrolling_frame() self.selected_type_button = None def on_create_new_attribute(): """Callback executed when the user creates a new dynamic attribute""" if not self.attribute_name_field.model.get_value_as_string(): self.error_message_label.text = "Error: Attribute name cannot be empty!" return if not self.attribute_name_field.model.get_value_as_string()[0].isalpha(): self.error_message_label.text = "Error: The first character of attribute name must be a letter!" return if ( not self.input_port_button.checked and not self.output_port_button.checked and not self.state_port_button.checked ): self.error_message_label.text = "Error: You must select a port type!" return if self.selected_type_button is None: self.error_message_label.text = "Error: You must select a type for the new attribute!" return attrib_name = self.attribute_name_field.model.get_value_as_string() attrib_port_type = og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT if self.output_port_button.checked: attrib_port_type = og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT elif self.state_port_button.checked: attrib_port_type = og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE attrib_type_name = self.selected_type_button.text attrib_type = og.AttributeType.type_from_ogn_type_name(attrib_type_name) self.create_new_attribute_callback( attrib_name, attrib_port_type, attrib_type, self.selected_memory_type, self.selected_cuda_pointers ) self.window.visible = False def on_cancel_clicked(): self.window.visible = False window_flags = ui.WINDOW_FLAGS_NO_RESIZE self.window = ui.Window( "Create Attribute", width=400, height=0, padding_x=15, padding_y=15, flags=window_flags, ) input_field_width = ui.Percent(60) with self.window.frame: with ui.VStack(spacing=10): # Attribute name string field with ui.HStack(height=0): ui.Label("Attribute Name: ") self.attribute_name_field = ui.StringField(width=input_field_width, height=20) # Attribute port type radio button with ui.HStack(height=0): ui.Label("Attribute Port Type: ") self.port_type_radio_collection = ui.RadioCollection() with ui.HStack(width=input_field_width, height=20): self.input_port_button = ui.RadioButton( text="input", radio_collection=self.port_type_radio_collection ) self.output_port_button = ui.RadioButton( text="output", radio_collection=self.port_type_radio_collection ) self.state_port_button = ui.RadioButton( text="state", radio_collection=self.port_type_radio_collection ) # Attribute type search bar with ui.HStack(height=0): ui.Label("Attribute Type: ", alignment=ui.Alignment.LEFT_TOP) with ui.VStack(width=input_field_width): # Search bar try: from omni.kit.widget.searchfield import SearchField SearchField(show_tokens=False, on_search_fn=filter_types_by_prefix) except ImportError: # skip the search bar if the module cannot be imported pass # List of attribute types self.scrolling_frame = ui.ScrollingFrame( height=150, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, style_type_name_override="TreeView", ) self.build_scrolling_frame() # TODO: Uncomment this block when dynamic attributes support memory types # # Attribute memory type combo box # with ui.HStack(height=0): # ui.Label("Attribute Memory Type: ") # memory_type_option_names = ["CPU", "CUDA", "Any"] # memory_type_option_values = [ogn.MemoryTypeValues.CPU, # ogn.MemoryTypeValues.CUDA, ogn.MemoryTypeValues.ANY] # self.selected_memory_type = ogn.MemoryTypeValues.CPU # def _on_memory_type_selected(new_memory_type): # self.selected_memory_type = new_memory_type # ui.ComboBox( # ComboBoxModel( # memory_type_option_names, # memory_type_option_values, # self.selected_memory_type, # _on_memory_type_selected, # ), # width=input_field_width, # ) # # CUDA pointers combo box # with ui.HStack(height=0): # ui.Label("CUDA Pointers: ") # cuda_pointers_option_names = ["CUDA", "CPU"] # cuda_pointers_option_values = [ogn.CudaPointerValues.CUDA, ogn.CudaPointerValues.CPU] # self.selected_cuda_pointers = ogn.CudaPointerValues.CUDA # def _on_cuda_pointers_selected(new_cuda_pointers): # self.selected_cuda_pointers = new_cuda_pointers # ui.ComboBox( # ComboBoxModel( # cuda_pointers_option_names, # cuda_pointers_option_values, # self.selected_cuda_pointers, # _on_cuda_pointers_selected, # ), # width=input_field_width, # ) # OK button to confirm selection with ui.HStack(height=0): ui.Spacer() with ui.HStack(width=input_field_width, height=20): ui.Button( "OK", clicked_fn=on_create_new_attribute, ) ui.Button( "Cancel", clicked_fn=on_cancel_clicked, ) # Some empty space to display error messages if needed self.error_message_label = ui.Label( " ", height=20, alignment=ui.Alignment.H_CENTER, style={"color": 0xFF0000FF} ) class ScriptTextbox(TextEditor): def __init__(self, script_model: OmniGraphAttributeModel): super().__init__( syntax=TextEditor.Syntax.PYTHON, style={"font": str(FONTS_PATH.joinpath("DejaVuSansMono.ttf"))}, text=script_model.get_value_as_string(), ) self.script_model = script_model self.script_model_callback_id = self.script_model.add_value_changed_fn(self._on_script_model_changed) self.set_edited_fn(self._on_script_edited) def _on_script_edited(self, text_changed: bool): if text_changed: # Don't trigger the model changed callback when script is edited self.script_model.remove_value_changed_fn(self.script_model_callback_id) # Remove the newline that TextEditor adds or else it will accumulate self.script_model.set_value(self.text[:-1]) self.script_model_callback_id = self.script_model.add_value_changed_fn(self._on_script_model_changed) def _on_script_model_changed(self, script_model): self.text = script_model.get_value_as_string() # noqa: PLW0201 class CustomLayout: def __init__(self, compute_node_widget): self._remove_attribute_menu = None self._code_snippets_menu = None self.enable = True self.compute_node_widget = compute_node_widget self.node_prim_path = self.compute_node_widget._payload[-1] self.node = og.Controller.node(self.node_prim_path) self.script_textbox_widget = None self.script_textbox_model = None self.script_textbox_resizer = None self.script_path_widget = None self.script_selector_window = None self.external_script_editor = None self.external_script_editor_ui_name = None self.DEFAULT_SCRIPT = "" self.EXAMPLE_SCRIPTS = [] self.EXAMPLE_SCRIPTS_TITLE = [] self.add_attribute_button = None self.remove_attribute_button = None self.code_snippets_button = None self.reset_button = None self.initialized_model = None self.EXISTING_ATTRIBUTES = [ "inputs:script", "inputs:scriptPath", "inputs:usePath", "inputs:execIn", "outputs:execOut", "state:omni_initialized", "node:type", "node:typeVersion", ] # Retrieve the example scripts cur_file_path = os.path.abspath(os.path.dirname(__file__)) example_scripts_path = os.path.join(cur_file_path, "..", "scriptnode_example_scripts.py") with open(example_scripts_path, "r", encoding="utf-8") as file: file_contents = file.read().split("# # # DELIMITER # # #") for script in file_contents[1:]: script = script.strip() script_lines = script.splitlines(keepends=True) script_title_line = script_lines[0] script_title = script_title_line.strip()[9:-1] script_content = "".join(script_lines[1:]) if script_title == "Default Script": self.DEFAULT_SCRIPT = script_content else: self.EXAMPLE_SCRIPTS.append(script_content) self.EXAMPLE_SCRIPTS_TITLE.append(script_title) # Determine the external script editor # Check the settings editor = carb.settings.get_settings().get("/app/editor") if not editor: # Check the environment variable EDITOR editor = os.environ.get("EDITOR", None) if not editor: # Default to VSCode editor = "code" # Remove quotes from the editor name if present if editor[0] == '"' and editor[-1] == '"': editor = editor[1:-1] # Get the user-friendly editor name editor_ui_name = editor if editor == "code": editor_ui_name = "VSCode" elif editor == "notepad": editor_ui_name = "Notepad" # Check that the editor exists and is executable if not (os.path.isfile(editor) and os.access(editor, os.X_OK)): try: editor = shutil.which(editor) except shutil.Error: editor = None if not editor: # Resort to notepad on windows and gedit on linux if os.name == "nt": editor = "notepad" editor_ui_name = "Notepad" else: editor = "gedit" editor_ui_name = "gedit" self.external_script_editor = editor self.external_script_editor_ui_name = editor_ui_name def retrieve_existing_attributes(self): """Retrieve the dynamic attributes that already exist on the node""" all_attributes = self.node.get_attributes() inputs = [ attrib for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ] outputs = [ attrib for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ] states = [ attrib for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE ] return (all_attributes, inputs, outputs, states) def _on_script_textbox_resizer_dragged(self, offset_y: ui.Length): self.script_textbox_resizer.offset_y = max(offset_y.value, 50) def _script_textbox_build_fn(self, *args): """Build the textbox used to input custom scripts""" self.script_textbox_model = OmniGraphAttributeModel( self.compute_node_widget.stage, [self.node_prim_path.AppendProperty("inputs:script")], False, {} ) if self.script_textbox_model.get_value_as_string() == "": self.script_textbox_model.set_value(self.DEFAULT_SCRIPT) with ui.VStack(): with ui.HStack(): UsdPropertiesWidgetBuilder._create_label( # noqa: PLW0212 "Script", {}, {"style": {"alignment": ui.Alignment.RIGHT_TOP}} ) ui.Spacer(width=7) with ui.ZStack(): with ui.VStack(): self.script_textbox_widget = ScriptTextbox(self.script_textbox_model) # Disable editing if the script value comes from an upstream connection if og.Controller.attribute("inputs:script", self.node).get_upstream_connection_count() > 0: self.script_textbox_widget.read_only = True # noqa: PLW0201 ui.Spacer(height=12) # Add a draggable bar below the script textbox to resize it self.script_textbox_resizer = ui.Placer(offset_y=200, draggable=True, drag_axis=ui.Axis.Y) self.script_textbox_resizer.set_offset_y_changed_fn(self._on_script_textbox_resizer_dragged) with self.script_textbox_resizer: script_textbox_resizer_style = { ":hovered": {"background_color": 0xFFB0703B}, ":pressed": {"background_color": 0xFFB0703B}, } with ui.ZStack(height=12): ui.Rectangle(style=script_textbox_resizer_style) with ui.HStack(): ui.Spacer() ui.Label("V", width=0) ui.Spacer() ui.Spacer(height=5) with ui.HStack(): ui.Spacer() self._code_snippets_button_build_fn() def _code_snippets_button_build_fn(self, *args): """Build the code snippets button used to show example scripts""" def _code_snippets_menu_build_fn(): """Build the code snippets popup menu""" self._code_snippets_menu = ui.Menu("Code Snippets") with self._code_snippets_menu: for example_script_title, example_script in zip(self.EXAMPLE_SCRIPTS_TITLE, self.EXAMPLE_SCRIPTS): ui.MenuItem( example_script_title, triggered_fn=partial(self.script_textbox_model.set_value, example_script) ) self._code_snippets_menu.show() self.code_snippets_button = ui.Button("Code Snippets", width=135, clicked_fn=_code_snippets_menu_build_fn) def _on_initialized_changed(self, initialized_model): self.reset_button.enabled = initialized_model.as_bool def _reset_button_build_fn(self, *args): """Build button that calls the cleanup script and forces the setup script to be called on next compute""" def do_reset(): """Call the user-defined cleanup function and set state:omni_initialized to false""" OgnScriptNodeDatabase.NODE_TYPE_CLASS._try_cleanup(self.node) # noqa: PLW0212 self.reset_button.enabled = False def get_initialized(): """Get the value of state:omni_initialized""" initialized_attr = og.Controller.attribute("state:omni_initialized", self.node) return og.Controller.get(initialized_attr) self.reset_button = ui.Button( "Reset", width=135, clicked_fn=do_reset, enabled=get_initialized(), tooltip="Execute the setup script again on the next compute", ) self.initialized_model = OmniGraphAttributeModel( self.compute_node_widget.stage, [self.node_prim_path.AppendProperty("state:omni_initialized")], False, {} ) self.initialized_model.add_value_changed_fn(self._on_initialized_changed) def _add_attribute_button_build_fn(self, *args): def create_dynamic_attribute(attrib_name, attrib_port_type, attrib_type, attrib_memory_type, cuda_pointers): if ( attrib_name == "execOut" and attrib_port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT and attrib_type.get_ogn_type_name() == "execution" ): # Unhide outputs:execOut instead of creating it self.node.get_attribute("outputs:execOut").set_metadata(ogn.MetadataKeys.HIDDEN, None) return new_attribute = og.Controller.create_attribute(self.node, attrib_name, attrib_type, attrib_port_type) if new_attribute is None: return if attrib_type.get_type_name() == "prim" and attrib_port_type in ( og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE, ): # For bundle output/state attribs, the default UI name contains the port type, so we set it here instead def make_ui_name(attrib_name: str): parts_out = [] words = attrib_name.replace("_", " ").split(" ") for word in words: # noqa: PLR1702 if word.islower() or word.isupper(): parts_out += [word] else: # Mixed case. # Lower-case followed by upper-case breaks between them. E.g. 'usdPrim' -> 'usd Prim' # Upper-case followed by lower-case breaks before them. E.g: 'USDPrim' -> 'USD Prim' # Combined example: abcDEFgHi -> abc DE Fg Hi sub_word = "" uppers = "" for c in word: if c.isupper(): if not uppers: # noqa: SIM102 if sub_word: parts_out += [sub_word] sub_word = "" uppers += c else: if len(uppers) > 1: parts_out += [uppers[:-1]] sub_word += uppers[-1:] + c uppers = "" if sub_word: parts_out += [sub_word] elif uppers: parts_out += [uppers] # Title-case any words which are all lower case. parts_out = [part.title() if part.islower() else part for part in parts_out] return " ".join(parts_out) new_attribute.set_metadata(ogn.MetadataKeys.UI_NAME, make_ui_name(attrib_name)) # TODO: Uncomment this when dynamic attributes support memory types # new_attribute.set_metadata(ogn.MetadataKeys.MEMORY_TYPE, attrib_memory_type) # new_attribute.set_metadata(ogn.MetadataKeys.CUDA_POINTERS, cuda_pointers) self.compute_node_widget.rebuild_window() def on_click_add(): CreateAttributePopupDialog(create_dynamic_attribute) self.add_attribute_button = ui.Button("Add +", width=100, clicked_fn=on_click_add) def _remove_attribute_button_build_fn(self, *args): def remove_dynamic_attribute(attrib): if attrib.get_name() == "outputs:execOut": # Hide outputs:execOut instead of removing it og.Controller.disconnect_all(("outputs:execOut", self.node)) attrib.set_metadata(ogn.MetadataKeys.HIDDEN, "1") return success = og.Controller.remove_attribute(attrib) if not success: return self.compute_node_widget.rebuild_window() def _remove_attribute_menu_build_fn(): self._remove_attribute_menu = ui.Menu("Remove Attribute") (all_attributes, _, _, _) = self.retrieve_existing_attributes() with self._remove_attribute_menu: for attrib in all_attributes: name = attrib.get_name() # These attributes were not created by user so they are not deletable, # except for outputs:execOut, which can be hidden if not already hidden if not attrib.is_dynamic() and not ( name == "outputs:execOut" and attrib.get_metadata(ogn.MetadataKeys.HIDDEN) != "1" ): continue # Any attribute without the inputs:/outputs:/state: prefix were not created by user so they are # not deletable, except for bundle output and state attributes, which are delimited with '_' if ( name[:7] != "inputs:" and name[:8] != "outputs:" and name[:6] != "state:" and not ( attrib.get_type_name() == "bundle" and (name[:8] == "outputs_" or name[:6] == "state_") ) ): continue # Otherwise we should allow user to delete this attribute ui.MenuItem(name, triggered_fn=partial(remove_dynamic_attribute, attrib)) self._remove_attribute_menu.show() self.remove_attribute_button = ui.Button("Remove -", width=100, clicked_fn=_remove_attribute_menu_build_fn) def _special_control_build_fn(self, *args): with ui.HStack(): self._add_attribute_button_build_fn() ui.Spacer(width=8) self._remove_attribute_button_build_fn() def _get_absolute_script_path(self): """Get the possibly relative path in inputs:scriptPath as an aboslute path""" script_path = og.Controller.get(og.Controller.attribute("inputs:scriptPath", self.node)) edit_layer = self.compute_node_widget.stage.GetEditTarget().GetLayer() if not edit_layer.anonymous: script_path = omni.client.combine_urls(edit_layer.realPath, script_path).replace("\\", "/") return script_path def _show_script_selector_window(self): """Create and show the file browser window which is used to select the script for inputs:scriptPath""" try: from omni.kit.window.filepicker import FilePickerDialog except ImportError: # Do nothing if the module cannot be imported return def _on_click_okay(filename: str, dirname: str): # Get the relative path relative to the edit layer chosen_file = omni.client.combine_urls(dirname, filename) edit_layer = self.compute_node_widget.stage.GetEditTarget().GetLayer() if not edit_layer.anonymous: chosen_file = omni.client.make_relative_url(edit_layer.realPath, chosen_file) chosen_file = chosen_file.replace("\\", "/") # Set the value of inputs:scriptPath self.script_path_widget.set_value(chosen_file) self.script_selector_window.hide() def _on_click_cancel(filename: str, dirname: str): self.script_selector_window.hide() self.script_selector_window = FilePickerDialog( "Select a Python script", click_apply_handler=_on_click_okay, click_cancel_handler=_on_click_cancel, allow_multi_selection=False, file_extension_options=[("*.py", "Python scripts (*.py)")], ) self.script_selector_window.show(self._get_absolute_script_path()) def _launch_external_script_editor(self): """Launch an external editor targeting the path specified in inputs:scriptPath""" # Use cmd in case the editor is a bat or cmd file call_command = ["cmd", "/c"] if os.name == "nt" else [] call_command.append(self.external_script_editor) call_command.append(self._get_absolute_script_path()) subprocess.Popen(call_command) # noqa: PLR1732 def _script_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *args): """Build the attribute label, textbox, browse button, and edit button for inputs:scriptPath""" self.script_path_widget = UsdPropertiesWidgetBuilder._string_builder( # noqa: PLW0212 self.compute_node_widget.stage, ui_prop.prop_name, ui_prop.property_type, ui_prop.metadata, [self.node_prim_path], {"style": {"alignment": ui.Alignment.RIGHT_TOP}}, ) ui.Spacer(width=5) ui.Button( image_url=str(ICONS_PATH.joinpath("folder_open.svg")), width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, clicked_fn=self._show_script_selector_window, tooltip="Browse...", ) ui.Spacer(width=5) ui.Button( image_url=str(ICONS_PATH.joinpath("external_link.svg")), width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, clicked_fn=self._launch_external_script_editor, tooltip=f"Open in {self.external_script_editor_ui_name}\n(set the preferred editor from the '/app/editor' setting)", ) def apply(self, props): """Called by compute_node_widget to apply UI when selection changes""" def find_prop(name): try: return next((p for p in props if p.prop_name == name)) except StopIteration: return None frame = CustomLayoutFrame(hide_extra=True) (_, inputs, outputs, states) = self.retrieve_existing_attributes() with frame: with ui.HStack(): ui.Spacer() self._reset_button_build_fn() with CustomLayoutGroup("Add and Remove Attributes"): CustomLayoutProperty(None, None, self._special_control_build_fn) with CustomLayoutGroup("Inputs"): prop = find_prop("inputs:script") CustomLayoutProperty(prop.prop_name, "Script", partial(self._script_textbox_build_fn, prop)) prop = find_prop("inputs:usePath") CustomLayoutProperty(prop.prop_name, "Use Path") prop = find_prop("inputs:scriptPath") CustomLayoutProperty(prop.prop_name, "Script Path", partial(self._script_path_build_fn, prop)) for input_attrib in inputs: attrib_name = input_attrib.get_name() if input_attrib.is_dynamic(): prop = find_prop(attrib_name) if prop is not None: CustomLayoutProperty(prop.prop_name, attrib_name[7:]) with CustomLayoutGroup("Outputs"): for output_attrib in outputs: attrib_name = output_attrib.get_name() if output_attrib.is_dynamic(): prop = find_prop(attrib_name) if prop is not None: CustomLayoutProperty(prop.prop_name, attrib_name[8:]) with CustomLayoutGroup("State"): for state_attrib in states: attrib_name = state_attrib.get_name() if state_attrib.is_dynamic(): prop = find_prop(attrib_name) if prop is not None: CustomLayoutProperty(prop.prop_name, attrib_name) return frame.apply(props)
34,537
Python
44.325459
128
0.559603
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/tests/test_scriptnode_ui.py
"""Tests for scriptnode which exercise the UI""" import os import tempfile import omni.graph.core as og import omni.graph.ui._impl.omnigraph_attribute_base as ogab import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_for_window from omni.ui.tests.test_base import OmniUiTest class TestScriptNodeUI(OmniUiTest): """ Tests for scriptnode which exercise the UI """ TEST_GRAPH_PATH = "/World/TestGraph" # Before running each test async def setUp(self): await super().setUp() # Ensure we have a clean stage for the test await omni.usd.get_context().new_stage_async() # Give OG a chance to set up on the first stage update await omni.kit.app.get_app().next_update_async() self._temp_file_path = None # A temporary file we need to clean up import omni.kit.window.property as p self._w = p.get_window() # The OG attribute-base UI should refresh every frame ogab.AUTO_REFRESH_PERIOD = 0 async def tearDown(self): if (self._temp_file_path is not None) and os.path.isfile(self._temp_file_path): os.remove(self._temp_file_path) # Close the stage to avoid dangling references to the graph. (OM-84680) await omni.usd.get_context().close_stage_async() await super().tearDown() async def test_interaction(self): """ Exercise the controls on the custom template """ usd_context = omni.usd.get_context() keys = og.Controller.Keys controller = og.Controller() (_, (script_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ScriptNode", "omni.graph.scriptnode.ScriptNode"), ], keys.SET_VALUES: [("ScriptNode.inputs:usePath", False), ("ScriptNode.inputs:scriptPath", "")], }, ) ok = script_node.create_attribute( "outputs:out", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) self.assertTrue(ok) attr_out = script_node.get_attribute("outputs:out") attr_script = script_node.get_attribute("inputs:script") # Select the node. usd_context.get_selection().set_selected_prim_paths([script_node.get_prim_path()], True) # Wait for property panel to converge await ui_test.human_delay(5) # Set the inline script back to empty attr_script.set("") reset_button = ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_reset'") script_path_model = ui_test.find("Property//Frame/**/.identifier=='sdf_asset_inputs:scriptPath'") use_path_toggle = ui_test.find("Property//Frame/**/.identifier=='bool_inputs:usePath'") snippets_button = ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_snippets'") # write out a script and change the file path await use_path_toggle.click() await ui_test.human_delay(5) # NamedTemporaryFile is not very nice on Windows, need to ensure we close before node tries to read with tempfile.NamedTemporaryFile(mode="w+t", encoding="utf-8", delete=False) as tf: self._temp_file_path = tf.name tf.write( """ def compute(db: og.Database): db.outputs.out = 42 return True""" ) await script_path_model.input(self._temp_file_path) await omni.kit.app.get_app().next_update_async() # verify it has now computed, because `input` above will trigger the widget `end_edit` self.assertEqual(attr_out.get(), 42) # change the script, verify it doesn't take effect until reset is pressed with open(self._temp_file_path, mode="w+t", encoding="utf-8") as tf: tf.write( """ def compute(db: og.Database): db.outputs.out = 1000 return True""" ) await omni.kit.app.get_app().next_update_async() # verify it has now computed self.assertEqual(attr_out.get(), 42) await reset_button.click() await ui_test.human_delay(1) # Verify the script now computed with the new script self.assertEqual(attr_out.get(), 1000) # Switch it back to inline script attr_script.set( """ def compute(db): db.outputs.out = 1 """ ) await ui_test.human_delay(1) await use_path_toggle.click() await reset_button.click() await ui_test.human_delay(1) self.assertEqual(attr_out.get(), 1) # Switch it back to external script await use_path_toggle.click() await ui_test.human_delay(1) self.assertEqual(attr_out.get(), 1000) # Now add an attribute using the dialog await ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_add_attribute'").click() await wait_for_window("Add Attribute") await ui_test.find("Add Attribute//Frame/**/StringField[*].identifier=='_scriptnode_name'").input("test_attrib") # Find the only string field without an identifier, that is the search field await ui_test.find("Add Attribute//Frame/**/StringField[*].identifier!='_scriptnode_name'").input("int64") await ui_test.find("Add Attribute//Frame/**/Button[*].text=='int64'").click() await ui_test.human_delay(1) await ui_test.find("Add Attribute//Frame/**/Button[*].identifier=='_scriptnode_add_ok'").click() await ui_test.human_delay(3) # Check the attribute was actually added attr_test = script_node.get_attribute("inputs:test_attrib") self.assertEqual(attr_test.get_resolved_type(), og.Type(og.BaseDataType.INT64, 1, 0)) # Show the remove menu, remove the item we added await ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_remove_attribute'").click() await ui_test.human_delay(1) menu = ui.Menu.get_current() test_item = next((item for item in ui.Inspector.get_children(menu) if item.text == "inputs:test_attrib")) test_item.call_triggered_fn() await ui_test.human_delay(1) self.assertFalse(script_node.get_attribute_exists("inputs:test_attrib")) menu.hide() # Clear the current script attr_script.set("") await ui_test.human_delay(1) # Show the snippets menu await snippets_button.click() await ui_test.human_delay(1) menu = ui.Menu.get_current() # select the first one, verify the script was changed ui.Inspector.get_children(menu)[0].call_triggered_fn() await ui_test.human_delay(1) self.assertTrue("def compute(db)" in attr_script.get())
6,930
Python
37.082417
120
0.623665
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.scriptnode as ogs from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphScriptNodeApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests"] async def test_api(self): _check_module_api_consistency(ogs, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(ogs.tests, is_test_module=True) # noqa: PLW0212 async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents(ogs.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
825
Python
44.888886
107
0.653333
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/tests/__init__.py
"""There is no public API to this module.""" __all__ = [] scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
201
Python
32.666661
112
0.716418
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/tests/test_scriptnode.py
"""Basic tests of the action graph""" import omni.graph.core as og import omni.graph.core.tests as ogts import omni.usd from pxr import OmniGraphSchemaTools # ====================================================================== class TestScriptNode(ogts.OmniGraphTestCase): """Tests for Script Node""" # ---------------------------------------------------------------------- async def test_script_node_instancing(self): """Test that the script node works in instanced graphs""" # Test with multiple graph evaluator types. evaluator_names = ["push", "dirty_push", "execution"] for evaluator_name in evaluator_names: # Create the graph with the ScriptNode. graph_path = "/World/Graph" (_, (_, script_node), _, _) = og.Controller.edit( {"graph_path": graph_path, "evaluator_name": evaluator_name}, { og.Controller.Keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], og.Controller.Keys.CONNECT: ("OnTick.outputs:tick", "Script.inputs:execIn"), og.Controller.Keys.SET_VALUES: ("OnTick.inputs:onlyPlayback", False), }, ) # Add some attributes to the script node. og.Controller.create_attribute( script_node, "inputs:step", og.Type(og.BaseDataType.INT, 1, 0, og.AttributeRole.NONE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, ) og.Controller.create_attribute( script_node, "outputs:counter", og.Type(og.BaseDataType.INT, 1, 0, og.AttributeRole.NONE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) og.Controller.create_attribute( script_node, "outputs:graph_target_name", og.Type(og.BaseDataType.TOKEN, 1, 0, og.AttributeRole.NONE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, ) script_node.get_attribute("inputs:step").set(2) # Simple script inside ScriptNode that increments a counter and writes out # the graph target name. script_string = "def compute(db):\n" script_string += " db.outputs.counter += db.inputs.step\n" script_string += " db.outputs.graph_target_name = db.abi_context.get_graph_target()\n" # Instance the graph 5 times. num_prims = 5 prim_paths = [None] * num_prims stage = omni.usd.get_context().get_stage() for i in range(num_prims): prim_paths[i] = f"/World/Prim_{i}" stage.DefinePrim(prim_paths[i]) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_paths[i], graph_path) # Set the script attribute on the script node in the instanced graph. script_node.get_attribute("inputs:script").set(script_string) # Evaluate and validate results. await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() for i in range(num_prims): if evaluator_name == "dirty_push": self.assertEqual(script_node.get_attribute("outputs:counter").get(instance=i), 2) else: self.assertEqual(script_node.get_attribute("outputs:counter").get(instance=i), 6) self.assertEqual(script_node.get_attribute("outputs:graph_target_name").get(instance=i), prim_paths[i]) # Delete the graph and prims. for i in range(num_prims): stage.RemovePrim(prim_paths[i]) stage.RemovePrim(graph_path) await omni.kit.app.get_app().next_update_async() # ---------------------------------------------------------------------- async def test_compute_creates_dynamic_attrib_legacy(self): """Test that the script node can create dynamic attribs within its compute""" controller = og.Controller() keys = og.Controller.Keys script = """ attribute_exists = db.node.get_attribute_exists("inputs:multiplier") if attribute_exists != True: db.node.create_attribute("inputs:multiplier", og.Type(og.BaseDataType.DOUBLE)) db.outputs.data = db.inputs.data * db.inputs.multiplier""" (graph, (on_impulse_node, script_node), _, _,) = controller.edit( {"graph_path": "/TestGraph", "evaluator_name": "execution"}, { keys.CREATE_NODES: [ ("OnImpulse", "omni.graph.action.OnImpulseEvent"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.CONNECT: ("OnImpulse.outputs:execOut", "Script.inputs:execIn"), keys.SET_VALUES: [ ("OnImpulse.inputs:onlyPlayback", False), ("Script.inputs:script", script), ], }, ) script_node.create_attribute( "inputs:data", og.Type(og.BaseDataType.DOUBLE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ) script_node.create_attribute( "outputs:data", og.Type(og.BaseDataType.DOUBLE), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:data", 42), ("Script.outputs:data", 0), ], }, ) await controller.evaluate(graph) # trigger graph evaluation once so the compute runs og.Controller.set(controller.attribute("state:enableImpulse", on_impulse_node), True) await controller.evaluate(graph) val = og.Controller.get(controller.attribute("outputs:data", script_node)) self.assertEqual(val, 0) # set value on the dynamic attrib and check compute og.Controller.set(controller.attribute("inputs:multiplier", script_node), 2.0) og.Controller.set(controller.attribute("state:enableImpulse", on_impulse_node), True) await controller.evaluate(graph) val = og.Controller.get(controller.attribute("outputs:data", script_node)) self.assertEqual(val, 84) # ---------------------------------------------------------------------- async def test_use_loaded_dynamic_attrib(self): """Test that the script node can use a dynamic attrib loaded from USD""" await ogts.load_test_file("TestScriptNode.usda", use_caller_subdirectory=True) controller = og.Controller() val = og.Controller.get(controller.attribute("outputs:data", "/World/ActionGraph/script_node")) self.assertEqual(val, 0) # trigger graph evaluation once so the compute runs og.Controller.set(controller.attribute("state:enableImpulse", "/World/ActionGraph/on_impulse_event"), True) await controller.evaluate() val = og.Controller.get(controller.attribute("outputs:data", "/World/ActionGraph/script_node")) self.assertEqual(val, 84) as_int = og.Controller.get(controller.attribute("outputs:asInt", "/World/ActionGraph/script_node")) as_float = og.Controller.get(controller.attribute("state:asFloat", "/World/ActionGraph/script_node")) self.assertEqual(as_int, 84) self.assertEqual(as_float, 84.0) # ---------------------------------------------------------------------- async def test_simple_scripts_legacy(self): """Test that some simple scripts work as intended""" controller = og.Controller() keys = og.Controller.Keys (graph, (script_node,), _, _,) = controller.edit( "/TestGraph", { keys.CREATE_NODES: ("Script", "omni.graph.scriptnode.ScriptNode"), }, ) script_node.create_attribute( "inputs:my_input_attribute", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ) script_node.create_attribute( "outputs:my_output_attribute", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) output_controller = og.Controller(og.Controller.attribute("outputs:my_output_attribute", script_node)) controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", "db.outputs.my_output_attribute = 123"), }, ) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 123) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:script", "db.outputs.my_output_attribute = -db.inputs.my_input_attribute"), ("Script.inputs:my_input_attribute", 1234), ("Script.state:omni_initialized", False), ] }, ) await controller.evaluate(graph) self.assertEqual(output_controller.get(), -1234) controller.edit( "/TestGraph", { keys.SET_VALUES: [ ( "Script.inputs:script", "db.outputs.my_output_attribute = db.inputs.my_input_attribute * db.inputs.my_input_attribute", ), ("Script.inputs:my_input_attribute", -12), ("Script.state:omni_initialized", False), ] }, ) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 144) # ---------------------------------------------------------------------- async def test_internal_state_keeps_persistent_info_legacy(self): """Test that the script node can keep persistent information using internal state""" script = """ if (not hasattr(db.internal_state, 'num1')): db.internal_state.num1 = 0 db.internal_state.num2 = 1 else: sum = db.internal_state.num1 + db.internal_state.num2 db.internal_state.num1 = db.internal_state.num2 db.internal_state.num2 = sum db.outputs.data = db.internal_state.num1""" controller = og.Controller() keys = og.Controller.Keys (graph, (_, script_node), _, _,) = controller.edit( {"graph_path": "/TestGraph", "evaluator_name": "execution"}, { keys.CREATE_NODES: [ ("OnTick", "omni.graph.action.OnTick"), ("Script", "omni.graph.scriptnode.ScriptNode"), ], keys.CONNECT: ("OnTick.outputs:tick", "Script.inputs:execIn"), keys.SET_VALUES: [ ("OnTick.inputs:onlyPlayback", False), ("Script.inputs:script", script), ], }, ) script_node.create_attribute( "outputs:data", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) output_controller = og.Controller(og.Controller.attribute("outputs:data", script_node)) # Check that the script node produces the Fibonacci numbers await controller.evaluate(graph) self.assertEqual(output_controller.get(), 0) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 1) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 1) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 2) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 3) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 5) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 8) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 13) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 21) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 34) await controller.evaluate(graph) self.assertEqual(output_controller.get(), 55) # ---------------------------------------------------------------------- async def test_script_global_scope(self): """Test that variables, functions, and classes defined outside of the user-defined callbacks are visible""" controller = og.Controller() keys = og.Controller.Keys (graph, (script_node,), _, _,) = controller.edit( "/TestGraph", { keys.CREATE_NODES: ("Script", "omni.graph.scriptnode.ScriptNode"), }, ) script_node.create_attribute( "outputs:output_a", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) script_node.create_attribute( "outputs:output_b", og.Type(og.BaseDataType.TOKEN), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) output_a_controller = og.Controller(og.Controller.attribute("outputs:output_a", script_node)) output_b_controller = og.Controller(og.Controller.attribute("outputs:output_b", script_node)) script_test_constants = """ MY_CONSTANT_A = 123 MY_CONSTANT_B = 'foo' def setup(db): db.outputs.output_a = MY_CONSTANT_A def compute(db): db.outputs.output_b = MY_CONSTANT_B""" controller.edit( "/TestGraph", { keys.SET_VALUES: ("Script.inputs:script", script_test_constants), }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 123) self.assertEqual(output_b_controller.get(), "foo") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "foo") script_test_variables = """ my_variable = 123 def setup(db): global my_variable my_variable = 234 db.outputs.output_a = my_variable def compute(db): global my_variable db.outputs.output_b = f'{my_variable}' my_variable += 1""" controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:script", script_test_variables), ("Script.state:omni_initialized", False), ], }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 234) self.assertEqual(output_b_controller.get(), "234") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "235") script_test_functions = """ def my_function_a(): return 123 my_variable_b = 'foo' def my_function_b(): return my_variable_b def setup(db): db.outputs.output_a = my_function_a() def compute(db): db.outputs.output_b = my_function_b() global my_variable_b my_variable_b = 'bar'""" controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:script", script_test_functions), ("Script.state:omni_initialized", False), ] }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 123) self.assertEqual(output_b_controller.get(), "foo") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "bar") script_test_imports = """ import inspect import math my_lambda = lambda x: x code_len = len(inspect.getsource(my_lambda)) def setup(db): db.outputs.output_a = code_len def compute(db): db.outputs.output_b = f'{math.pi:.2f}'""" controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:script", script_test_imports), ("Script.state:omni_initialized", False), ] }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 24) self.assertEqual(output_b_controller.get(), "3.14") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "3.14") script_test_classes = """ class MyClass: def __init__(self, value): self.value = value def get_value(self): return self.value @staticmethod def get_num(): return 123 my_variable = MyClass('foo') def setup(db): db.outputs.output_a = MyClass.get_num() def compute(db): db.outputs.output_b = my_variable.get_value() my_variable.value = 'bar'""" controller.edit( "/TestGraph", { keys.SET_VALUES: [ ("Script.inputs:script", script_test_classes), ("Script.state:omni_initialized", False), ] }, ) await controller.evaluate(graph) self.assertEqual(output_a_controller.get(), 123) self.assertEqual(output_b_controller.get(), "foo") await controller.evaluate(graph) self.assertEqual(output_b_controller.get(), "bar")
17,556
Python
37.929046
120
0.5626
omniverse-code/kit/exts/omni.graph.scriptnode/docs/CHANGELOG.md
# CHANGELOG ## [0.10.0] - 2023-01-23 ### Changed - opt-in is enabled by /app/omni.graph.scriptnode/enable_opt_in - modify the dialog to appear after loading - disable all graphs until opt-in is verified ## [0.9.3] - 2022-10-16 ### Changed - opt-in mechanism reads from remote file instead of app setting ## [0.9.2] - 2022-10-08 ### Changed - Fix for font size in 104 ## [0.9.1] - 2022-10-07 ### Fixed - Font size of code editor ## [0.9.0] - 2022-09-29 ### Added - User-defined callbacks 'compute', 'setup', and 'cleanup', along with a reset button - Ability to "remove" outputs:execOut by hiding it - Support for warp, inspect, ast, and other modules by saving inputs:script to a temp file - Script path input for reading scripts from files - Improved textbox UI for inputs:script using omni.kit.widget.text_editor ## [0.8.0] - 2022-09-14 ### Added - opt-in mechanism on attach. Controlled by /app/omni.graph.scriptnode/enable_opt_in and /app/omni.graph.scriptnode/opt_in ## [0.7.2] - 2022-08-23 ### Changed - Removed security warnings. We don't want to advertise the problem. ## [0.7.1] - 2022-08-09 ### Fixed - Applied formatting to all of the Python files ## [0.7.0] - 2022-08-09 ### Changed - Removed omni.graph.action dependency ## [0.6.0] - 2022-07-07 ### Changed - Refactored imports from omni.graph.tools to get the new locations ## [0.5.0] - 2022-03-30 ### Changed - Give each example code snippet a title, which will be displayed when you click on the Code Snippets button - Change title of Add Attribute window from "Create a new attribute..." to "Create Attribute" - Disable resizing of the Add Attribute dialog - Add Cancel button to the Add Attribute dialog - Make the Add Attribute/Remove Attribute/Code Snippets buttons left aligned - Allow users to add Script Node to push graphs by removing the graph:action category ### Fixed - Fixed a bug where Remove Attribute button allows you to remove the node-as-bundle output attribute ## [0.4.1] - 2022-03-10 ### Fixed - Made property panel only display non-None props - Renamed some variables to better match what they are doing ## [0.4.0] - 2022-02-28 ### Added - Gave user the ability to add and remove dynamic attribute from the script node via UI - Also allowed user to select a fixed, static type for their new attributes - Created a popup dialog window for the Add Attribute button, which has a search bar for the attribute types ### Removed - Removed the existing inputs:data and outputs:data attributes which are of type "any" ## [0.3.0] - 2022-02-18 ### Added - A default script with a simple example, and some comments explaining how to use the script node - Three example scripts to illustrate the various functionalities of the script node ### Changed - Move the script node widget into a template - Move the multiline editor to the top of property window, so that we don't have two multiline editors - Compile the script before executing it - Catch errors and log the errors ## [0.2.0] - 2022-02-15 ### Added - icon and category ## [0.1.2] - 2021-10-19 ### Modified - Restructured plugin files as part of repo relocation ## [0.1.1] - 2021-06-30 ### Modified - Change bundle input to Any type ## [0.1.0] - 2021-06-30 ### Added - Initial publish
3,239
Markdown
31.4
122
0.724298
omniverse-code/kit/exts/omni.graph.scriptnode/docs/README.md
# OgnScriptNode [omni.graph.scriptnode] Provides the Script Node for use in OmniGraph graphs. This node allows custom python code to be executed when the node is computed. The python code is compiled and computed when the graph runs using the embedded interpreter in Kit. The python script itself is stored as an attribute value in the USD where the graph is stored. Dynamic inputs and output attributes can be added to the node to provide inputs and outputs from the script.
478
Markdown
94.799981
435
0.807531
omniverse-code/kit/exts/omni.graph.scriptnode/docs/index.rst
OmniGraph Script Node ##################### Provides the Script Node for use in OmniGraph graphs. This node allows custom python code to be executed when the node is computed. The python code is compiled and computed when the graph runs using the embedded interpreter in Kit. The python script itself is stored as an attribute value in the USD where the graph is stored. Dynamic inputs and output attributes can be added to the node to provide inputs and outputs from the script. .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension**: omni.graph.scriptnode,**Documentation Generated**: |today| .. toctree:: :maxdepth: 1 CHANGELOG
662
reStructuredText
37.999998
435
0.732628
omniverse-code/kit/exts/omni.graph.scriptnode/docs/Overview.md
# OmniGraph Script Node Provides the Script Node for use in OmniGraph graphs. This node allows custom python code to be executed when the node is computed. The python code is compiled and computed when the graph runs using the embedded interpreter in Kit. The python script itself is stored as an attribute value in the USD where the graph is stored. Dynamic inputs and output attributes can be added to the node to provide inputs and outputs from the script. ```{csv-table} **Extension**: omni.graph.scriptnode,**Documentation Generated**: {sub-ref}`today` ```
564
Markdown
69.624991
435
0.783688
omniverse-code/kit/exts/omni.rtx.window.settings/PACKAGE-LICENSES/omni.rtx.window.settings-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.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.rtx.window.settings/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.6.2" # 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 = "RTX Settings Window" description="Core extension for renderers which use the carbonite settings framework " # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Rendering" # Keywords for the extension keywords = ["kit", "rtx", "rendering"] # 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" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" [dependencies] "omni.kit.commands" = {} "omni.ui" = {} "omni.kit.window.filepicker" = {} "omni.usd" = {} "omni.kit.widget.prompt" = {} "omni.kit.widget.settings" = {} "omni.kit.menu.utils" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.rtx.window.settings"
1,640
TOML
33.914893
118
0.737195
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rtx_settings_widget.py
from pathlib import Path from typing import Callable, Dict, List import os import traceback import sys import omni.ui as ui import carb import omni.kit.commands import omni.kit.app from omni.kit.widget.settings import get_style, get_ui_style_name from .rtx_settings_stack import RTXSettingsStack from omni.kit.window.file_importer import get_file_importer from omni.kit.window.file_exporter import get_file_exporter from .usd_serializer import USDSettingsSerialiser CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons") RENDERER_CHANGED_EVT = carb.events.type_from_string( "render_settings.renderer.CHANGED" ) RENDERER_EVT_PAYLOAD_KEY = "renderer" # global renderers/stacks so any widget can use them registered_renderers: Dict[str, List[str]] = {} registered_stacks: Dict[str, Callable] = {} class RTXSettingsWidget(): engine_to_mode = { 'iray': '/rtx/iray/rendermode', 'rtx': '/rtx/rendermode', 'pxr': '/pxr/rendermode' } rendermode_to_settings = { 'RaytracedLighting': 'Real-Time', 'PathTracing': 'Interactive (Path Tracing)', 'iray': 'Accurate (Iray)' } def __init__(self, frame): style = None use_default_style = carb.settings.get_settings().get_as_bool("/persistent/app/window/useDefaultStyle") or False if not use_default_style: style = get_style() ui_style_name = get_ui_style_name() if ui_style_name == "NvidiaLight": option_icon_style = {"image_url": f"{ICON_PATH}/NvidiaLight/options.svg","color": 0xFF535354} else: option_icon_style = {"image_url": f"{ICON_PATH}/NvidiaDark/options.svg","color": 0xFF8A8777} self._option_icon_style = option_icon_style self._style = style self._frame = frame self._stack_frame = None self._renderer_model = None self._visible_stacks: Dict[str, RTXSettingsStack] = {} self.picker_open = False self._folder_exist_popup = None self._event_stream = omni.kit.app.get_app().get_message_bus_event_stream() def renderChangedSubscription(path): return omni.kit.app.SettingChangeSubscription(path, self.__active_renderer_changed) # If the viewport renderer is changed, update render settings to reflect it self._renderer_subscriptions = [renderChangedSubscription("/renderer/active")] # Also need to watch all engine-mode changes for _, path in self.engine_to_mode.items(): self._renderer_subscriptions.append(renderChangedSubscription(path)) # menu self._options_menu = ui.Menu("Options") with self._options_menu: ui.MenuItem("Load Settings", triggered_fn=self.load_from_usd) ui.MenuItem("Save Settings", triggered_fn=self.save_to_usd) ui.MenuItem("Reset Settings", triggered_fn=self.restore_all_settings) def destroy(self) -> None: """ """ for k, s in self._visible_stacks.items(): s.destroy() self._renderer_subscriptions = None def get_current_viewport_renderer(self, hydra_engine: str = None, render_mode: str = None): settings = carb.settings.get_settings() if hydra_engine is None: hydra_engine = settings.get('/renderer/active') if hydra_engine in self.engine_to_mode: if render_mode is None: render_mode = settings.get(self.engine_to_mode[hydra_engine]) # XXX: Delegate this to the render-settings-extension instance # (i.e.) let omni.hydra.pxr map HdStormRenderPlugin => Storm return self.rendermode_to_settings.get(render_mode, render_mode) return None def set_render_settings_to_viewport_renderer(self, hydra_engine: str = None, render_mode: str = None): renderer = self.get_current_viewport_renderer(hydra_engine, render_mode) if not renderer or not self._renderer_model: return renderer_list = list(registered_renderers.keys()) if renderer in renderer_list: index = renderer_list.index(renderer) self._renderer_model.get_item_value_model().set_value(index) def __active_renderer_changed(self, *args, **kwargs): self.set_render_settings_to_viewport_renderer() def build_ui(self) -> None: if not self._frame: return if self._style is not None: self._frame.set_style(self._style) self._frame.clear() with self._frame: with ui.VStack(spacing=5): ui.Spacer(height=5) with ui.HStack(height=20): ui.Spacer(width=20) ui.Label("Renderer", name="RenderLabel", width=80) renderer_list = list(registered_renderers.keys()) index = 0 current_renderer = self.get_current_viewport_renderer() #Set to the default renderer if it's there if current_renderer in renderer_list: index = renderer_list.index(current_renderer) self._renderer_model = ui.ComboBox(index, *renderer_list, name="renderer_choice").model self._renderer_model.add_item_changed_fn(lambda i, m: self.renderer_item_changed()) # build_stacks()) ui.Spacer(width=10) ui.Button( style=self._option_icon_style, width=20, clicked_fn=lambda: self._options_menu.show() ) ui.Spacer(width=10) ui.Spacer(height=0) self._stack_frame = ui.VStack() def build_stacks(self): """ "stacks" are the tabs in the Render Settings UI that contain groups of settings They can be reused amongst different renderers. This method is called every time the renderer is changed """ if not self._stack_frame: return for k, s in self._visible_stacks.items(): s.destroy() self._stack_frame.clear() if not registered_renderers: return current_renderer = self.get_current_renderer() current_renderer_stacks = registered_renderers.get(current_renderer, None) if not current_renderer_stacks: print("RTXSettingsWidget: renderer Not supported") return with self._stack_frame: # Build the stacks ("Common", "Ray Tracing" etc) self._collection = ui.RadioCollection() with ui.HStack(height=30): ui.Spacer(width=15) for name in current_renderer_stacks: ui.RadioButton( text=name, radio_collection=self._collection, clicked_fn=lambda p=name: self.show_stack_from_name(p), ) ui.Spacer(width=10) ui.Spacer(height=7) with ui.ScrollingFrame(): # stack pages with ui.ZStack(): for name in current_renderer_stacks: stack_class = registered_stacks.get(name, None) if not stack_class: continue self._visible_stacks[name] = stack_class() ui.Spacer(height=1) # Assume we want to show the middle stack - the renderer specific one if len(current_renderer_stacks) > 1 and self.have_stack(current_renderer_stacks[1]): self.show_stack_from_name(current_renderer_stacks[1]) def register_renderer(self, name: str, stacks_list: List[str]) -> None: registered_renderers[name] = stacks_list def register_stack(self, name: str, stack_class: Callable) -> None: registered_stacks[name] = stack_class self.build_stacks() def unregister_renderer(self, name): if name in registered_renderers: del registered_renderers[name] def unregister_stack(self, name): if name in registered_stacks: del registered_stacks[name] def set_current_renderer(self, renderer_name: str) -> None: """ sets the current renderer and updates the UI model """ if renderer_name in registered_renderers.keys(): renderer_names = list(registered_renderers.keys()) for cnt, r in enumerate(renderer_names): if r == renderer_name: self._renderer_model.get_item_value_model().set_value(cnt) def get_registered_renderers(self): return list(registered_renderers.keys()) def get_current_renderer(self) -> str: return list(registered_renderers.keys())[self._renderer_model.get_item_value_model().as_int] def have_stack(self, name: str) -> None: return name in self._visible_stacks.keys() def show_stack_from_name(self, name: str) -> None: if name not in self._visible_stacks.keys(): print("RTXSettingsWidget: Error No Key of that Name ") return for _, stack in self._visible_stacks.items(): stack.set_visible(False) # work out which index the named stack is in the current UI stack_index = 0 current_renderer_stack_names = registered_renderers.get(self.get_current_renderer(), None) for cnt, curr_stack_name in enumerate(current_renderer_stack_names): if curr_stack_name == name: stack_index = cnt self._visible_stacks[name].set_visible(True) self._collection.model.set_value(stack_index) def get_current_stack(self) -> str: for name, stack in self._visible_stacks.items(): if stack.get_visible(): return name return "" def get_renderer_stacks(self, renderer_name): return registered_renderers.get(renderer_name, None) def restore_all_settings(btn_widget): omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx") def save_to_usd(self): def save_handler(filename: str, dirname: str, extension: str = "", selections: List[str] = []): final_path = f"{dirname}{filename}{extension}" try: if os.path.exists(final_path): self._show_folder_exist_popup(final_path) else: serialiser = USDSettingsSerialiser() serialiser.save_to_usd(final_path) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback) file_exporter = get_file_exporter() if file_exporter: file_exporter.show_window( title="Save USD File", export_button_label="Save", export_handler=save_handler, file_postfix_options=["settings"]) def load_from_usd(self): def load_handler(filename: str, dirname: str, selections: List[str]): final_path = f"{dirname}{filename}" try: serialiser = USDSettingsSerialiser() serialiser.load_from_usd(final_path) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback) file_importer = get_file_importer() if file_importer: file_importer.show_window( title="Load USD File", import_button_label="Load", import_handler=load_handler, file_postfix_options=["settings"]) def renderer_item_changed(self) -> None: try: self._emit_renderer_changed_event() finally: self.build_stacks() def _emit_renderer_changed_event(self) -> None: payload = {RENDERER_EVT_PAYLOAD_KEY: self.get_current_renderer()} self._event_stream.push( event_type=RENDERER_CHANGED_EVT, payload=payload )
12,147
Python
37.811501
122
0.595044
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rtx_settings_window.py
import omni.ui as ui import carb from typing import Callable, Dict, List from .rtx_settings_widget import RTXSettingsWidget class RTXSettingsWindow: def __init__(self): self._window = None if carb.settings.get_settings().get("/exts/omni.rtx.window.settings/startup/autoCreateWindow"): self._window = ui.Window("Render Settings", dockPreference=ui.DockPreference.RIGHT_TOP) self._window.deferred_dock_in("Stage", ui.DockPolicy.TARGET_WINDOW_IS_ACTIVE) self._settings_widget = RTXSettingsWidget(self._window.frame) self._build_ui() else: self._settings_widget = RTXSettingsWidget(None) def register_renderer(self, name: str, stacks_list: List[str]) -> None: return self._settings_widget.register_renderer(name, stacks_list) def get_registered_renderers(self): return self._settings_widget.get_registered_renderers() def get_current_renderer(self): return self._settings_widget.get_current_renderer() def set_current_renderer(self, renderer_name: str) -> None: return self._settings_widget.set_current_renderer(renderer_name) def register_stack(self, name: str, stack_class: Callable) -> None: return self._settings_widget.register_stack(name, stack_class) def show_stack_from_name(self, name: str) -> None: return self._settings_widget.show_stack_from_name(name) def get_renderer_stacks(self, renderer_name): return self._settings_widget.get_renderer_stacks(renderer_name) def get_current_stack(self) -> str: return self._settings_widget.get_current_stack() def unregister_renderer(self, name): return self._settings_widget.unregister_renderer(name) def unregister_stack(self, name): return self._settings_widget.unregister_stack(name) def set_visibility_changed_listener(self, listener): if self._window: self._window.set_visibility_changed_fn(listener) def set_render_settings_to_viewport_renderer(self, *args, **kwargs): return self._settings_widget.set_render_settings_to_viewport_renderer(*args, **kwargs) def set_visible(self, value: bool) -> None: if self._window: self._window.visible = value def destroy(self) -> None: """ """ self._settings_widget.destroy() self._settings_widget = None self._window = None def _build_ui(self) -> None: """ """ self._settings_widget.build_ui() def _build_stacks(self) -> None: """ "stacks" are the tabs in the Render Settings UI that contain groups of settings They can be reused amongst different renderers. This method is called every time the renderer is changed """ self._settings_widget.build_stacks()
2,843
Python
35.935064
103
0.663384
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/commands.py
import carb import carb.dictionary import carb.settings import omni.kit.commands from omni.rtx.window.settings.rendersettingsdefaults import RenderSettingsDefaults from omni.rtx.window.settings import RendererSettingsFactory class RestoreDefaultRenderSettingCommand(omni.kit.commands.Command): """ Restore default setting for Renderer **Command**. Args: path: Path to the setting to be reset. """ def __init__(self, path: str): self._path = path self._settings = carb.settings.get_settings() def do(self): self._value = self._settings.get(self._path) RenderSettingsDefaults().reset_setting_to_default(self._path) def undo(self): self._settings.set(self._path, self._value) class RestoreDefaultRenderSettingSectionCommand(omni.kit.commands.Command): """ Restore default settings for the whole section **Command**. Args: path: Path to the settings section to be reset. """ def __init__(self, path: str): self._path = path self._settings = carb.settings.get_settings() def do(self): self._section_copy = self._settings.create_dictionary_from_settings(self._path) RenderSettingsDefaults().reset_setting_to_default(self._path) def undo(self): self._settings.destroy_item(self._path) self._settings.update(self._path, self._section_copy, "", carb.dictionary.UpdateAction.OVERWRITE) class SetCurrentRenderer(omni.kit.commands.Command): """ Sets the current renderer Args: renderer_name: name of the renderer """ def __init__(self, renderer_name: str): self._renderer = renderer_name self._prev_renderer = None def do(self): self._prev_renderer = RendererSettingsFactory.get_current_renderer() RendererSettingsFactory.set_current_renderer(self._renderer) def undo(self): if self._prev_renderer: RendererSettingsFactory.set_current_renderer(self._prev_renderer) class SetCurrentStack(omni.kit.commands.Command): """ Sets the current stack (needs to be one which is valid for the current renderer) Args: stack_name: name of the stack """ def __init__(self, stack_name: str): self._stack = stack_name self._prev_stack = None def do(self): self._prev_stack = RendererSettingsFactory.get_current_stack() RendererSettingsFactory.set_current_stack(self._stack) def undo(self): if self._prev_stack: RendererSettingsFactory.set_current_stack(self._prev_stack) omni.kit.commands.register_all_commands_in_module(__name__)
2,664
Python
28.285714
105
0.671547
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rtx_settings_stack.py
import omni.ui as ui from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame class RTXSettingsStack: """ define a stack of Settings Widgets """ def __init__(self) -> None: self._stack: ui.VStack = None def set_visible(self, value: bool): if self._stack: self._stack.visible = value def get_visible(self) -> bool: if self._stack: return self._stack.visible return False def destroy(self): if self in SettingsCollectionFrame.parents: mySettingsFrames = SettingsCollectionFrame.parents[self] for frame in mySettingsFrames: frame.destroy() del SettingsCollectionFrame.parents[self]
751
Python
27.923076
86
0.637816
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/extension.py
from functools import partial from typing import Callable, List import omni.ext import omni.kit.ui import omni.ui as ui import carb.settings from .rtx_settings_window import RTXSettingsWindow class RTXSettingsExtension(omni.ext.IExt): """The entry point for the extension""" WINDOW_NAME = "Render Settings" def __init__(self) -> None: super().__init__() RendererSettingsFactory.render_settings_extension_instance = self self._settings_window = RTXSettingsWindow() self._settings_window.set_visibility_changed_listener(self._visiblity_changed_fn) def on_startup(self): ui.Workspace.set_show_window_fn(self.WINDOW_NAME, partial(self.show_window, None)) window_menu = carb.settings.get_settings().get("exts/omni.rtx.window.settings/window_menu") self._menu_path = f"{window_menu}/{self.WINDOW_NAME}" editor_menu = omni.kit.ui.get_editor_menu() self._menu = None if editor_menu: self._menu = editor_menu.add_item( f"{self._menu_path}", self.show_window, priority=21, toggle=True, value=True, ) ui.Workspace.show_window(self.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._settings_window: self._settings_window.set_visibility_changed_listener(None) self._settings_window.destroy() self._settings_window = None RendererSettingsFactory.render_settings_extension_instance = None ui.Workspace.set_show_window_fn(RTXSettingsExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(f"{self._menu_path}", value) def _visiblity_changed_fn(self, visible): if visible: self._set_menu(visible) else: self.show_window(None, False) def show_window(self, menu, value): self._set_menu(value) self._settings_window.set_visible(value) def show_render_settings(self, hd_engine: str, render_mode: str, show_window: bool = True): self._settings_window.set_render_settings_to_viewport_renderer(hd_engine, render_mode) if not show_window: return self.show_window(self._menu_path, True) async def focus_async(): window = ui.Workspace.get_window(self.WINDOW_NAME) if window: window.focus() import asyncio asyncio.ensure_future(focus_async()) class RendererSettingsFactory: """ entry point for other extensions to register renderers and settings stacks """ render_settings_extension_instance = None @classmethod def _get_render_settings_extension(cls): if not cls.render_settings_extension_instance: cls.render_settings_extension_instance = RTXSettingsExtension() return cls.render_settings_extension_instance @classmethod def register_renderer(cls, name: str, stacks_list: List[str]): rs = cls._get_render_settings_extension() rs._settings_window.register_renderer(name, stacks_list) rs._settings_window._build_ui() @classmethod def unregister_renderer(cls, name): rs = cls._get_render_settings_extension() rs._settings_window.unregister_renderer(name) @classmethod def build_ui(cls): """ This method may be called by either: + a dependent extension that's shutting down or starting up + when the app is shutting down We want to distinguish between them """ if omni.kit.app.get_app().is_running(): rs = cls._get_render_settings_extension() rs._settings_window._build_ui() rs._settings_window._build_stacks() @classmethod def set_current_renderer(cls, renderer_name: str) -> None: """ sets the current stack and updates the UI model """ rs = cls._get_render_settings_extension() rs._settings_window.set_current_renderer(renderer_name) @classmethod def get_current_renderer(cls): rs = cls._get_render_settings_extension() return rs._settings_window.get_current_renderer() @classmethod def register_stack(cls, name: str, stack_class: Callable): rs = cls._get_render_settings_extension() rs._settings_window.register_stack(name, stack_class) @classmethod def unregister_stack(cls, name) -> None: rs = cls._get_render_settings_extension() rs._settings_window.unregister_stack(name) @classmethod def set_current_stack(cls, name) -> None: """ sets the current stack and updates the UI model """ rs = cls._get_render_settings_extension() rs._settings_window.show_stack_from_name(name) @classmethod def get_current_stack(cls) -> str: rs = cls._get_render_settings_extension() return rs._settings_window.get_current_stack() @classmethod def get_registered_renderers(cls) -> list: rs = cls._get_render_settings_extension() return rs._settings_window.get_registered_renderers() @classmethod def get_renderer_stacks(cls, renderer) -> list: rs = cls._get_render_settings_extension() return rs._settings_window.get_renderer_stacks(renderer)
5,518
Python
32.858896
99
0.633563
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/__init__.py
from .extension import * from .commands import *
50
Python
11.749997
24
0.74
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/usd_serializer.py
import carb import os.path import omni.kit.commands import rtx.settings from omni.rtx.window.settings.rendersettingsdefaults import RenderSettingsDefaults from pxr import Usd, Gf class USDSettingsSerialiser: """ Save and Load RTX settings to/from USD @TOOD: get rtx:fog:fogColor working """ def __init__(self): self._settings = carb.settings.get_settings() def iterate_settings(self, usd_dict, d, path_string=""): for k, v in d.items(): key_string = path_string + "/" + str(k) if isinstance(v, dict): self.iterate_settings(usd_dict, v, path_string=path_string + "/" + k) else: default_flags = self._settings.get(rtx.settings.get_associated_setting_flags_path(key_string)) if default_flags is None or (default_flags & rtx.settings.SETTING_FLAGS_TRANSIENT): continue val = self._settings.get(key_string) default_key = RenderSettingsDefaults._get_associated_defaults_path(key_string) default_val = self._settings.get(default_key) usd_str = key_string.replace("/", ":") if default_val != val: # TODO: This code looks fairly dodgy if isinstance(val, list) and len(val) in [3, 4]: if isinstance(val[0], float): usd_dict[usd_str[1:]] = Gf.Vec3f(val) else: usd_dict[usd_str[1:]] = Gf.Vec3d(val) else: usd_dict[usd_str[1:]] = val def save_to_usd(self, stage_file_path=""): if os.path.exists(stage_file_path): curr_stage = Usd.Stage.Open(stage_file_path) # Save or overwrite else: curr_stage = Usd.Stage.CreateNew(stage_file_path) rootLayer = curr_stage.GetRootLayer() customLayerData = rootLayer.customLayerData settings_dict = self._settings.get_settings_dictionary("/rtx") usdDict = {} self.iterate_settings(usdDict, settings_dict.get_dict(), "/rtx") customLayerData["renderSettings"] = usdDict rootLayer.customLayerData = customLayerData curr_stage.Save() carb.log_info(f"saved {stage_file_path} {len(usdDict)} settings") def load_from_usd(self, stage_file_path=""): currStage = Usd.Stage.Open(stage_file_path) rootLayer = currStage.GetRootLayer() customLayerData = rootLayer.customLayerData renderSettingsVtVal = customLayerData["renderSettings"] loaded_count = 0 if renderSettingsVtVal: omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx") for k, v in renderSettingsVtVal.items(): rtx_key = k.replace(":", "/") default_flags = self._settings.get(rtx.settings.get_associated_setting_flags_path(rtx_key)) if default_flags is None or (default_flags & rtx.settings.SETTING_FLAGS_TRANSIENT): continue if isinstance(v, Gf.Vec3f) or isinstance(v, Gf.Vec3d): self._settings.set("/" + rtx_key, [v[0], v[1], v[2]]) else: self._settings.set(rtx_key, v) loaded_count += 1 carb.log_info(f"loaded {stage_file_path} {loaded_count} settings")
3,440
Python
39.011627
110
0.575291
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rendersettingsdefaults.py
import carb.dictionary import carb.settings class SettingsDefaultHandler: def __init__(self): self._settings = carb.settings.get_settings() self._dictionary = carb.dictionary.get_dictionary() def _get_sanitized_path(self, path): if path is not None and len(path) > 0 and path[0] == "/": return path[1:] return "" def get_type(self, path): settings_dict = self._settings.get_settings_dictionary("") path = self._get_sanitized_path(path) item = self._dictionary.get_item(settings_dict, path) item_type = self._dictionary.get_item_type(item) return item_type def does_exist(self, path): return self.get_type(path) != carb.dictionary.ItemType.COUNT def set_default(self, path): item_type = self.get_type(path) if item_type == carb.dictionary.ItemType.FLOAT: self._settings.set(path, 0.0) elif item_type == carb.dictionary.ItemType.INT: self._settings.set(path, 0) elif item_type == carb.dictionary.ItemType.BOOL: self._settings.set(path, False) else: print("SettingsDefaultHandler unrecognised type", item_type) class RenderSettingsDefaults: """ This is a partial python implementation of Kit/rendering/include/rtx/utils/Settings.h which only provides sufficient functionality for getting/resetting default values by """ _settings = carb.settings.get_settings() _settings_dict = _settings.get_settings_dictionary("") @classmethod def _get_associated_defaults_path(cls, settings_path: str): bits = settings_path.split("/") if len(bits) == 2: return "/" + bits[1] + "-defaults" else: return "/" + bits[1] + "-defaults/" + "/".join(bits[2:]) def reset_setting_to_default(self, settings_path: str): defaultsPathStorage = self._get_associated_defaults_path(settings_path) srcItem = self._settings.get_settings_dictionary(defaultsPathStorage) # If we can't find a dictionary item, it's likely to be leaf node/scalar value if not srcItem: defaultValue = self._settings.get(defaultsPathStorage) self._settings.set(settings_path, defaultValue) # It's a dictionary Item.. just update the whole section elif isinstance(srcItem, carb.dictionary._dictionary.Item): self._settings.update(settings_path, srcItem, "", carb.dictionary.UpdateAction.OVERWRITE) else: print("reset_setting_to_default: unknown type")
2,597
Python
37.205882
101
0.640739
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/settings_collection_frame.py
from typing import Union, Any import carb.settings from omni.kit.widget.settings import SettingType import omni.kit.commands import omni.rtx.window.settings import omni.ui as ui from omni.kit.widget.settings import create_setting_widget, create_setting_widget_combo from omni.kit.widget.settings import SettingsWidgetBuilder, SettingsSearchableCombo import rtx.settings class FrameSessionState: """ stre any state we would like to persist across the Session """ frame_state = {} @classmethod def get_state(cls, frame_id: str, key: str) -> Any: if frame_id not in cls.frame_state: return None if key not in cls.frame_state[frame_id]: return None return cls.frame_state[frame_id][key] @classmethod def has_state(cls, frame_id: str, key: str) -> bool: if frame_id not in cls.frame_state: return False if key not in cls.frame_state[frame_id]: return False return True @classmethod def set_state(cls, frame_id: str, key: str, value: Any) -> None: if frame_id not in cls.frame_state: cls.frame_state[frame_id] = {} cls.frame_state[frame_id][key] = value class SettingsCollectionFrame: parents = {} # For later deletion of parents def __init__(self, frame_label: str, collapsed=True, parent=None) -> None: self.classNamespace = ".".join([self.__class__.__module__, self.__class__.__name__]) self._settings = carb.settings.get_settings() self._collapsedState = collapsed self._setting_path = self._frame_setting_path() if FrameSessionState.has_state(self.classNamespace, "collapsed"): self._collapsedState = FrameSessionState.get_state(self.classNamespace, "collapsed") self._widget = ui.CollapsableFrame( frame_label, height=0, build_fn=self.build_ui, build_header_fn=self.build_header, skip_draw_when_clipped=True, collapsed=self._collapsedState, ) self._widget.identifier = frame_label self._widget.set_collapsed_changed_fn(self.on_collapsed_changed) self.sub_widgets = [] self.sub_models = [] # store a reference to our parent to allow later destruction if parent: if parent in self.parents: self.parents[parent].append(self) else: self.parents[parent] = [self] def _frame_setting_path(self): """ subclass can overtide that to get a checkbox in the frame """ return None def destroy(self): """ We need to explicitly destroy widgets/models - there's usually a number of circular ref between model and Widget which can be difficult to track down and keep widgets alive after the Frame is rebuilt """ for w in self.sub_models: w.destroy() self.sub_models = [] for w in self.sub_widgets: del w self.sub_widgets = [] self._widget.set_collapsed_changed_fn(None) self._widget.set_build_fn(None) self._widget.clear() self._widget = None def _on_change(self, *_): self._rebuild() def on_collapsed_changed(self, collapsed): FrameSessionState.set_state(self.classNamespace, "collapsed", collapsed) def build_header(self, collapsed, title): triangle_alignment = ui.Alignment.RIGHT_CENTER triangle_width = 4 triangle_height = 6 if not collapsed: triangle_alignment = ui.Alignment.CENTER_BOTTOM triangle_width = 7 triangle_height = 5 with ui.HStack(height=20, style={"HStack": {"margin_height": 5}}): ui.Spacer(width=5) with ui.VStack(width=15): ui.Spacer() ui.Triangle( alignment=triangle_alignment, name="title", width=triangle_width, height=triangle_height, # Using the style defined in style.py" # style={"background_color": 0xFFCCCCCC}, ) ui.Spacer() ui.Label(title, name="title", width=0) ui.Spacer() if self._setting_path: with ui.VStack(width=20, content_clipping=True): ui.Spacer(height=4) widget, model = create_setting_widget(self._setting_path, SettingType.BOOL) if widget and model: widget.set_tooltip("Check to Activate") def expand_frame(model, frame): if frame: frame.collapsed = not model.get_value_as_bool() model.add_value_changed_fn(lambda m, frame=self._widget: expand_frame(m, frame)) ui.Spacer() def build_ui(self): with ui.VStack(height=0, spacing=5, style={"VStack": {"margin_width": 10}}): ui.Spacer(height=5) self._build_ui() ui.Spacer(height=5) def _rebuild(self): if self._widget: self._widget.rebuild() def _restore_defaults(self, path: str): omni.kit.commands.execute("RestoreDefaultSetting", path=path) def _add_setting( self, setting_type, name: str, path: str, range_from=0, range_to=0, speed=1, has_reset=True, tooltip="", hard_range=False, cleartext_path=None ): the_stack = ui.HStack(skip_draw_when_clipped=True) the_stack.identifier = "HStack_" + name.replace(" ","_") with the_stack: SettingsWidgetBuilder._create_label(name, path if not cleartext_path else cleartext_path, tooltip) widget, model = create_setting_widget(path, setting_type, range_from, range_to, speed, hard_range=hard_range) self.sub_widgets.append(widget) self.sub_models.append(model) if has_reset: button = SettingsWidgetBuilder._build_reset_button(path) model.set_reset_button(button) return widget def _add_internal_setting( self, setting_type, name: str, path: str, range_from=0, range_to=0, speed=1, has_reset=True, tooltip="" ): internal_path = rtx.settings.get_internal_setting_string(path) return self._add_setting(setting_type, name, internal_path, range_from, range_to, speed, has_reset, tooltip, cleartext_path=path) def _add_setting_combo( self, name: str, path: str, items: Union[list, dict], callback=None, has_reset=True, tooltip="", cleartext_path=None ): the_stack = ui.HStack(skip_draw_when_clipped=True) the_stack.identifier = "HStack_" + name.replace(" ","_") with the_stack: SettingsWidgetBuilder._create_label(name, path if not cleartext_path else cleartext_path, tooltip) widget, model = create_setting_widget_combo(path, items) self.sub_widgets.append(widget) self.sub_models.append(model) if has_reset: button = SettingsWidgetBuilder._build_reset_button(path) model.set_reset_button(button) return widget def _add_setting_searchable_combo(self, name: str, path: str, items: dict, default_item: str, tooltip=""): with ui.HStack(): SettingsWidgetBuilder._create_label(name, path, tooltip) widget = SettingsSearchableCombo(path, items, default_item) self.sub_widgets.append(widget) def _add_internal_setting_combo( self, name: str, path: str, items: Union[list, dict], callback=None, has_reset=True, tooltip="" ): internal_path = rtx.settings.get_internal_setting_string(path) return self._add_setting_combo(name, internal_path, items, callback, has_reset, tooltip, cleartext_path=path) def _get_internal_setting(self, path: str): return self._settings.get(rtx.settings.get_internal_setting_string(path)) def _subscribe_to_internal_setting_change(self, path: str): omni.kit.app.SettingChangeSubscription(rtx.settings.get_internal_setting_string(path), self._on_change) def _build_ui(self): """ virtual function that will be called in the Collapsable frame """ pass
8,412
Python
37.240909
124
0.601046
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/test_defaults.py
import omni.kit.test import carb.settings from omni.rtx.window.settings.rendersettingsdefaults import RenderSettingsDefaults from omni.rtx.window.settings import commands from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows import omni.kit.commands class TestDefaults(omni.kit.test.AsyncTestCase): async def setUp(self): super().setUp() await arrange_windows() await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() settings = carb.settings.get_settings() # Am not sure what sets the default normally.. settings.set("/rtx-defaults/pathtracing/maxBounces", 4) async def test_rtx_setting(self): """ Test single item /rtx/pathtracing/maxBounces """ settings = carb.settings.get_settings() blah = RenderSettingsDefaults() blah.reset_setting_to_default("/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 12) currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 12) blah.reset_setting_to_default("/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) async def test_rtx_setting_section(self): """ Test section /rtx/pathtracing """ settings = carb.settings.get_settings() blah = RenderSettingsDefaults() blah.reset_setting_to_default("/rtx/pathtracing") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 12) currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 12) blah.reset_setting_to_default("/rtx/pathtracing") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) async def test_rtx_settings_all(self): """ Test entire section /rtx """ settings = carb.settings.get_settings() blah = RenderSettingsDefaults() blah.reset_setting_to_default("/rtx") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 12) currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 12) blah.reset_setting_to_default("/rtx") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) async def test_commands(self): settings = carb.settings.get_settings() settings.set("/rtx/pathtracing/maxBounces", 15) omni.kit.commands.execute("RestoreDefaultRenderSetting", path="/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 16) omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4)
3,336
Python
40.19753
121
0.668465
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/test_serialiser.py
import os import tempfile import omni.kit.test import carb.settings import omni.kit.commands from omni.rtx.window.settings import RendererSettingsFactory from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows class TestSerialiser(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() # After running each test async def tearDown(self): pass async def test_serialiser(self): from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser with tempfile.TemporaryDirectory() as tempdir: file = os.path.join(tempdir, "test.usd") serialiser = USDSettingsSerialiser() serialiser.save_to_usd(file) serialiser.load_from_usd(file)
925
Python
30.931033
121
0.724324
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/__init__.py
from .test_defaults import * from .test_ui import * from .test_serialiser import *
83
Python
19.999995
30
0.746988
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/test_ui.py
import omni.kit.test import carb.settings import omni.kit.commands from omni.rtx.window.settings import RendererSettingsFactory import random class SettingsIterator(object): def __init__(self, output_dict): self._settings = carb.settings.get_settings() self._output_dict = output_dict def iterate(self, settings_dict, path_string=""): """ iterate rtx settings and get a flat dictionary back we can work with """ for k, v in settings_dict.items(): key_string = path_string + "/" + str(k) if isinstance(v, dict): self.iterate(v, path_string=path_string + "/" + k) else: val = self._settings.get(key_string) self._output_dict[key_string] = val class TestSetRenderSettings: @classmethod def generate_change_setting_command(cls, setting_path, current_value): if isinstance(current_value, bool): bool_choice = random.choice([True, False]) omni.kit.commands.execute("ChangeSetting", path=setting_path, value=bool_choice) elif isinstance(current_value, float): float_choice = 0.0 if abs(current_value) < 0.1: float_choice = random.uniform(0, 100) else: # TODO: We can make a better guess if we have more info about the range float_choice = random.uniform(current_value / 2, current_value * 2) omni.kit.commands.execute("ChangeSetting", path=setting_path, value=float_choice) elif isinstance(current_value, int): int_choice = 0 if current_value == 0: int_choice = random.choice(range(0, 100)) else: int_range = range(int(current_value / 2), int(current_value * 2)) if len(int_range) > 1: int_choice = random.choice(range(int(current_value / 2), int(current_value * 2))) omni.kit.commands.execute("ChangeSetting", path=setting_path, value=int_choice) elif isinstance(current_value, list): # TODO: add pass elif isinstance(current_value, str): # TODO: Without a bit more info (e.g from the "add_setting" calls in the UI) # it's hard to know what to do with strings - they could be filepaths/assets, # combo box elements etc. We should probably look at extracting that data pass else: print("this type is not supported") async def run_test_render_settings_ui(self, settings_path: str): """ we're really not attempting to assert anything here, just cycle through a bunch of commands and hope it doesn't segfault """ settings = carb.settings.get_settings() # if the renderers have initialised properly, this should have items settings_dict = settings.get_settings_dictionary(settings_path) output_dict = {} settingsIt = SettingsIterator(output_dict) settingsIt.iterate(settings_dict.get_dict(), settings_path) setting_list = list(output_dict) # TODO: add in ResetAllSettings and other commands # Set some settings, switch renderer, set stack, and do the same again several times for x in range(0, 20): for y in range(0, 10): key = random.choice(setting_list) self.generate_change_setting_command(key, output_dict[key]) await omni.kit.app.get_app().next_update_async() renderers = RendererSettingsFactory.get_registered_renderers() if renderers: renderer_choice = random.choice(RendererSettingsFactory.get_registered_renderers()) omni.kit.commands.execute("SetCurrentRenderer", renderer_name=renderer_choice) await omni.kit.app.get_app().next_update_async() for y in range(0, 10): key = random.choice(setting_list) self.generate_change_setting_command(key, output_dict[key]) await omni.kit.app.get_app().next_update_async() stacks = RendererSettingsFactory.get_renderer_stacks(renderer_choice) if stacks: stack_choice = random.choice(stacks) omni.kit.commands.execute("SetCurrentStack", stack_name=stack_choice) await omni.kit.app.get_app().next_update_async() # If we have get a crash, we should be able to replay it outside the unit testing framework # with commands... history = omni.kit.undo.get_history().values() for cmd in history: continue # print (cmd) class TestRTXCommandsDefaults(TestSetRenderSettings, omni.kit.test.AsyncTestCase): async def test_rtx_settings_ui(self): import omni.ui as ui w = ui.Workspace.get_window("Render Settings") w.position_x = 0 w.position_y = 20 w.width = 1440 w.height = 840 return await self.run_test_render_settings_ui("/rtx")
5,121
Python
41.683333
101
0.603788
omniverse-code/kit/exts/omni.rtx.window.settings/rtx/settings.pyi
"""pybind11 rtx.settings bindings""" from __future__ import annotations import rtx.settings import typing __all__ = [ "SETTING_FLAGS_NONE", "SETTING_FLAGS_RESET_DISABLED", "SETTING_FLAGS_TRANSIENT", "get_associated_setting_flags_path", "get_internal_setting_string" ] def get_associated_setting_flags_path(arg0: str) -> str: """ Gets the associated internal setting path to modify the behavior flags that are assigned to each rtx setting. It must be set before the app starts or before RTX plugins are loaded to avoid rtx-defaults from being set mistakenly. This path is simply produced by replacing 'rtx' parent in the setting path with 'rtx-flags'. It allows the behavior of RTX settings to be overridden via SETTING_FLAGS_X flags/attributes. Note that using SETTING_FLAGS_TRANSIENT will cause such settings to not be saved to or loaded from USD. Args: settingPath: RTX setting path to get the associated rtx-flags. Returns: The equivalent rtx setting flag path as string. """ def get_internal_setting_string(arg0: str) -> str: pass SETTING_FLAGS_NONE = 0 SETTING_FLAGS_RESET_DISABLED = 2 SETTING_FLAGS_TRANSIENT = 1
1,278
unknown
35.542856
130
0.680751
omniverse-code/kit/exts/omni.rtx.window.settings/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.rtx.window.settings`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [Unreleased] ### Added ### Changed ### Removed ## [0.6.2] - 2022-09-20 ### Added - API to switch to explicitly switch to a renderer's settings and show the window. ## [0.6.1] - 2022-02-15 ### Changed - Made test suite runnable for carb-settings paths other than 'rtx' ## [0.6.0] - 2020-11-27 ### Changed - Added RenderSettingsFactory interface as entry point for dependent extensions, and removed existing get_rtx_settings_window. This is an interface breaking change - Cleaned up Reset Button logic so any changes to settings result in reset button status being checked - Set an active tab when you add any Render Settings (previously wasn't set) - Start frames collapsed, and store collapse state during session - try and delete widgets/models etc that don't get destroyed/garbage collected when UI is rebuilt due to circular references ## [0.5.4] - 2020-11-25 ### Changed - Added Registration process - Moved hardcoded RTX registration out - Custom tooltips support ## [0.5.3] - 2020-11-18 ### Changed - Additional fix to make labels wider - Additional fix to Default to centre panel when Renderer Changed - removed IRay ## [0.5.2] - 2020-11-16 ### Changed - Made labels wider to accommodate longer label width on single line - Changed colour of float/int drag bars - Default to centre panel when Renderer Changed ## [0.5.1] - 2020-11-11 ### Changed - Cleaned up code - type annotations, comments etc - Added some tests - Added skip_draw_when_clipped=True performance optimisation ## [0.5.0] - 2020-11-04 ### Changed - initial release
1,729
Markdown
25.615384
163
0.735107
omniverse-code/kit/exts/omni.rtx.window.settings/docs/README.md
# The RTX Renderer Settings Window Framework [omni.rtx.window.settings] This extensions build the Base settings window and API so different rendering extensions can register their settings
191
Markdown
37.399993
116
0.827225
omniverse-code/kit/exts/omni.rtx.window.settings/docs/index.rst
omni.rtx.window.settings ########################### .. toctree:: :maxdepth: 1 CHANGELOG
99
reStructuredText
8.999999
27
0.464646
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/__init__.py
from .scripts.extension import *
33
Python
15.999992
32
0.787879
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/scripts/main_window.py
import asyncio import carb.settings import omni.kit.app import omni.ui as ui class MainWindow(object): def __init__(self): # Show gray color the first several frames. It will hode the windows # that are not yet docked. self._ui_main_window = ui.MainWindow(show_foreground=True) # this will be False for Release self.get_main_menu_bar().visible = False settings = carb.settings.get_settings() margin_width = settings.get_as_float("ext/omni.kit.mainwindow/margin/width") margin_height = settings.get_as_float("ext/omni.kit.mainwindow/margin/height") background_color = settings.get_as_int("ext/omni.kit.mainwindow/backgroundColor") self._ui_main_window.main_frame.set_style( {"margin_width": margin_width, "margin_height": margin_height, "background_color": background_color} ) self._setup_window_task = asyncio.ensure_future(self._dock_windows()) def destroy(self): self._ui_main_window = None def get_main_menu_bar(self) -> ui.MenuBar: return self._ui_main_window.main_menu_bar def get_status_bar_frame(self) -> ui.Frame: return self._ui_main_window.status_bar_frame def show_hide_menu(self): self.get_main_menu_bar().visible = not self.get_main_menu_bar().visible def show_hide_status_bar(self): self.get_status_bar_frame().visible = not self.get_status_bar_frame().visible async def _dock_windows(self): stage_win = None viewport = None property_win = None toolbar = None console = None frames = 3 while frames > 0: # setup the docking Space if not stage_win: stage_win = ui.Workspace.get_window("Stage") if not viewport: viewport = ui.Workspace.get_window("Viewport") if not property_win: property_win = ui.Workspace.get_window("Property") if not toolbar: toolbar = ui.Workspace.get_window("Main ToolBar") if not console: console = ui.Workspace.get_window("Console") if stage_win and viewport and property_win and toolbar and console: break # early out frames = frames - 1 await omni.kit.app.get_app().next_update_async() main_dockspace = ui.Workspace.get_window("DockSpace") if viewport: viewport.dock_in(main_dockspace, ui.DockPosition.SAME) if stage_win: stage_win.dock_in(viewport, ui.DockPosition.RIGHT, 0.3) if property_win: if stage_win: property_win.dock_in(stage_win, ui.DockPosition.BOTTOM, 0.5) else: property_win.dock_in(viewport, ui.DockPosition.RIGHT, 0.3) if console: console.dock_in(viewport, ui.DockPosition.BOTTOM, 0.3) if toolbar: toolbar.dock_in(viewport, ui.DockPosition.LEFT) self._setup_window_task = None # Hide foreground after 5 frames. It's enough for windows to appear. for _ in range(5): await omni.kit.app.get_app().next_update_async() self._ui_main_window.show_foreground = False
3,270
Python
33.431579
112
0.606422
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/scripts/extension.py
import omni.ext from .main_window import MainWindow global g_main_window g_main_window = None def get_main_window() -> MainWindow: global g_main_window return g_main_window class MainWindowExtension(omni.ext.IExt): # 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 on_startup(self, ext_id): global g_main_window self._main_window = MainWindow() g_main_window = self._main_window def on_shutdown(self): global g_main_window if (g_main_window): g_main_window.destroy() self._main_window = None g_main_window = None
727
Python
23.266666
119
0.662999
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/tests/test_main_window.py
## Copyright (c) 2018-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 ..scripts.extension import get_main_window from omni.ui.tests.test_base import OmniUiTest import omni.kit.app import omni.kit.mainwindow import omni.kit.test import omni.ui as ui import carb.settings from pathlib import Path GOLDEN_IMAGE_PATH = Path(omni.kit.test.get_test_output_path()).resolve().absolute() class Test(OmniUiTest): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass async def test_dockspace(self): """Checking mainwindow is initialized""" self.assertIsNotNone(get_main_window()) await omni.kit.app.get_app().next_update_async() main_dockspace = ui.Workspace.get_window("DockSpace") self.assertIsNotNone(main_dockspace) async def test_windows(self): """Testing windows""" await self.create_test_area() width = ui.Workspace.get_main_window_width() height = ui.Workspace.get_main_window_height() window1 = ui.Window("Viewport", width=width, height=height) window2 = ui.Window("Viewport", width=width, height=height) window3 = ui.Window("Something Else", width=width, height=height) with window1.frame: ui.Rectangle(style={"background_color": ui.color.indigo}) with window2.frame: ui.Label("NVIDIA") for i in range(10): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=GOLDEN_IMAGE_PATH) for i in range(3): await omni.kit.app.get_app().next_update_async()
2,054
Python
32.688524
83
0.685492
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/tests/__init__.py
from .test_main_window import *
32
Python
15.499992
31
0.75
omniverse-code/kit/exts/omni.kit.mainwindow/docs/index.rst
omni.kit.mainwindow ########################### This class describe the MainWindow workflow, that include 3 main components # MainMenuBar # DockSpace # StatusBar Python API Reference ********************* .. automodule:: omni.kit.mainwindow :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: .. toctree:: :maxdepth: 1 CHANGELOG
390
reStructuredText
16.772727
76
0.625641
omniverse-code/kit/exts/omni.kit.window.stats/PACKAGE-LICENSES/omni.kit.window.stats-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.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.window.stats/config/extension.toml
[package] version = "0.1.2" category = "Core" feature = true [dependencies] "omni.stats" = {} "omni.ui" = {} "omni.usd.libs" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.window.stats" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window", ] dependencies = [ "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.ui_test", ]
437
TOML
14.642857
41
0.601831
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/stats_window.py
import carb import sys import os import omni.ext import omni.ui import omni.kit.ui import omni.kit.app import omni.stats import carb.settings WINDOW_NAME = "Statistics" class Extension(omni.ext.IExt): """Statistics view extension""" class ComboBoxItem(omni.ui.AbstractItem): def __init__(self, text): super().__init__() self.model = omni.ui.SimpleStringModel(text) class ComboBoxModel(omni.ui.AbstractItemModel): def __init__(self): super().__init__() self._current_index = omni.ui.SimpleIntModel() self._current_index.add_value_changed_fn(self._changed_model) self._items = [] def _changed_model(self, model): # update stats at the end of the frame instead self._item_changed(None) def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model def _update_scopes(self, stat_iface): scopes = stat_iface.get_scopes() scope_count = len(scopes) item_count = len(self._items) if item_count != scope_count: selected_scope = "" if item_count != 0: selected_scope = self._current_index self._items.clear() for i in range(scope_count): scope = scopes[i] self._items.append(Extension.ComboBoxItem(scope["name"])) # verify if a scope is already selected if selected_scope == scope["name"]: self._current_index.as_int = i # A default selection if it is not already picked if not selected_scope: self._current_index.as_int = 0 # update stats if scope_count != 0: selected_scope_node = scopes[self._current_index.as_int] self._item_changed(None) return selected_scope_node return None def __init__(self): self._window = None self._app = None self._stats_mode = None self._scope_description = None self._stats = None self._stat_grid = None self._scope_combo_model = None self._stats_names = None self._stats_values = None self._stats_desc = None self._show_names = False # Don't show names by default, just descriptions super().__init__() def get_name(self): return WINDOW_NAME def _menu_callback(self, menu, value): self._window.visible = value # update menu state if self._menu: omni.kit.ui.get_editor_menu().set_value(f"Window/{WINDOW_NAME}", value) def on_startup(self): self._app = omni.kit.app.get_app() self._stats = omni.stats.get_stats_interface() menu_path = f"Window/{WINDOW_NAME}" self._window = omni.ui.Window( WINDOW_NAME, width=400, height=600, padding_x=10, visible=False, dockPreference=omni.ui.DockPreference.RIGHT_TOP, ) self._window.deferred_dock_in("Details", omni.ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) with self._window.frame: with omni.ui.VStack(height=0, spacing=8): with omni.ui.HStack(): omni.ui.Label("Scope to display:") self._scope_combo_model = Extension.ComboBoxModel() self._scope_combo = omni.ui.ComboBox(self._scope_combo_model) with omni.ui.HStack(): omni.ui.Label("Scope description:") self._scope_description = omni.ui.Label("", word_wrap=True) omni.ui.Line() # green color for header style_header = {"color": 0xFF00B976} with omni.ui.HStack(style=style_header): if self._show_names: omni.ui.Label("Name", alignment=omni.ui.Alignment.LEFT) omni.ui.Label("Description", alignment=omni.ui.Alignment.LEFT) omni.ui.Label("Amount", alignment=omni.ui.Alignment.RIGHT) omni.ui.Line() # For performance, draw with two labels (per-frame update) with omni.ui.HStack(style=style_header): if self._show_names: self._stats_names = omni.ui.Label("", alignment=omni.ui.Alignment.LEFT) self._stats_desc = omni.ui.Label("", alignment=omni.ui.Alignment.LEFT) self._stats_values = omni.ui.Label("", alignment=omni.ui.Alignment.RIGHT) try: editor_menu = omni.kit.ui.get_editor_menu() self._menu = editor_menu.add_item(menu_path, self._menu_callback, toggle=True) editor_menu.set_priority(menu_path, 15) except: pass self._sub_event = self._app.get_update_event_stream().create_subscription_to_pop( self._on_update, name="omni.stats frame statistics" ) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) def on_shutdown(self): self._menu = None self._window = None self._sub_event = None def _visiblity_changed_fn(self, visible): # update menu state if self._menu: omni.kit.ui.get_editor_menu().set_value(f"Window/{WINDOW_NAME}", visible) carb.settings.get_settings().set("/profiler/enableDeviceUtilizationQuery", visible) def _update_stats(self, scope_node): stat_nodes = self._stats.get_stats(scope_node["scopeId"]) stats_names = "" stats_values = "" stats_descs = "" # Sort nodes in descending order based on the alphabet stat_nodes = sorted(stat_nodes, key=lambda node: node["description"].lower(), reverse=False) for node in stat_nodes: if self._show_names: stats_names += node["name"] + "\n" stats_descs += node["description"] + "\n" if node["type"] == 0: stats_values += "{:,}".format(node["value"]) + "\n" elif node["type"] == 1: stats_values += "{:.3f}".format(node["value"]) + "\n" if self._show_names: self._stats_names.text = stats_names self._stats_values.text = stats_values self._stats_desc.text = stats_descs def _on_update(self, evt): if not self._window.visible: return scope_node = self._scope_combo_model._update_scopes(self._stats) if scope_node is not None: self._scope_description.text = scope_node["description"] self._update_stats(scope_node)
6,944
Python
37.15934
100
0.548819
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/__init__.py
from .stats_window import *
28
Python
13.499993
27
0.75
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/tests/__init__.py
from .test_stats import *
26
Python
12.499994
25
0.730769
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/tests/test_stats.py
import asyncio import carb import unittest import carb import omni.kit.test import omni.usd import omni.ui as ui from omni.kit import ui_test class TestStats(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_stats_window(self): stats_window = ui_test.find("Statistics") stats_window.widget.visible = True await stats_window.focus() line_count = [0, 0, 0] for index in range(0, 3): # can't use widget.click as open combobox has no readable size and clicks goto stage window stats_window.find("**/ComboBox[*]").model.get_item_value_model(None, 0).set_value(index) await ui_test.human_delay(10) for widget in stats_window.find_all("**/Label[*]"): line_count[index] += len(widget.widget.text.split('\n')) self.assertNotEqual(line_count[0], 0) self.assertNotEqual(line_count[1], 0) self.assertNotEqual(line_count[2], 0)
1,031
Python
29.35294
103
0.634336
omniverse-code/kit/exts/omni.kit.window.stats/docs/index.rst
omni.kit.window.stats ########################### Window to display omni.stats
81
reStructuredText
12.666665
28
0.518519
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/tools.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from pathlib import Path from typing import List import traceback import carb import carb.dictionary import carb.events import carb.settings import omni.kit.app import omni.kit.context_menu import omni.usd from omni.kit.manipulator.tool.snap import SnapToolButton from omni.kit.manipulator.transform.manipulator import TransformManipulator from omni.kit.manipulator.transform.toolbar_tool import SimpleToolButton from omni.kit.manipulator.transform.types import Operation from .settings_constants import Constants as prim_c from .tool_models import LocalGlobalModeModel from .toolbar_registry import get_toolbar_registry ICON_FOLDER_PATH = Path( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons" ) TOOLS_ENABLED_SETTING_PATH = "/exts/omni.kit.manipulator.prim/tools/enabled" class SelectionPivotTool(SimpleToolButton): # menu entry only needs to register once __menu_entries = [] @classmethod def register_menu(cls): def build_placement_setting_entry(setting: str): menu = { "name": setting, "checked_fn": lambda _: carb.settings.get_settings().get(prim_c.MANIPULATOR_PLACEMENT_SETTING) == setting, "onclick_fn": lambda _: carb.settings.get_settings().set(prim_c.MANIPULATOR_PLACEMENT_SETTING, setting), } return menu menu = [ build_placement_setting_entry(s) for s in [ prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE, prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER, prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER, prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM, ] ] for item in menu: cls.__menu_entries.append(omni.kit.context_menu.add_menu(item, "sel_pivot", "omni.kit.manipulator.prim")) @classmethod def unregister_menu(cls): for sub in cls.__menu_entries: sub.release() cls.__menu_entries.clear() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO assume the context is "" for VP1 self._usd_context = omni.usd.get_context(self._toolbar_payload.get("usd_context_name", "")) self._selection = self._usd_context.get_selection() enabled_img_url = f"{ICON_FOLDER_PATH}/pivot_location.svg" self._build_widget( button_name="sel_pivot", enabled_img_url=enabled_img_url, model=None, menu_index="sel_pivot", menu_extension_id="omni.kit.manipulator.prim", no_toggle=True, menu_on_left_click=True, tooltip="Selection Pivot Placement", ) # order=1 to register after prim manipulator so _on_selection_changed gets updated len of xformable_prim_paths self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop_by_type( int(omni.usd.StageEventType.SELECTION_CHANGED), self._on_stage_selection_event, name="SelectionPivotTool stage event", order=1, ) if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_selection_changed() def destroy(self): super().destroy() self._stage_event_sub = None if self._model: self._model.destroy() self._model = None @classmethod def can_build(cls, manipulator: TransformManipulator, operation: Operation) -> bool: return operation == Operation.TRANSLATE or operation == Operation.ROTATE or operation == Operation.SCALE def _on_stage_selection_event(self, event: carb.events.IEvent): self._on_selection_changed() def _on_selection_changed(self): selected_xformable_paths_count = ( len(self._manipulator.model.xformable_prim_paths) if self._manipulator.model else 0 ) if self._stack: visible = selected_xformable_paths_count > 0 if self._stack.visible != visible: self._stack.visible = visible self._manipulator.refresh_toolbar() class LocalGlobalTool(SimpleToolButton): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._operation == Operation.TRANSLATE: setting_path = "/app/transform/moveMode" elif self._operation == Operation.ROTATE: setting_path = "/app/transform/rotateMode" else: raise RuntimeError("Invalid operation") self._model = LocalGlobalModeModel(setting_path) enabled_img_url = f"{ICON_FOLDER_PATH}/transformspace_global_dark.svg" disabled_img_url = f"{ICON_FOLDER_PATH}/transformspace_local_dark.svg" self._build_widget( button_name="local_global", enabled_img_url=enabled_img_url, disabled_img_url=disabled_img_url, model=self._model, tooltip="Current Transform Space: World", disabled_tooltip="Current Transform Space: Local" ) def destroy(self): super().destroy() if self._model: self._model.destroy() self._model = None @classmethod def can_build(cls, manipulator: TransformManipulator, operation: Operation) -> bool: return operation == Operation.TRANSLATE or operation == Operation.ROTATE class PrimManipTools: def __init__(self): self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._toolbar_reg = get_toolbar_registry() SelectionPivotTool.register_menu() # one time startup self._builtin_tool_classes = { "prim:1space": LocalGlobalTool, "prim:2snap": SnapToolButton, "prim:3sel_pivot": SelectionPivotTool, } self._registered_tool_ids: List[str] = [] self._sub = self._settings.subscribe_to_node_change_events(TOOLS_ENABLED_SETTING_PATH, self._on_setting_changed) if self._settings.get(TOOLS_ENABLED_SETTING_PATH) is True: self._register_tools() self._pivot_button_group = None # register pivot placement to "factory explorer" toolbar app_name = omni.kit.app.get_app().get_app_filename() if "omni.factory_explorer" in app_name: # add manu entry to factory explorer toolbar manager = omni.kit.app.get_app().get_extension_manager() self._hooks = manager.subscribe_to_extension_enable( lambda _: self._register_main_toolbar_button(), lambda _: self._unregister_main_toolbar_button(), ext_name="omni.explore.toolbar", hook_name="omni.kit.manipulator.prim.pivot_placement listener", ) def __del__(self): self.destroy() def destroy(self): self._hooks = None if self._pivot_button_group is not None: self._unregister_main_toolbar_button() self._unregister_tools() if self._sub is not None: self._settings.unsubscribe_to_change_events(self._sub) self._sub = None SelectionPivotTool.unregister_menu() # one time shutdown def _register_tools(self): for id, tool_class in self._builtin_tool_classes.items(): self._toolbar_reg.register_tool(tool_class, id) self._registered_tool_ids.append(id) def _unregister_tools(self): for id in self._registered_tool_ids: self._toolbar_reg.unregister_tool(id) self._registered_tool_ids.clear() def _on_setting_changed(self, item, event_type): enabled = self._dict.get(item) if enabled and not self._registered_tool_ids: self._register_tools() elif not enabled: self._unregister_tools() def _register_main_toolbar_button(self): # pragma: no cover # Can't be tested from within kit since omni.explore.toolbar is outside of kit repo try: if not self._pivot_button_group: import omni.explore.toolbar from .pivot_button_group import PivotButtonGroup self._pivot_button_group = PivotButtonGroup() explorer_toolbar_ext = omni.explore.toolbar.get_toolbar_instance() explorer_toolbar_ext.toolbar.add_widget_group(self._pivot_button_group, 1) # also add to MODIFY_TOOLS list, when menu Modify is selected # all items in toolbar will be cleared and re-added from MODIFY_TOOLS list explorer_tools = omni.explore.toolbar.groups.MODIFY_TOOLS explorer_tools.append(self._pivot_button_group) except Exception: carb.log_warn(traceback.format_exc()) def _unregister_main_toolbar_button(self): # pragma: no cover # Can't be tested from within kit since omni.explore.toolbar is outside of kit repo try: if self._pivot_button_group: import omni.explore.toolbar explorer_toolbar_ext = omni.explore.toolbar.get_toolbar_instance() explorer_toolbar_ext.toolbar.remove_widget_group(self._pivot_button_group) # remove from MODIFY_TOOLS list as well explorer_tools = omni.explore.toolbar.groups.MODIFY_TOOLS if self._pivot_button_group in explorer_tools: explorer_tools.remove(self._pivot_button_group) self._pivot_button_group.clean() self._pivot_button_group = None except Exception: carb.log_warn(traceback.format_exc())
10,250
Python
37.107807
120
0.629268
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ext from omni.kit.manipulator.viewport import ManipulatorFactory from .prim_transform_manipulator import PrimTransformManipulator from .prim_transform_manipulator_registry import TransformManipulatorRegistry from .reference_prim_marker import ReferencePrimMarker from .tools import PrimManipTools class ManipulatorPrim(omni.ext.IExt): def on_startup(self, ext_id): self._tools = PrimManipTools() # For VP1 self._legacy_manipulator = PrimTransformManipulator() self._legacy_marker = ManipulatorFactory.create_manipulator( ReferencePrimMarker, usd_context_name="", manipulator_model=self._legacy_manipulator.model, legacy=True ) # For VP2 self._manipulator_registry = TransformManipulatorRegistry() def on_shutdown(self): if self._legacy_manipulator is not None: self._legacy_manipulator.destroy() self._legacy_manipulator = None if self._legacy_marker is not None: ManipulatorFactory.destroy_manipulator(self._legacy_marker) self._legacy_marker = None if self._manipulator_registry is not None: self._manipulator_registry.destroy() self._manipulator_registry = None if self._tools is not None: self._tools.destroy() self._tools = None
1,788
Python
36.270833
115
0.714765
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/__init__.py
from .extension import * from .model import * from .toolbar_registry import *
78
Python
18.749995
31
0.75641
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/prim_transform_manipulator.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 copy from typing import List, Union import carb.dictionary import carb.events import carb.settings import omni.ext import omni.usd from omni.kit.manipulator.selector import ManipulatorBase from omni.kit.manipulator.tool.snap import SnapProviderManager from omni.kit.manipulator.tool.snap import settings_constants as snap_c from omni.kit.manipulator.transform import get_default_style from omni.kit.manipulator.transform.manipulator import TransformManipulator from omni.kit.manipulator.transform.settings_constants import c from omni.kit.manipulator.transform.settings_listener import OpSettingsListener, SnapSettingsListener from omni.kit.manipulator.viewport import ManipulatorFactory from pxr import Sdf, Usd, UsdGeom from .model import PrimRotateChangedGesture, PrimScaleChangedGesture, PrimTransformModel, PrimTranslateChangedGesture from .toolbar_registry import get_toolbar_registry TRANSFORM_GIZMO_HIDDEN_OVERRIDE = "/app/transform/gizmoHiddenOverride" class PrimTransformManipulator(ManipulatorBase): def __init__( self, usd_context_name: str = "", viewport_api=None, name="omni.kit.manipulator.prim", model: PrimTransformModel = None, size: float = 1.0, ): super().__init__(name=name, usd_context_name=usd_context_name) self._dict = carb.dictionary.get_dictionary() self._settings = carb.settings.get_settings() self._usd_context = omni.usd.get_context(usd_context_name) self._selection = self._usd_context.get_selection() self._model_is_external = model is not None self._model = model if self._model_is_external else PrimTransformModel(usd_context_name, viewport_api) self._legacy_mode = viewport_api is None # if no viewport_api is supplied, it is from VP1 self._snap_manager = SnapProviderManager(viewport_api=viewport_api) if self._legacy_mode: self._manipulator = ManipulatorFactory.create_manipulator( TransformManipulator, size=size, model=self._model, enabled=False, gestures=[ PrimTranslateChangedGesture( self._snap_manager, usd_context_name=usd_context_name, viewport_api=viewport_api ), PrimRotateChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api), PrimScaleChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api), ], tool_registry=get_toolbar_registry(), ) else: self._manipulator = TransformManipulator( size=size, model=self._model, enabled=False, gestures=[ PrimTranslateChangedGesture( self._snap_manager, usd_context_name=usd_context_name, viewport_api=viewport_api ), PrimRotateChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api), PrimScaleChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api), ], tool_registry=get_toolbar_registry(), tool_button_additional_payload={"viewport_api": viewport_api, "usd_context_name": usd_context_name}, ) # Hide the old C++ imguizmo when omni.ui.scene manipulator is enabled self._prev_transform_hidden_override = self._settings.get(TRANSFORM_GIZMO_HIDDEN_OVERRIDE) self._settings.set(TRANSFORM_GIZMO_HIDDEN_OVERRIDE, True) self._set_default_settings() self._create_local_global_styles() self._op_settings_listener = OpSettingsListener() self._op_settings_listener_sub = self._op_settings_listener.subscribe_listener(self._on_op_listener_changed) self._snap_settings_listener = SnapSettingsListener( enabled_setting_path=None, move_x_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_y_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_z_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, rotate_setting_path=snap_c.SNAP_ROTATE_SETTING_PATH, scale_setting_path=snap_c.SNAP_SCALE_SETTING_PATH, provider_setting_path=snap_c.SNAP_PROVIDER_NAME_SETTING_PATH, ) self._snap_settings_listener_sub = self._snap_settings_listener.subscribe_listener( self._on_snap_listener_changed ) self._enabled: bool = self._manipulator.enabled self._prim_style_applied: bool = False self._set_style() def __del__(self): self.destroy() def destroy(self): super().destroy() self._op_settings_listener_sub = None self._snap_settings_listener_sub = None if self._op_settings_listener: self._op_settings_listener.destroy() self._op_settings_listener = None if self._manipulator: if self._legacy_mode: ManipulatorFactory.destroy_manipulator(self._manipulator) else: self._manipulator.destroy() self._manipulator = None if self._model and not self._model_is_external: self._model.destroy() self._model = None if self._snap_manager: self._snap_manager.destroy() self._snap_manager = None # restore imguizmo visibility self._settings.set(TRANSFORM_GIZMO_HIDDEN_OVERRIDE, self._prev_transform_hidden_override) @property def model(self) -> PrimTransformModel: return self._model @property def snap_manager(self) -> SnapProviderManager: return self._snap_manager @property def enabled(self): return self._manipulator.enabled @enabled.setter def enabled(self, value: bool): if value != self._enabled: self._enabled = value self._update_manipulator_enable() def _set_default_settings(self): self._settings.set_default_string(c.TRANSFORM_OP_SETTING, c.TRANSFORM_OP_MOVE) self._settings.set_default_string(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL) self._settings.set_default_string(c.TRANSFORM_ROTATE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL) def _create_local_global_styles(self): COLOR_LOCAL = 0x8A248AE3 local_style = get_default_style() local_style["Translate.Point"]["color"] = COLOR_LOCAL local_style["Rotate.Arc::screen"]["color"] = COLOR_LOCAL local_style["Scale.Point"]["color"] = COLOR_LOCAL self._styles = {c.TRANSFORM_MODE_GLOBAL: get_default_style(), c.TRANSFORM_MODE_LOCAL: local_style} self._snap_styles = copy.deepcopy(self._styles) self._snap_styles[c.TRANSFORM_MODE_GLOBAL]["Translate.Focal"]["visible"] = True self._snap_styles[c.TRANSFORM_MODE_LOCAL]["Translate.Focal"]["visible"] = True def on_selection_changed(self, stage: Usd.Stage, selection: Union[List[Sdf.Path], None], *args, **kwargs) -> bool: if selection is None: if self.model: self.model.on_selection_changed([]) return False if self.model: self.model.on_selection_changed(selection) for path in selection: prim = stage.GetPrimAtPath(path) if prim.IsA(UsdGeom.Xformable): return True return False def _update_manipulator_enable(self) -> None: if not self._manipulator: return is_enabled: bool = self._prim_style_applied and self._enabled if not self._manipulator.enabled and is_enabled: self._manipulator.enabled = True elif self._manipulator.enabled and not is_enabled: self._manipulator.enabled = False def _set_style(self) -> None: def set_manipulator_style(styles, mode: str): # An unknown style will return false here. if mode in styles: self._manipulator.style = styles[mode] return True else: return False if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: styles = ( self._snap_styles if self._snap_settings_listener.snap_enabled and self._snap_settings_listener.snap_to_surface else self._styles ) self._prim_style_applied = set_manipulator_style(styles, self._op_settings_listener.translation_mode) elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: self._prim_style_applied = set_manipulator_style(self._styles, self._op_settings_listener.rotation_mode) elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_SCALE: self._prim_style_applied = set_manipulator_style(self._styles, c.TRANSFORM_MODE_LOCAL) else: # unknown op disables. self._prim_style_applied = False self._update_manipulator_enable() def _on_op_listener_changed(self, type: OpSettingsListener.CallbackType, value: str): if ( type == OpSettingsListener.CallbackType.OP_CHANGED or type == OpSettingsListener.CallbackType.TRANSLATION_MODE_CHANGED or type == OpSettingsListener.CallbackType.ROTATION_MODE_CHANGED ): self._set_style() def _on_snap_listener_changed(self, setting_val_name: str, value: str): if setting_val_name == "snap_enabled" or setting_val_name == "snap_to_surface": self._set_style()
10,120
Python
41.34728
118
0.644269
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/tool_models.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 carb.dictionary import carb.settings import omni.ui as ui class LocalGlobalModeModel(ui.AbstractValueModel): TRANSFORM_MODE_GLOBAL = "global" TRANSFORM_MODE_LOCAL = "local" def __init__(self, op_space_setting_path): super().__init__() self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() 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 __del__(self): self.destroy() def destroy(self): if self._op_space_sub is not None: self._settings.unsubscribe_to_change_events(self._op_space_sub) self._op_space_sub = None def _on_op_space_changed(self, item, event_type): self._op_space = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._op_space != self.TRANSFORM_MODE_LOCAL def set_value(self, value): self._settings.set( self._setting_path, self.TRANSFORM_MODE_LOCAL if value == False else self.TRANSFORM_MODE_GLOBAL, )
1,719
Python
32.72549
88
0.669575
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/settings_constants.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. # class Constants: MANIPULATOR_PLACEMENT_SETTING = "/persistent/exts/omni.kit.manipulator.prim/manipulator/placement" MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT = "Authored Pivot" MANIPULATOR_PLACEMENT_SELECTION_CENTER = "Selection Center" MANIPULATOR_PLACEMENT_BBOX_BASE = "Bounding Box Base" MANIPULATOR_PLACEMENT_BBOX_CENTER = "Bounding Box Center" MANIPULATOR_PLACEMENT_PICK_REF_PRIM = "Pick Reference Prim"
859
Python
46.777775
102
0.788126
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/utils.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import math from typing import List import carb import carb.profiler import carb.settings from pxr import Gf, Usd, UsdGeom @carb.profiler.profile def flatten(transform): """Convert array[4][4] to array[16]""" # flatten the matrix by hand # USING LIST COMPREHENSION IS VERY SLOW (e.g. return [item for sublist in transform for item in sublist]), which takes around 10ms. m0, m1, m2, m3 = transform[0], transform[1], transform[2], transform[3] return [ m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3], ] @carb.profiler.profile def get_local_transform_pivot_inv(prim: Usd.Prim, time: Usd.TimeCode = Usd.TimeCode): xform = UsdGeom.Xformable(prim) xform_ops = xform.GetOrderedXformOps() if len(xform_ops): pivot_op_inv = xform_ops[-1] if ( pivot_op_inv.GetOpType() == UsdGeom.XformOp.TypeTranslate and pivot_op_inv.IsInverseOp() and pivot_op_inv.GetName().endswith("pivot") ): return pivot_op_inv.GetOpTransform(time) return Gf.Matrix4d(1.0) def compose_transform_ops_to_matrix( translation: Gf.Vec3d, rotation: Gf.Vec3d, rotation_order: Gf.Vec3i, scale: Gf.Vec3d ): axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] rot = [] for i in range(3): axis_idx = rotation_order[i] rot.append(Gf.Rotation(axes[axis_idx], rotation[axis_idx])) rotation_mtx = Gf.Matrix4d(1.0) rotation_mtx.SetRotate(rot[0] * rot[1] * rot[2]) valid_scale = Gf.Vec3d(0.0) for i in range(3): if abs(scale[i]) == 0: valid_scale[i] = 0.001 else: valid_scale[i] = scale[i] scale_mtx = Gf.Matrix4d(1.0) scale_mtx.SetScale(valid_scale) translate_mtx = Gf.Matrix4d(1.0) translate_mtx.SetTranslate(translation) return scale_mtx * rotation_mtx * translate_mtx def repeat(t: float, length: float) -> float: return t - (math.floor(t / length) * length) def generate_compatible_euler_angles(euler: Gf.Vec3d, rotation_order: Gf.Vec3i) -> List[Gf.Vec3d]: equal_eulers = [euler] mid_order = rotation_order[1] equal = Gf.Vec3d() for i in range(3): if i == mid_order: equal[i] = 180 - euler[i] else: equal[i] = euler[i] + 180 equal_eulers.append(equal) for i in range(3): equal[i] -= 360 equal_eulers.append(equal) return equal_eulers def find_best_euler_angles(old_rot_vec: Gf.Vec3d, new_rot_vec: Gf.Vec3d, rotation_order: Gf.Vec3i) -> Gf.Vec3d: equal_eulers = generate_compatible_euler_angles(new_rot_vec, rotation_order) nearest_euler = None for euler in equal_eulers: for i in range(3): euler[i] = repeat(euler[i] - old_rot_vec[i] + 180.0, 360.0) + old_rot_vec[i] - 180.0 if nearest_euler is None: nearest_euler = euler else: distance_1 = (nearest_euler - old_rot_vec).GetLength() distance_2 = (euler - old_rot_vec).GetLength() if distance_2 < distance_1: nearest_euler = euler return nearest_euler
3,734
Python
26.873134
135
0.61248
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/toolbar_registry.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.kit.manipulator.transform.toolbar_registry import ToolbarRegistry _toolbar_registry = ToolbarRegistry() def get_toolbar_registry() -> ToolbarRegistry: return _toolbar_registry
622
Python
35.647057
76
0.803859
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/reference_prim_marker.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from __future__ import annotations import asyncio import colorsys import weakref from collections import defaultdict from typing import DefaultDict, Dict, Set, Union from weakref import ProxyType import concurrent.futures import carb import carb.dictionary import carb.events import carb.profiler import carb.settings import omni.timeline import omni.usd from omni.kit.async_engine import run_coroutine from omni.kit.manipulator.transform.style import COLOR_X, COLOR_Y, COLOR_Z, abgr_to_color from omni.kit.manipulator.transform.settings_constants import Constants as TrCon from omni.ui import color as cl from omni.ui import scene as sc from pxr import Sdf, Tf, Usd, UsdGeom from .model import PrimTransformModel, Viewport1WindowState from .settings_constants import Constants from .utils import flatten, get_local_transform_pivot_inv LARGE_SELECTION_CAP = 20 class PreventViewportOthers(sc.GestureManager): def can_be_prevented(self, gesture): return True def should_prevent(self, gesture, preventer): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: if issubclass(type(preventer), ClickMarkerGesture): if issubclass(type(gesture), ClickMarkerGesture): return gesture.gesture_payload.ray_distance > preventer.gesture_payload.ray_distance elif isinstance(gesture, ClickMarkerGesture): return False else: return True else: return True return super().should_prevent(gesture, preventer) class ClickMarkerGesture(sc.DragGesture): def __init__( self, prim_path: Sdf.Path, marker: ProxyType[ReferencePrimMarker], ): super().__init__(manager=PreventViewportOthers()) self._prim_path = prim_path self._marker = marker self._vp1_window_state = None def on_began(self): self._viewport_on_began() def on_canceled(self): self._viewport_on_ended() def on_ended(self): self._viewport_on_ended() self._marker.on_pivot_marker_picked(self._prim_path) def _viewport_on_began(self): self._viewport_on_ended() if self._marker.legacy: self._vp1_window_state = Viewport1WindowState() def _viewport_on_ended(self): if self._vp1_window_state: self._vp1_window_state.destroy() self._vp1_window_state = None class MarkerHoverGesture(sc.HoverGesture): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.items = [] self._began_count = 0 self._original_colors = [] self._original_ends = [] def on_began(self): self._began_count += 1 if self._began_count == 1: self._original_colors = [None] * len(self.items) self._original_ends = [None] * len(self.items) for i, item in enumerate(self.items): self._original_colors[i] = item.color item.color = self._make_brighter(item.color) if isinstance(item, sc.Line): self._original_ends[i] = item.end end = [dim * 1.2 for dim in item.end] item.end = end if isinstance(item, sc.Arc): ... # TODO change color to white, blocked by OM-56044 def on_ended(self): self._began_count -= 1 if self._began_count <= 0: self._began_count = 0 for i, item in enumerate(self.items): item.color = self._original_colors[i] if isinstance(item, sc.Line): item.end = self._original_ends[i] if isinstance(item, sc.Arc): ... # TODO change color back, blocked by OM-56044 def _make_brighter(self, color): hsv = colorsys.rgb_to_hsv(color[0], color[1], color[2]) rgb = colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2] * 1.2) return cl(rgb[0], rgb[1], rgb[2], color[3]) class ReferencePrimMarker(sc.Manipulator): def __init__( self, usd_context_name: str = "", manipulator_model: ProxyType[PrimTransformModel] = None, legacy: bool = False ): super().__init__() self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._usd_context_name = usd_context_name self._usd_context = omni.usd.get_context(self._usd_context_name) self._manipulator_model = manipulator_model self._legacy = legacy self._selection = self._usd_context.get_selection() self._timeline = omni.timeline.get_timeline_interface() self._current_time = self._timeline.get_current_time() # dict from prefixes -> dict of affected markers. self._markers: DefaultDict[Dict] = defaultdict(dict) self._stage_listener = None self._pending_changed_paths: Set[Sdf.Path] = set() self._process_pending_change_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None # order=1 to ensure the event handler is called after prim manipulator self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="ReferencePrimMarker stage event", order=1 ) self._placement_sub = self._settings.subscribe_to_node_change_events( Constants.MANIPULATOR_PLACEMENT_SETTING, self._on_placement_changed ) self._placement = self._settings.get(Constants.MANIPULATOR_PLACEMENT_SETTING) self._op_sub = self._settings.subscribe_to_node_change_events(TrCon.TRANSFORM_OP_SETTING, self._on_op_changed) self._selected_op = self._settings.get(TrCon.TRANSFORM_OP_SETTING) def destroy(self): self._stage_event_sub = None if self._placement_sub: self._settings.unsubscribe_to_change_events(self._placement_sub) self._placement_sub = None if self._op_sub: self._settings.unsubscribe_to_change_events(self._op_sub) self._op_sub = None if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None if self._process_pending_change_task_or_future and not self._process_pending_change_task_or_future.done(): self._process_pending_change_task_or_future.cancel() self._process_pending_change_task_or_future = None self._timeline_sub = None @property def usd_context_name(self) -> str: return self._usd_context_name @usd_context_name.setter def usd_context_name(self, value: str): if value != self._usd_context_name: new_usd_context = omni.usd.get_context(value) if not new_usd_context: carb.log_error(f"Invalid usd context name {value}") return if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None self._usd_context_name = value self._usd_context = new_usd_context # order=1 to ensure the event handler is called after prim manipulator self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="ReferencePrimMarker stage event", order=1 ) self.invalidate() @property def manipulator_model(self) -> ProxyType[PrimTransformModel]: return self._manipulator_model @manipulator_model.setter def manipulator_model(self, value): if value != self._manipulator_model: self._manipulator_model = value self.invalidate() @property def legacy(self) -> bool: return self._legacy @legacy.setter def legacy(self, value): self._legacy = value def on_pivot_marker_picked(self, path: Sdf.Path): if self._manipulator_model.set_pivot_prim_path(path): # Hide marker on the new pivot prim and show marker on old pivot prim old_pivot_marker = self._markers.get(self._pivot_prim_path, {}).get(self._pivot_prim_path, None) if old_pivot_marker: old_pivot_marker.visible = True self._pivot_prim_path = self._manipulator_model.get_pivot_prim_path() new_pivot_marker = self._markers.get(self._pivot_prim_path, {}).get(self._pivot_prim_path, None) if new_pivot_marker: new_pivot_marker.visible = False def on_build(self): if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None self._timeline_sub = None self._markers.clear() if self._placement != Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM: return # don't build marker on "select" mode if self._selected_op == TrCon.TRANSFORM_OP_SELECT: return selected_xformable_paths = self._manipulator_model.xformable_prim_paths stage = self._usd_context.get_stage() self._current_time = self._timeline.get_current_time() selection_count = len(selected_xformable_paths) # skip if there's only one xformable if selection_count <= 1: return if selection_count > LARGE_SELECTION_CAP: carb.log_warn( f"{selection_count} is greater than the maximum selection cap {LARGE_SELECTION_CAP}, " f"{Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM} mode will be disabled and fallback to " f"{Constants.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT} due to performance concern." ) return timecode = self._get_current_time_code() self._pivot_prim_path = self._manipulator_model.get_pivot_prim_path() xform_cache = UsdGeom.XformCache(timecode) for path in selected_xformable_paths: prim = stage.GetPrimAtPath(path) pivot_inv = get_local_transform_pivot_inv(prim, timecode) transform = pivot_inv.GetInverse() * xform_cache.GetLocalToWorldTransform(prim) transform.Orthonormalize() # in case of a none uniform scale marker_transform = sc.Transform(transform=flatten(transform), visible=self._pivot_prim_path != path) with marker_transform: with sc.Transform(scale_to=sc.Space.SCREEN): gesture = ClickMarkerGesture(path, marker=weakref.proxy(self)) hover_gesture = MarkerHoverGesture() x_line = sc.Line( (0, 0, 0), (50, 0, 0), color=abgr_to_color(COLOR_X), thickness=2, intersection_thickness=8, gestures=[gesture, hover_gesture], ) y_line = sc.Line( (0, 0, 0), (0, 50, 0), color=abgr_to_color(COLOR_Y), thickness=2, intersection_thickness=8, gestures=[gesture, hover_gesture], ) z_line = sc.Line( (0, 0, 0), (0, 0, 50), color=abgr_to_color(COLOR_Z), thickness=2, intersection_thickness=8, gestures=[gesture, hover_gesture], ) with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): point = sc.Arc( radius=6, wireframe=False, tesselation=8, color=cl.white, # TODO default color grey, blocked by OM-56044 ) hover_gesture.items = [x_line, y_line, z_line, point] prefixes = path.GetPrefixes() for prefix in prefixes: self._markers[prefix][path] = marker_transform if self._markers: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_objects_changed, stage) self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop( self._on_timeline_event ) def _on_stage_event(self, event: carb.events.IEvent): if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): if self._placement == Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM: self.invalidate() def _on_placement_changed(self, item, event_type): placement = self._dict.get(item) if placement != self._placement: self._placement = placement self.invalidate() def _on_op_changed(self, item, event_type): selected_op = self._dict.get(item) if selected_op != self._selected_op: if selected_op == TrCon.TRANSFORM_OP_SELECT or self._selected_op == TrCon.TRANSFORM_OP_SELECT: self.invalidate() self._selected_op = selected_op def _on_timeline_event(self, e: carb.events.IEvent): if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED): current_time = e.payload["currentTime"] if current_time != self._current_time: self._current_time = current_time if self._placement != Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM: # TODO only invalidate transform if this prim or ancestors transforms are time varying? self.invalidate() @carb.profiler.profile async def _process_pending_change(self): processed_transforms = set() timecode = self._get_current_time_code() xform_cache = UsdGeom.XformCache(timecode) stage = self._usd_context.get_stage() for path in self._pending_changed_paths: prim_path = path.GetPrimPath() affected_transforms = self._markers.get(prim_path, {}) if affected_transforms: if not UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name): continue for path, transform in affected_transforms.items(): if transform in processed_transforms: continue prim = stage.GetPrimAtPath(path) if not prim: continue pivot_inv = get_local_transform_pivot_inv(prim, timecode) xform = pivot_inv.GetInverse() * xform_cache.GetLocalToWorldTransform(prim) xform.Orthonormalize() # in case of a none uniform scale transform_value = flatten(xform) transform.transform = transform_value processed_transforms.add(transform) self._pending_changed_paths.clear() @carb.profiler.profile def _on_objects_changed(self, notice, sender): self._pending_changed_paths.update(notice.GetChangedInfoOnlyPaths()) if self._process_pending_change_task_or_future is None or self._process_pending_change_task_or_future.done(): self._process_pending_change_task_or_future = run_coroutine(self._process_pending_change()) def _get_current_time_code(self): return Usd.TimeCode( omni.usd.get_frame_time_code(self._current_time, self._usd_context.get_stage().GetTimeCodesPerSecond()) )
16,265
Python
38.673171
119
0.595573
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/model.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from __future__ import annotations import asyncio import math import traceback from enum import Enum, Flag, IntEnum, auto from typing import Dict, List, Sequence, Set, Tuple, Union import concurrent.futures import carb import carb.dictionary import carb.events import carb.profiler import carb.settings import omni.kit.app from omni.kit.async_engine import run_coroutine import omni.kit.commands import omni.kit.undo import omni.timeline from omni.kit.manipulator.tool.snap import SnapProviderManager from omni.kit.manipulator.tool.snap import settings_constants as snap_c from omni.kit.manipulator.transform import AbstractTransformManipulatorModel, Operation from omni.kit.manipulator.transform.gestures import ( RotateChangedGesture, RotateDragGesturePayload, ScaleChangedGesture, ScaleDragGesturePayload, TransformDragGesturePayload, TranslateChangedGesture, TranslateDragGesturePayload, ) from omni.kit.manipulator.transform.settings_constants import c from omni.kit.manipulator.transform.settings_listener import OpSettingsListener, SnapSettingsListener from omni.ui import scene as sc from pxr import Gf, Sdf, Tf, Usd, UsdGeom, UsdUtils from .settings_constants import Constants as prim_c from .utils import * # Settings needed for zero-gravity TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED = "/app/transform/gizmoCustomManipulatorEnabled" TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS = "/app/transform/gizmoCustomManipulatorPrims" TRANSFORM_GIZMO_IS_USING = "/app/transform/gizmoIsUsing" TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ = "/app/transform/gizmoTranslateDeltaXYZ" TRANSFORM_GIZMO_PIVOT_WORLD_POSITION = "/app/transform/tempPivotWorldPosition" TRANSFORM_GIZMO_ROTATE_DELTA_XYZW = "/app/transform/gizmoRotateDeltaXYZW" TRANSFORM_GIZMO_SCALE_DELTA_XYZ = "/app/transform/gizmoScaleDeltaXYZ" TRANSLATE_DELAY_FRAME_SETTING = "/exts/omni.kit.manipulator.prim/visual/delayFrame" class OpFlag(Flag): TRANSLATE = auto() ROTATE = auto() SCALE = auto() class Placement(Enum): LAST_PRIM_PIVOT = auto() SELECTION_CENTER = auto() BBOX_CENTER = auto() REF_PRIM = auto() BBOX_BASE = auto() class ManipulationMode(IntEnum): PIVOT = 0 # transform around manipulator pivot UNIFORM = 1 # set same world transform from manipulator to all prims equally INDIVIDUAL = 2 # 2: (TODO) transform around each prim's own pivot respectively class Viewport1WindowState: def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact is the focused window! # And there's no good solution to this when multiple Viewport-1 instances are open; so we just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) # Schedule a picking request so if snap needs it later, it may arrive by the on_change event window.request_picking() except Exception: pass def get_picked_world_pos(self): if self._focused_windows: # Try to reduce to the focused window now after, we've had some mouse-move input focused_windows = [window for window in self._focused_windows if window.is_focused()] if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: window.disable_selection_rect(True) # request picking FOR NEXT FRAME window.request_picking() # get PREVIOUSLY picked pos, it may be None the first frame but that's fine return window.get_picked_world_pos() return None def __del__(self): self.destroy() def destroy(self): self._focused_windows = None def get_usd_context_name(self): if self._focused_windows: return self._focused_windows[0].get_usd_context_name() else: return "" class PrimTransformChangedGestureBase: def __init__(self, usd_context_name: str = "", viewport_api=None): self._settings = carb.settings.get_settings() self._usd_context_name = usd_context_name self._usd_context = omni.usd.get_context(self._usd_context_name) self._viewport_api = viewport_api # VP2 self._vp1_window_state = None self._stage_id = None def on_began(self, payload_type=TransformDragGesturePayload): self._viewport_on_began() if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return model = self.sender.model if not model: return item = self.gesture_payload.changing_item self._current_editing_op = item.operation # NOTE! self._begin_xform has no scale. To get the full matrix, do self._begin_scale_mtx * self._begin_xform self._begin_xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator"))) manip_scale = Gf.Vec3d(*model.get_as_floats(model.get_item("scale_manipulator"))) self._begin_scale_mtx = Gf.Matrix4d(1.0) self._begin_scale_mtx.SetScale(manip_scale) model.set_floats(model.get_item("viewport_fps"), [0.0]) model.on_began(self.gesture_payload) def on_changed(self, payload_type=TransformDragGesturePayload): if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return model = self.sender.model if not model: return if self._viewport_api: fps = self._viewport_api.frame_info.get("fps") model.set_floats(model.get_item("viewport_fps"), [fps]) model.on_changed(self.gesture_payload) def on_ended(self, payload_type=TransformDragGesturePayload): self._viewport_on_ended() if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return model = self.sender.model if not model: return item = self.gesture_payload.changing_item if item.operation != self._current_editing_op: return model.set_floats(model.get_item("viewport_fps"), [0.0]) model.on_ended(self.gesture_payload) self._current_editing_op = None def on_canceled(self, payload_type=TransformDragGesturePayload): self._viewport_on_ended() if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return model = self.sender.model if not model: return item = self.gesture_payload.changing_item if item.operation != self._current_editing_op: return model.on_canceled(self.gesture_payload) self._current_editing_op = None def _publish_delta(self, operation: Operation, delta: List[float]): # pragma: no cover if operation == Operation.TRANSLATE: self._settings.set_float_array(TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ, delta) elif operation == Operation.ROTATE: self._settings.set_float_array(TRANSFORM_GIZMO_ROTATE_DELTA_XYZW, delta) elif operation == Operation.SCALE: self._settings.set_float_array(TRANSFORM_GIZMO_SCALE_DELTA_XYZ, delta) def __set_viewport_manipulating(self, value: int): # Signal that user-manipulation has started for this stage if self._stage_id is None: self._stage_id = UsdUtils.StageCache.Get().GetId(self._usd_context.get_stage()).ToLongInt() key = f"/app/viewport/{self._stage_id}/manipulating" cur_value = self._settings.get(key) or 0 self._settings.set(key, cur_value + value) def _viewport_on_began(self): self._viewport_on_ended() if self._viewport_api is None: self._vp1_window_state = Viewport1WindowState() self.__set_viewport_manipulating(1) def _viewport_on_ended(self): if self._vp1_window_state: self._vp1_window_state.destroy() self._vp1_window_state = None if self._stage_id: self.__set_viewport_manipulating(-1) self._stage_id = None class PrimTranslateChangedGesture(TranslateChangedGesture, PrimTransformChangedGestureBase): def __init__(self, snap_manager: SnapProviderManager, **kwargs): PrimTransformChangedGestureBase.__init__(self, **kwargs) TranslateChangedGesture.__init__(self) self._accumulated_translate = Gf.Vec3d(0) self._snap_manager = snap_manager def on_began(self): PrimTransformChangedGestureBase.on_began(self, TranslateDragGesturePayload) self._accumulated_translate = Gf.Vec3d(0) model = self._get_model(TranslateDragGesturePayload) if model and self._can_snap(model): # TODO No need for gesture=self when VP1 has viewport_api self._snap_manager.on_began(model.consolidated_xformable_prim_data_curr.keys(), gesture=self) if model: model.set_floats(model.get_item("translate_delta"), [0, 0, 0]) def on_ended(self): PrimTransformChangedGestureBase.on_ended(self, TranslateDragGesturePayload) model = self._get_model(TranslateDragGesturePayload) if model and self._can_snap(model): self._snap_manager.on_ended() def on_canceled(self): PrimTransformChangedGestureBase.on_canceled(self, TranslateDragGesturePayload) model = self._get_model(TranslateDragGesturePayload) if model and self._can_snap(model): self._snap_manager.on_ended() @carb.profiler.profile def on_changed(self): PrimTransformChangedGestureBase.on_changed(self, TranslateDragGesturePayload) model = self._get_model(TranslateDragGesturePayload) if not model: return manip_xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator"))) new_manip_xform = Gf.Matrix4d(manip_xform) rotation_mtx = manip_xform.ExtractRotationMatrix() rotation_mtx.Orthonormalize() translate_delta = self.gesture_payload.moved_delta translate = self.gesture_payload.moved axis = self.gesture_payload.axis # slow Gf.Vec3d(*translate_delta) translate_delta = Gf.Vec3d(translate_delta[0], translate_delta[1], translate_delta[2]) if model.op_settings_listener.translation_mode == c.TRANSFORM_MODE_LOCAL: translate_delta = translate_delta * rotation_mtx self._accumulated_translate += translate_delta def apply_position(snap_world_pos=None, snap_world_orient=None, keep_spacing: bool = True): nonlocal new_manip_xform if self.state != sc.GestureState.CHANGED: return # only set translate if no snap or only snap to position item_name = "translate" if snap_world_pos and ( math.isfinite(snap_world_pos[0]) and math.isfinite(snap_world_pos[1]) and math.isfinite(snap_world_pos[2]) ): if snap_world_orient is None: new_manip_xform.SetTranslateOnly(Gf.Vec3d(snap_world_pos[0], snap_world_pos[1], snap_world_pos[2])) new_manip_xform = self._begin_scale_mtx * new_manip_xform else: new_manip_xform.SetTranslateOnly(Gf.Vec3d(snap_world_pos[0], snap_world_pos[1], snap_world_pos[2])) new_manip_xform.SetRotateOnly(snap_world_orient) # set transform if snap both position and orientation item_name = "no_scale_transform_manipulator" else: new_manip_xform.SetTranslateOnly(self._begin_xform.ExtractTranslation() + self._accumulated_translate) new_manip_xform = self._begin_scale_mtx * new_manip_xform model.set_floats(model.get_item("translate_delta"), translate_delta) if model.custom_manipulator_enabled: self._publish_delta(Operation.TRANSLATE, translate_delta) if keep_spacing is False: mode_item = model.get_item("manipulator_mode") prev_mode = model.get_as_ints(mode_item) model.set_ints(mode_item, [int(ManipulationMode.UNIFORM)]) model.set_floats(model.get_item(item_name), flatten(new_manip_xform)) if keep_spacing is False: model.set_ints(mode_item, prev_mode) # only do snap to surface if drag the center point if ( model.snap_settings_listener.snap_enabled and model.snap_settings_listener.snap_provider and axis == [1, 1, 1] ): ndc_location = None if self._viewport_api: # No mouse location is available, have to convert back to NDC space ndc_location = self.sender.transform_space( sc.Space.WORLD, sc.Space.NDC, self.gesture_payload.ray_closest_point ) if self._snap_manager.get_snap_pos( new_manip_xform, ndc_location, self.sender.scene_view, lambda **kwargs: apply_position( kwargs.get("position", None), kwargs.get("orient", None), kwargs.get("keep_spacing", True) ), ): return apply_position() def _get_model(self, payload_type) -> PrimTransformModel: if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return None return self.sender.model def _can_snap(self, model: PrimTransformModel): axis = self.gesture_payload.axis if ( model.snap_settings_listener.snap_enabled and model.snap_settings_listener.snap_provider and axis == [1, 1, 1] ): return True return False class PrimRotateChangedGesture(RotateChangedGesture, PrimTransformChangedGestureBase): def __init__(self, **kwargs): PrimTransformChangedGestureBase.__init__(self, **kwargs) RotateChangedGesture.__init__(self) def on_began(self): PrimTransformChangedGestureBase.on_began(self, RotateDragGesturePayload) model = self.sender.model if model: model.set_floats(model.get_item("rotate_delta"), [0, 0, 0, 0]) def on_ended(self): PrimTransformChangedGestureBase.on_ended(self, RotateDragGesturePayload) def on_canceled(self): PrimTransformChangedGestureBase.on_canceled(self, RotateDragGesturePayload) @carb.profiler.profile def on_changed(self): PrimTransformChangedGestureBase.on_changed(self, RotateDragGesturePayload) if ( not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, RotateDragGesturePayload) ): return model = self.sender.model if not model: return axis = self.gesture_payload.axis angle = self.gesture_payload.angle angle_delta = self.gesture_payload.angle_delta screen_space = self.gesture_payload.screen_space free_rotation = self.gesture_payload.free_rotation axis = Gf.Vec3d(*axis[:3]) rotate = Gf.Rotation(axis, angle) delta_axis = Gf.Vec4d(*axis, 0.0) rot_matrix = Gf.Matrix4d(1) rot_matrix.SetRotate(rotate) if free_rotation: rotate = Gf.Rotation(axis, angle_delta) rot_matrix = Gf.Matrix4d(1) rot_matrix.SetRotate(rotate) xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator"))) full_xform = self._begin_scale_mtx * xform translate = full_xform.ExtractTranslation() no_translate_mtx = Gf.Matrix4d(full_xform) no_translate_mtx.SetTranslateOnly(Gf.Vec3d(0)) no_translate_mtx = no_translate_mtx * rot_matrix new_transform_matrix = no_translate_mtx.SetTranslateOnly(translate) delta_axis = no_translate_mtx * delta_axis elif model.op_settings_listener.rotation_mode == c.TRANSFORM_MODE_GLOBAL or screen_space: begin_full_xform = self._begin_scale_mtx * self._begin_xform translate = begin_full_xform.ExtractTranslation() no_translate_mtx = Gf.Matrix4d(begin_full_xform) no_translate_mtx.SetTranslateOnly(Gf.Vec3d(0)) no_translate_mtx = no_translate_mtx * rot_matrix new_transform_matrix = no_translate_mtx.SetTranslateOnly(translate) delta_axis = no_translate_mtx * delta_axis else: self._begin_xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator"))) new_transform_matrix = self._begin_scale_mtx * rot_matrix * self._begin_xform delta_axis.Normalize() delta_rotate = Gf.Rotation(delta_axis[:3], angle_delta) quat = delta_rotate.GetQuaternion() real = quat.GetReal() imaginary = quat.GetImaginary() rd = [imaginary[0], imaginary[1], imaginary[2], real] model.set_floats(model.get_item("rotate_delta"), rd) if model.custom_manipulator_enabled: self._publish_delta(Operation.ROTATE, rd) model.set_floats(model.get_item("rotate"), flatten(new_transform_matrix)) class PrimScaleChangedGesture(ScaleChangedGesture, PrimTransformChangedGestureBase): def __init__(self, **kwargs): PrimTransformChangedGestureBase.__init__(self, **kwargs) ScaleChangedGesture.__init__(self) def on_began(self): PrimTransformChangedGestureBase.on_began(self, ScaleDragGesturePayload) model = self.sender.model if model: model.set_floats(model.get_item("scale_delta"), [0, 0, 0]) def on_ended(self): PrimTransformChangedGestureBase.on_ended(self, ScaleDragGesturePayload) def on_canceled(self): PrimTransformChangedGestureBase.on_canceled(self, ScaleDragGesturePayload) @carb.profiler.profile def on_changed(self): PrimTransformChangedGestureBase.on_changed(self, ScaleDragGesturePayload) if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, ScaleDragGesturePayload): return model = self.sender.model if not model: return axis = self.gesture_payload.axis scale = self.gesture_payload.scale axis = Gf.Vec3d(*axis[:3]) scale_delta = scale * axis scale_vec = Gf.Vec3d() for i in range(3): scale_vec[i] = scale_delta[i] if scale_delta[i] else 1 scale_matrix = Gf.Matrix4d(1.0) scale_matrix.SetScale(scale_vec) scale_matrix *= self._begin_scale_mtx new_transform_matrix = scale_matrix * self._begin_xform s = Gf.Vec3d(*model.get_as_floats(model.get_item("scale_manipulator"))) sd = [s_n / s_o for s_n, s_o in zip([scale_matrix[0][0], scale_matrix[1][1], scale_matrix[2][2]], s)] model.set_floats(model.get_item("scale_delta"), sd) if model.custom_manipulator_enabled: self._publish_delta(Operation.SCALE, sd) model.set_floats(model.get_item("scale"), flatten(new_transform_matrix)) class PrimTransformModel(AbstractTransformManipulatorModel): def __init__(self, usd_context_name: str = "", viewport_api=None): super().__init__() self._transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] # visual transform of manipulator self._no_scale_transform_manipulator = Gf.Matrix4d(1.0) # transform of manipulator without scale self._scale_manipulator = Gf.Vec3d(1.0) # scale of manipulator self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._timeline = omni.timeline.get_timeline_interface() self._app = omni.kit.app.get_app() self._usd_context_name = usd_context_name self._usd_context = omni.usd.get_context(usd_context_name) self._stage: Usd.Stage = None self._enabled_hosting_widget_count: int = 0 self._stage_listener = None self._xformable_prim_paths: List[Sdf.Path] = [] self._xformable_prim_paths_sorted: List[Sdf.Path] = [] self._xformable_prim_paths_set: Set[Sdf.Path] = set() self._xformable_prim_paths_prefix_set: Set[Sdf.Path] = set() self._consolidated_xformable_prim_paths: List[Sdf.Path] = [] self._pivot_prim: Usd.Prim = None self._update_prim_xform_from_prim_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None self._current_editing_op: Operation = None self._ignore_xform_data_change = False self._timeline_sub = None self._pending_changed_paths: Dict[Sdf.Path, bool] = {} self._pending_changed_paths_for_xform_data: Set[Sdf.Path] = set() self._mode = ManipulationMode.PIVOT self._viewport_fps: float = 0.0 # needed this as heuristic for delaying the visual update of manipulator to match rendering self._viewport_api = viewport_api self._delay_dirty_tasks_or_futures: Dict[int, Union[asyncio.Task, concurrent.futures.Future]] = {} self._no_scale_transform_manipulator_item = sc.AbstractManipulatorItem() self._items["no_scale_transform_manipulator"] = self._no_scale_transform_manipulator_item self._scale_manipulator_item = sc.AbstractManipulatorItem() self._items["scale_manipulator"] = self._scale_manipulator_item self._transform_manipulator_item = sc.AbstractManipulatorItem() self._items["transform_manipulator"] = self._transform_manipulator_item self._manipulator_mode_item = sc.AbstractManipulatorItem() self._items["manipulator_mode"] = self._manipulator_mode_item self._viewport_fps_item = sc.AbstractManipulatorItem() self._items["viewport_fps"] = self._viewport_fps_item self._set_default_settings() # subscribe to snap events self._snap_settings_listener = SnapSettingsListener( enabled_setting_path=None, move_x_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_y_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_z_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, rotate_setting_path=snap_c.SNAP_ROTATE_SETTING_PATH, scale_setting_path=snap_c.SNAP_SCALE_SETTING_PATH, provider_setting_path=snap_c.SNAP_PROVIDER_NAME_SETTING_PATH, ) # subscribe to operation/mode events self._op_settings_listener = OpSettingsListener() self._op_settings_listener_sub = self._op_settings_listener.subscribe_listener(self._on_op_listener_changed) self._placement_sub = self._settings.subscribe_to_node_change_events( prim_c.MANIPULATOR_PLACEMENT_SETTING, self._on_placement_setting_changed ) self._placement = Placement.LAST_PRIM_PIVOT placement = self._settings.get(prim_c.MANIPULATOR_PLACEMENT_SETTING) self._update_placement(placement) # cache unique setting path for selection pivot position # vp1 default self._selection_pivot_position_path = TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/Viewport" # vp2 if self._viewport_api: self._selection_pivot_position_path = ( TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/" + self._viewport_api.id.split("/")[0] ) # update setting with pivot placement position on init self._update_temp_pivot_world_position() def subscribe_to_value_and_get_current(setting_val_name: str, setting_path: str): sub = self._settings.subscribe_to_node_change_events( setting_path, lambda item, type: setattr(self, setting_val_name, self._dict.get(item)) ) setattr(self, setting_val_name, self._settings.get(setting_path)) return sub # subscribe to zero-gravity settings self._custom_manipulator_enabled_sub = subscribe_to_value_and_get_current( "_custom_manipulator_enabled", TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED ) # subscribe to USD related events self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="PrimTransformModel stage event" ) if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_opened() self._warning_notification = None self._selected_instance_proxy_paths = set() def __del__(self): self.destroy() def destroy(self): if self._warning_notification: self._warning_notification.dismiss() self._warning_notification = None self._op_settings_listener_sub = None if self._op_settings_listener: self._op_settings_listener.destroy() self._op_settings_listener = None self._stage_event_sub = None if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_closing() self._timeline_sub = None if self._snap_settings_listener: self._snap_settings_listener.destroy() self._snap_settings_listener = None if self._custom_manipulator_enabled_sub: self._settings.unsubscribe_to_change_events(self._custom_manipulator_enabled_sub) self._custom_manipulator_enabled_sub = None if self._placement_sub: self._settings.unsubscribe_to_change_events(self._placement_sub) self._placement_sub = None for task_or_future in self._delay_dirty_tasks_or_futures.values(): task_or_future.cancel() self._delay_dirty_tasks_or_futures.clear() def set_pivot_prim_path(self, path: Sdf.Path) -> bool: if path not in self._xformable_prim_paths_set: carb.log_warn(f"Cannot set pivot prim path to {path}") return False if not self._pivot_prim or self._pivot_prim.GetPath() != path: self._pivot_prim = self._stage.GetPrimAtPath(path) else: return False if self._update_transform_from_prims(): self._item_changed(self._transform_item) return True def get_pivot_prim_path(self) -> Sdf.Path: if self._pivot_prim: return self._pivot_prim.GetPath() return None def on_began(self, payload): item = payload.changing_item self._current_editing_op = item.operation # All selected xformable prims' transforms. Store this for when `Keep Spacing` option is off during snapping, # because it can modify parent's and child're transform differently. self._all_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d, Gf.Vec3d]] = {} # consolidated xformable prims' transforms. If parent is in the dict, child will be excluded. self._consolidated_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d]] = {} for path in self._xformable_prim_paths: prim = self.stage.GetPrimAtPath(path) xform_tuple = omni.usd.get_local_transform_SRT(prim, self._get_current_time_code()) pivot = get_local_transform_pivot_inv(prim, self._get_current_time_code()).GetInverse() self._all_xformable_prim_data_prev[path] = xform_tuple + (pivot,) if path in self._consolidated_xformable_prim_paths: self._consolidated_xformable_prim_data_prev[path] = xform_tuple + (pivot,) self.all_xformable_prim_data_curr = self._all_xformable_prim_data_prev.copy() self.consolidated_xformable_prim_data_curr = self._consolidated_xformable_prim_data_prev.copy() self._pending_changed_paths_for_xform_data.clear() if self.custom_manipulator_enabled: self._settings.set(TRANSFORM_GIZMO_IS_USING, True) def on_changed(self, payload): # Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator, # prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest. self._update_xform_data_from_dirty_paths() def on_ended(self, payload): # Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator, # prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest. self._update_xform_data_from_dirty_paths() carb.profiler.begin(1, "PrimTransformChangedGestureBase.TransformPrimSRT.all") paths = [] new_translations = [] new_rotation_eulers = [] new_rotation_orders = [] new_scales = [] old_translations = [] old_rotation_eulers = [] old_rotation_orders = [] old_scales = [] for path, (s, r, ro, t, pivot) in self.all_xformable_prim_data_curr.items(): # Data didn't change if self._all_xformable_prim_data_prev[path] == self.all_xformable_prim_data_curr[path]: # carb.log_info(f"Skip {path}") continue (old_s, old_r, old_ro, old_t, old_pivot) = self._all_xformable_prim_data_prev[path] paths.append(path.pathString) new_translations += [t[0], t[1], t[2]] new_rotation_eulers += [r[0], r[1], r[2]] new_rotation_orders += [ro[0], ro[1], ro[2]] new_scales += [s[0], s[1], s[2]] old_translations += [old_t[0], old_t[1], old_t[2]] old_rotation_eulers += [old_r[0], old_r[1], old_r[2]] old_rotation_orders += [old_ro[0], old_ro[1], old_ro[2]] old_scales += [old_s[0], old_s[1], old_s[2]] self._ignore_xform_data_change = True self._on_ended_transform( paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales, old_translations, old_rotation_eulers, old_rotation_orders, old_scales, ) self._ignore_xform_data_change = False carb.profiler.end(1) if self.custom_manipulator_enabled: self._settings.set(TRANSFORM_GIZMO_IS_USING, False) # if the manipulator was locked to orientation or translation, # refresh it on_ended so the transform is up to date mode = self._get_transform_mode_for_current_op() if self._should_keep_manipulator_orientation_unchanged( mode ) or self._should_keep_manipulator_translation_unchanged(mode): # set editing op to None AFTER _should_keep_manipulator_*_unchanged but # BEFORE self._update_transform_from_prims self._current_editing_op = None if self._update_transform_from_prims(): self._item_changed(self._transform_item) self._current_editing_op = None def _on_ended_transform( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], old_translations: List[float], old_rotation_eulers: List[float], old_rotation_orders: List[int], old_scales: List[float], ): """Function ran by on_ended(). Can be overridden to change the behavior. Do not remove this function: can be used outside of this code""" self._alert_if_selection_has_instance_proxies() omni.kit.commands.execute( "TransformMultiPrimsSRTCpp", count=len(paths), paths=paths, new_translations=new_translations, new_rotation_eulers=new_rotation_eulers, new_rotation_orders=new_rotation_orders, new_scales=new_scales, old_translations=old_translations, old_rotation_eulers=old_rotation_eulers, old_rotation_orders=old_rotation_orders, old_scales=old_scales, usd_context_name=self._usd_context_name, time_code=self._get_current_time_code().GetValue(), ) def on_canceled(self, payload): if self.custom_manipulator_enabled: self._settings.set(TRANSFORM_GIZMO_IS_USING, False) self._current_editing_op = None def widget_enabled(self): self._enabled_hosting_widget_count += 1 # just changed from no active widget to 1 active widget if self._enabled_hosting_widget_count == 1: # listener only needs to be activated if manipulator is visible if self._consolidated_xformable_prim_paths: assert self._stage_listener is None self._stage_listener = Tf.Notice.Register( Usd.Notice.ObjectsChanged, self._on_objects_changed, self._stage ) carb.log_info("Tf.Notice.Register in PrimTransformModel") def _clear_temp_pivot_position_setting(self): if self._settings.get(self._selection_pivot_position_path): self._settings.destroy_item(self._selection_pivot_position_path) def widget_disabled(self): self._enabled_hosting_widget_count -= 1 self._clear_temp_pivot_position_setting() assert self._enabled_hosting_widget_count >= 0 if self._enabled_hosting_widget_count < 0: carb.log_error(f"manipulator enabled widget tracker out of sync: {self._enabled_hosting_widget_count}") self._enabled_hosting_widget_count = 0 # If no hosting manipulator is active, revoke the listener since there's no need to sync Transform if self._enabled_hosting_widget_count == 0: if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None carb.log_info("Tf.Notice.Revoke in PrimTransformModel") for task_or_future in self._delay_dirty_tasks_or_futures.values(): task_or_future.cancel() self._delay_dirty_tasks_or_futures.clear() def set_floats(self, item: sc.AbstractManipulatorItem, value: Sequence[float]): if item == self._viewport_fps_item: self._viewport_fps = value[0] return flag = None if issubclass(type(item), AbstractTransformManipulatorModel.OperationItem): if ( item.operation == Operation.TRANSLATE_DELTA or item.operation == Operation.ROTATE_DELTA or item.operation == Operation.SCALE_DELTA ): return if item.operation == Operation.TRANSLATE: flag = OpFlag.TRANSLATE elif item.operation == Operation.ROTATE: flag = OpFlag.ROTATE elif item.operation == Operation.SCALE: flag = OpFlag.SCALE transform = Gf.Matrix4d(*value) elif item == self._transform_manipulator_item: flag = OpFlag.TRANSLATE | OpFlag.ROTATE | OpFlag.SCALE transform = Gf.Matrix4d(*value) elif item == self._no_scale_transform_manipulator_item: flag = OpFlag.TRANSLATE | OpFlag.ROTATE old_manipulator_scale_mtx = Gf.Matrix4d(1.0) old_manipulator_scale_mtx.SetScale(self._scale_manipulator) transform = old_manipulator_scale_mtx * Gf.Matrix4d(*value) if flag is not None: if self._mode == ManipulationMode.PIVOT: self._transform_selected_prims( transform, self._no_scale_transform_manipulator, self._scale_manipulator, flag ) elif self._mode == ManipulationMode.UNIFORM: self._transform_all_selected_prims_to_manipulator_pivot(transform, flag) else: carb.log_warn(f"Unsupported item {item}") def set_ints(self, item: sc.AbstractManipulatorItem, value: Sequence[int]): if item == self._manipulator_mode_item: try: self._mode = ManipulationMode(value[0]) except: carb.log_error(traceback.format_exc()) else: carb.log_warn(f"unsupported item {item}") return None def get_as_floats(self, item: sc.AbstractManipulatorItem): if item == self._transform_item: return self._transform elif item == self._no_scale_transform_manipulator_item: return flatten(self._no_scale_transform_manipulator) elif item == self._scale_manipulator_item: return [self._scale_manipulator[0], self._scale_manipulator[1], self._scale_manipulator[2]] elif item == self._transform_manipulator_item: scale_mtx = Gf.Matrix4d(1) scale_mtx.SetScale(self._scale_manipulator) return flatten(scale_mtx * self._no_scale_transform_manipulator) else: carb.log_warn(f"unsupported item {item}") return None def get_as_ints(self, item: sc.AbstractManipulatorItem): if item == self._manipulator_mode_item: return [int(self._mode)] else: carb.log_warn(f"unsupported item {item}") return None def get_operation(self) -> Operation: if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: return Operation.TRANSLATE elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: return Operation.ROTATE elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_SCALE: return Operation.SCALE return Operation.NONE def get_snap(self, item: AbstractTransformManipulatorModel.OperationItem): if not self._snap_settings_listener.snap_enabled: return None if item.operation == Operation.TRANSLATE: if self._snap_settings_listener.snap_provider: return None return ( self._snap_settings_listener.snap_move_x, self._snap_settings_listener.snap_move_y, self._snap_settings_listener.snap_move_z, ) elif item.operation == Operation.ROTATE: return self._snap_settings_listener.snap_rotate elif item.operation == Operation.SCALE: return self._snap_settings_listener.snap_scale return None @property def stage(self): return self._stage @property def custom_manipulator_enabled(self): return self._custom_manipulator_enabled @property def snap_settings_listener(self): return self._snap_settings_listener @property def op_settings_listener(self): return self._op_settings_listener @property def usd_context(self) -> omni.usd.UsdContext: return self._usd_context @property def xformable_prim_paths(self) -> List[Sdf.Path]: return self._xformable_prim_paths @carb.profiler.profile def _update_xform_data_from_dirty_paths(self): for p in self._pending_changed_paths_for_xform_data: prim_path = p.GetPrimPath() if prim_path in self.all_xformable_prim_data_curr and self._path_may_affect_transform(p): prim = self.stage.GetPrimAtPath(prim_path) xform_tuple = omni.usd.get_local_transform_SRT(prim, self._get_current_time_code()) pivot = get_local_transform_pivot_inv(prim, self._get_current_time_code()).GetInverse() self.all_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,) if prim_path in self._consolidated_xformable_prim_paths: self.consolidated_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,) self._pending_changed_paths_for_xform_data.clear() @carb.profiler.profile def _transform_selected_prims( self, new_manipulator_transform: Gf.Matrix4d, old_manipulator_transform_no_scale: Gf.Matrix4d, old_manipulator_scale: Gf.Vec3d, dirty_ops: OpFlag, ): carb.profiler.begin(1, "omni.kit.manipulator.prim.model._transform_selected_prims.prepare_data") paths = [] new_translations = [] new_rotation_eulers = [] new_rotation_orders = [] new_scales = [] self._xform_cache.Clear() # any op may trigger a translation change if multi-manipulating should_update_translate = dirty_ops & OpFlag.TRANSLATE or len( self._xformable_prim_paths) > 1 or self._placement != Placement.LAST_PRIM_PIVOT should_update_rotate = dirty_ops & OpFlag.ROTATE should_update_scale = dirty_ops & OpFlag.SCALE old_manipulator_scale_mtx = Gf.Matrix4d(1.0) old_manipulator_scale_mtx.SetScale(old_manipulator_scale) old_manipulator_transform_inv = (old_manipulator_scale_mtx * old_manipulator_transform_no_scale).GetInverse() for path in self._consolidated_xformable_prim_paths: if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString): continue selected_prim = self._stage.GetPrimAtPath(path) # We check whether path is in consolidated_xformable_prim_data_curr because it may have not made it the dictionary if an error occured if not selected_prim or path not in self.consolidated_xformable_prim_data_curr: continue (s, r, ro, t, selected_pivot) = self.consolidated_xformable_prim_data_curr[path] selected_pivot_inv = selected_pivot.GetInverse() selected_local_to_world_mtx = self._xform_cache.GetLocalToWorldTransform(selected_prim) selected_parent_to_world_mtx = self._xform_cache.GetParentToWorldTransform(selected_prim) # Transform the prim from world space to pivot's space # Then apply the new pivotPrim-to-world-space transform matrix selected_local_to_world_pivot_mtx = ( selected_pivot * selected_local_to_world_mtx * old_manipulator_transform_inv * new_manipulator_transform ) world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse() selected_local_mtx_new = selected_local_to_world_pivot_mtx * world_to_parent_mtx * selected_pivot_inv if should_update_translate: translation = selected_local_mtx_new.ExtractTranslation() if should_update_rotate: # Construct the new rotation from old scale and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_s_mtx = Gf.Matrix4d(1.0) old_s_mtx.SetScale(Gf.Vec3d(s)) old_t_mtx = Gf.Matrix4d(1.0) old_t_mtx.SetTranslate(Gf.Vec3d(t)) rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation() axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]]) index_order = Gf.Vec3i() for i in range(3): index_order[ro[i]] = 2 - i rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]]) rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro) if should_update_scale: # Construct the new scale from old rotation and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1)) new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse() scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2]) translation = translation if should_update_translate else t rotation = rotation if should_update_rotate else r scale = scale if should_update_scale else s paths.append(path.pathString) new_translations += [translation[0], translation[1], translation[2]] new_rotation_eulers += [rotation[0], rotation[1], rotation[2]] new_rotation_orders += [ro[0], ro[1], ro[2]] new_scales += [scale[0], scale[1], scale[2]] xform_tuple = (scale, rotation, ro, translation, selected_pivot) self.consolidated_xformable_prim_data_curr[path] = xform_tuple self.all_xformable_prim_data_curr[path] = xform_tuple carb.profiler.end(1) self._ignore_xform_data_change = True self._do_transform_selected_prims(paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales) self._ignore_xform_data_change = False def _do_transform_selected_prims( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], ): """Function ran by _transform_selected_prims(). Can be overridden to change the behavior Do not remove this function: can be used outside of this code""" self._alert_if_selection_has_instance_proxies() omni.kit.commands.create( "TransformMultiPrimsSRTCpp", count=len(paths), no_undo=True, paths=paths, new_translations=new_translations, new_rotation_eulers=new_rotation_eulers, new_rotation_orders=new_rotation_orders, new_scales=new_scales, usd_context_name=self._usd_context_name, time_code=self._get_current_time_code().GetValue(), ).do() @carb.profiler.profile def _transform_all_selected_prims_to_manipulator_pivot( self, new_manipulator_transform: Gf.Matrix4d, dirty_ops: OpFlag, ): paths = [] new_translations = [] new_rotation_eulers = [] new_rotation_orders = [] new_scales = [] old_translations = [] old_rotation_eulers = [] old_rotation_orders = [] old_scales = [] self._xform_cache.Clear() # any op may trigger a translation change if multi-manipulating should_update_translate = dirty_ops & OpFlag.TRANSLATE or len(self._xformable_prim_paths) > 1 should_update_rotate = dirty_ops & OpFlag.ROTATE should_update_scale = dirty_ops & OpFlag.SCALE for path in self._xformable_prim_paths_sorted: if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString): continue selected_prim = self._stage.GetPrimAtPath(path) # We check whether path is in all_xformable_prim_data_curr because it may have not made it the dictionary if an error occured if not selected_prim or path not in self.all_xformable_prim_data_curr: continue (s, r, ro, t, selected_pivot) = self.all_xformable_prim_data_curr[path] selected_parent_to_world_mtx = self._xform_cache.GetParentToWorldTransform(selected_prim) world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse() selected_local_mtx_new = new_manipulator_transform * world_to_parent_mtx * selected_pivot.GetInverse() if should_update_translate: translation = selected_local_mtx_new.ExtractTranslation() if should_update_rotate: # Construct the new rotation from old scale and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_s_mtx = Gf.Matrix4d(1.0) old_s_mtx.SetScale(Gf.Vec3d(s)) old_t_mtx = Gf.Matrix4d(1.0) old_t_mtx.SetTranslate(Gf.Vec3d(t)) rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation() axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]]) index_order = Gf.Vec3i() for i in range(3): index_order[ro[i]] = 2 - i rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]]) rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro) if should_update_scale: # Construct the new scale from old rotation and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1)) new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse() scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2]) # any op may trigger a translation change if multi-manipulating translation = translation if should_update_translate else t rotation = rotation if should_update_rotate else r scale = scale if should_update_scale else s paths.append(path.pathString) new_translations += [translation[0], translation[1], translation[2]] new_rotation_eulers += [rotation[0], rotation[1], rotation[2]] new_rotation_orders += [ro[0], ro[1], ro[2]] new_scales += [scale[0], scale[1], scale[2]] old_translations += [t[0], t[1], t[2]] old_rotation_eulers += [r[0], r[1], r[2]] old_rotation_orders += [ro[0], ro[1], ro[2]] old_scales += [s[0], s[1], s[2]] xform_tuple = (scale, rotation, ro, translation, selected_pivot) self.all_xformable_prim_data_curr[path] = xform_tuple if path in self.consolidated_xformable_prim_data_curr: self.consolidated_xformable_prim_data_curr[path] = xform_tuple self._ignore_xform_data_change = True self._do_transform_all_selected_prims_to_manipulator_pivot( paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales ) self._ignore_xform_data_change = False def _alert_if_selection_has_instance_proxies(self): if self._selected_instance_proxy_paths and (not self._warning_notification or self._warning_notification.dismissed): try: import omni.kit.notification_manager as nm self._warning_notification = nm.post_notification( "Children of an instanced prim cannot be modified, uncheck Instanceable on the instanced prim to modify child prims.", status=nm.NotificationStatus.WARNING ) except ImportError: pass def _do_transform_all_selected_prims_to_manipulator_pivot( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], ): """Function ran by _transform_all_selected_prims_to_manipulator_pivot(). Can be overridden to change the behavior. Do not remove this function: can be used outside of this code""" self._alert_if_selection_has_instance_proxies() omni.kit.commands.create( "TransformMultiPrimsSRTCpp", count=len(paths), no_undo=True, paths=paths, new_translations=new_translations, new_rotation_eulers=new_rotation_eulers, new_rotation_orders=new_rotation_orders, new_scales=new_scales, usd_context_name=self._usd_context_name, time_code=self._get_current_time_code().GetValue(), ).do() def _on_stage_event(self, event: carb.events.IEvent): if event.type == int(omni.usd.StageEventType.OPENED): self._on_stage_opened() elif event.type == int(omni.usd.StageEventType.CLOSING): self._on_stage_closing() def _on_stage_opened(self): self._stage = self._usd_context.get_stage() self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop( self._on_timeline_event ) self._current_time = self._timeline.get_current_time() self._xform_cache = UsdGeom.XformCache(self._get_current_time_code()) def _on_stage_closing(self): self._stage = None self._xform_cache = None self._xformable_prim_paths.clear() self._xformable_prim_paths_sorted.clear() self._xformable_prim_paths_set.clear() self._xformable_prim_paths_prefix_set.clear() self._consolidated_xformable_prim_paths.clear() self._pivot_prim = None self._timeline_sub = None if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None carb.log_info("Tf.Notice.Revoke in PrimTransformModel") self._pending_changed_paths.clear() if self._update_prim_xform_from_prim_task_or_future is not None: self._update_prim_xform_from_prim_task_or_future.cancel() self._update_prim_xform_from_prim_task_or_future = None def on_selection_changed(self, selection: List[Sdf.Path]): if self._update_prim_xform_from_prim_task_or_future is not None: self._update_prim_xform_from_prim_task_or_future.cancel() self._update_prim_xform_from_prim_task_or_future = None self._selected_instance_proxy_paths.clear() self._xformable_prim_paths.clear() self._xformable_prim_paths_set.clear() self._xformable_prim_paths_prefix_set.clear() self._consolidated_xformable_prim_paths.clear() self._pivot_prim = None for sdf_path in selection: prim = self._stage.GetPrimAtPath(sdf_path) if prim and prim.IsA(UsdGeom.Xformable) and prim.IsActive(): self._xformable_prim_paths.append(sdf_path) if self._xformable_prim_paths: # Make a sorted list so parents always appears before child self._xformable_prim_paths_sorted = self._xformable_prim_paths.copy() self._xformable_prim_paths_sorted.sort() # Find the most recently selected valid xformable prim as the pivot prim where the transform gizmo is located at. self._pivot_prim = self._stage.GetPrimAtPath(self._xformable_prim_paths[-1]) # Get least common prims ancestors. # We do this so that if one selected prim is a descendant of other selected prim, the descendant prim won't be # transformed twice. self._consolidated_xformable_prim_paths = Sdf.Path.RemoveDescendentPaths(self._xformable_prim_paths) # Filter all instance proxy paths. for path in self._consolidated_xformable_prim_paths: prim = self._stage.GetPrimAtPath(path) if prim.IsInstanceProxy(): self._selected_instance_proxy_paths.add(sdf_path) self._xformable_prim_paths_set.update(self._xformable_prim_paths) for path in self._xformable_prim_paths_set: self._xformable_prim_paths_prefix_set.update(path.GetPrefixes()) if self._update_transform_from_prims(): self._item_changed(self._transform_item) # Happens when host widget is already enabled and first selection in a new stage if self._enabled_hosting_widget_count > 0 and self._stage_listener is None: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_objects_changed, self._stage) carb.log_info("Tf.Notice.Register in PrimTransformModel") def _should_keep_manipulator_orientation_unchanged(self, mode: str) -> bool: # Exclude snap_to_face. During snap_to_face operation, it may modify the orientation of object to confrom to surface # normal and the `new_manipulator_transform` param for `_transform_selected_prims` is set to the final transform # of the manipulated prim. However, if we use old rotation in the condition below, _no_scale_transform_manipulator # will not confrom to the new orientation, and _transform_selected_prims would double rotate the prims because it # sees the rotation diff between the old prim orientation (captured at on_began) vs new normal orient, instead of # current prim orientation vs new normal orientation. # Plus, it is nice to see the normal of the object changing while snapping. snap_provider_enabled = self.snap_settings_listener.snap_enabled and self.snap_settings_listener.snap_provider # When the manipulator is being manipulated as local translate or scale, we do not want to change the rotation of # the manipulator even if it's rotated, otherwise the direction of moving or scaling will change and can be very hard to control. # It can happen when you move a prim that has a constraint on it (e.g. lookAt) # In this case keep the rotation the same as on_began return ( mode == c.TRANSFORM_MODE_LOCAL and (self._current_editing_op == Operation.TRANSLATE or self._current_editing_op == Operation.SCALE) and not snap_provider_enabled ) def _should_keep_manipulator_translation_unchanged(self, mode: str) -> bool: # When the pivot placement is BBOX_CENTER and multiple prims being rotated, the bbox center may shifts, and the # rotation center will shift with them. This causes weird user experience. So we pin the rotation center until # mouse is released. return ( self._current_editing_op == Operation.ROTATE and (self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE) ) def _get_transform_mode_for_current_op(self) -> str: mode = c.TRANSFORM_MODE_LOCAL if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: mode = self._op_settings_listener.rotation_mode elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: mode = self._op_settings_listener.translation_mode return mode # Adds a delay to the visual update during translate (only) manipulation # It's due to the renderer having a delay of rendering the mesh and the manipulator appears to drift apart. # It's only an estimation and may varying from scene/renderer setup. async def _delay_dirty(self, transform, id): if self._viewport_fps: render_frame_time = 1.0 / self._viewport_fps * self._settings.get(TRANSLATE_DELAY_FRAME_SETTING) while True: dt = await self._app.next_update_async() render_frame_time -= dt # break a frame early if render_frame_time < dt: break # cancel earlier job if a later one catches up (fps suddenly changed?) earlier_tasks_or_futures = [] for key, task_or_future in self._delay_dirty_tasks_or_futures.items(): if key < id: earlier_tasks_or_futures.append(key) task_or_future.cancel() else: break for key in earlier_tasks_or_futures: self._delay_dirty_tasks_or_futures.pop(key) self._transform = transform self._item_changed(self._transform_item) self._delay_dirty_tasks_or_futures.pop(id) def _update_temp_pivot_world_position(self): if type(self._transform) is not list: return new_world_position = self._transform[12:15] self._settings.set_float_array( self._selection_pivot_position_path, new_world_position ) @carb.profiler.profile def _update_transform_from_prims(self): xform_flattened = self._calculate_transform_from_prim() if self._transform != xform_flattened: self._transform = xform_flattened # update setting with new pivot placement position self._update_temp_pivot_world_position() return True return False def _calculate_transform_from_prim(self): if not self._stage: return False if not self._pivot_prim: return False self._xform_cache.Clear() cur_time = self._get_current_time_code() mode = self._get_transform_mode_for_current_op() pivot_inv = get_local_transform_pivot_inv(self._pivot_prim, cur_time) if self._should_keep_manipulator_orientation_unchanged(mode): pivot_prim_path = self._pivot_prim.GetPath() (s, r, ro, t) = omni.usd.get_local_transform_SRT(self._pivot_prim, cur_time) pivot = get_local_transform_pivot_inv(self._pivot_prim, self._get_current_time_code()).GetInverse() self.all_xformable_prim_data_curr[pivot_prim_path] = (s, r, ro, t) + (pivot,) # This method may be called from _on_op_listener_changed, before any gesture has started # in which case _all_xformable_prim_data_prev would be empty piv_xf_tuple = self._all_xformable_prim_data_prev.get(pivot_prim_path, False) if not piv_xf_tuple: piv_xf_tuple = omni.usd.get_local_transform_SRT(self._pivot_prim, cur_time) pv_xf_pivot = get_local_transform_pivot_inv( self._pivot_prim, self._get_current_time_code() ).GetInverse() self._all_xformable_prim_data_prev[self._pivot_prim.GetPath()] = piv_xf_tuple + (pv_xf_pivot,) (s_p, r_p, ro_p, t_p, t_piv) = piv_xf_tuple xform = self._construct_transform_matrix_from_SRT(t, r_p, ro_p, s, pivot_inv) parent = self._xform_cache.GetLocalToWorldTransform(self._pivot_prim.GetParent()) xform *= parent else: xform = self._xform_cache.GetLocalToWorldTransform(self._pivot_prim) xform = pivot_inv.GetInverse() * xform if self._should_keep_manipulator_translation_unchanged(mode): xform.SetTranslateOnly((self._transform[12], self._transform[13], self._transform[14])) else: # if there's only one selection, we always use LAST_PRIM_PIVOT though if ( self._placement != Placement.LAST_PRIM_PIVOT and self._placement != Placement.REF_PRIM ): average_translation = Gf.Vec3d(0.0) if self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE: world_bound = Gf.Range3d() def get_prim_translation(xformable): xformable_world_mtx = self._xform_cache.GetLocalToWorldTransform(xformable) xformable_pivot_inv = get_local_transform_pivot_inv(xformable, cur_time) xformable_world_mtx = xformable_pivot_inv.GetInverse() * xformable_world_mtx return xformable_world_mtx.ExtractTranslation() for path in self._xformable_prim_paths: xformable = self._stage.GetPrimAtPath(path) if self._placement == Placement.SELECTION_CENTER: average_translation += get_prim_translation(xformable) elif self._placement == Placement.BBOX_CENTER or Placement.BBOX_BASE: bound_range = self._usd_context.compute_path_world_bounding_box(path.pathString) bound_range = Gf.Range3d(Gf.Vec3d(*bound_range[0]), Gf.Vec3d(*bound_range[1])) if not bound_range.IsEmpty(): world_bound = Gf.Range3d.GetUnion(world_bound, bound_range) else: # extend world bound with tranlation for prims with zero bbox, e.g. Xform, Camera prim_translation = get_prim_translation(xformable) world_bound.UnionWith(prim_translation) if self._placement == Placement.SELECTION_CENTER: average_translation /= len(self._xformable_prim_paths) elif self._placement == Placement.BBOX_CENTER: average_translation = world_bound.GetMidpoint() elif self._placement == Placement.BBOX_BASE: # xform may not have bbox but its descendants may have, exclude cases that only xform are selected if not world_bound.IsEmpty(): bbox_center = world_bound.GetMidpoint() bbox_size = world_bound.GetSize() if UsdGeom.GetStageUpAxis(self._stage) == UsdGeom.Tokens.y: # Y-up world average_translation = bbox_center - Gf.Vec3d(0.0, bbox_size[1] / 2.0, 0.0) else: # Z-up world average_translation = bbox_center - Gf.Vec3d(0.0, 0.0, bbox_size[2] / 2.0) else: # fallback to SELECTION_CENTER average_translation /= len(self._xformable_prim_paths) # Only take the translate from selected prim average. # The rotation and scale still comes from pivot prim xform.SetTranslateOnly(average_translation) # instead of using RemoveScaleShear, additional steps made to handle negative scale properly scale, _, _, _ = omni.usd.get_local_transform_SRT(self._pivot_prim, cur_time) scale_epsilon = 1e-6 for i in range(3): if Gf.IsClose(scale[i], 0.0, scale_epsilon): scale[i] = -scale_epsilon if scale[i] < 0 else scale_epsilon inverse_scale = Gf.Matrix4d().SetScale(Gf.Vec3d(1.0 / scale[0], 1.0 / scale[1], 1.0 / scale[2])) xform = inverse_scale * xform # this is the average xform without scale self._no_scale_transform_manipulator = Gf.Matrix4d(xform) # store the scale separately self._scale_manipulator = Gf.Vec3d(scale) # Visual transform of the manipulator xform = xform.RemoveScaleShear() if mode == c.TRANSFORM_MODE_GLOBAL: xform = xform.SetTranslate(xform.ExtractTranslation()) return flatten(xform) def _construct_transform_matrix_from_SRT( self, translation: Gf.Vec3d, rotation_euler: Gf.Vec3d, rotation_order: Gf.Vec3i, scale: Gf.Vec3d, pivot_inv: Gf.Matrix4d, ): trans_mtx = Gf.Matrix4d() rot_mtx = Gf.Matrix4d() scale_mtx = Gf.Matrix4d() trans_mtx.SetTranslate(Gf.Vec3d(translation)) axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] rotation = ( Gf.Rotation(axes[rotation_order[0]], rotation_euler[rotation_order[0]]) * Gf.Rotation(axes[rotation_order[1]], rotation_euler[rotation_order[1]]) * Gf.Rotation(axes[rotation_order[2]], rotation_euler[rotation_order[2]]) ) rot_mtx.SetRotate(rotation) scale_mtx.SetScale(Gf.Vec3d(scale)) return pivot_inv * scale_mtx * rot_mtx * pivot_inv.GetInverse() * trans_mtx def _on_op_listener_changed(self, type: OpSettingsListener.CallbackType, value: str): if type == OpSettingsListener.CallbackType.OP_CHANGED: # cancel all delayed tasks for task_or_future in self._delay_dirty_tasks_or_futures.values(): task_or_future.cancel() self._delay_dirty_tasks_or_futures.clear() self._update_transform_from_prims() self._item_changed(self._transform_item) elif type == OpSettingsListener.CallbackType.TRANSLATION_MODE_CHANGED: if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: if self._update_transform_from_prims(): self._item_changed(self._transform_item) elif type == OpSettingsListener.CallbackType.ROTATION_MODE_CHANGED: if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: if self._update_transform_from_prims(): self._item_changed(self._transform_item) def _update_placement(self, placement_str: str): if placement_str == prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER: placement = Placement.SELECTION_CENTER elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER: placement = Placement.BBOX_CENTER elif placement_str == prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM: placement = Placement.REF_PRIM elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE: placement = Placement.BBOX_BASE else: # placement == prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT or bad values placement = Placement.LAST_PRIM_PIVOT if placement != self._placement: if placement == Placement.LAST_PRIM_PIVOT and self._placement == Placement.REF_PRIM: # reset the pivot prim in case it was changed by MANIPULATOR_PLACEMENT_PICK_REF_PRIM if self._xformable_prim_paths: self._pivot_prim = self._stage.GetPrimAtPath(self._xformable_prim_paths[-1]) self._placement = placement if self._update_transform_from_prims(): self._item_changed(self._transform_item) def _on_placement_setting_changed(self, item, event_type): placement_str = self._dict.get(item) self._update_placement(placement_str) def _check_update_selected_instance_proxy_list(self, path: Sdf.Path, resynced): def track_or_remove_from_instance_proxy_list(prim): valid_proxy = prim and prim.IsActive() and prim.IsInstanceProxy() if valid_proxy: self._selected_instance_proxy_paths.add(prim.GetPath()) else: self._selected_instance_proxy_paths.discard(prim.GetPath()) prim_path = path.GetPrimPath() changed_prim = self._stage.GetPrimAtPath(prim_path) # Update list of instance proxy paths. if resynced and path.IsPrimPath(): if prim_path in self._consolidated_xformable_prim_paths: # Quick path if it's selected already. track_or_remove_from_instance_proxy_list(changed_prim) else: # Slow path to verify if any of its ancestors are changed. for path in self._consolidated_xformable_prim_paths: if not path.HasPrefix(prim_path): continue prim = self._stage.GetPrimAtPath(path) track_or_remove_from_instance_proxy_list(prim) @carb.profiler.profile async def _update_transform_from_prims_async(self): try: check_all_prims = ( self._placement != Placement.LAST_PRIM_PIVOT and self._placement != Placement.REF_PRIM and len(self._xformable_prim_paths) > 1 ) pivot_prim_path = self._pivot_prim.GetPath() for p, resynced in self._pending_changed_paths.items(): self._check_update_selected_instance_proxy_list(p, resynced) prim_path = p.GetPrimPath() # Update either check_all_prims # or prim_path is a prefix of pivot_prim_path (pivot prim's parent affect pivot prim transform) # Note: If you move the manipulator and the prim flies away while manipulator stays in place, check this # condition! if ( # check _xformable_prim_paths_prefix_set so that if the parent path of selected prim(s) changed, it # can still update manipulator transform prim_path in self._xformable_prim_paths_prefix_set if check_all_prims else pivot_prim_path.HasPrefix(prim_path) ): if self._path_may_affect_transform(p): # only delay the visual update in translate mode. should_delay_frame = self._settings.get(TRANSLATE_DELAY_FRAME_SETTING) > 0 if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE and should_delay_frame: xform = self._calculate_transform_from_prim() id = self._app.get_update_number() self._delay_dirty_tasks_or_futures[id] = run_coroutine(self._delay_dirty(xform, id)) else: if self._update_transform_from_prims(): self._item_changed(self._transform_item) break except Exception as e: carb.log_error(traceback.format_exc()) finally: self._pending_changed_paths.clear() self._update_prim_xform_from_prim_task_or_future = None @carb.profiler.profile def _on_objects_changed(self, notice, sender): if not self._pivot_prim: return # collect resynced paths so that removed/added xformOps triggers refresh for path in notice.GetResyncedPaths(): self._pending_changed_paths[path] = True # collect changed only paths for path in notice.GetChangedInfoOnlyPaths(): self._pending_changed_paths[path] = False # if an operation is in progess, record all dirty xform path if self._current_editing_op is not None and not self._ignore_xform_data_change: self._pending_changed_paths_for_xform_data.update(notice.GetChangedInfoOnlyPaths()) if self._update_prim_xform_from_prim_task_or_future is None or self._update_prim_xform_from_prim_task_or_future.done(): self._update_prim_xform_from_prim_task_or_future = run_coroutine(self._update_transform_from_prims_async()) def _on_timeline_event(self, e: carb.events.IEvent): if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED): current_time = e.payload["currentTime"] if current_time != self._current_time: self._current_time = current_time self._xform_cache.SetTime(self._get_current_time_code()) # TODO only update transform if this prim or ancestors transforms are time varying? if self._update_transform_from_prims(): self._item_changed(self._transform_item) def _get_current_time_code(self): return Usd.TimeCode(omni.usd.get_frame_time_code(self._current_time, self._stage.GetTimeCodesPerSecond())) def _set_default_settings(self): self._settings.set_default(TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED, False) self._settings.set_default(TRANSFORM_GIZMO_IS_USING, False) self._settings.set_default(TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ, [0, 0, 0]) self._settings.set_default(TRANSFORM_GIZMO_ROTATE_DELTA_XYZW, [0, 0, 0, 1]) self._settings.set_default(TRANSFORM_GIZMO_SCALE_DELTA_XYZ, [0, 0, 0]) def _should_skip_custom_manipulator_path(self, path: str) -> bool: custom_manipulator_path_prims_settings_path = TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS + path return self._settings.get(custom_manipulator_path_prims_settings_path) def _path_may_affect_transform(self, path: Sdf.Path) -> bool: # Batched changes sent in a SdfChangeBlock may not have property name but only the prim path return not path.ContainsPropertyElements() or UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name)
78,021
Python
44.308943
146
0.623922
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/pivot_button_group.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from pathlib import Path import carb.input import carb.settings import omni.kit.app import omni.kit.context_menu import omni.ui as ui from omni.kit.widget.toolbar.widget_group import WidgetGroup ICON_FOLDER_PATH = Path( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons" ) class PivotButtonGroup(WidgetGroup): # Can't be tested from within kit since it's used by omni.explore.toolbar which is outside of kit repo """ Toolbar entry for pivot placement """ def __init__(self): super().__init__() self._input = carb.input.acquire_input_interface() self._settings = carb.settings.get_settings() def clean(self): super().clean() def __del__(self): self.clean() def get_style(self): style = { "Button.Image::pivot_placement": {"image_url": f"{ICON_FOLDER_PATH}/pivot_location.svg"} } return style def get_button(self) -> ui.ToolButton: return self._button def create(self, default_size): self._button = ui.Button( name="pivot_placement", width=default_size, height=default_size, tooltip="Pivot Placement", mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "multi_sel_pivot", min_menu_entries=1), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b) ) return {"pivot": self._button} def _on_mouse_pressed(self, button, button_id: str, min_menu_entries: int = 2): # override default behavior, left or right click will show menu without delay self._acquire_toolbar_context() if button == 0 or button == 1: self._invoke_context_menu(button_id, min_menu_entries) 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). """ button_id = "multi_sel_pivot" context_menu = omni.kit.context_menu.get_instance() objects = {"widget_name": button_id, "main_toolbar": True} menu_list = omni.kit.context_menu.get_menu_dict(button_id, "omni.kit.manipulator.prim") context_menu.show_context_menu( button_id, objects, menu_list, min_menu_entries, delegate=ui.MenuDelegate() )
3,013
Python
33.25
113
0.637902
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/prim_transform_manipulator_registry.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["TransformManipulatorRegistry"] import weakref from omni.kit.viewport.registry import RegisterScene from .prim_transform_manipulator import PrimTransformManipulator from .reference_prim_marker import ReferencePrimMarker class PrimTransformManipulatorScene: def __init__(self, desc: dict): usd_context_name = desc.get("usd_context_name") self.__transform_manip = PrimTransformManipulator( usd_context_name=usd_context_name, viewport_api=desc.get("viewport_api") ) self.__reference_prim_marker = ReferencePrimMarker( usd_context_name=usd_context_name, manipulator_model=weakref.proxy(self.__transform_manip.model) ) def destroy(self): if self.__transform_manip: self.__transform_manip.destroy() self.__transform_manip = None if self.__reference_prim_marker: self.__reference_prim_marker.destroy() self.__reference_prim_marker = None # PrimTransformManipulator & TransformManipulator don't have their own visibility @property def visible(self): return True @visible.setter def visible(self, value): pass @property def categories(self): return ("manipulator",) @property def name(self): return "Prim Transform" class TransformManipulatorRegistry: def __init__(self): self._scene = RegisterScene(PrimTransformManipulatorScene, "omni.kit.manipulator.prim") def __del__(self): self.destroy() def destroy(self): self._scene = None
2,018
Python
29.590909
108
0.691774
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/tests/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .test_manipulator_prim import TestTransform
478
Python
42.545451
76
0.811715
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/tests/test_manipulator_prim.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import inspect import logging import math import os from pathlib import Path from typing import Awaitable, Callable, List import carb import carb.input import carb.settings import omni.kit.commands import omni.kit.test import omni.kit.ui_test as ui_test import omni.kit.undo import omni.usd from carb.input import MouseEventType from omni.kit.manipulator.prim.settings_constants import Constants as prim_c from omni.kit.manipulator.tool.snap import settings_constants as snap_c from omni.kit.manipulator.tool.snap.builtin_snap_tools import PRIM_SNAP_NAME, SURFACE_SNAP_NAME from omni.kit.manipulator.transform.settings_constants import c from omni.kit.test_helpers_gfx.compare_utils import ComparisonMetric, capture_and_compare from omni.kit.ui_test import Vec2 from omni.kit.viewport.utility import get_active_viewport from omni.ui.tests.test_base import OmniUiTest from pxr import Gf, UsdGeom CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.prim}/data")) OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()).resolve().absolute() logger = logging.getLogger(__name__) class TestTransform(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._context = omni.usd.get_context() self._selection = self._context.get_selection() self._settings = carb.settings.get_settings() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests").joinpath("golden") self._usd_scene_dir = CURRENT_PATH.absolute().resolve().joinpath("tests").joinpath("usd") self._window_width = self._settings.get("/app/window/width") self._window_height = self._settings.get("/app/window/height") # Load renderer before USD is loaded await self._context.new_stage_async() # After running each test async def tearDown(self): # Move and close the stage so selections are reset to avoid triggering ghost gestures. await ui_test.emulate_mouse_move(Vec2(0, 0)) await ui_test.human_delay(5) await self._context.close_stage_async() self._golden_img_dir = None await super().tearDown() async def _snapshot(self, golden_img_name: str = "", threshold: float = 2e-4): await ui_test.human_delay() test_fn_name = "" for frame_info in inspect.stack(): if os.path.samefile(frame_info[1], __file__): test_fn_name = frame_info[3] golden_img_name = f"{test_fn_name}.{golden_img_name}.png" # Because we're testing RTX renderered pixels, use a better threshold filter for differences diff = await capture_and_compare( golden_img_name, threshold=threshold, output_img_dir=OUTPUTS_DIR, golden_img_dir=self._golden_img_dir, metric=ComparisonMetric.MEAN_ERROR_SQUARED, ) self.assertLessEqual( diff, threshold, f"The generated image {golden_img_name} has a difference of {diff}, but max difference is {threshold}", ) async def _setup_global( self, op: str, enable_toolbar: bool = False, file_name: str = "test_scene.usda", prims_to_select=["/World/Cube", "/World/Xform", "/World/Xform/Cube_01"], placement=prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, ): await self._setup(file_name, c.TRANSFORM_MODE_GLOBAL, op, enable_toolbar, prims_to_select, placement) async def _setup_local( self, op: str, enable_toolbar: bool = False, file_name: str = "test_scene.usda", prims_to_select=["/World/Cube", "/World/Xform", "/World/Xform/Cube_01"], placement=prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, ): await self._setup(file_name, c.TRANSFORM_MODE_LOCAL, op, enable_toolbar, prims_to_select, placement) async def _setup( self, scene_file: str, mode: str, op: str, enable_toolbar: bool = False, prims_to_select=["/World/Cube", "/World/Xform", "/World/Xform/Cube_01"], placement=prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, ): usd_path = self._usd_scene_dir.joinpath(scene_file) success, error = await self._context.open_stage_async(str(usd_path)) self.assertTrue(success, error) # move the mouse out of the way await ui_test.emulate_mouse_move(Vec2(0, 0)) await ui_test.human_delay() viewport_api = get_active_viewport() await viewport_api.wait_for_rendered_frames(5) self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, placement) self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, mode) self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, mode) self._settings.set(c.TRANSFORM_OP_SETTING, op) self._settings.set("/app/viewport/snapEnabled", False) self._settings.set("/persistent/app/viewport/snapToSurface", False) self._settings.set("/exts/omni.kit.manipulator.prim/tools/enabled", enable_toolbar) self._selection.set_selected_prim_paths([], True) await ui_test.human_delay(human_delay_speed=10) self._selection.set_selected_prim_paths(prims_to_select, True) await ui_test.human_delay(human_delay_speed=10) # Save prims initial state to restore to. stage = self._context.get_stage() self._restore_transform = {} for prim_path in prims_to_select: xform_ops = [] for xform_op in UsdGeom.Xformable(stage.GetPrimAtPath(prim_path)).GetOrderedXformOps(): if not xform_op.IsInverseOp(): xform_ops.append((xform_op, xform_op.Get())) self._restore_transform[prim_path] = xform_ops async def _restore_initial_state(self): for xform_op_list in self._restore_transform.values(): for xform_op_tuple in xform_op_list: xform_op, start_value = xform_op_tuple[0], xform_op_tuple[1] xform_op.Set(start_value) async def _emulate_mouse_drag_and_drop_multiple_waypoints( self, waypoints: List[Vec2], right_click=False, human_delay_speed: int = 4, num_steps: int = 8, on_before_drop: Callable[[int], Awaitable[None]] = None, ): """Emulate Mouse Drag & Drop. Click at start position and slowly move to end position.""" logger.info(f"emulate_mouse_drag_and_drop poses: {waypoints} (right_click: {right_click})") count = len(waypoints) if count < 2: return await ui_test.input.emulate_mouse(MouseEventType.MOVE, waypoints[0]) await ui_test.human_delay(human_delay_speed) await ui_test.input.emulate_mouse( MouseEventType.RIGHT_BUTTON_DOWN if right_click else MouseEventType.LEFT_BUTTON_DOWN ) await ui_test.human_delay(human_delay_speed) for i in range(1, count): await ui_test.input.emulate_mouse_slow_move( waypoints[i - 1], waypoints[i], num_steps=num_steps, human_delay_speed=human_delay_speed ) if on_before_drop: await ui_test.human_delay(human_delay_speed) await on_before_drop() await ui_test.input.emulate_mouse( MouseEventType.RIGHT_BUTTON_UP if right_click else MouseEventType.LEFT_BUTTON_UP ) await ui_test.human_delay(human_delay_speed) ################################################################ ################## test manipulator placement ################## ################################################################ async def test_placement(self): await self._setup_global(c.TRANSFORM_OP_MOVE) PLACEMENTS = { "placement_selection_center": prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER, "placement_bbox_center": prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER, "placement_authored_pivot": prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, "placement_bbox_base": prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE, } for test_name, val in PLACEMENTS.items(): self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, val) await ui_test.human_delay() await self._snapshot(test_name) async def test_tmp_placement(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01", "/World/Cube"]) self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM) await ui_test.human_delay() await self._snapshot("pick_default") center = Vec2(self._window_width, self._window_height) / 2 # pick the other prim as tmp pivot prim await ui_test.emulate_mouse_move_and_click(center) await ui_test.human_delay() await self._snapshot("pick") # move "/World/Cube", make sure the marker moves with it omni.kit.commands.execute("TransformPrimSRT", path="/World/Cube", new_translation=(0, 0, 300)) await ui_test.human_delay(5) await self._snapshot("move") # move it back omni.kit.undo.undo() await ui_test.human_delay(5) # reset placement to last prim, the manipulator should go to last prim and marker disappears self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT) await ui_test.human_delay() await self._snapshot("last_selected") async def test_bbox_placement_for_xform(self): await self._setup_global( c.TRANSFORM_OP_MOVE, file_name="test_pivot_with_invalid_bbox.usda", prims_to_select=["/World/Xform"] ) self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER) await ui_test.human_delay() await self._snapshot("placement_bbox_center") self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE) await ui_test.human_delay() await self._snapshot("placement_bbox_base") ################################################################ ####################### test translation ####################### ################################################################ ################## test manipulator move axis ################## async def test_move_global_axis(self): await self._setup_global(c.TRANSFORM_OP_MOVE) await self._test_move_axis() async def test_move_local_axis(self): await self._setup_local(c.TRANSFORM_OP_MOVE) await self._test_move_axis(180) async def _test_move_axis(self, angle_offset: float = 0, distance: float = 50): OFFSET = 50 MOVEMENT = ["x", "y", "z"] center = Vec2(self._window_width, self._window_height) / 2 for i, test_name in enumerate(MOVEMENT): await ui_test.human_delay() dir = Vec2( math.cos(math.radians(-i * 120 + 30 + angle_offset)), math.sin(math.radians(-i * 120 + 30 + angle_offset)), ) try: await ui_test.emulate_mouse_drag_and_drop(center + dir * OFFSET, center + dir * (OFFSET + distance)) await self._snapshot(f"{test_name}.{angle_offset}.{distance}") finally: await self._restore_initial_state() ################## test manipulator move plane ################## async def test_move_global_plane(self): await self._setup_global(c.TRANSFORM_OP_MOVE) await self._test_move_plane() async def test_move_local_plane(self): await self._setup_local(c.TRANSFORM_OP_MOVE) await self._test_move_plane(180) async def _test_move_plane(self, angle_offset: float = 0, distance=75): OFFSET = 50 MOVEMENT = ["xz", "zy", "yx"] center = Vec2(self._window_width, self._window_height) / 2 for i, test_name in enumerate(MOVEMENT): await ui_test.human_delay() dir = Vec2( math.cos(math.radians(-i * 120 + 90 + angle_offset)), math.sin(math.radians(-i * 120 + 90 + angle_offset)), ) try: await ui_test.emulate_mouse_drag_and_drop(center + dir * OFFSET, center + dir * (OFFSET + distance)) await self._snapshot(f"{test_name}.{angle_offset}.{distance}") finally: await self._restore_initial_state() ################## test manipulator move center ################## async def test_move_global_center(self): await self._setup_global(c.TRANSFORM_OP_MOVE) await self._test_move_center() await self._test_move_center( modifier=carb.input.KeyboardInput.LEFT_ALT ) # with alt down, transform is not changed async def test_move_local_center(self): await self._setup_local(c.TRANSFORM_OP_MOVE) await self._test_move_center() async def _test_move_center(self, dirs=[Vec2(50, 0)], modifier: carb.input.KeyboardInput = None): try: center = Vec2(self._window_width, self._window_height) / 2 waypoints = [center] for dir in dirs: waypoints.append(center + dir) if modifier: await ui_test.input.emulate_keyboard(carb.input.KeyboardEventType.KEY_PRESS, modifier) await ui_test.human_delay() await self._emulate_mouse_drag_and_drop_multiple_waypoints(waypoints) if modifier: await ui_test.input.emulate_keyboard(carb.input.KeyboardEventType.KEY_RELEASE, modifier) await ui_test.human_delay() test_name = f"xyz.{len(dirs)}" if modifier: test_name += str(modifier).split(".")[-1] await self._snapshot(test_name) # todo better hash name? finally: await self._restore_initial_state() # Test manipulator is placed correctly if the selected prim's parent is moved async def test_move_selected_parent(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01"]) stage = self._context.get_stage() parent_translate_attr = stage.GetAttributeAtPath("/World/Xform.xformOp:translate") try: parent_translate_attr.Set((0, 100, -100)) await ui_test.human_delay(4) await self._snapshot() finally: await self._restore_initial_state() # Test manipulator is placed correctly if the selected prim is moved by USD update async def test_move_selected_self(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01"]) stage = self._context.get_stage() parent_translate_attr = stage.GetAttributeAtPath("/World/Xform/Cube_01.xformOp:translate") try: parent_translate_attr.Set((0, 100, -100)) await ui_test.human_delay(4) await self._snapshot() finally: await self._restore_initial_state() ################################################################ ######################## test rotation ######################### ################################################################ ################## test manipulator rotate arc ################## async def test_rotate_global_arc(self): await self._setup_global(c.TRANSFORM_OP_ROTATE) await self._test_rotate_arc() # add a test to only select prims in the same hierarchy and pivot prim being the child # to cover the bug when consolidated prim path has one entry and is not the pivot prim async def test_rotate_global_arc_single_hierarchy(self): await self._setup_global(c.TRANSFORM_OP_ROTATE, prims_to_select=["/World/Xform", "/World/Xform/Cube_01"]) await self._test_rotate_arc() async def test_rotate_local_arc(self): await self._setup_local(c.TRANSFORM_OP_ROTATE) await self._test_rotate_arc(180) async def test_free_rotation_clamped(self): await self._setup_global(c.TRANSFORM_OP_ROTATE) self._settings.set(c.FREE_ROTATION_TYPE_SETTING, c.FREE_ROTATION_TYPE_CLAMPED) await self._test_move_center(dirs=[Vec2(100, 100)]) async def test_free_rotation_continuous(self): await self._setup_global(c.TRANSFORM_OP_ROTATE) self._settings.set(c.FREE_ROTATION_TYPE_SETTING, c.FREE_ROTATION_TYPE_CONTINUOUS) await self._test_move_center(dirs=[Vec2(100, 100)]) async def test_bbox_center_multi_prim_rotate_global(self): await self._test_bbox_center_multi_prim_rotate(self._setup_global) async def test_bbox_center_multi_prim_rotate_local(self): await self._test_bbox_center_multi_prim_rotate(self._setup_local) async def _test_bbox_center_multi_prim_rotate(self, test_fn): await test_fn( c.TRANSFORM_OP_ROTATE, file_name="test_bbox_rotation.usda", prims_to_select=["/World/Cube", "/World/Cube_01", "/World/Cube_02"], placement=prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER, ) await self._test_rotate_arc(post_snap=True) async def _test_rotate_arc(self, offset: float = 0, post_snap=False): OFFSET = 45 MOVEMENT = ["x", "y", "z", "screen"] SEGMENT_COUNT = 12 center = Vec2(self._window_width, self._window_height) / 2 for i, test_name in enumerate(MOVEMENT): await ui_test.human_delay() waypoints = [] step = 360 / SEGMENT_COUNT for wi in range(int(SEGMENT_COUNT * 1.5)): dir = Vec2( math.cos(math.radians(-i * 120 - 30 + wi * step + offset)), math.sin(math.radians(-i * 120 - 30 + wi * step + offset)), ) waypoints.append(center + dir * (OFFSET if i < 3 else 80)) try: async def before_drop(): await self._snapshot(test_name) await self._emulate_mouse_drag_and_drop_multiple_waypoints(waypoints, on_before_drop=before_drop) if post_snap: await ui_test.human_delay(human_delay_speed=4) await self._snapshot(f"{test_name}.post") finally: await self._restore_initial_state() ################################################################ ########################## test scale ########################## ################################################################ # Given the complexity of multi-manipulating with non-uniform scale and potential shear from parents, # we reduce the test complexity using a simpler manipulating case. # Revisit when there's more complicated scaling needs. ################## test manipulator scale axis ################## async def test_scale_local_axis(self): await self._setup_local(c.TRANSFORM_OP_SCALE) self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await ui_test.human_delay() # test scale up await self._test_move_axis(180) # test scale down await self._test_move_axis(180, distance=-100) ################## test manipulator move plane ################## async def test_scale_local_plane(self): await self._setup_local(c.TRANSFORM_OP_SCALE) self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await ui_test.human_delay() # test scale up await self._test_move_plane(180) # test scale down await self._test_move_plane(180, distance=-100) ################## test manipulator move center ################## async def test_scale_local_center(self): await self._setup_local(c.TRANSFORM_OP_SCALE) self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await ui_test.human_delay() await self._test_move_center() await ui_test.human_delay() await self._test_move_center(dirs=[Vec2(50, 0), Vec2(-100, 0)]) ################################################################ ################### test manipulator toolbar ################### ################################################################ async def test_toolbar(self): await self._setup_global(c.TRANSFORM_OP_MOVE, True) await ui_test.human_delay(30) # move it slowly, otherwise it may not be able to click on the collapsable header and instead unselects the prim await ui_test.input.emulate_mouse_slow_move(Vec2(0, 0), Vec2(210, 345), num_steps=16, human_delay_speed=10) await ui_test.human_delay(5) await ui_test.emulate_mouse_click() await ui_test.human_delay(human_delay_speed=20) # expand the toolbar and take a snapshot to make sure the render/layout is correct. # if you changed the look of toolbar button or toolbar layout, update the golden image for this test. # added since OM-65012 for a broken button image await self._snapshot("visual") # Test the local/global button await ui_test.human_delay(30) await ui_test.emulate_mouse_move_and_click(Vec2(215, 365), human_delay_speed=20) self.assertEqual(self._settings.get(c.TRANSFORM_MOVE_MODE_SETTING), c.TRANSFORM_MODE_LOCAL) await ui_test.human_delay(30) await ui_test.emulate_mouse_move_and_click(Vec2(215, 365), human_delay_speed=20) self.assertEqual(self._settings.get(c.TRANSFORM_MOVE_MODE_SETTING), c.TRANSFORM_MODE_GLOBAL) ################################################################ #################### test manipulator snap ##################### ################################################################ async def _run_snap_test(self, keep_spacing: bool): await self._setup_global(c.TRANSFORM_OP_MOVE, True, "test_snap.usda", ["/World/Cube", "/World/Cube_01"]) stage = self._context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") cube01_prim = stage.GetPrimAtPath("/World/Cube_01") _, _, _, translate_cube_original = omni.usd.get_local_transform_SRT(cube_prim) _, _, _, translate_cube01_original = omni.usd.get_local_transform_SRT(cube01_prim) self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER) self._settings.set(snap_c.SNAP_PROVIDER_NAME_SETTING_PATH, [SURFACE_SNAP_NAME]) self._settings.set(snap_c.CONFORM_TO_TARGET_SETTING_PATH, True) self._settings.set(snap_c.KEEP_SPACING_SETTING_PATH, keep_spacing) self._settings.set("/app/viewport/snapEnabled", True) center = Vec2(self._window_width, self._window_height) / 2 await ui_test.human_delay() await ui_test.emulate_mouse_move(center, 10) await self._emulate_mouse_drag_and_drop_multiple_waypoints( [center, center / 1.5], human_delay_speed=1, num_steps=50 ) _, _, _, translate_cube = omni.usd.get_local_transform_SRT(cube_prim) _, _, _, translate_cube01 = omni.usd.get_local_transform_SRT(cube01_prim) self._settings.set("/app/viewport/snapEnabled", False) return translate_cube, translate_cube_original, translate_cube01, translate_cube01_original async def test_snap_keep_spacing(self): ( translate_cube, translate_cube_original, translate_cube01, translate_cube01_original, ) = await self._run_snap_test(True) # Make sure start conditions aren't already on Plane self.assertFalse(Gf.IsClose(translate_cube_original[1], -100, 0.02)) self.assertFalse(Gf.IsClose(translate_cube01_original[1], -100, 0.02)) # Y position should be snapped to surface at -100 Y (within a tolerance for Storm) self.assertTrue(Gf.IsClose(translate_cube[1], -100, 0.02)) self.assertTrue(Gf.IsClose(translate_cube01[1], -100, 0.02)) # X and Z should be greater than original self.assertTrue(translate_cube[0] > translate_cube_original[0]) self.assertTrue(translate_cube[2] > translate_cube_original[2]) # X and Z should be greater than original self.assertTrue(translate_cube01[2] > translate_cube01_original[2]) self.assertTrue(translate_cube01[0] > translate_cube01_original[0]) # Workaround for testing on new Viewport, needs delay before running test_snap_no_keep_spacing test. self._selection.set_selected_prim_paths([], True) await ui_test.human_delay(10) async def test_snap_no_keep_spacing(self): ( translate_cube, translate_cube_original, translate_cube01, translate_cube01_original, ) = await self._run_snap_test(False) self.assertFalse(Gf.IsClose(translate_cube_original[1], -100, 0.02)) self.assertFalse(Gf.IsClose(translate_cube01_original[1], -100, 0.02)) # cube and cube01 should be at same location since keep spacing is off self.assertTrue(Gf.IsClose(translate_cube, translate_cube01, 1e-6)) # Y position should be snapped to surface at -100 Y self.assertTrue(Gf.IsClose(translate_cube[1], -100, 0.02)) # X and Z should be greater than original self.assertTrue(translate_cube[0] > translate_cube_original[0]) self.assertTrue(translate_cube[2] > translate_cube_original[2]) # Workaround for testing on new Viewport, needs delay before running test_snap_no_keep_spacing test. self._selection.set_selected_prim_paths([], True) await ui_test.human_delay(10) async def test_snap_orient(self): try: import omni.kit.viewport_legacy # Don't test VP1. Prim snap only works with VP2 return except ImportError: pass await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Cube"]) stage = self._context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") cube01_prim = stage.GetPrimAtPath("/World/Xform/Cube_01") self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER) self._settings.set(snap_c.SNAP_PROVIDER_NAME_SETTING_PATH, [PRIM_SNAP_NAME]) self._settings.set(snap_c.CONFORM_TO_TARGET_SETTING_PATH, True) self._settings.set(snap_c.KEEP_SPACING_SETTING_PATH, True) self._settings.set(snap_c.CONFORM_UP_AXIS_SETTING_PATH, "Stage") self._settings.set("/app/viewport/snapEnabled", True) start = Vec2(166, 296) end = Vec2(self._window_width, self._window_height) / 2 await ui_test.human_delay() await ui_test.emulate_mouse_move(start, 10) await self._emulate_mouse_drag_and_drop_multiple_waypoints([start, end], human_delay_speed=1, num_steps=50) xform_cube = Gf.Matrix4d(*self._context.compute_path_world_transform("/World/Cube")) xform_cube_01 = Gf.Matrix4d(*self._context.compute_path_world_transform("/World/Xform/Cube_01")) self.assertTrue(Gf.IsClose(xform_cube.ExtractTranslation(), xform_cube_01.ExtractTranslation(), 1e-4)) rotation_cube = xform_cube.GetOrthonormalized().ExtractRotationMatrix() rotation_cube_01 = xform_cube_01.GetOrthonormalized().ExtractRotationMatrix() self.assertTrue(Gf.IsClose(rotation_cube, rotation_cube_01, 1e-4)) self._settings.set("/app/viewport/snapEnabled", False) ################################################################ ##################### test prim with pivot ##################### ################################################################ async def _test_move_axis_one_dir(self, dir: Vec2 = Vec2(0, 1), distance: float = 50): OFFSET = 50 center = Vec2(self._window_width, self._window_height) / 2 try: await ui_test.emulate_mouse_drag_and_drop(center + dir * OFFSET, center + dir * (OFFSET + distance)) await self._snapshot(f"{distance}") finally: await self._restore_initial_state() async def test_move_local_axis_with_pivot(self): # tests for when _should_keep_manipulator_orientation_unchanged is true await self._setup_local(c.TRANSFORM_OP_MOVE, file_name="test_pivot.usda", prims_to_select=["/World/Cube"]) await self._test_move_axis_one_dir() async def test_scale_local_axis_with_pivot(self): # tests for when _should_keep_manipulator_orientation_unchanged is true await self._setup_local(c.TRANSFORM_OP_SCALE, file_name="test_pivot.usda", prims_to_select=["/World/Cube"]) await self._test_move_axis_one_dir() ################################################################ ##################### test remove xformOps ##################### ################################################################ async def test_remove_xform_ops_pivot(self): # remove the xformOps attributes, the manipulator position should update await self._setup_local( c.TRANSFORM_OP_MOVE, file_name="test_remove_xformOps.usda", prims_to_select=["/World/Cube"] ) stage = self._context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") attrs_to_remove = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] for attr in attrs_to_remove: cube_prim.RemoveProperty(attr) await ui_test.human_delay(10) await self._snapshot() async def test_remove_xform_op_order_pivot(self): # remove the xformOpOrder attribute, the manipulator position should update await self._setup_local( c.TRANSFORM_OP_MOVE, file_name="test_remove_xformOps.usda", prims_to_select=["/World/Cube"] ) stage = self._context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") cube_prim.RemoveProperty("xformOpOrder") await ui_test.human_delay(10) await self._snapshot() ################################################################ ################### test unknown op & modes #################### ################################################################ async def test_unknown_move_mode(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01"]) await self._snapshot("pre-unknown-mode") self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, "UNKNOWN") await self._snapshot("post-unknown-mode") self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_LOCAL) await self._snapshot("reset-known-mode") async def test_unknown_rotate_mode(self): await self._setup_global(c.TRANSFORM_OP_ROTATE, prims_to_select=["/World/Xform/Cube_01"]) await self._snapshot("pre-unknown-mode") self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, "UNKNOWN") await self._snapshot("post-unknown-mode") self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, c.TRANSFORM_MODE_LOCAL) await self._snapshot("reset-known-mode") async def test_unknown_mode_enabled(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=[]) await self._snapshot("known-mode-unselected") self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, "UNKNOWN") await self._snapshot("unknown-mode-unselected") self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await self._snapshot("unknown-mode-selected") self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL) await self._snapshot("known-mode-selected") async def test_unknown_op_enabled(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=[]) await self._snapshot("move-op-unselected") self._settings.set(c.TRANSFORM_OP_SETTING, "UNKNOWN") await self._snapshot("unknown-op-selected") self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await self._snapshot("unknown-op-selected") self._settings.set(c.TRANSFORM_OP_SETTING, c.TRANSFORM_OP_ROTATE) await self._snapshot("rotate-op-selected")
32,962
Python
42.950667
120
0.606122
omniverse-code/kit/exts/omni.kit.manipulator.prim/docs/index.rst
omni.kit.manipulator.prim ########################### Prim Manipulator Extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule:: omni.kit.manipulator.prim :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
342
reStructuredText
15.333333
43
0.631579
omniverse-code/kit/exts/omni.kit.window.inspector/PACKAGE-LICENSES/omni.kit.window.inspector-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.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.window.inspector/config/extension.toml
[package] title = "Inspector Window (Preview)" description = "Inspect your UI Elements" version = "1.0.6" category = "Developer" authors = ["NVIDIA"] repository = "" keywords = ["stage", "outliner", "scene"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" preview_image = "data/inspector_full.png" icon = "data/clouseau.png" [dependencies] "omni.ui" = {} "omni.ui_query" = {} "omni.kit.widget.inspector" = {} [[python.module]] name = "omni.kit.window.inspector" [settings] exts."omni.kit.window.inspector".use_demo_window = false [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", ] stdoutFailPatterns.exclude = [ ] dependencies = [ "omni.kit.mainwindow", "omni.kit.ui_test", "omni.kit.window.viewport", "omni.rtx.window.settings", "omni.kit.window.stage" ] [documentation] pages = [ "docs/overview.md", "docs/CHANGELOG.md", ]
923
TOML
18.659574
56
0.664139
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_preview.py
__all__ = ["InspectorPreview"] from typing import Union import omni.ui as ui import omni.kit.app import carb.events import carb from omni.ui_query import OmniUIQuery from omni.kit.widget.inspector import InspectorWidget, PreviewMode class InspectorPreview: """The Stage widget""" def destroy(self): self._window = None self._inspector = None def __init__(self, window: ui.Window, **kwargs): self._window = window self._widget = window.frame if window else None self._preview_mode = ["BOTH", "WIRE", "COLOR"] self._preview_mode_model = None self._inspector: Union[ui.Inspector, None] = None self._main_stack = ui.VStack() self._sender_id = hash("InspectorPreview") & 0xFFFFFFFF self._build_ui() app = omni.kit.app.get_app() self._update_sub = app.get_message_bus_event_stream().create_subscription_to_pop( self.on_selection_changed, name="Inspector Selection Changed" ) def on_selection_changed(self, event: carb.events.IEvent): if event.sender == self._sender_id: # we don't respond to our own events return from .inspector_widget import INSPECTOR_ITEM_SELECTED_ID, INSPECTOR_PREVIEW_CHANGED_ID if event.type == INSPECTOR_ITEM_SELECTED_ID: selection = OmniUIQuery.find_widget(event.payload["item_path"]) if selection: self.set_widget(selection) elif event.type == INSPECTOR_PREVIEW_CHANGED_ID: selection = OmniUIQuery.find_widget(event.payload["item_path"]) if selection: if "window_name" in event.payload: window_name = event.payload["window_name"] window = ui.Workspace.get_window(window_name) if window: self._window = window else: carb.log_error(f"Failed to find {window_name}") self.set_main_widget(selection) def toggle_visibility(self): self._main_stack.visible = not self._main_stack.visible def _build_ui(self): with self._main_stack: ui.Spacer(height=5) with ui.ZStack(): ui.Rectangle(name="render_background", style={"background_color": 0xFF333333}) with ui.VStack(): ui.Spacer(height=10) with ui.ZStack(): ui.Rectangle() with ui.HStack(): self._inspector = InspectorWidget(widget=self._widget) def selection_changed(widget): # Send the Selection Changed Message from .inspector_widget import INSPECTOR_ITEM_SELECTED_ID stream = omni.kit.app.get_app().get_message_bus_event_stream() widget_path = OmniUIQuery.get_widget_path(self._window, widget) if widget_path: stream.push( INSPECTOR_ITEM_SELECTED_ID, sender=self._sender_id, payload={"item_path": widget_path}, ) self._inspector.set_selected_widget_changed_fn(selection_changed) with ui.HStack(height=0): ui.Label("Depth", width=0) ui.Spacer(width=4) def value_changed_fn(model: ui.AbstractValueModel): self._inspector.depth_scale = float(model.as_int) model = ui.IntDrag(min=0, max=300, width=40).model model.set_value(50) model.add_value_changed_fn(value_changed_fn) ui.Spacer() # def build Preview Type Radio with ui.HStack(width=0, style={"margin": 0, "padding_width": 6, "border_radius": 0}): self._preview_mode_collection = ui.RadioCollection() def preview_mode_changed(item: ui.AbstractValueModel): index = item.as_int if index == 0: self._inspector.preview_mode = PreviewMode.WIREFRAME_AND_COLOR elif index == 1: self._inspector.preview_mode = PreviewMode.WIRE_ONLY else: self._inspector.preview_mode = PreviewMode.COLOR_ONLY self._preview_mode_collection.model.add_value_changed_fn(preview_mode_changed) for preview_mode in self._preview_mode: style = {} radius = 4 if preview_mode == "BOTH": style = {"border_radius": radius, "corner_flag": ui.CornerFlag.LEFT} if preview_mode == "COLOR": style = {"border_radius": radius, "corner_flag": ui.CornerFlag.RIGHT} ui.RadioButton( width=50, style=style, text=preview_mode, radio_collection=self._preview_mode_collection ) def preview_mode_value_changed(value): if value == PreviewMode.WIREFRAME_AND_COLOR: self._preview_mode_collection.model.set_value(0) elif value == PreviewMode.WIRE_ONLY: self._preview_mode_collection.model.set_value(1) elif value == PreviewMode.COLOR_ONLY: self._preview_mode_collection.model.set_value(2) self._inspector.set_preview_mode_change_fn(preview_mode_value_changed) ui.Spacer() ui.Label("Range ", width=0) def min_value_changed_fn(model: ui.AbstractValueModel): self._inspector.start_depth = model.as_int model = ui.IntDrag(min=0, max=20, width=50).model.add_value_changed_fn(min_value_changed_fn) ui.Spacer(width=4) def max_value_changed_fn(model: ui.AbstractValueModel): self._inspector.end_depth = model.as_int ui.IntDrag(min=0, max=6000, width=50).model.add_value_changed_fn(max_value_changed_fn) def set_main_widget(self, widget: ui.Widget): self._widget = widget self._inspector.widget = widget def set_widget(self, widget: ui.Widget): self._inspector.selected_widget = widget def update_window(self, window: ui.Window): self._inspector = None self._window = window self._widget = window.frame self._main_stack.clear() self._build_ui()
6,936
Python
40.047337
116
0.523933
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_window.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["InspectorWindow"] import omni.ui as ui import carb.events import omni.kit.app from typing import cast from .tree.inspector_tree import WindowListModel, WindowItem from .demo_window import InspectorDemoWindow from .inspector_widget import InspectorWidget from pathlib import Path ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") class InspectorWindow: """The inspector window""" def __init__(self): window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._window = ui.Window( "Inspector", width=1000, height=800, flags=window_flags, dockPreference=ui.DockPreference.RIGHT_TOP, padding_x=0, padding_y=0, ) # Create a Demo Window to show case the general feature self._demo_window = None use_demo_window = carb.settings.get_settings().get("/exts/omni.kit.window.inspector/use_demo_window") with self._window.frame: if use_demo_window: self._demo_window = InspectorDemoWindow() self._inspector_widget = InspectorWidget(self._demo_window.window) else: self._inspector_widget = InspectorWidget(None) def destroy(self): """ Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ if self._demo_window: self._demo_window.destroy() self._demo_window = None self._inspector_widget.destroy() self._inspector_widget = None self._window = None
2,094
Python
32.790322
109
0.661891
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_tests.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["test_widget_tool_button", "test_select_frame", "test_change_query", "test_menu_activation"] from omni.ui_query import OmniUIQuery import omni.kit.app import asyncio import carb import omni.ui as ui wait = None def test_widget_tool_button(): preview_tool_button = OmniUIQuery.find_widget("Inspector/Frame[0]/ZStack[1]/VStack[0]/HStack[2]/ToolButton") if preview_tool_button: preview_tool_button.call_clicked_fn() property_tool_button = OmniUIQuery.find_widget("Inspector/Frame[0]/ZStack[1]/VStack[0]/HStack[3]/ToolButton") if property_tool_button: property_tool_button.call_clicked_fn() style_tool_button = OmniUIQuery.find_widget("Inspector/Frame[0]/ZStack[1]/VStack[0]/HStack[4]/ToolButton") if style_tool_button: style_tool_button.call_clicked_fn() def test_select_frame(): global wait from .inspector_widget import INSPECTOR_ITEM_SELECTED_ID stream = omni.kit.app.get_app().get_message_bus_event_stream() stream.push(INSPECTOR_ITEM_SELECTED_ID, sender=444, payload={"item_path": "DemoWindow/Frame[0]/VStack"}) async def wait_a_frame(): await omni.kit.app.get_app().next_update_async() spacing_label_path = "Inspector/Frame[0]/ZStack[1]/VStack[2]/HStack[3]/VStack[3]/CollapsableFrame[0]/Frame[0]/VStack[1]/HStack[0]/Label" spacing_value_path = "Inspector/Frame[0]/ZStack[1]/VStack[2]/HStack[3]/VStack[3]/CollapsableFrame[0]/Frame[0]/VStack[1]/HStack[2]/FloatDrag" spacing_label = OmniUIQuery.find_widget(spacing_label_path) print("spacing_label", spacing_label) if spacing_label and isinstance(spacing_label, ui.Label): if not spacing_label.text == "spacing": carb.log_error(f"Failed the Frame Selection Test , Label is {spacing_label.text}") return spacing_value = OmniUIQuery.find_widget(spacing_value_path) print("spacing_value", spacing_value) if spacing_value and isinstance(spacing_value, ui.FloatDrag): if not spacing_value.model.as_float == 0.0: carb.log_error(f"Failed the Frame Selection Test , spacing value is {spacing_value.model.as_float}") return carb.log_warn("Frame Selection Test PASSED") wait = asyncio.ensure_future(wait_a_frame()) def test_change_query(): query_field = OmniUIQuery.find_widget( "Inspector/Frame[0]/ZStack[1]/VStack[4]/ZStack[1]/VStack[1]/HStack[2]/StringField" ) if query_field and isinstance(query_field, ui.StringField): response_field_path = "Inspector/Frame[0]/ZStack[1]/VStack[4]/ZStack[1]/VStack[1]/HStack[4]/StringField" query_field.model.set_value(response_field_path) query_field.model.end_edit() response_field = OmniUIQuery.find_widget(response_field_path) if not isinstance(response_field, ui.StringField): carb.log_error(f"Faild to find the right widget at {response_field_path}") else: print(response_field, response_field.model.as_string) def test_menu_activation(): menu_item = OmniUIQuery.find_menu_item("MainWindow/MenuBar[0]/Menu[14]/MenuItem") print(menu_item) if isinstance(menu_item, ui.MenuItem): print(menu_item.text) menu_item.call_triggered_fn()
3,737
Python
41
148
0.693069
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/demo_window.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["InspectorDemoWindow"] from typing import cast from pathlib import Path import omni.ui as ui ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") class InspectorDemoWindow: """The demo window for the inspector""" @property def window(self) -> ui.Window: return cast(ui.Window, self._window) def destroy(self): self._window = None def __init__(self): self._window = ui.Window("DemoWindow", width=300, height=900) style_testing = { "Label:hovered": {"color": 0xFF00FFFF}, "Label::title": {"font_size": 18, "color": 0xFF00EEEE, "alignment": ui.Alignment.LEFT}, "Label": {"font_size": 14, "color": 0xFFEEEEEE}, "Button.Label": {"font_size": 15, "color": 0xFF33FF33}, "Line": {"color": 0xFFFF0000}, "Slider": {"draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": 0xFFAA0000}, "Stack::blue": {"stack_direction": ui.Direction.RIGHT_TO_LEFT}, "Button::green": { "background_color": 0xFF333333, "color": 0xFF00FFFF, "border_width": 2, "border_color": 0xFF00FF00, "border_radius": 3, "corner_flag": ui.CornerFlag.BOTTOM, "alignment": ui.Alignment.CENTER, }, "Button.Image::green": { # "image_url": "c:/path/to/an/image.png", "fill_policy": ui.FillPolicy.PRESERVE_ASPECT_FIT }, } self._window.frame.set_style(style_testing) with self._window.frame: with ui.VStack(): ui.Label("Title", height=0, name="title") with ui.HStack(height=0): ui.Label("THis is Cool", style={"Label": {"font_size": 12, "color": 0xFF0000FF}}) def button_fn(name: str): print(f"Executed Button Labled {name}") ui.Button("Button 1", name="button1", clicked_fn=lambda n="Button 1": button_fn(n)) ui.Button("Button 2", name="green", clicked_fn=lambda n="Button 2": button_fn(n)) ui.Line(height=2) ui.Spacer(height=10) ui.IntSlider(height=0, min=0, max=100) ui.Spacer(height=10) with ui.HStack(height=0): ui.Label("Field", style={"color": 0xFF00FF00}) ui.StringField().model.set_value("This is Cool ") with ui.HStack(height=0): ui.Rectangle( height=30, style={ "backgroun_color": 0xFFAAAAAA, "border_width": 2, "border_radius": 3, "border_color": 0xFFAADDAA, }, ) with ui.Frame(height=100): with ui.Placer(draggable=True): ui.Rectangle(width=20, height=20, style={"background_color": 0xFF0000FF}) ui.ComboBox(1, "One", "Two", "Inspector", "Is", "Amazing", height=0) ui.Spacer(height=10) with ui.VGrid(height=50, column_count=5, row_height=50): for i in range(5): ui.Rectangle(style={"background_color": 0xFF000000}) ui.Rectangle(style={"background_color": 0xFFFFFFFF}) with ui.HGrid(height=50, column_width=30, row_count=3): for i in range(10): ui.Rectangle(style={"background_color": 0xFF00FFAA}) ui.Rectangle(style={"background_color": 0xFFF00FFF}) ui.Spacer(height=10) with ui.CollapsableFrame(title="Image", height=0): # ui.Image("/dfagnou/Desktop/omniverse_background.png", height=100) ui.Image(f"{ICON_PATH}/sync.svg", height=100) with ui.HStack(height=30): ui.Triangle(height=20, style={"background_color": 0xFFAAFFAA}) ui.Circle(style={"background_color": 0xFFAAFFFF}) canvas = ui.CanvasFrame(height=20, style={"background_color": 0xFFDD00DD}) # canvas.set_pan_key_shortcut(1, carb.K) with canvas: # ui.Image("/dfagnou/Desktop/omniverse_background.png") ui.Image(f"{ICON_PATH}/sync.svg", height=20)
4,997
Python
41.355932
103
0.529518
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_widget.py
__all__ = ["InspectorWidget"] import omni.ui as ui from .tree.inspector_tree import InspectorTreeView from .style.style_tree import StyleTreeView from .property.inspector_property_widget import InspectorPropertyWidget from .inspector_preview import InspectorPreview from omni.ui_query import OmniUIQuery # move the test into a menu on the top widget to experiment from .inspector_tests import test_widget_tool_button, test_select_frame, test_change_query, test_menu_activation from .inspector_style import INSPECTOR_STYLE DARK_BACKGROUND = 0xFF333333 INSPECTOR_ITEM_SELECTED_ID = 427273737 # hash("INSPECTOR_ITEM_SELECTED") INSPECTOR_PREVIEW_CHANGED_ID = 427273738 # hash("INSPECTOR_PREVIEW_CHANGED") INSPECTOR_ITEM_EXPANDED_ID = 427273739 KIT_GREEN = 0xFF888888 class InspectorWidget: def destroy(self): self._tree_view.destroy() self._tree_view = None self._render_view.set_widget(None) self._render_view._window = None self._render_view = None self._property_view.set_widget(None) self._property_view = None def __init__(self, window: ui.Window, **kwargs): self._test_menu = None self._window = window self._render_view = None self._main_stack = ui.ZStack(style=INSPECTOR_STYLE) self._build_ui() def _build_ui(self): with self._main_stack: ui.Rectangle(name="background") with ui.VStack(): with ui.HStack(height=30): bt = ui.Button("TestMenu", width=0) def show_test_menu(): self._test_menu = ui.Menu("Test") with self._test_menu: ui.MenuItem("ToolButton1", triggered_fn=test_widget_tool_button) ui.MenuItem("Select Frame", triggered_fn=test_select_frame) ui.MenuItem("Change Query", triggered_fn=test_change_query) ui.MenuItem("Test Menu", triggered_fn=test_menu_activation) self._test_menu.show_at(bt.screen_position_x, bt.screen_position_y + bt.computed_height) bt.set_clicked_fn(show_test_menu) ui.Spacer() # self._tree_vis_model = ui.ToolButton(text="Tree", width=100).model self._preview_vis_model = ui.ToolButton(text="Preview", name="toolbutton", width=100).model self._property_vis_model = ui.ToolButton(text="Property", name="toolbutton", width=100).model self._style_vis_model = ui.ToolButton(text="Style", name="toolbutton", width=100).model ui.Spacer() ui.Line(height=3, name="dark_separator") with ui.HStack(): # Build adjustable Inspector Tree Widget with "Splitter" with ui.ZStack(width=0): handle_width = 3 # the placer will increate the stack width with ui.Placer(offset_x=300, draggable=True, drag_axis=ui.Axis.X): ui.Rectangle(width=handle_width, name="splitter") # the tree view will fit the all ZStack Width minus the Handle Width with ui.HStack(name="tree", style={"HStack::tree": {"margin_width": 5}}): # Extensions List Widget (on the left) self._tree_view = InspectorTreeView(self._window, self.update_window) ui.Spacer(width=handle_width) # Build Inspector Preview self._render_view = InspectorPreview(self._window) ui.Line(alignment=ui.Alignment.H_CENTER, width=2, style={"color": 0xFF222222, "border_width": 2}) # Build Inspector Property Window self._property_view = InspectorPropertyWidget() ui.Line(alignment=ui.Alignment.H_CENTER, width=2, style={"color": 0xFF222222, "border_width": 2}) self._style_view = StyleTreeView() ui.Line(height=3, style={"color": 0xFF222222, "border_width": 3}) with ui.ZStack(height=30): ui.Rectangle(name="background") with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer(width=10) ui.Label("Query : ", width=0) model = ui.StringField(width=400).model model.set_value("DemoWindow//Frame/VStack[1]/HStack[1]/Button") ui.Spacer(width=10) result = ui.StringField(width=200, read_only=True).model def execute_query(model: ui.AbstractValueModel): query = model.as_string children = OmniUIQuery.find_widget(query) if children: result.set_value(children.__class__.__name__) else: result.set_value("NO RESULT") if type(children) == ui.Button: print("Has Clicked Fn", children.has_clicked_fn) children.call_clicked_fn() model.add_end_edit_fn(execute_query) ui.Spacer() def visiblity_changed_fn(w): w.toggle_visibility() self._preview_vis_model.set_value(True) self._property_vis_model.set_value(True) self._style_vis_model.set_value(True) # self._tree_vis_model.add_value_changed_fn(lambda m, w=self._tree_view: visiblity_changed_fn(w)) self._preview_vis_model.add_value_changed_fn(lambda m, w=self._render_view: visiblity_changed_fn(w)) self._property_vis_model.add_value_changed_fn(lambda m, w=self._property_view: visiblity_changed_fn(w)) self._style_vis_model.add_value_changed_fn(lambda m, w=self._style_view: visiblity_changed_fn(w)) self._preview_vis_model.set_value(False) self._property_vis_model.set_value(False) self._style_vis_model.set_value(False) def update_window(self, window: ui.Window): self._window = window if self._render_view: self._render_view.update_window(window)
6,568
Python
42.503311
117
0.549635
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/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 omni.ext import omni.kit.ui from .inspector_window import InspectorWindow class InspectorExtension(omni.ext.IExt): """The entry point for Inspector Window""" MENU_PATH = "Window/Inspector" def on_startup(self): editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item(InspectorExtension.MENU_PATH, self.show_window, toggle=True, value=True) self.show_window(None, True) def on_shutdown(self): self._menu = None self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(InspectorExtension.MENU_PATH, visible) def show_window(self, menu, value): if value: self._window = InspectorWindow() elif self._window: self._window.destroy() self._window = None
1,408
Python
31.767441
118
0.683239
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import InspectorExtension
476
Python
42.363633
76
0.813025
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_style.py
__all__ = ["INSPECTOR_STYLE"] import omni.ui as ui KIT_GREEN = 0xFF888888 DARK_BACKGROUND = 0xFF333333 INSPECTOR_STYLE = { "Rectangle::background": {"background_color": DARK_BACKGROUND}, # toolbutton "Button.Label::toolbutton": {"color": 0xFF7B7B7B}, "Button.Label::toolbutton:checked": {"color": 0xFFD4D4D4}, "Button::toolbutton": {"background_color": 0xFF424242, "margin": 2.0}, "Button::toolbutton:checked": {"background_color": 0xFF5D5D5D}, "CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F}, "Line::dark_separator": {"color": 0xFF222222, "border_width": 3}, "Rectangle::splitter": {"background_color": 0xFF222222}, "Rectangle::splitter:hovered": {"background_color": 0xFFFFCA83}, "Tooltip": {"background_color": 0xFF000000, "color": 0xFF333333}, }
845
Python
35.782607
98
0.67574
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/style_model.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["StyleComboValueModel", "StyleComboNameValueItem", "StyleComboItemModel", "StylePropertyType", "StyleColorComponentItem", "StyleColorModel", "StyleItem", "StyleGroupItem", "StyleModel"] from os import remove from typing import Callable, Union, List, cast import omni.ui as ui from enum import Enum import copy, carb StyleFloatProperty = [ "border_radius", "border_width", "font_size", "margin", "margin_width", "margin_height", "padding", "padding_width", "padding_height", "secondary_padding", "scrollbar_size", ] StyleColorProperties = [ "background_color", "background_gradient_color", "background_selected_color", "border_color", "color", "selected_color", "secondary_color", "secondary_selected_color", "debug_color", ] StyleEnumProperty = ["corner_flag", "alignment", "fill_policy", "draw_mode", "stack_direction"] StyleStringProperty = ["image_url"] def get_enum_class(property_name: str) -> Union[Callable, None]: if property_name == "corner_flag": return ui.CornerFlag elif property_name == "alignment": return ui.Alignment elif property_name == "fill_policy": return ui.FillPolicy elif property_name == "draw_mode": return ui.SliderDrawMode elif property_name == "stack_direction": return ui.Direction else: return None class StyleComboValueModel(ui.AbstractValueModel): """ Model to store a pair (label, value of arbitrary type) for use in a ComboBox """ def __init__(self, key, value): """ Args: value: the instance of the Style value """ ui.AbstractValueModel.__init__(self) self.key = key self.value = value def __repr__(self): return f'"StyleComboValueModel name:{self.key} value:{int(self.value)}"' def get_value_as_string(self) -> str: """ this is called to get the label of the combo box item """ return self.key def get_style_value(self) -> int: """ we call this to get the value of the combo box item """ return int(self.value) class StyleComboNameValueItem(ui.AbstractItem): def __init__(self, key, value): super().__init__() self.model = StyleComboValueModel(key, value) def __repr__(self): return f'"StyleComboNameValueItem {self.model}"' class StyleComboItemModel(ui.AbstractItemModel): """ Model for a combo box - for each setting we have a dictionary of key, values """ def __init__(self, class_obj: Callable, default_value: int): super().__init__() self._class = class_obj self._items = [] self._default_value = default_value default_index = 0 current_index = 0 for key, value in class_obj.__members__.items(): if self._default_value == value: default_index = current_index self._items.append(StyleComboNameValueItem(key, value)) current_index += 1 self._current_index = ui.SimpleIntModel(default_index) self._current_index.add_value_changed_fn(self._current_index_changed) def get_current_value(self): return self._items[self._current_index.as_int].model.get_style_value() def _current_index_changed(self, model): self._item_changed(None) def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id: int): if item is None: return self._current_index return item.model class StylePropertyType(Enum): ENUM = 0 COLOR = 1 FLOAT = 2 STRING = 3 def get_property_type(property_name: str) -> StylePropertyType: if property_name in StyleStringProperty: return StylePropertyType.STRING elif property_name in StyleEnumProperty: return StylePropertyType.ENUM elif property_name in StyleColorProperties: return StylePropertyType.COLOR elif property_name in StyleFloatProperty: return StylePropertyType.FLOAT else: return StylePropertyType.FLOAT class StyleColorComponentItem(ui.AbstractItem): def __init__(self, model: ui.SimpleFloatModel) -> None: super().__init__() self.model = model class StyleColorModel(ui.AbstractItemModel): """ define a model for a style color, and enable coversion from int32 etc """ def __init__(self, value: int) -> None: super().__init__() self._value = value # Create root model self._root_model = ui.SimpleIntModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) # convert Value from int red = self._value & 255 green = (self._value >> 8) & 255 blue = (self._value >> 16) & 255 alpha = (self._value >> 24) & 255 rgba_values = [red / 255, green / 255, blue / 255, alpha / 255] # Create three models per component self._items: List[StyleColorComponentItem] = [ StyleColorComponentItem(ui.SimpleFloatModel(rgba_values[i])) for i in range(4) ] for item in self._items: item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item)) def set_value(self, value: int): self._value = value def set_components_values(self, values: List[float]): if len(values) != 4: print("Error: List need to be exactly 4 long") return for i in range(4): self._items[i].model.set_value(values[i]) def set_components_values_as_int(self, values: List[int]): if len(values) != 4: print("Error: List need to be exactly 4 long") return for i in range(4): self._items[i].model.set_value(values[i] / 255) def get_value_as_int8s(self) -> List[int]: result: List[int] = [] for i in range(4): result.append(int(round(self._items[i].model.get_value_as_float() * 255))) return result def get_value_as_floats(self) -> List[float]: result: List[float] = [] for i in range(4): result.append(self._items[i].model.get_value_as_float()) return result def get_value_as_int32(self) -> int: red, green, blue, alpha = self.get_value_as_int8s() # we store then in AABBGGRR result = (alpha << 24) + (blue << 16) + (green << 8) + red return result def _on_value_changed(self, item): self._item_changed(item) def get_item_children(self, parentItem: ui.AbstractItem) -> List[StyleColorComponentItem]: return self._items def get_item_value_model(self, item: ui.AbstractItem, column_id: int) -> ui.AbstractValueModel: if item is None: return self._root_model return item.model def begin_edit(self, item): """ TODO: if we don't add this override (even without a real implementation) we get crashes """ pass def end_edit(self, item): """ TODO: if we don't add this override (even without a real implementation) we get crashes """ pass class StyleItem(ui.AbstractItem): """A single AbstractItemModel item that represents a single prim""" def __init__( self, property_name: str, style_type: StylePropertyType, values: dict, parent_model: "StyleModel", parent_item: "StyleGroupItem", ): super().__init__() self.parent_item = parent_item self.parent_model = parent_model self.property = property_name self.style_type = style_type self.value = values[property_name] self._values = values self._model: Union[ui.AbstractValueModel, ui.AbstractItemModel, None] = None if self.style_type == StylePropertyType.STRING: self._model = ui.SimpleStringModel(str(self.value)) elif self.style_type == StylePropertyType.ENUM: enum_cls = get_enum_class(property_name) self._model = StyleComboItemModel(enum_cls, self.value) elif self.style_type == StylePropertyType.COLOR: self._model = StyleColorModel(int(self.value)) elif self.style_type == StylePropertyType.FLOAT: self._model = ui.SimpleFloatModel(float(self.value)) else: raise ValueError("The Style Type need to be either STRING, ENUM, COLOR or FLOAT") if self.style_type in [StylePropertyType.STRING, StylePropertyType.FLOAT]: def value_changed(model: ui.AbstractValueModel): self._values[self.property] = model.as_float self.parent_model.update() self._model.add_value_changed_fn(value_changed) elif self.style_type == StylePropertyType.COLOR: def value_changed(model: StyleColorModel, item: ui.AbstractItem): self._values[self.property] = model.get_value_as_int32() self.parent_model.update() self._model.add_item_changed_fn(value_changed) elif self.style_type == StylePropertyType.ENUM: def value_changed(model: StyleComboItemModel, item: ui.AbstractItem): self._values[self.property] = model.get_current_value() self.parent_model.update() self._model.add_item_changed_fn(value_changed) def delete(self): # we simply remove the key from the referenced Value Dict del self._values[self.property] def get_model(self) -> Union[ui.AbstractValueModel, None]: return self._model def __repr__(self): return f"<StyleItem '{self.property} . {self.style_type}'>" def __str__(self): return f"<StyleItem '{self.property} . {self.style_type}'>" class StyleGroupItem(ui.AbstractItem): """A single AbstractItemModel item that represents a single prim""" def __init__(self, type_name: str, style_dict: dict, parent_model: "StyleModel"): super().__init__() self.children = [] self.type_name = type_name self._parent_dict = style_dict self.style_dict = self._parent_dict[type_name] self.parent_model = parent_model self._name_model = ui.SimpleStringModel() self._name_model.set_value(type_name) def value_changed(model: ui.AbstractValueModel): new_name = model.as_string if new_name in self._parent_dict: carb.log_warn(f"Entry with type {new_name} already exits, skipping") return self._parent_dict[new_name] = self.style_dict del self._parent_dict[self.type_name] self.type_name = new_name self.parent_model.update() self._name_model.add_value_changed_fn(value_changed) def get_model(self): return self._name_model def delete_item(self, item: StyleItem): # we call delete on the item but also make sure we clear our cach for it self.children.remove(item) item.delete() def delete(self): # we simply remove the key from the referenced Value Dict del self._parent_dict[self.type_name] def __repr__(self): return f"<StyleItem '{self.type_name} . {self.style_dict}'>" def __str__(self): return f"<StyleItem '{self.type_name} . {self.style_dict}'>" class StyleModel(ui.AbstractItemModel): """The item model that watches the stage""" def __init__(self, treeview): """Flat means the root node has all the children and children of children, etc.""" super().__init__() self._widget = None self._style_dict: dict = {} self._is_generic = False self._root: List[StyleGroupItem] = [] self._treeview: "StyleTreeView" = treeview def _update_style_dict(self, style: dict) -> dict: style_dict = copy.copy(style) # find if there are "Generic" entry (with no sub dictionary) and move them around remove_keys = [] has_generic_entries = False for key, value in style_dict.items(): if not type(value) == dict: has_generic_entries = True break if has_generic_entries: style_dict["All"] = {} for key, value in style_dict.items(): if not type(value) == dict: style_dict["All"][key] = value remove_keys.append(key) for a_key in remove_keys: del style_dict[a_key] return style_dict def set_widget(self, widget: ui.Widget): self._widget = widget self.update_cached_style() self._root: List[StyleGroupItem] = [] self._item_changed(None) def update_cached_style(self): if not self._widget.style: style_dict = {} else: style_dict = cast(dict, self._widget.style) self._style_dict = self._update_style_dict(style_dict) # rebuild self._item_changed(None) def can_item_have_children(self, parentItem: Union[StyleGroupItem, StyleItem]) -> bool: if not parentItem: return True if isinstance(parentItem, StyleGroupItem): return True return False def get_item_children(self, item: Union[StyleGroupItem, StyleItem, None]) -> Union[None, list]: """Reimplemented from AbstractItemModel""" if not item: if not self._root: self._root = [] for key, value in self._style_dict.items(): group_item = StyleGroupItem(key, self._style_dict, self) self._root.append(group_item) return self._root if isinstance(item, StyleItem): return [] if isinstance(item, StyleGroupItem): children = [] for key, value in item.style_dict.items(): property_type = get_property_type(key) # value is passed by reference and updated internally on change style_item = StyleItem(key, property_type, item.style_dict, self, item) children.append(style_item) item.children = children return item.children # we should not get here .. return [] def duplicate_item(self, item: StyleGroupItem): new_item = item.type_name + "1" self._style_dict[new_item] = copy.copy(self._style_dict[item.type_name]) new_item = StyleGroupItem(new_item, self._style_dict, self) self._root.append(new_item) self._item_changed(None) self.update() def delete_item(self, item: Union[StyleGroupItem, StyleItem]): if isinstance(item, StyleItem): item.parent_item.delete_item(item) self._item_changed(item.parent_item) self.update() elif isinstance(item, StyleGroupItem): item.delete() self._root.remove(item) self._item_changed(None) self.update() else: carb.log_error("Delete_item only support Union[StyleGroupItem, StyleItem]") def update(self): style_dict = cast(dict, copy.copy(self._style_dict)) if "All" in style_dict: # update Generic Entry for key, value in style_dict["All"].items(): style_dict[key] = value del style_dict["All"] self._widget.set_style(style_dict) def get_item_value_model_count(self, item): """Reimplemented from AbstractItemModel""" return 1 def get_item_value_model(self, item: Union[StyleItem, StyleGroupItem], column_id: int): """Reimplemented from AbstractItemModel""" if isinstance(item, StyleGroupItem): if column_id == 0: return item.get_model() elif isinstance(item, StyleItem): if column_id == 0: return ui.SimpleStringModel(item.property) if column_id == 1: return item.get_model() def destroy(self): self._widget = None
16,635
Python
30.992308
196
0.603727
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/style_delegate.py
__all__ = ["StyleTreeDelegate"] import omni.ui as ui from typing import Union from .style_model import StyleGroupItem, StyleModel, StyleItem, StylePropertyType from .widget_styles import ClassStyles from pathlib import Path ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons") LINE_COLOR = 0x00555555 STYLE_NAME_DEFAULT = { "Colors": { "background_color": 0xFFAAAAAA, "color": 0xFFAAAAAA, "secondary_color": 0xFFAAAAAA, "selected_color": 0xFFAAAAAA, "secondary_selected_color": 0xFFAAAAAA, "debug_color": 0xAAAAFFAA, }, "Border": {"border_radius": 2.0, "border_width": 1.0, "border_color": 0xFFAAFFAA, "corner_flag": ui.CornerFlag.ALL}, "Text": {"alignment": ui.Alignment.LEFT, "font_size": 16.0}, "Images": {"image_url": "", "fill_policy": ui.FillPolicy.STRETCH}, "-Margin-": {"margin": 0, "margin_width": 0, "margin_height": 0}, "-Padding-": {"padding": 0, "padding_width": 0, "padding_height": 0}, "-Misc-": {"secondary_padding": 0, "scrollbar_size": 10, "draw_mode": ui.SliderDrawMode.DRAG}, } class StyleTreeDelegate(ui.AbstractItemDelegate): def __init__(self, model: StyleModel): super().__init__() self._add_menu = None self._model = model self._delete_menu = None self._delete_group_menu = None def _show_group_menu(self, b, item: StyleGroupItem): if not b == 1: return if not self._delete_group_menu: self._delete_group_menu = ui.Menu("Delete") self._delete_group_menu.clear() def duplicate_item(): self._model.duplicate_item(item) def delete_item(): self._model.delete_item(item) with self._delete_group_menu: ui.MenuItem("Delete", triggered_fn=delete_item) ui.MenuItem("Duplicate", triggered_fn=duplicate_item) self._delete_group_menu.show() def _show_delete_menu(self, b, item: StyleItem): if not b == 1: return if not self._delete_menu: self._delete_menu = ui.Menu("Delete") self._delete_menu.clear() def delete_item(): self._model.delete_item(item) with self._delete_menu: ui.MenuItem("Delete", triggered_fn=delete_item) self._delete_menu.show() def _show_add_menu(self, x, y, b, m, type: str, item: StyleGroupItem): if not self._add_menu: self._add_menu = ui.Menu("Add") # menu is dynamically built based on type self._add_menu.clear() def add_style(key, value): # this is capture by the closure item.style_dict[key] = value self._model._item_changed(item) self._model.update() # we extact the base type item_type = item.type_name.split(":")[0] if "." in item_type: item_type = item_type.split(".")[0] filtered_style = ClassStyles.get(item_type, None) def add_menu_item(name: str, default): if filtered_style and name not in filtered_style: return ui.MenuItem(name, triggered_fn=lambda key=name, value=default: add_style(key, value)) with self._add_menu: for category, values in STYLE_NAME_DEFAULT.items(): if category[0] == "-" or filtered_style: ui.Separator() for style, default in values.items(): add_menu_item(style, default) else: with ui.Menu(category): for style, default in values.items(): add_menu_item(style, default) self._add_menu.show() def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" if column_id == 0: if isinstance(item, StyleGroupItem): with ui.VStack(height=0): ui.Spacer(height=10) with ui.ZStack(width=10 * (level + 1), height=0): ui.Rectangle(height=25) with ui.HStack(width=10 * (level + 1)): ui.Spacer(height=10) ui.Spacer() if model.can_item_have_children(item): with ui.VStack(): ui.Spacer() image_name = "Minus" if expanded else "Plus" ui.Image( f"{ICON_PATH}/{image_name}.svg", width=10, height=10, style={"color": 0xFFCCCCCC}, ) ui.Spacer() ui.Spacer(width=5) else: ui.Spacer(width=20) def build_widget(self, model, item: Union[StyleGroupItem, StyleItem], column_id: int, level, expanded): """Create a widget per column per item""" value_model: ui.AbstractValueModel = model.get_item_value_model(item, column_id) # some cells are empty if not value_model: ui.Spacer() return # Group Instance = Group Title and Add Button if isinstance(item, StyleGroupItem): with ui.VStack(): # small Space before Group Title ui.Spacer(height=10) with ui.ZStack( height=25, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_group_menu(b, item) ): ui.Rectangle(style={"background_color": 0xFF222222}) with ui.HStack(): ui.Spacer(width=5) with ui.VStack(): ui.Spacer() ui.StringField( value_model, height=20, style={"font_size": 16, "background_color": 0xFF222222} ) ui.Spacer() ui.Spacer(width=5) group_type = model.get_item_value_model(item, 0).as_string with ui.VStack(width=0): ui.Spacer() ui.Button( image_url=f"{ICON_PATH}/Add.svg", width=20, height=20, style={"background_color": 0xFF556655, "border_radius": 5}, mouse_pressed_fn=lambda x, y, b, m, type=group_type, item=item: self._show_add_menu( x, y, b, m, type, item ), ) ui.Spacer() # Style Property Row else: with ui.HStack(height=25, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_delete_menu(b, item)): ui.Spacer(width=5) with ui.VStack(): ui.Spacer() ui.Label( value_model.as_string, height=0, style={"font_size": 14, "alignment": ui.Alignment.RIGHT_CENTER, "margin_width": 5}, ) ui.Spacer() # Value Model for the Second Columns value_model: ui.AbstractValueModel = model.get_item_value_model(item, 1) with ui.VStack(): ui.Spacer() with ui.HStack(height=0): # key: str = model.get_item_value_model(item, 0).as_string if item.style_type == StylePropertyType.COLOR: # color_model = StyleColorModel(value_model.as_int) ui.ColorWidget(value_model, width=12, height=12) elif item.style_type == StylePropertyType.FLOAT: ui.FloatDrag(value_model).step = 1 elif item.style_type == StylePropertyType.STRING: ui.StringField(value_model) elif item.style_type == StylePropertyType.ENUM: ui.ComboBox(value_model) ui.Spacer(width=20) ui.Spacer()
8,610
Python
37.271111
120
0.483275
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/resolved_style.py
__all__ = ["ResolvedStyleWidget"] from typing import Union import omni.ui as ui from .widget_styles import ClassStyles from .style_model import get_property_type, StylePropertyType, StyleColorModel, StyleComboItemModel, get_enum_class class ResolvedStyleWidget: """The Stage widget""" def __init__(self, **kwargs): self._widget = None # self._frame_widget = ui.CollapsableFrame("Resolved Styles", height=0, build_fn=self._build_ui) # with self._frame_widget: self._stack = ui.VStack(height=0, spacing=5) self._class_name_mapping = { "CollapsableFrame": "Frame", "VStack": "Stack", "HStack": "Stack", "ZStack": "Stack", "IntSlider": "AbstractSlider", "FloatSlider": "AbstractSlider", "IntDrag": "AbstractSlider", "FloatDrag": "AbstractSlider", } def set_widget(self, widget: ui.Widget): self._widget = widget self._widget_type = self._widget.__class__.__name__ self._widget_type = self._class_name_mapping.get(self._widget_type, self._widget_type) self._widget_styles = ClassStyles.get(self._widget_type, []) self._build_ui() def _build_ui(self): self._stack.clear() if not self._widget: return with self._stack: ui.Label("Resolved Styles", height=0) ui.Spacer(height=5) for name in self._widget_styles: with ui.HStack(height=0): ui.Spacer(width=10) ui.Label(name, width=150) prop_type = get_property_type(name) if prop_type == StylePropertyType.COLOR: print(ui.Inspector.get_resolved_style(self._widget)) value = False # value: Union[int, bool] = ui.Inspector.get_resolved_style(self._widget.get_resolved_style_value(name) if value: model = StyleColorModel(value) color_widget = ui.ColorWidget(enabled=False) color_widget.model = model else: ui.Label("Default") elif prop_type == StylePropertyType.FLOAT: print(ui.Inspector.get_resolved_style(self._widget)) value = False # value: Union[float, bool] = self._widget.get_resolved_style_value(name) if value: field = ui.FloatField().model field.set_value(value) else: ui.Label("Default") elif prop_type == StylePropertyType.STRING: print(ui.Inspector.get_resolved_style(self._widget)) value = False # value: Union[str, bool] = self._widget.get_resolved_style_value(name) if value: ui.StringField().model.set_value(value) else: ui.Label("Default") elif prop_type == StylePropertyType.ENUM: print(ui.Inspector.get_resolved_style(self._widget)) value = False # value: Union[int, bool] = self._widget.get_resolved_style_value(name) if value: enum_cls = get_enum_class(name) self._model = StyleComboItemModel(enum_cls, value) ui.ComboBox(self._model) else: ui.Label("Default") else: ui.Label("MISSING ... TYPE")
3,885
Python
39.905263
127
0.487259