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.manipulator.camera/omni/kit/manipulator/camera/tests/test_manipulator_gamepad.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. # __all__ = ['TestManipulatorGamepad'] import omni.kit.test from omni.kit.manipulator.camera.manipulator import CameraManipulatorBase, SceneViewCameraManipulator, adjust_center_of_interest import omni.ui as ui from omni.ui import scene as sc from omni.ui.tests.test_base import OmniUiTest import omni.kit.ui_test as ui_test import carb from carb.input import GamepadInput from pxr import Gf from functools import partial TEST_WIDTH, TEST_HEIGHT = 500, 500 def _flatten_matrix(matrix: Gf.Matrix4d): return [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]] class SimpleGrid(): def __init__(self, lineCount: float = 100, lineStep: float = 10, thicknes: float = 1, color: ui.color = ui.color(0.25)): self.__transform = ui.scene.Transform() with self.__transform: for i in range(lineCount * 2 + 1): ui.scene.Line( ((i - lineCount) * lineStep, 0, -lineCount * lineStep), ((i - lineCount) * lineStep, 0, lineCount * lineStep), color=color, thickness=thicknes, ) ui.scene.Line( (-lineCount * lineStep, 0, (i - lineCount) * lineStep), (lineCount * lineStep, 0, (i - lineCount) * lineStep), color=color, thickness=thicknes, ) class SimpleOrigin(): def __init__(self, length: float = 5, thickness: float = 4): origin = (0, 0, 0) with ui.scene.Transform(): ui.scene.Line(origin, (length, 0, 0), color=ui.color.red, thickness=thickness) ui.scene.Line(origin, (0, length, 0), color=ui.color.green, thickness=thickness) ui.scene.Line(origin, (0, 0, length), color=ui.color.blue, thickness=thickness) # Create a few scenes with different camera-maniupulators (a general ui.scene manip and one that allows ortho-tumble ) class SimpleScene: def __init__(self, ortho: bool = False, custom: bool = False, *args, **kwargs): self.__scene_view = ui.scene.SceneView(*args, **kwargs) if ortho: view = [-1, 0, 0, 0, 0, 0, 0.9999999999999998, 0, 0, 0.9999999999999998, 0, 0, 0, 0, -1000, 1] projection = [0.008, 0, 0, 0, 0, 0.008, 0, 0, 0, 0, -2.000002000002e-06, 0, 0, 0, -1.000002000002, 1] else: view = [0.7071067811865476, -0.40557978767263897, 0.5792279653395693, 0, -2.775557561562892e-17, 0.8191520442889919, 0.5735764363510462, 0, -0.7071067811865477, -0.4055797876726389, 0.5792279653395692, 0, 6.838973831690966e-14, -3.996234471857009, -866.0161835150924, 1.0000000000000002] projection = [4.7602203407949375, 0, 0, 0, 0, 8.483787309173106, 0, 0, 0, 0, -1.000002000002, -1, 0, 0, -2.000002000002, 0] view = Gf.Matrix4d(*view) center_of_interest = [0, 0, -view.Transform((0, 0, 0)).GetLength()] with self.__scene_view.scene: self.items = [SimpleGrid(), ui.scene.Arc(100, axis=1, wireframe=True), SimpleOrigin()] with ui.scene.Transform(transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1000, 0, 1000, 1]): self.items.append(ui.scene.Arc(100, axis=1, wireframe=True, color=ui.color.green)) with ui.scene.Transform(transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -260, 0, 260, 1]): self.items.append(ui.scene.Arc(100, axis=1, wireframe=True, color=ui.color.blue)) if custom: self.items.append(CameraManipulatorBase()) else: self.items.append(SceneViewCameraManipulator(center_of_interest)) # Push the start values into the CameraManipulator self.setup_camera_model(self.items[-1].model, view, projection, center_of_interest, ortho) def __del__(self): self.destroy() def destroy(self): for item in self.items: if hasattr(item, 'destroy'): item.destroy() self.items = None if self.__scene_view: self.__scene_view.destroy() self.__scene_view = None def setup_camera_model(self, cam_model, view, projection, center_of_interest, ortho): cam_model.set_floats('transform', _flatten_matrix(view.GetInverse())) cam_model.set_floats('projection', projection) cam_model.set_floats('center_of_interest', [0, 0, -view.Transform((0, 0, 0)).GetLength()]) if ortho: cam_model.set_ints('orthographic', [ortho]) # Setup up the subscription to the CameraModel so changes here get pushed to SceneView self.model_changed_sub = cam_model.subscribe_item_changed_fn(self.model_changed) # And push the view and projection into the SceneView.model cam_model._item_changed(cam_model.get_item('transform')) cam_model._item_changed(cam_model.get_item('projection')) def model_changed(self, model, item): if item == model.get_item('transform'): transform = Gf.Matrix4d(*model.get_as_floats(item)) # Signal that this this is the final change block, adjust our center-of-interest then interaction_ended = model.get_as_ints('interaction_ended') if interaction_ended and interaction_ended[0]: transform = Gf.Matrix4d(*model.get_as_floats(item)) # Adjust the center-of-interest if requested (zoom out in perspective does this) initial_transform = Gf.Matrix4d(*model.get_as_floats('initial_transform')) coi_start, coi_end = adjust_center_of_interest(model, initial_transform, transform) if coi_end: model.set_floats('center_of_interest', [coi_end[0], coi_end[1], coi_end[2]]) # Push the start values into the SceneView self.model.set_floats('view', _flatten_matrix(transform.GetInverse())) elif item == model.get_item('projection'): self.model.set_floats('projection', model.get_as_floats('projection')) @property def scene(self): return self.__scene_view.scene @property def model(self): return self.__scene_view.model @property def camera_maipulator(self): return self.items[-1] async def wait_human_delay(delay=1): await ui_test.human_delay(delay) def get_translation(model): matrix = model.get_as_floats('view') return (matrix[12], matrix[13], matrix[14]) class TestManipulatorGamepad(OmniUiTest): async def create_test_view(self, name: str, custom=False, ortho: bool = False): window = await self.create_test_window(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) with window.frame: simple_scene = SimpleScene() return (window, simple_scene) async def test_gamepad_initilization(self): """Test gamepad controller setup and destrution via carb.input.""" window, simple_scene = await self.create_test_view('Gamepad Movement') simple_scene.camera_maipulator.gamepad_enabled = False self.assertFalse(simple_scene.camera_maipulator.gamepad_enabled) simple_scene.camera_maipulator.gamepad_enabled = True self.assertTrue(simple_scene.camera_maipulator.gamepad_enabled) simple_scene.camera_maipulator.gamepad_enabled = False self.assertFalse(simple_scene.camera_maipulator.gamepad_enabled) simple_scene.destroy() async def test_gamepad_connection(self): """Test gamepad controller connection and disconnection doesn't throw""" window, simple_scene = await self.create_test_view('Gamepad Movement') simple_scene.camera_maipulator.gamepad_enabled = True self.assertTrue(simple_scene.camera_maipulator.gamepad_enabled) game_pad, game_pad_connected = None, False input_provider = carb.input.acquire_input_provider() try: game_pad = input_provider.create_gamepad("Fake Gamepad for test", "00000000-00000000-0000-0000") self.assertIsNotNone(game_pad) input_provider.set_gamepad_connected(game_pad, True) game_pad_connected = True await wait_human_delay(5) input_provider.set_gamepad_connected(game_pad, False) game_pad_connected = False await wait_human_delay(5) finally: if game_pad is not None: if game_pad_connected: input_provider.set_gamepad_connected(game_pad, False) input_provider.destroy_gamepad(game_pad) simple_scene.destroy() async def test_gamepad_movement(self): """Test gamepad controller functionality""" window, simple_scene = await self.create_test_view('Gamepad Movement') self.assertIsNotNone(simple_scene.model) simple_scene.camera_maipulator.gamepad_enabled = True self.assertTrue(simple_scene.camera_maipulator.gamepad_enabled) game_pad, game_pad_connected = None, False input_provider = carb.input.acquire_input_provider() try: game_pad = input_provider.create_gamepad("Fake Gamepad for test", "00000000-00000000-0000-0000") self.assertIsNotNone(game_pad) input_provider.set_gamepad_connected(game_pad, True) game_pad_connected = True await wait_human_delay(5) def test_moved_left(m_a, m_b): tr_a = (m_a[12], m_a[13], m_a[14]) tr_b = (m_b[12], m_b[13], m_b[14]) self.assertTrue(tr_b[0] > tr_a[0]) self.assertTrue(Gf.IsClose(tr_a[1], tr_b[1], 1.0e-5)) self.assertTrue(Gf.IsClose(tr_a[2], tr_b[2], 1.0e-5)) def test_moved_right(m_a, m_b): tr_a = (m_a[12], m_a[13], m_a[14]) tr_b = (m_b[12], m_b[13], m_b[14]) self.assertTrue(tr_b[0] < tr_a[0]) self.assertTrue(Gf.IsClose(tr_a[1], tr_b[1], 1.0e-5)) self.assertTrue(Gf.IsClose(tr_a[2], tr_b[2], 1.0e-5)) def test_moved_up(m_a, m_b): tr_a = (m_a[12], m_a[13], m_a[14]) tr_b = (m_b[12], m_b[13], m_b[14]) self.assertTrue(Gf.IsClose(tr_a[0], tr_b[0], 1.0e-5)) self.assertTrue(tr_a[1] > tr_b[1]) self.assertTrue(Gf.IsClose(tr_a[2], tr_b[2], 1.0e-5)) def test_moved_down(m_a, m_b): tr_a = (m_a[12], m_a[13], m_a[14]) tr_b = (m_b[12], m_b[13], m_b[14]) self.assertTrue(Gf.IsClose(tr_a[0], tr_b[0], 1.0e-5)) self.assertTrue(tr_a[1] < tr_b[1]) self.assertTrue(Gf.IsClose(tr_a[2], tr_b[2], 1.0e-5)) def test_moved_forward(m_a, m_b): tr_a = (m_a[12], m_a[13], m_a[14]) tr_b = (m_b[12], m_b[13], m_b[14]) self.assertTrue(Gf.IsClose(tr_a[0], tr_b[0], 1.0e-5)) self.assertTrue(Gf.IsClose(tr_a[1], tr_b[1], 1.0e-5)) self.assertTrue(tr_a[2] < tr_b[2]) def test_moved_backward(m_a, m_b): tr_a = (m_a[12], m_a[13], m_a[14]) tr_b = (m_b[12], m_b[13], m_b[14]) self.assertTrue(Gf.IsClose(tr_a[0], tr_b[0], 1.0e-5)) self.assertTrue(Gf.IsClose(tr_a[1], tr_b[1], 1.0e-5)) self.assertTrue(tr_a[2] > tr_b[2]) def test_no_move(m_a, m_b): tr_a = (m_a[12], m_a[13], m_a[14]) tr_b = (m_b[12], m_b[13], m_b[14]) self.assertTrue(Gf.IsClose(tr_a, tr_b, 1.0e-5)) async def test_gamepad_input(input_dict, event_delay=15): prev_m = simple_scene.model.get_as_floats('view').copy() for input, test_fn in input_dict.items(): input_provider.buffer_gamepad_event(game_pad, input, 1.0) await wait_human_delay(event_delay) input_provider.buffer_gamepad_event(game_pad, input, 0.0) await wait_human_delay(event_delay) cur_m = simple_scene.model.get_as_floats('view').copy() test_fn(prev_m, cur_m) prev_m = cur_m await test_gamepad_input({ GamepadInput.LEFT_STICK_LEFT: test_moved_left, GamepadInput.LEFT_STICK_RIGHT: test_moved_right, GamepadInput.LEFT_STICK_UP: test_moved_forward, GamepadInput.LEFT_STICK_DOWN: test_moved_backward }) await test_gamepad_input({ GamepadInput.DPAD_LEFT: test_moved_left, GamepadInput.DPAD_RIGHT: test_moved_right, GamepadInput.DPAD_UP: test_moved_forward, GamepadInput.DPAD_DOWN: test_moved_backward }) await test_gamepad_input({ GamepadInput.LEFT_TRIGGER: test_moved_down, GamepadInput.RIGHT_TRIGGER: test_moved_up, }) await test_gamepad_input({ GamepadInput.LEFT_SHOULDER: test_moved_left, GamepadInput.RIGHT_SHOULDER: test_moved_right, }) def test_rot_x(is_greater: bool, m_a, m_b): rt_a = Gf.Matrix4d(*m_a).ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) rt_b = Gf.Matrix4d(*m_b).ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) self.assertEqual(rt_a[0] > rt_b[0], is_greater) self.assertTrue(Gf.IsClose(rt_a[1], rt_a[1], 1.0e-3)) self.assertTrue(Gf.IsClose(rt_a[2], rt_a[2], 1.0e-3)) def test_rot_y(is_greater: bool, m_a, m_b): rt_a = Gf.Matrix4d(*m_a).ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) rt_b = Gf.Matrix4d(*m_b).ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) self.assertTrue(Gf.IsClose(rt_a[0], rt_a[0], 1.0e-3)) self.assertEqual(rt_a[1] > rt_b[1], is_greater) self.assertTrue(Gf.IsClose(rt_a[2], rt_a[2], 1.0e-3)) await test_gamepad_input({ GamepadInput.RIGHT_STICK_LEFT: partial(test_rot_y, True), GamepadInput.RIGHT_STICK_RIGHT: partial(test_rot_y, False), GamepadInput.RIGHT_STICK_UP: partial(test_rot_x, True), GamepadInput.RIGHT_STICK_DOWN: partial(test_rot_x, False), }) # Test disabling flight-mode in the model would stop gamepad from doing anything simple_scene.items[-1].model.set_ints('disable_fly', [1]) await test_gamepad_input({ GamepadInput.LEFT_STICK_LEFT: test_no_move, GamepadInput.LEFT_STICK_RIGHT: test_no_move, GamepadInput.LEFT_STICK_UP: test_no_move, GamepadInput.LEFT_STICK_DOWN: test_no_move }) await test_gamepad_input({ GamepadInput.DPAD_LEFT: test_no_move, GamepadInput.DPAD_RIGHT: test_no_move, GamepadInput.DPAD_UP: test_no_move, GamepadInput.DPAD_DOWN: test_no_move }) simple_scene.items[-1].model.set_ints('disable_fly', [0]) await wait_human_delay(5) finally: if game_pad is not None: if game_pad_connected: input_provider.set_gamepad_connected(game_pad, False) input_provider.destroy_gamepad(game_pad) simple_scene.destroy()
16,226
Python
45.230769
299
0.585418
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/tests/test_viewport_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. ## __all__ = ['TestViewportCamera'] import omni.kit.app import omni.kit.ui_test as ui_test from carb.input import MouseEventType, KeyboardEventType, KeyboardInput from pxr import Gf, Sdf, UsdGeom TEST_GUTTER = 10 TEST_WIDTH, TEST_HEIGHT = 500, 500 TEST_UI_CENTER = ui_test.Vec2(TEST_WIDTH / 2, TEST_HEIGHT / 2) TEST_UI_LEFT = ui_test.Vec2(TEST_GUTTER, TEST_UI_CENTER.y) TEST_UI_RIGHT = ui_test.Vec2(TEST_WIDTH - TEST_GUTTER, TEST_UI_CENTER.y) TEST_UI_TOP = ui_test.Vec2(TEST_UI_CENTER.x, TEST_GUTTER) TEST_UI_BOTTOM = ui_test.Vec2(TEST_UI_CENTER.x, TEST_HEIGHT - TEST_GUTTER) class TestViewportCamera(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): from omni.kit.viewport.utility import get_active_viewport self.viewport = get_active_viewport() await self.viewport.usd_context.new_stage_async() self.stage = self.viewport.stage self.camera = UsdGeom.Xformable(self.stage.GetPrimAtPath(self.viewport.camera_path)) # Disable locking to render results, as there are no render-results self.viewport.lock_to_render_result = False super().setUp() await self.wait_n_updates() # After running each test async def tearDown(self): super().tearDown() async def wait_n_updates(self, n_frames: int = 3): app = omni.kit.app.get_app() for _ in range(n_frames): await app.next_update_async() async def __do_mouse_interaction(self, mouse_down: MouseEventType, start: ui_test.Vec2, end: ui_test.Vec2, mouse_up: MouseEventType, modifier: KeyboardInput | None = None): if modifier: await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_PRESS, modifier) await ui_test.human_delay() else: await self.wait_n_updates(10) await ui_test.input.emulate_mouse(MouseEventType.MOVE, start) await ui_test.input.emulate_mouse(mouse_down, start) await ui_test.input.emulate_mouse_slow_move(start, end) await ui_test.input.emulate_mouse(mouse_up, end) if modifier: await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_RELEASE, modifier) await ui_test.human_delay() else: await self.wait_n_updates() def assertIsClose(self, a, b): self.assertTrue(Gf.IsClose(a, b, 0.1)) def assertRotationIsClose(self, a, b): self.assertTrue(Gf.IsClose(a.GetReal(), b.GetReal(), 0.1)) self.assertTrue(Gf.IsClose(a.GetImaginary(), b.GetImaginary(), 0.1)) @property def camera_position(self): return self.camera.GetLocalTransformation(self.viewport.time).ExtractTranslation() @property def camera_rotation(self): return self.camera.GetLocalTransformation(self.viewport.time).ExtractRotation().GetQuaternion() async def test_viewport_scroll(self, is_locked: bool = False): """Test scrollwheel with a Viewport""" test_pos = [ Gf.Vec3d(500, 500, 500), Gf.Vec3d(1007.76, 1007.76, 1007.76), Gf.Vec3d(555.97, 555.97, 555.97), ] if is_locked: test_pos = [test_pos[0]] * len(test_pos) await ui_test.input.emulate_mouse_move_and_click(TEST_UI_CENTER) self.assertIsClose(self.camera_position, test_pos[0]) await ui_test.input.emulate_mouse_scroll(ui_test.Vec2(0, -2500)) await self.wait_n_updates(100) self.assertIsClose(self.camera_position, test_pos[1]) await ui_test.input.emulate_mouse_scroll(ui_test.Vec2(0, 1000)) await self.wait_n_updates(100) self.assertIsClose(self.camera_position, test_pos[2]) async def test_viewport_pan(self, is_locked: bool = False): """Test panning across a Viewport""" test_pos = [ Gf.Vec3d(500, 500, 500), Gf.Vec3d(1189.86, 500, -189.86), Gf.Vec3d(699.14, 101.7, 699.14), ] if is_locked: test_pos = [test_pos[0]] * len(test_pos) self.assertIsClose(self.camera_position, test_pos[0]) await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN, TEST_UI_RIGHT, TEST_UI_LEFT, MouseEventType.MIDDLE_BUTTON_UP) self.assertIsClose(self.camera_position, test_pos[1]) await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN, TEST_UI_LEFT, TEST_UI_RIGHT, MouseEventType.MIDDLE_BUTTON_UP) self.assertIsClose(self.camera_position, test_pos[0]) await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_TOP, MouseEventType.MIDDLE_BUTTON_UP) self.assertIsClose(self.camera_position, test_pos[2]) await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_BOTTOM, MouseEventType.MIDDLE_BUTTON_UP) self.assertIsClose(self.camera_position, test_pos[0]) async def test_viewport_look(self, is_locked: bool = False): """Test panning across a Viewport""" test_rot = [ Gf.Quaternion(0.88, Gf.Vec3d(-0.27, 0.36, 0.11)), Gf.Quaternion(-0.33, Gf.Vec3d(0.10, 0.89, 0.28)), Gf.Quaternion(0.86, Gf.Vec3d(0.33, 0.35, -0.13)), ] if is_locked: test_rot = [test_rot[0]] * len(test_rot) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_RIGHT, TEST_UI_LEFT, MouseEventType.RIGHT_BUTTON_UP) self.assertRotationIsClose(self.camera_rotation, test_rot[1]) await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_LEFT, TEST_UI_RIGHT, MouseEventType.RIGHT_BUTTON_UP) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_TOP, MouseEventType.RIGHT_BUTTON_UP) self.assertRotationIsClose(self.camera_rotation, test_rot[2]) await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_BOTTOM, MouseEventType.RIGHT_BUTTON_UP) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) async def __test_viewport_orbit_modifer_not_working(self, is_locked: bool = False): """Test orbit across a Viewport""" test_rot = [ Gf.Quaternion(0.88, Gf.Vec3d(-0.27, 0.36, 0.11)), Gf.Quaternion(-0.33, Gf.Vec3d(0.10, 0.89, 0.28)), Gf.Quaternion(0.86, Gf.Vec3d(0.33, 0.35, -0.13)), ] if is_locked: test_rot = [test_rot[0]] * len(test_rot) await ui_test.input.emulate_mouse_move_and_click(TEST_UI_CENTER) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN, TEST_UI_RIGHT, TEST_UI_LEFT, MouseEventType.LEFT_BUTTON_UP, KeyboardInput.LEFT_ALT) self.assertRotationIsClose(self.camera_rotation, test_rot[1]) await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN, TEST_UI_LEFT, TEST_UI_RIGHT, MouseEventType.LEFT_BUTTON_UP, KeyboardInput.LEFT_ALT) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_TOP, MouseEventType.LEFT_BUTTON_UP, KeyboardInput.LEFT_ALT) self.assertRotationIsClose(self.camera_rotation, test_rot[2]) await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN, TEST_UI_CENTER, TEST_UI_BOTTOM, MouseEventType.LEFT_BUTTON_UP, KeyboardInput.LEFT_ALT) self.assertRotationIsClose(self.camera_rotation, test_rot[0]) async def test_viewport_lock(self): """Test the lock attribute blocks navigation""" self.camera.GetPrim().CreateAttribute("omni:kit:cameraLock", Sdf.ValueTypeNames.Bool, True).Set(True) await self.test_viewport_pan(is_locked=True) await self.test_viewport_look(is_locked=True) await self.test_viewport_scroll(is_locked=True)
9,868
Python
44.270642
109
0.582286
omniverse-code/kit/exts/omni.kit.manipulator.camera/docs/index.rst
omni.kit.manipulator.camera ########################### Camera Manipultors for omni.ui.scene .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule:: omni.kit.manipulator.camera :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members:
320
reStructuredText
15.049999
43
0.621875
omniverse-code/kit/exts/omni.kit.window.tests/PACKAGE-LICENSES/omni.kit.window.tests-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.tests/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "Kit Tests Window" description="Window to list/run all found python tests." # URL of the extension source repository. repository = "" # One of categories for UI. category = "Internal" # Keywords for the extension keywords = ["kit"] # https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" [dependencies] "omni.ui" = {} "omni.kit.test" = {} "omni.kit.commands" = {} [[python.module]] name = "omni.kit.window.tests" [[test]] args = ["--/exts/omni.kit.window.tests/openWindow=1"] stdoutFailPatterns.exclude = [] waiver = "Old UI, hard to test" # This window works well, but really needs an update on omni.ui. That will enable using ui_test to test. [settings] # Open window by default exts."omni.kit.window.tests".openWindow = false
1,028
TOML
24.09756
136
0.719844
omniverse-code/kit/exts/omni.kit.window.tests/omni/kit/window/_test_runner_window.py
"""Implementation of the manager of the Test Runner window. Exports only TestRunnerWindow: The object managing the window, a singleton. Instatiate it to create the window. Limitations: - When tests are running and extensions are disabled then enabled as part of it any tests owned by the disabled extensions are removed and not restored. Toolbar Interactions - what happens when each control on the toolbar is used: Run Selected: Gather the list of all selected tests and run them one at a time until completion (disabled when no tests exist) Select All: Add all tests to the selection list (disabled when all tests are currently selected) Deselect All: Remove all tests from the selection list (disabled when no tests are currently selected) Filter: Text that full tests names must match before being displayed Load Tests...: Reload the set of available tests from one of the plug-in options Properties: Display the settings in a separate window Note that all tests displayed must come from an enabled extension. To add tests on currently disabled extensions you would just enable the extension and the test list will be repopulated from the new set of enabled extensions. Similarly if you disable an extension its tests will be removed from the list. Individual Test Interactions - what happens when each per-test control is used: Checkbox: Adds or removes the test from the selection list Run: Run the one test and modify its icon to indicate test state Soak: Run the one test 1,000 times and modify its icon to indicate test state Open: Open the source file of the test script for the test (Final icon is updated to depict the state of the test - not run, running, successful, failed) TODO: Fix the text file processing to show potential missing extensions TODO: Add in editing of the user settings in the window # -------------------------------------------------------------------------------------------------------------- # def _edit_filter_settings(self): # # Emit the UI commands required to edit the filters defined in the user settings # from carb.settings import get_settings # include_tests = get_settings().get("/exts/omni.kit.test/includeTests") # exclude_tests = get_settings().get("/exts/omni.kit.test/excludeTests") """ from __future__ import annotations import asyncio from contextlib import suppress from enum import auto, Enum import fnmatch from functools import partial import logging from pathlib import Path import sys import unittest import carb import carb.settings import omni.ext import omni.kit.test import omni.kit.commands import omni.kit.app import omni.kit.ui from omni.kit.test import TestRunStatus from omni.kit.test import TestPopulator from omni.kit.test import TestPopulateAll from omni.kit.test import TestPopulateDisabled from omni.kit.test import DEFAULT_POPULATOR_NAME from omni.kit.window.properties import TestingPropertiesWindow import omni.ui as ui __all__ = ["TestRunnerWindow"] # Size constants _BUTTON_HEIGHT = 24 # ============================================================================================================== # Local logger for dumping debug information about the test runner window operation. # By default it is off but it can be enabled in the extension setup. _LOG = logging.getLogger("test_runner_window") # ============================================================================================================== class _TestUiEntry: """UI Data for a single test in the test runner""" def __init__(self, test: unittest.TestCase, file_path: str): """Initialize the entry with the given test""" self.test: unittest.TestCase = test # Test this entry manages self.checkbox: ui.Checkbox = None # Selection checkbox for this test self.sub_checked: ui.Subscription = None # Subscription to the checkbox change self.label_stack: ui.HStack = None # Container stack for the test module and name self.run_button: ui.Button = None # Button for running the test self.soak_button: ui.Button = None # Button for running the test 1000 times self.open_button: ui.Button = None # Button for opening the file containing the test self.file_path: Path = file_path # Path to the file containing the test self.status: TestRunStatus = TestRunStatus.UNKNOWN # Current test status self.status_label: ui.Label = None # Icon label indicating the test status def destroy(self): """Destroy the test entry; mostly to avoid leaking caused by dangling callbacks""" with suppress(AttributeError): self.sub_checked = None self.checkbox = None with suppress(AttributeError): self.run_button.set_clicked_fn(None) self.run_button = None with suppress(AttributeError): self.soak_button.set_clicked_fn(None) self.soak_button = None with suppress(AttributeError): self.open_button.set_clicked_fn(None) self.open_button = None def __del__(self): """Ensure the destroy is always called - it's safe to call it multiple times""" self.destroy() # ============================================================================================================== class _Buttons(Enum): """Index for all of the buttons created in the toolbar""" RUN = auto() # Run all selected tests SELECT_ALL = auto() # Select every listed test DESELECT_ALL = auto() # Deselect every listed test PROPERTIES = auto() # Open the properties window LOAD_MENU = auto() # Open the menu for loading a test list # ============================================================================================================== class _TestUiPopulator: """Base class for the objects used to populate the initial list of tests, before filtering.""" def __init__(self, populator: TestPopulator): """Set up the populator with the important information it needs for getting tests from some location Args: name: Name of the populator, which can be used for a menu description: Verbose description of the populator, which can be used for the tooltip of the menu item doing_what: Parameter to the descriptive waiting sentence "Rebuilding after {doing_what}..." source: Source type this populator implements """ self.populator = populator self._cached_tests: list[_TestUiEntry] = [] # -------------------------------------------------------------------------------------------------------------- @property def name(self) -> str: """The name of the populator""" return self.populator.name @property def description(self) -> str: """The description of the populator""" return self.populator.description @property def tests(self) -> list[_TestUiEntry]: """The list of test UI entries gleaned from the raw test list supplied by the populator implementation""" if not self._cached_tests: _LOG.info("Translating %d unit tests into a _TestUiEntry list", len(self.populator.tests)) self._cached_tests = {} for test in self.populator.tests: try: file_path = sys.modules[test.__module__].__file__ except KeyError: # if the module is not enabled the test does not belong in the list continue entry = _TestUiEntry(test, file_path) self._cached_tests[test.id()] = entry return self._cached_tests # -------------------------------------------------------------------------------------------------------------- def clear(self): """Remove the cache so that it can be rebuilt on demand, usually if the contents might have changed""" self._cached_tests = {} # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Opportunity to clean up any allocated resources""" self._cached_tests = {} self.populator.destroy() # -------------------------------------------------------------------------------------------------------------- def get_tests(self, call_when_done: callable): """Main method for retrieving the list of tests that the populator provides. When the tests are available invoke the callback with the test list. call_when_done(_TestUiPopulator, canceled: bool) """ def __create_cache(canceled: bool = False): call_when_done(self, canceled) if not self._cached_tests: self.populator.get_tests(__create_cache) else: call_when_done(self) # ============================================================================================================== class TestRunnerWindow: """Managers the window containing the test runner Members: _buttons: Dictionary of _Buttons:ui.Button for all of the toolbar buttons _change_sub: Subscription to the extension list change event _count: Temporary variable to count number of iterations during test soak _filter_begin_edit_sub: Subscription to the start of editing the filter text field _filter_end_edit_sub: Subscription to the end of editing the filter text field _filter_hint: Label widget holding the overlay text for the filter text field _filter_regex: Expression on which to filter the list of source tests _filter: StringField widget holding the filter text _is_running_tests: Are the selected tests currently running? _load_menu: UI Widget containing the menu used for loading the test list _properties_window: The temporary dialog that displays the test running properties set by the user _refresh_task: Async task to refresh the test status values as they are completed _status_label: Text to show in the label in the toolbar that shows test counts _test_frame: UI Widget encompassing the frame containing the list of tests to run _test_list_source_rc: RadioCollection containing the test source choices _test_populators: Dictionary of name:_TestUiPopulator used to populate the full list of tests in the window _tests: Dictionary of (ID, Checkbox) corresponding to all visible tests _tests_selected: Number of tests in the dictionary currently selected. This is maintained on the fly to avoid an O(N^2) update problem when monitoring checkbox changes and updating the SelectAll buttons _toolbar_frame: UI Widget encompassing the set of tools at the top of the window _ui_status_label: UI Widget containing the label displaying test runner status _window: UI Widget of the toolbar window """ # Location of the window in the larger UI element path space WINDOW_NAME = "Test Runner" MENU_PATH = f"Window/{WINDOW_NAME}" _POPULATORS = [TestPopulateAll(), TestPopulateDisabled()] WINDOW_MANAGER = None # -------------------------------------------------------------------------------------------------------------- # API for adding and removing custom populators of the test list @classmethod def add_populator(cls, new_populator: TestPopulator): """Adds the new populator to the available list, raising ValueError if there already is one with that name""" if new_populator in cls._POPULATORS: raise ValueError(f"Tried to add the same populator twice '{new_populator.name}'") cls._POPULATORS.append(new_populator) # Updating the window allows dynamic adding and removal of populator types if cls.WINDOW_MANAGER is not None: cls.WINDOW_MANAGER._test_populators[new_populator.name] = _TestUiPopulator(new_populator) # noqa: PLW0212 cls.WINDOW_MANAGER._toolbar_frame.rebuild() # noqa: PLW0212 @classmethod def remove_populator(cls, populator_to_remove: str): """Removes the populator with the given name, raising KeyError if it does not exist""" to_remove = None for populator in cls._POPULATORS: if populator.name == populator_to_remove: to_remove = populator break if to_remove is None: raise KeyError(f"Trying to remove populator named {populator_to_remove} before adding it") # Updating the window allows dynamic adding and removal of populator types if cls.WINDOW_MANAGER is not None: del cls.WINDOW_MANAGER._test_populators[populator_to_remove] # pylint: disable=protected-access cls.WINDOW_MANAGER._toolbar_frame.rebuild() # pylint: disable=protected-access cls._POPULATORS.remove(to_remove) def __init__(self, start_open: bool): """Set up the window and open it if the setting to always open it is enabled""" TestRunnerWindow.WINDOW_MANAGER = self self._buttons: dict[_Buttons, ui.Button] = {} self._change_sub: carb.Subscription = None self._count: int = 0 self._filter_begin_edit_sub: carb.Subscription = None self._filter_end_edit_sub: carb.Subscription = None self._filter_hint: ui.Label = None self._filter_regex: str = "" self._filter: ui.StringField = None self._is_running_tests: bool = False self._load_menu: ui.Menu = None self._test_file_path: Path = None self._properties_window: TestingPropertiesWindow = None self._refresh_task: asyncio.Task = None self._test_frame: ui.ScrollingFrame = None self._status_label: str = "Checking for tests..." self._test_list_source_rc: ui.RadioCollection = None self._tests: dict[str, ui.CheckBox] = {} self._tests_selected: int = 0 self._test_populators = { populator.name: _TestUiPopulator(populator) for populator in self._POPULATORS } self._test_populator: TestPopulator = None self._toolbar_frame: ui.Frame = None self._ui_status_label: ui.Label = None _LOG.info("Initializing the main window") manager = omni.kit.app.get_app().get_extension_manager() self._change_sub = manager.get_change_event_stream().create_subscription_to_pop( self.on_extensions_changed, name="test_runner extensions change event" ) self._window = ui.Window( self.WINDOW_NAME, menu_path=self.MENU_PATH, width=1200, height=800, dockPreference=ui.DockPreference.RIGHT_TOP, visibility_changed_fn=self._visibility_changed, width_changed_fn=self._width_changed, ) with self._window.frame: with ui.VStack(): self._toolbar_frame = ui.Frame(height=_BUTTON_HEIGHT + 4) self._toolbar_frame.set_build_fn(self._build_toolbar_frame) with self._toolbar_frame: self._build_toolbar_frame() self._test_frame = ui.ScrollingFrame( vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, ) self._test_frame.set_build_fn(self._build_test_frame) # Populate the initial test list self._populate_test_entries(self._test_populators[DEFAULT_POPULATOR_NAME]) self._window.visible = start_open # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Detach all subscriptions and destroy the window elements to avoid dangling callbacks and UI elements""" _LOG.info("Destroying the main window {") self.WINDOW_MANAGER = None if self._window is not None: self._window.visible = False # Remove the callbacks first for _button_id, button in self._buttons.items(): button.set_clicked_fn(None) self._buttons = {} for populator in self._test_populators.values(): populator.destroy() self._test_populators = None # Remove the widget elements before removing the window itself self._clean_refresh_task() self._change_sub = None self._count = 0 self._filter = None self._filter_begin_edit_sub = None self._filter_end_edit_sub = None self._filter_hint = None self._filter_regex = "" self._load_menu = None self._ui_status_label = None self._status_label = None self._test_list_source_rc = None self._test_populator = None self._tests = {} self._tests_selected = 0 if self._properties_window is not None: self._properties_window.destroy() del self._properties_window self._properties_window = None if self._toolbar_frame is not None: self._toolbar_frame.set_build_fn(None) del self._toolbar_frame self._toolbar_frame = None if self._test_frame is not None: self._test_frame.set_build_fn(None) del self._test_frame self._test_frame = None if self._window is not None: self._window.set_visibility_changed_fn(None) self._window.set_width_changed_fn(None) self._window.frame.set_build_fn(None) del self._window self._window = None # -------------------------------------------------------------------------------------------------------------- @property def visible(self) -> bool: return self._window.visible if self._window is not None else False @visible.setter def visible(self, visible: bool): if self._window is not None: self._window.visible = visible elif visible: raise ValueError("Tried to change visibility after window was destroyed") def _visibility_changed(self, visible: bool): """Update the menu with the visibility state""" _LOG.info("Window visibility changed to %s", visible) editor_menu = omni.kit.ui.EditorMenu() editor_menu.set_value(self.MENU_PATH, visible) # -------------------------------------------------------------------------------------------------------------- def _width_changed(self, new_width: float): """Update the sizing of the test frame when the window size changes""" _LOG.info("Window width changed to %f", new_width) if self._test_frame is not None: self._resize_test_frame(new_width) # -------------------------------------------------------------------------------------------------------------- def on_extensions_changed(self, *_): """Callback executed when the known extensions may have changed.""" # Protect calls to _LOG since if it's this extension being disabled it may not exist if self._is_running_tests: if _LOG is not None: _LOG.info("Extension changes ignored while tests are running as it could be part of the tests") else: if _LOG is not None: _LOG.info("Extensions were changed, tests are rebuilding") for populator in self._test_populators.values(): populator.clear() self._refresh_after_tests_complete(load_tests=True, cause="extensions changed") # -------------------------------------------------------------------------------------------------------------- def _refresh_after_tests_complete(self, load_tests: bool, cause: str, new_populator: TestPopulator = None): """Refresh the window information after the tests finish running. If load_tests is True then reconstruct all of the tests from the current test source selected. If cause is not empty then place a temporary message in the test pane to indicate a rebuild is happening. If a new_populator is specified then it will replace the existing one if its population step succeeds, otherwise the original will remain. """ async def _delayed_refresh(): try: # Busy wait until the tests are done running slept = 0.0 while self._is_running_tests: _LOG.debug("....sleep(%f)", slept) slept += 0.2 await asyncio.sleep(0.2) # Refresh the test information _LOG.info("Delayed refresh triggered with load_tests=%s", load_tests) if cause: self._ui_status_label.text = f"Rebuilding after {cause}..." await omni.kit.app.get_app().next_update_async() if load_tests: _LOG.info("...repopulating the test list") self._populate_test_entries(new_populator) else: _LOG.info("...rebuilding the test frame") with self._test_frame: self._build_test_frame() except asyncio.CancelledError: pass except Exception as error: # pylint: disable=broad-except carb.log_warn(f"Failed to refresh content of window.tests. Error: '{error}' {type(error)}.") self._clean_refresh_task() self._refresh_task = asyncio.ensure_future(_delayed_refresh()) # -------------------------------------------------------------------------------------------------------------- def _update_toolbar_status(self): """Update the state of the elements in the toolbar, avoiding a full rebuild when values change""" filtered_tests = self._filtered_tests() _LOG.info("Refreshing the toolbar status for %d tests", len(filtered_tests)) any_on = self._tests_selected > 0 any_off = self._tests_selected < len(filtered_tests) _LOG.info(" RUN=%s, SELECT_ALL=%s, DESELECT_ALL=%s", any_on, any_off, any_on) self._buttons[_Buttons.RUN].enabled = any_on self._buttons[_Buttons.SELECT_ALL].enabled = any_off self._buttons[_Buttons.DESELECT_ALL].enabled = any_on _LOG.info("Reset status to '%s'", self._status_label) self._ui_status_label.text = self._status_label # -------------------------------------------------------------------------------------------------------------- def _build_toolbar_frame(self): """Emit the UI commands required to build the toolbar that appears at the top of the window""" _LOG.info("Rebuilding the toolbar frame") # Defining the toolbar callbacks at the top of this method because they are so small def on_run(*_): _LOG.info("Hit the Run button") tests = [entry.test for entry in self._tests.values() if entry.checkbox.model.as_bool] self._run_tests(tests) def on_select_all(*_): _LOG.info("Hit the Select All button") filtered_tests = self._filtered_tests() for entry in filtered_tests.values(): entry.checkbox.model.set_value(True) self._tests_selected = len(filtered_tests) self._update_toolbar_status() def on_deselect_all(*_): _LOG.info("Hit the Deselect All button") filtered_tests = self._filtered_tests() for entry in filtered_tests.values(): entry.checkbox.model.set_value(False) self._tests_selected = 0 self._update_toolbar_status() def _on_filter_begin_edit(model: ui.AbstractValueModel): self._filter_hint.visible = False def _on_filter_end_edit(model: ui.AbstractValueModel): if len(model.get_value_as_string()) == 0: self._filter_hint.visible = True self._filter_regex = "" else: self._filter_regex = f"*{model.get_value_as_string()}*" _LOG.info("Reset filter to '%s'", self._filter_regex) self._refresh_after_tests_complete(load_tests=False, cause="filter changed") def on_properties(*_): _LOG.info("Hit the Properties button") if self._properties_window is None: self._properties_window = TestingPropertiesWindow() self._properties_window.show() # + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + with ui.HStack(height=_BUTTON_HEIGHT + 4, style={"Button.Label:disabled": {"color": 0xFF606060}}): self._buttons[_Buttons.RUN] = ui.Button( "Run Selected", clicked_fn=on_run, width=ui.Percent(10), style={"border_radius": 5.0}) self._buttons[_Buttons.SELECT_ALL] = ui.Button( "Select All", clicked_fn=on_select_all, width=ui.Percent(10), style={"border_radius": 5.0}) self._buttons[_Buttons.DESELECT_ALL] = ui.Button( "Deselect All", clicked_fn=on_deselect_all, width=ui.Percent(10), style={"border_radius": 5.0}) with ui.ZStack(width=ui.Percent(20)): ui.Spacer(width=ui.Pixel(10)) # Trick required to give the string field a greyed out "hint" as to what should be typed in it self._filter = ui.StringField(height=_BUTTON_HEIGHT) self._filter_hint = ui.Label( " Filter (*, ?)", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F} ) if self._filter_regex: self._filter.model.set_value(self._filter_regex[1:-1]) self._filter_hint.visible = False self._filter_begin_edit_sub = self._filter.model.subscribe_begin_edit_fn(_on_filter_begin_edit) self._filter_end_edit_sub = self._filter.model.subscribe_value_changed_fn(_on_filter_end_edit) with ui.HStack(height=0, width=ui.Percent(20)): ui.Spacer(width=ui.Pixel(3)) def __on_flag_set(populator): _LOG.info("Invoking load menu with %s", populator) self._load_menu = None self._refresh_after_tests_complete( load_tests=True, cause=f"selecting populator '{populator.name}'", new_populator=populator ) def __show_load_menu(mouse_x: int, mouse_y: int, mouse_button: int, modifier: int): _LOG.info("Invoked load menu at %d,%d - B%d/%d", mouse_x, mouse_y, mouse_button, modifier) widget = self._buttons[_Buttons.LOAD_MENU] self._load_menu = ui.Menu() with self._load_menu: for populator_name in sorted(self._test_populators.keys()): populator = self._test_populators[populator_name] ui.MenuItem( populator.name, triggered_fn=partial(__on_flag_set, populator), checkable=True, checked=( self._test_populator is not None and (populator.name == self._test_populator.name) ), ) self._load_menu.show_at( (int)(widget.screen_position_x), (int)(widget.screen_position_y + widget.computed_content_height) ) self._buttons[_Buttons.LOAD_MENU] = ui.Button( "Load Tests From...", height=_BUTTON_HEIGHT + 4, width=0, mouse_released_fn=__show_load_menu, style={"border_radius": 5.0}, ) with ui.HStack(width=ui.Percent(10)): self._buttons[_Buttons.PROPERTIES] = ui.Button( "Properties", clicked_fn=on_properties, style={"border_radius": 5.0}, ) ui.Spacer(width=ui.Pixel(10)) with ui.HStack(height=_BUTTON_HEIGHT + 4, width=ui.Percent(15)): self._ui_status_label = ui.Label("Initializing tests...") # -------------------------------------------------------------------------------------------------------------- def _space_for_test_labels(self, full_width: float) -> float: """Returns the number of pixels available for the test labels in the test frame, for manual resizing""" label_space = full_width - 20 - 45 - 50 - 50 - 30 - 5 * 3 # Arbitrary "minimum readable" limit if label_space < 200: _LOG.info("Label space went below the threshold of 200 to %f, clipping it to 200", label_space) label_space = 200 return label_space # -------------------------------------------------------------------------------------------------------------- def _resize_test_frame(self, new_size: float): """Reset the manually computed size for all of the elements in the test frame. Avoids full rebuild.""" label_space = self._space_for_test_labels(new_size) _LOG.info("Resizing test frame with %d pixels of %d for labels", label_space, new_size) for _test_id, entry in self._tests.items(): if entry.label_stack is None: continue entry.label_stack.width = ui.Pixel(int(label_space)) # -------------------------------------------------------------------------------------------------------------- def _filtered_tests(self) -> dict[str, ui.CheckBox]: return { test_id: entry for test_id, entry in self._tests.items() if (not self._filter_regex) or fnmatch.fnmatch(test_id.lower(), self._filter_regex.lower()) } # -------------------------------------------------------------------------------------------------------------- def _build_test_frame(self): """Emit the UI commands required to populate the test frame with the list of visible tests""" _LOG.info("Rebuilding the test frame with %d tests", len(self._tests)) # Compute the space available for the test names by taking the total frame width and subtracting the size # used by the checkbox, run button, soak button, open button, and status icon, plus spacing between them label_space = self._space_for_test_labels(self._window.frame.computed_width) with ui.VStack(): ui.Spacer(height=ui.Pixel(10)) filtered_tests = self._filtered_tests() for test_id, entry in filtered_tests.items(): # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Test-specific callbacks def on_checked(check_model: ui.AbstractValueModel): filtered_tests = self._filtered_tests() if check_model.as_bool: self._tests_selected += 1 if self._tests_selected in (1, len(filtered_tests)): self._update_toolbar_status() else: self._tests_selected -= 1 if self._tests_selected in (0, len(filtered_tests) - 1): self._update_toolbar_status() def on_run_test(*_, test: unittest.TestCase = entry.test): self._run_tests([test]) def on_soak_test(*_, test: unittest.TestCase = entry.test): self._run_tests([test], repeats=1000) def on_open(*_, path: str = entry.file_path): import webbrowser webbrowser.open(path) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Test row entry.hstack = ui.HStack(spacing=2, height=0, width=ui.Percent(100)) with entry.hstack: entry.checkbox = ui.CheckBox( value=False, on_changed_fn=on_checked, style={"margin_height": 2}, width=20, ) entry.sub_checked = entry.checkbox.model.subscribe_value_changed_fn(on_checked) test_class, test_method = test_id.rsplit(".", 1) entry.label_stack = ui.HStack(width=label_space) with entry.label_stack: entry.label1 = ui.Label( test_class, tooltip=entry.file_path, elided_text=True, alignment=ui.Alignment.LEFT_TOP, width=ui.Fraction(2), ) entry.label2 = ui.Label( test_method, tooltip=test_method, elided_text=True, alignment=ui.Alignment.LEFT_TOP, width=ui.Fraction(1), ) entry.run_button = ui.Button("Run", clicked_fn=on_run_test, width=45) entry.soak_button = ui.Button("Soak", clicked_fn=on_soak_test, width=50) entry.open_button = ui.Button("Open", clicked_fn=on_open, width=50) entry.status_label = ui.Label("", width=30) entry.status = TestRunStatus.UNKNOWN self._refresh_test_status(test_id) tests_available = len(self._tests) tests_used = len(filtered_tests) if self._test_populator is not None: self._status_label = f"Showing {tests_used} of {tests_available} test(s) from {self._test_populator.name}" else: self._status_label = f"Showing {tests_used} of {tests_available} test(s) with no populator" self._update_toolbar_status() # -------------------------------------------------------------------------------------------------------------- def _refresh_test_status(self, test_id: str): _LOG.debug("Refresh status of test %s to %s", test_id, self._tests[test_id].status) status = self._tests[test_id].status status_to_svg = { TestRunStatus.UNKNOWN: "${glyphs}/question.svg", TestRunStatus.RUNNING: "${glyphs}/spinner.svg", TestRunStatus.FAILED: "${glyphs}/exclamation.svg", TestRunStatus.PASSED: "${glyphs}/check_solid.svg", } status_to_color = { TestRunStatus.UNKNOWN: 0xFFFFFFFF, TestRunStatus.RUNNING: 0xFFFF7D7D, TestRunStatus.PASSED: 0xFF00FF00, TestRunStatus.FAILED: 0xFF0000FF, } code = ui.get_custom_glyph_code(status_to_svg.get(status, "")) label = self._tests[test_id].status_label label.text = f"{code}" label.set_style({"color": status_to_color[status]}) # -------------------------------------------------------------------------------------------------------------- def _set_test_status(self, test_id: str, status: TestRunStatus): _LOG.info("Setting status of test '%s' to %s", test_id, status) try: self._tests[test_id].status = status self._refresh_test_status(test_id) except KeyError: _LOG.warning("...could not find test %s in the list", test_id) # -------------------------------------------------------------------------------------------------------------- def _set_is_running(self, running: bool): _LOG.info("Change running state to %s", running) self._is_running_tests = running self._buttons[_Buttons.RUN].enabled = not running if running: self._ui_status_label.text = "Running Tests..." else: self._ui_status_label.text = "" # ------------------------------------------------------------------------------------------------------------- def _populate_test_entries(self, new_populator: TestPopulator = None): """Repopulate the test entry information based on the current filtered source test list. If a new_populator is specified then set the current one to it if the population succeeded, otherwise retain the original. """ async def __populate(): _LOG.info("Retrieving the tests from the populator") def __repopulate(populator: _TestUiPopulator, canceled: bool = False): if canceled: _LOG.info("...test retrieval was canceled") self._test_frame.enabled = True else: self._tests_selected = 0 self._tests = populator.tests if new_populator is not None: self._test_populator = new_populator _LOG.info("...triggering the test frame rebuild after repopulation") self._test_frame.enabled = True self._test_frame.rebuild() self._test_frame.enabled = False if new_populator is not None: new_populator.get_tests(__repopulate) elif self._test_populator is not None: self._test_populator.get_tests(__repopulate) asyncio.ensure_future(__populate()) # -------------------------------------------------------------------------------------------------------------- def _run_tests(self, tests, repeats=0, ignore_running=False): """Find all of the selected tests and execute them all asynchronously""" _LOG.info("Running the tests with a repeat of %d", repeats) if self._is_running_tests and not ignore_running: _LOG.info("...skipping, already running the tests") return def on_finish(runner): if self._count > 0: self._count -= 1 print(f"\n\n\n\n{'-'*40} Iteration {self._count} {'-'*40}\n\n") self._run_tests(tests, self._count, ignore_running=True) return self._set_is_running(False) def on_status_report(test_id, status, **_): self._set_test_status(test_id, status) self._count = repeats self._set_is_running(True) for t in tests: self._set_test_status(t.id(), TestRunStatus.UNKNOWN) omni.kit.test.run_tests(tests, on_finish, on_status_report) # -------------------------------------------------------------------------------------------------------------- def _clean_refresh_task(self): """Clean up the refresh task, canceling it if it is in progress first""" with suppress(asyncio.CancelledError, AttributeError): self._refresh_task.cancel() self._refresh_task = None
39,484
Python
48.854798
119
0.54731
omniverse-code/kit/exts/omni.kit.window.tests/omni/kit/window/tests.py
"""Implementation of the extension containing the Test Runner window.""" import logging import sys import carb import omni.ext from omni.kit.ui import EditorMenu # Cannot do relative imports here due to the way the omni.kit.window import space is duplicated in multiple extensions from omni.kit.window._test_runner_window import _LOG from omni.kit.window._test_runner_window import TestRunnerWindow # ============================================================================================================== class Extension(omni.ext.IExt): """The extension manager that handles the life span of the test runner window""" def __init__(self): self._test_runner_window = None self._menu_item = None super().__init__() def _show_window(self, menu: str, value: bool): if self._test_runner_window is None: self._test_runner_window = TestRunnerWindow(value) else: self._test_runner_window.visible = value def on_startup(self): _LOG.disabled = True # Set to False to dump out debugging information for the extension if not _LOG.disabled: _handler = logging.StreamHandler(sys.stdout) _handler.setFormatter(logging.Formatter("TestRunner: %(levelname)s: %(message)s")) _LOG.addHandler(_handler) _LOG.setLevel(logging.INFO) _LOG.info("Starting up the test runner extension") open_window = carb.settings.get_settings().get("/exts/omni.kit.window.tests/openWindow") self._menu_item = EditorMenu.add_item(TestRunnerWindow.MENU_PATH, self._show_window, toggle=True, value=open_window) if open_window: self._show_window(TestRunnerWindow.MENU_PATH, True) def on_shutdown(self): """Cleanup the constructed elements""" _LOG.info("Shutting down the test runner extension") if self._test_runner_window is not None: _LOG.info("Destroying the test runner window") self._test_runner_window.visible = False self._test_runner_window.destroy() self._test_runner_window = None EditorMenu.remove_item(TestRunnerWindow.MENU_PATH) handler_list = _LOG.handlers for handler in handler_list: _LOG.removeHandler(handler) self._menu_item = None
2,333
Python
41.436363
124
0.63009
omniverse-code/kit/exts/omni.kit.window.tests/omni/kit/window/properties.py
import carb import carb.settings import omni.kit.app import omni.ui as ui HUMAN_DELAY_SETTING = "/exts/omni.kit.ui_test/humanDelay" class TestingPropertiesWindow: def __init__(self): self._window = ui.Window("Testing Properties", width=400, height=200, flags=ui.WINDOW_FLAGS_NO_DOCKING) self._window.visible = False def destroy(self): self._window = None def show(self): if not self._window.visible: self._window.visible = True self.refresh() def refresh(self): with self._window.frame: with ui.VStack(height=0): settings = carb.settings.get_settings() ui.Spacer(height=10) ui.Label("Test Settings:", style={"color": 0xFFB7F222, "font_size": 16}) ui.Spacer(height=5) for key in ["/exts/omni.kit.test/includeTests", "/exts/omni.kit.test/excludeTests"]: value = settings.get(key) ui.Label(f"{key}: {value}") ui.Spacer(height=5) # Setting specific to UI tests manager = omni.kit.app.get_app().get_extension_manager() if manager.is_extension_enabled("omni.kit.ui_test"): ui.Spacer(height=10) ui.Label("UI Test (omni.kit.ui_test) Settings:", style={"color": 0xFFB7F222, "font_size": 16}) ui.Spacer(height=5) with ui.HStack(height=0): ui.Label("UI Test Delay (s)") delay_widget = ui.FloatDrag(min=0, max=1000000) delay_widget.model.set_value(settings.get_as_float(HUMAN_DELAY_SETTING)) delay_widget.model.add_value_changed_fn( lambda m: settings.set(HUMAN_DELAY_SETTING, m.get_value_as_float()) )
1,912
Python
35.094339
114
0.538703
omniverse-code/kit/exts/omni.kit.window.tests/docs/CHANGELOG.md
# CHANGELOG ## [0.1.0] - 2020-10-29 - Ported old version to extensions 2.0
78
Markdown
10.285713
38
0.641026
omniverse-code/kit/exts/omni.kit.window.tests/docs/index.rst
omni.kit.window.tests ########################### .. toctree:: :maxdepth: 1 CHANGELOG
96
reStructuredText
8.699999
27
0.447917
omniverse-code/kit/exts/omni.kit.exec.core/omni/kit/exec/core/unstable/__init__.py
"""Python Module Initialization for omni.kit.exec.core""" from ._omni_kit_exec_core_unstable import * from .scripts.extension import _PublicExtension
151
Python
29.399994
57
0.781457
omniverse-code/kit/exts/omni.kit.exec.core/omni/kit/exec/core/unstable/_omni_kit_exec_core_unstable.pyi
from __future__ import annotations import omni.kit.exec.core.unstable._omni_kit_exec_core_unstable import typing __all__ = [ "dump_graph_topology" ] def dump_graph_topology(fileName: str) -> None: """ Write the default execution controller's corresponding execution graph topology out as a GraphViz file. """
328
unknown
22.499998
107
0.713415
omniverse-code/kit/exts/omni.kit.exec.core/omni/kit/exec/core/unstable/scripts/extension.py
"""Support required by the Carbonite extension loader""" import omni.ext class _PublicExtension(omni.ext.IExt): """Object that tracks the lifetime of the Python part of the extension loading""" def on_startup(self): """Set up initial conditions for the Python part of the extension""" def on_shutdown(self): """Shutting down this part of the extension prepares it for hot reload"""
414
Python
30.923075
85
0.705314
omniverse-code/kit/exts/omni.kit.widget.prompt/PACKAGE-LICENSES/omni.kit.widget.prompt-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.widget.prompt/config/extension.toml
[package] title = "Prompt dialog for omni.ui widgets" category = "Internal" description = "Prompt dialog for use with omni.ui widgets" version = "1.0.5" authors = ["NVIDIA"] repository = "" keywords = ["widget"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.ui" = {} [[python.module]] name = "omni.kit.widget.prompt" [[test]] args = [ "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.commands", "omni.kit.selection", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.ui_test" ] stdoutFailPatterns.include = [] stdoutFailPatterns.exclude = []
757
TOML
20.055555
58
0.667107
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/extension.py
import omni.ext from .prompt import PromptManager class PromptExtension(omni.ext.IExt): def on_startup(self): PromptManager.on_startup() def on_shutdown(self): PromptManager.on_shutdown()
225
Python
16.384614
37
0.671111
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/__init__.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. # from .prompt import Prompt, PromptManager, PromptButtonInfo from .extension import PromptExtension
527
Python
46.999996
76
0.817837
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/prompt.py
from typing import Callable, List import carb import carb.input import omni import uuid class PromptButtonInfo: def __init__(self, name: str, on_button_clicked_fn: Callable[[], None] = None): self._name = name self._on_button_clicked_fn = on_button_clicked_fn @property def name(self): return self._name @property def on_button_clicked_fn(self): return self._on_button_clicked_fn class PromptManager: _prompts = set([]) @staticmethod def on_startup(): pass @staticmethod def on_shutdown(): all_prompts = PromptManager._prompts PromptManager._prompts = set([]) for prompt in all_prompts: prompt.destroy() @staticmethod def query_prompt_by_title(title: str): for prompt in PromptManager._prompts: if prompt._title == title: return prompt return None @staticmethod def add_prompt(prompt): if prompt not in PromptManager._prompts: PromptManager._prompts.add(prompt) @staticmethod def remove_prompt(prompt): if prompt in PromptManager._prompts: PromptManager._prompts.remove(prompt) @staticmethod def post_simple_prompt( title: str, message: str, ok_button_info: PromptButtonInfo = PromptButtonInfo("OK", None), cancel_button_info: PromptButtonInfo = None, middle_button_info: PromptButtonInfo = None, middle_2_button_info: PromptButtonInfo = None, on_window_closed_fn: Callable[[], None] = None, modal=True, shortcut_keys=True, standalone=True, no_title_bar=False, width=None, height=None, callback_addons: List = [], ): """When standalone is true, it will hide all other managed prompts in this manager.""" def unwrap_button_info(button_info: PromptButtonInfo): if button_info: return button_info.name, button_info.on_button_clicked_fn else: return None, None ok_button_text, ok_button_fn = unwrap_button_info(ok_button_info) cancel_button_text, cancel_button_fn = unwrap_button_info(cancel_button_info) middle_button_text, middle_button_fn = unwrap_button_info(middle_button_info) middle_2_button_text, middle_2_button_fn = unwrap_button_info(middle_2_button_info) if standalone: prompts = PromptManager._prompts PromptManager._prompts = set([]) for prompt in prompts: prompt.destroy() prompt = Prompt( title, message, ok_button_text=ok_button_text, cancel_button_text=cancel_button_text, middle_button_text=middle_button_text, middle_2_button_text=middle_2_button_text, ok_button_fn=ok_button_fn, cancel_button_fn=cancel_button_fn, middle_button_fn=middle_button_fn, middle_2_button_fn=middle_2_button_fn, modal=modal, on_closed_fn=on_window_closed_fn, shortcut_keys=shortcut_keys, no_title_bar=no_title_bar, width=width, height=height, callback_addons=callback_addons ) prompt.show() return prompt class Prompt: """Pop up a prompt window that asks the user a simple question with up to four buttons for answers. Callbacks are executed for each button press, as well as when the window is closed manually. """ def __init__( self, title, text, ok_button_text="OK", cancel_button_text=None, middle_button_text=None, middle_2_button_text=None, ok_button_fn=None, cancel_button_fn=None, middle_button_fn=None, middle_2_button_fn=None, modal=False, on_closed_fn=None, shortcut_keys=True, no_title_bar=False, width=None, height=None, callback_addons: List = [] ): """Initialize the callbacks and window information Args: title: Text appearing in the titlebar of the window text: Text of the question being posed to the user ok_button_text: Text for the first button cancel_button_text: Text for the last button middle_button_text: Text for the middle button middle_button_2_text: Text for the second middle button ok_button_fn: Function executed when the first button is pressed cancel_button_fn: Function executed when the last button is pressed middle_button_fn: Function executed when the middle button is pressed middle_2_button_fn: Function executed when the second middle button is pressed modal: True if the window is modal, shutting down other UI until an answer is received on_closed_fn: Function executed when the window is closed without hitting a button shortcut_keys: If it can be confirmed or hidden with shortcut keys like Enter or ESC. no_title_bar: If it needs to show title bar. width: The specified width. By default, it will use the computed width. height: The specified height. By default, it will use the computed height. callback_addons: Addon widgets which is appended in the prompt window. By default, it is empty """ self._title = title self._text = text self._cancel_button_text = cancel_button_text self._cancel_button_fn = cancel_button_fn self._ok_button_fn = ok_button_fn self._ok_button_text = ok_button_text self._middle_button_text = middle_button_text self._middle_button_fn = middle_button_fn self._middle_2_button_text = middle_2_button_text self._middle_2_button_fn = middle_2_button_fn self._modal = modal self._on_closed_fn = on_closed_fn self._button_clicked = False self._shortcut_keys = shortcut_keys self._no_title_bar = no_title_bar self._width = width self._height = height self._callback_addons = callback_addons self._key_functions = { int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn, int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn } self._buttons = [] self._build_ui() def __del__(self): self.destroy() def destroy(self): for button in self._buttons: button.set_clicked_fn(None) self._buttons.clear() self.hide() if self._window: self._window.set_visibility_changed_fn(None) self._window = None def __enter__(self): """Called on entering a 'with' loop""" self.show() return self def __exit__(self, type, value, trace): """Called on exiting a 'with' loop""" self.hide() @property def visible(self): return self.is_visible() @visible.setter def visible(self, value): if value: self.show() else: self.hide() def show(self): """Make the prompt window visible""" if not self._window: self._build_ui() self._window.visible = True self._button_clicked = False PromptManager.add_prompt(self) def hide(self): """Make the prompt window invisible""" if self._window: self._window.visible = False PromptManager.remove_prompt(self) def is_visible(self): """Returns True if the prompt is currently visible""" return self._window and self._window.visible def set_text(self, text): """Set a new question label""" self._text_label.text = text def set_confirm_fn(self, on_ok_button_clicked): """Define a new callback for when the first (okay) button is clicked""" self._ok_button_fn = on_ok_button_clicked def set_cancel_fn(self, on_cancel_button_clicked): """Define a new callback for when the third (cancel) button is clicked""" self._cancel_button_fn = on_cancel_button_clicked def set_middle_button_fn(self, on_middle_button_clicked): """Define a new callback for when the second (middle) button is clicked""" self._middle_button_fn = on_middle_button_clicked def set_middle_2_button_fn(self, on_middle_2_button_clicked): self._middle_2_button_fn = on_middle_2_button_clicked def set_on_closed_fn(self, on_on_closed): """Define a new callback for when the window is closed without pressing a button""" self._on_closed_fn = on_on_closed def _on_visibility_changed(self, new_visibility: bool): """Callback executed when visibility of the window closes""" if not new_visibility: if not self._button_clicked and self._on_closed_fn is not None: self._on_closed_fn() self.hide() def _on_ok_button_fn(self): """Callback executed when the first (okay) button is pressed""" self._button_clicked = True self.hide() if self._ok_button_fn: self._ok_button_fn() def _on_cancel_button_fn(self): """Callback executed when the third (cancel) button is pressed""" self._button_clicked = True self.hide() if self._cancel_button_fn: self._cancel_button_fn() def _on_middle_button_fn(self): """Callback executed when the second (middle) button is pressed""" self._button_clicked = True self.hide() if self._middle_button_fn: self._middle_button_fn() def _on_closed_fn(self): """Callback executed when the window is closed without pressing a button""" self._button_clicked = True self.hide() if self._on_closed_fn: self._on_closed_fn() def _on_middle_2_button_fn(self): self._button_clicked = True self.hide() if self._middle_2_button_fn: self._middle_2_button_fn() def _on_key_pressed_fn(self, key, mod, pressed): if not pressed or not self._shortcut_keys: return func = self._key_functions.get(key) if func: func() def _build_ui(self): """Construct the window based on the current parameters""" num_buttons = 0 if self._ok_button_text: num_buttons += 1 if self._cancel_button_text: num_buttons += 1 if self._middle_button_text: num_buttons += 1 if self._middle_2_button_text: num_buttons += 1 button_width = 120 spacer_width = 60 if self._width: window_width = self._width else: window_width = button_width * num_buttons + spacer_width * 2 if window_width < 400: window_width = 400 if self._height: window_height = self._height else: window_height = 0 if self._title: window_id = self._title else: # Generates unique id for this window to make sure all prompts are unique. window_id = f"##{str(uuid.uuid1())}" self._window = omni.ui.Window( window_id, visible=False, height=window_height, width=window_width, dockPreference=omni.ui.DockPreference.DISABLED, visibility_changed_fn=self._on_visibility_changed, ) self._window.flags = ( omni.ui.WINDOW_FLAGS_NO_COLLAPSE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_RESIZE | omni.ui.WINDOW_FLAGS_NO_MOVE ) self._window.set_key_pressed_fn(self._on_key_pressed_fn) if self._no_title_bar: self._window.flags = self._window.flags | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR if self._modal: self._window.flags = self._window.flags | omni.ui.WINDOW_FLAGS_MODAL num_buttons = 0 if self._ok_button_text: num_buttons += 1 if self._cancel_button_text: num_buttons += 1 if self._middle_button_text: num_buttons += 1 if self._middle_2_button_text: num_buttons += 1 button_width = 120 with self._window.frame: with omni.ui.VStack(height=0): omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(width=40) self._text_label = omni.ui.Label( self._text, word_wrap=True, width=self._window.width - 80, height=0, name="prompt_text" ) omni.ui.Spacer(width=40) omni.ui.Spacer(width=0, height=10) with omni.ui.HStack(height=0): omni.ui.Spacer(height=0) if self._ok_button_text: ok_button = omni.ui.Button(self._ok_button_text, name="confirm_button", width=button_width, height=0) ok_button.set_clicked_fn(self._on_ok_button_fn) self._buttons.append(ok_button) if self._middle_button_text: middle_button = omni.ui.Button(self._middle_button_text, name="middle_button", width=button_width, height=0) middle_button.set_clicked_fn(self._on_middle_button_fn) self._buttons.append(middle_button) if self._middle_2_button_text: middle_2_button = omni.ui.Button(self._middle_2_button_text, name="middle_2_button", width=button_width, height=0) middle_2_button.set_clicked_fn(self._on_middle_2_button_fn) self._buttons.append(middle_2_button) if self._cancel_button_text: cancel_button = omni.ui.Button(self._cancel_button_text, name="cancel_button", width=button_width, height=0) cancel_button.set_clicked_fn(self._on_cancel_button_fn) self._buttons.append(cancel_button) omni.ui.Spacer(height=0) omni.ui.Spacer(width=0, height=10) for callback in self._callback_addons: if callback and callable(callback): callback()
14,437
Python
35.004987
138
0.584748
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/tests/__init__.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. # from .test_prompt import TestPrompt
463
Python
50.55555
76
0.812095
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/tests/test_prompt.py
import omni.kit.test import omni.kit.ui_test as ui_test from functools import partial from omni.kit.widget.prompt import Prompt, PromptManager, PromptButtonInfo class TestPrompt(omni.kit.test.AsyncTestCase): async def setUp(self): PromptManager.on_shutdown() async def _wait(self, frames=5): for i in range(frames): await omni.kit.app.get_app().next_update_async() async def test_show_prompt_and_button_clicks(self): value = "" def f(text): nonlocal value value = text button_names = ["left", "right", "middle", "middle_2"] prompt = Prompt( "title", "information text", *button_names, ok_button_fn=partial(f, button_names[0]), cancel_button_fn=partial(f, button_names[1]), middle_button_fn=partial(f, button_names[2]), middle_2_button_fn=partial(f, button_names[3]) ) for button_name in button_names: prompt.show() self.assertTrue(prompt.visible) await ui_test.find("title").focus() label = ui_test.find("title//Frame/**/Label[*].text=='information text'") self.assertTrue(label) button = ui_test.find(f"title//Frame/**/Button[*].text=='{button_name}'") self.assertTrue(button) await button.click() self.assertEqual(value, button_name) self.assertFalse(prompt.visible) self.assertFalse(prompt.is_visible()) prompt.destroy() async def test_set_buttons_fn(self): value = "" def f(text): nonlocal value value = text button_names = ["left", "right", "middle", "middle_2"] prompt = Prompt("title", "test", *button_names) prompt.set_confirm_fn(partial(f, button_names[0])) prompt.set_cancel_fn(partial(f, button_names[1])) prompt.set_middle_button_fn(partial(f, button_names[2])) prompt.set_middle_2_button_fn(partial(f, button_names[3])) prompt.set_on_closed_fn(partial(f, "closed")) for button_name in button_names: prompt.show() self.assertTrue(prompt.visible) await ui_test.find("title").focus() label = ui_test.find("title//Frame/**/Label[*].text=='test'") self.assertTrue(label) button = ui_test.find(f"title//Frame/**/Button[*].text=='{button_name}'") self.assertTrue(button) await button.click() self.assertEqual(value, button_name) self.assertFalse(prompt.visible) self.assertFalse(prompt.is_visible()) prompt.show() prompt.hide() self.assertEqual(value, "closed") prompt.destroy() async def test_hide_prompt(self): value = "" def f(text): nonlocal value value = text prompt = Prompt("title", "hide dialog", on_closed_fn=partial(f, "closed")) prompt.show() self.assertTrue(prompt.visible) prompt.hide() self.assertEqual(value, "closed") self.assertFalse(prompt.visible) prompt.show() self.assertTrue(prompt.visible) prompt.visible = False self.assertFalse(prompt.visible) async def test_set_text(self): prompt = Prompt("test", "test") prompt.show() prompt.set_text("set text") await ui_test.find("test").focus() label = ui_test.find("test//Frame/**/Label[*].text=='set text'") self.assertTrue(label) async def test_prompt_manager(self): value = "" def f(text): nonlocal value value = text n = ["1left", "1right", "1middle", "1middle_2"] prompt = PromptManager.post_simple_prompt( "title", "test", ok_button_info=PromptButtonInfo(n[0], partial(f, n[0])), cancel_button_info=PromptButtonInfo(n[1], partial(f, n[1])), middle_button_info=PromptButtonInfo(n[2], partial(f, n[2])), middle_2_button_info=PromptButtonInfo(n[3], partial(f, n[3])), on_window_closed_fn=partial(f, "closed") ) for button_name in n: prompt.show() self.assertTrue(prompt.visible) await ui_test.find("title").focus() label = ui_test.find("title//Frame/**/Label[*].text=='test'") self.assertTrue(label) button = ui_test.find(f"title//Frame/**/Button[*].text=='{button_name}'") self.assertTrue(button) await button.click() self.assertEqual(value, button_name) self.assertFalse(prompt.visible) self.assertFalse(prompt.is_visible()) prompt.show() prompt.hide() self.assertEqual(value, "closed") prompt.destroy()
4,873
Python
34.838235
104
0.567823
omniverse-code/kit/exts/omni.kit.widget.prompt/docs/CHANGELOG.md
# Changelog Omniverse Kit Prompt Dialog ## [1.0.5] - 2023-01-19 ### Fixed - Generates unique id when title is not provided for prompt. ## [1.0.4] - 2022-12-07 ### Fixed - Missing import (OM-75466). ## [1.0.3] - 2022-11-21 ### Changed - Adjust button size. ## [1.0.2] - 2022-06-15 ### Changed - Add prompt manager to simplify prompt notifications. ## [1.0.1] - 2022-03-01 ### Changed - Add unittests. ## [1.0.0] - 2021-02-24 ### Added - Prompt Dialog
457
Markdown
15.357142
60
0.630197
omniverse-code/kit/exts/omni.kit.viewport.utility/PACKAGE-LICENSES/omni.kit.viewport.utility-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.viewport.utility/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.14" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Viewport Utility" description="Utility functions to access [active] Viewport information" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "viewport", "utility"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.rst" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" category = "Viewport" [dependencies] "omni.kit.viewport.window" = { optional = true } # Viewport-Next "omni.kit.window.viewport" = { optional = true } # Viewport-Legacy "omni.ui" = { optional = true } # Required for Viewport-Legacy adapter # Main python module this extension provides, it will be publicly available as "import omni.kit.viewport.registry". [[python.module]] name = "omni.kit.viewport.utility" [settings] # exts."omni.kit.viewport.registry".xxx = "" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/pxr/rendermode=HdStormRendererPlugin", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/window/hideUi=true", "--/app/renderer/resolution/width=500", "--/app/renderer/resolution/height=500", "--/app/window/width=500", "--/app/window/height=500", "--/app/viewport/forceHideFps=true", "--no-window" ] dependencies = [ "omni.ui", "omni.kit.mainwindow", "omni.kit.test_helpers_gfx", "omni.kit.ui_test", "omni.kit.manipulator.selection", "omni.hydra.pxr", "omni.kit.window.viewport", "omni.kit.context_menu" ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop ] [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
2,499
TOML
30.25
115
0.697079
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/__init__.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__ = [ 'frame_viewport_prims', 'frame_viewport_selection', 'get_viewport_from_window_name', 'get_active_viewport', 'get_active_viewport_window' 'get_active_viewport_and_window', 'get_viewport_window_camera_path', 'get_viewport_window_camera_string', 'get_active_viewport_camera_path', 'get_active_viewport_camera_string', 'get_num_viewports', 'capture_viewport_to_file', 'capture_viewport_to_buffer', 'post_viewport_message', 'toggle_global_visibility', 'create_drop_helper', 'disable_selection', 'get_ground_plane_info' ] import asyncio import carb from pxr import Gf, Sdf from typing import Callable, List, Optional, Tuple _g_is_viewport_next = None def _is_viewport_next(self): global _g_is_viewport_next if _g_is_viewport_next is None: vp_window_name = carb.settings.get_settings().get('/exts/omni.kit.viewport.window/startup/windowName') _g_is_viewport_next = vp_window_name and (vp_window_name == 'Viewport') return _g_is_viewport_next def _get_default_viewport_window_name(window_name: str = None): if window_name: return window_name return carb.settings.get_settings().get('/exts/omni.kit.viewport.window/startup/windowName') or 'Viewport' def get_viewport_from_window_name(window_name: str = None): '''Return the first Viewport that is held inside a specific Window name.''' window_name = _get_default_viewport_window_name(window_name) try: from omni.kit.viewport.window import get_viewport_window_instances # Get every ViewportWindow, regardless of UsdContext it is attached to for window in get_viewport_window_instances(None): if window.title == window_name: return window.viewport_api except ImportError: pass try: import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() viewport_handle = vp_iface.get_instance(window_name) if viewport_handle: vp_window = vp_iface.get_viewport_window(viewport_handle) if vp_window: from .legacy_viewport_api import LegacyViewportAPI return LegacyViewportAPI(vp_iface.get_viewport_window_name(viewport_handle)) except ImportError: pass return None def get_active_viewport_and_window(usd_context_name: str = '', wrap_legacy: bool = True, window_name: str = None): '''Return the active Viewport for a given UsdContext and the name of the Window it is inside of.''' default_window_name = _get_default_viewport_window_name(window_name) try: from omni.kit.viewport.window import get_viewport_window_instances, ViewportWindow # If no windowname provided, see if the ViewportWindow already knows what is active if window_name is None: active_window = ViewportWindow.active_window if active_window: # Have an active Window, need to make sure UsdContext name matches (or passed None to avoid the match) viewport_api = active_window.viewport_api if (usd_context_name is None) or (usd_context_name == viewport_api.usd_context_name): return (viewport_api, active_window) active_window = None # Get all ViewportWindows attached the UsdContext with this name for window in get_viewport_window_instances(usd_context_name): # If matching by name, check that first ignoring whether focused or not (multiple Windows cannot have same name) window_title = window.title if window_name and window_name != window_title: continue # If this Window is focused, then return it if window.focused: active_window = window break # Save the first encountered Window as he fallback 'default' Window if window_title == default_window_name: active_window = window elif active_window is None: active_window = window if active_window: return (active_window.viewport_api, active_window) except ImportError: pass try: import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() instance_list = vp_iface.get_instance_list() if instance_list: first_context_match = None for viewport_handle in vp_iface.get_instance_list(): vp_window = vp_iface.get_viewport_window(viewport_handle) if not vp_window: continue # If matching by name, check that first ignoring whether focused or not (multiple Windows cannot have same name) window_title = vp_iface.get_viewport_window_name(viewport_handle) if window_name and window_name != vp_iface.get_viewport_window_name(viewport_handle): continue # Filter by UsdContext name, where None means any UsdContext if (usd_context_name is not None) and (usd_context_name != vp_window.get_usd_context_name()): continue if vp_window.is_focused(): first_context_match = viewport_handle break elif window_title == default_window_name: first_context_match = viewport_handle elif first_context_match is None: first_context_match = viewport_handle # If there was a match on UsdContext name (but not focused), return the first one if first_context_match is not None: vp_window = vp_iface.get_viewport_window(first_context_match) if vp_window: from .legacy_viewport_api import LegacyViewportAPI window_name = vp_iface.get_viewport_window_name(first_context_match) viewport_api = LegacyViewportAPI(vp_iface.get_viewport_window_name(first_context_match)) if wrap_legacy: from .legacy_viewport_window import LegacyViewportWindow vp_window = LegacyViewportWindow(window_name, viewport_api) return (viewport_api, vp_window) except ImportError: pass return (None, None) def get_active_viewport_window(window_name: str = None, wrap_legacy: bool = True, usd_context_name: str = ''): '''Return the active Viewport for a given UsdContext.''' return get_active_viewport_and_window(usd_context_name, wrap_legacy, window_name)[1] def get_active_viewport(usd_context_name: str = ''): '''Return the active Viewport for a given UsdContext.''' return get_active_viewport_and_window(usd_context_name, False)[0] def get_viewport_window_camera_path(window_name: str = None) -> Sdf.Path: '''Return a Sdf.Path to the camera used by the active Viewport in a named Window.''' viewport_api = get_viewport_from_window_name(window_name) return viewport_api.camera_path if viewport_api else None def get_viewport_window_camera_string(window_name: str = None) -> str: '''Return a string path to the camera used by the active Viewport in a named Window.''' viewport_api = get_viewport_from_window_name(window_name) return viewport_api.camera_path.pathString if viewport_api else None def get_active_viewport_camera_path(usd_context_name: str = '') -> Sdf.Path: '''Return a Sdf.Path to the camera used by the active Viewport for a specific UsdContext.''' viewport_api = get_active_viewport(usd_context_name) return viewport_api.camera_path if viewport_api else None def get_active_viewport_camera_string(usd_context_name: str = '') -> str: '''Return a string path to the camera used by the active Viewport for a specific UsdContext.''' viewport_api = get_active_viewport(usd_context_name) return viewport_api.camera_path.pathString if viewport_api else None def get_available_aovs_for_viewport(viewport_api): if hasattr(viewport_api, 'legacy_window'): viewport_handle = viewport_api.frame_info.get('viewport_handle') asyncio.ensure_future(viewport_api.usd_context.next_frame_async(viewport_handle)) return viewport_api.legacy_window.get_aov_list() carb.log_error('Available AOVs not implemented') return [] def add_aov_to_viewport(viewport_api, aov_name: str): if hasattr(viewport_api, 'legacy_window'): return viewport_api.legacy_window.add_aov(aov_name) from pxr import Usd, UsdRender from omni.usd import editor stage = viewport_api.stage render_product_path = viewport_api.render_product_path with Usd.EditContext(stage, stage.GetSessionLayer()): render_prod_prim = stage.GetPrimAtPath(render_product_path) if not render_prod_prim: raise RuntimeError(f'Invalid renderProduct "{render_product_path}"') render_var_prim_path = Sdf.Path(f'/Render/Vars/{aov_name}') render_var_prim = stage.GetPrimAtPath(render_var_prim_path) if not render_var_prim: render_var_prim = stage.DefinePrim(render_var_prim_path) if not render_var_prim: raise RuntimeError(f'Cannot create renderVar "{render_var_prim_path}"') render_var_prim.CreateAttribute("sourceName", Sdf.ValueTypeNames.String).Set(aov_name) render_prod_var_rel = render_prod_prim.GetRelationship('orderedVars') if not render_prod_var_rel: render_prod_prim.CreateRelationship('orderedVars') if not render_prod_var_rel: raise RuntimeError(f'cannot set orderedVars relationship for renderProduct "{render_product_path}"') render_prod_var_rel.AddTarget(render_var_prim_path) editor.set_hide_in_stage_window(render_var_prim, True) editor.set_no_delete(render_var_prim, True) return True def post_viewport_message(viewport_api_or_window, message: str, message_id: str = None): if hasattr(viewport_api_or_window, 'legacy_window'): viewport_api_or_window.legacy_window.post_toast(message) return if hasattr(viewport_api_or_window, '_post_toast_message'): viewport_api_or_window._post_toast_message(message, message_id) return try: from omni.kit.viewport.window import get_viewport_window_instances for window in get_viewport_window_instances(viewport_api_or_window.usd_context_name): if window.viewport_api.id == viewport_api_or_window.id: window._post_toast_message(message, message_id) return except (ImportError, AttributeError): pass class _CaptureHelper: def __init__(self, legacy_window, is_hdr: bool, file_path: str = None, render_product_path: str = None, on_capture_fn: Callable = None, format_desc: dict = None): import omni.renderer_capture self.__future = asyncio.Future() self.__renderer = omni.renderer_capture.acquire_renderer_capture_interface() if render_product_path: self.__future.set_result(True) self.__renderer.capture_next_frame_using_render_product(viewport_handle=legacy_window.get_id(), filepath=file_path, render_product=render_product_path) return self.__is_hdr = is_hdr self.__legacy_window = legacy_window self.__file_path = file_path self.__on_capture_fn = on_capture_fn self.__format_desc = format_desc event_stream = legacy_window.get_ui_draw_event_stream() self.__capture_sub = event_stream.create_subscription_to_pop(self.capture_function, name='omni.kit.viewport.utility.capture_viewport') def capture_function(self, *args): self.__capture_sub = None legacy_window, self.__legacy_window = self.__legacy_window, None renderer, self.__renderer = self.__renderer, None if self.__is_hdr: viewport_rp_resource = legacy_window.get_drawable_hdr_resource() else: viewport_rp_resource = legacy_window.get_drawable_ldr_resource() if self.__on_capture_fn: def _interecept_capture(*args, **kwargs): try: self.__on_capture_fn(*args, **kwargs) finally: if not self.__future.done(): self.__future.set_result(True) renderer.capture_next_frame_rp_resource_callback(_interecept_capture, resource=viewport_rp_resource) elif self.__file_path: if not self.__future.done(): self.__future.set_result(True) if self.__format_desc: if hasattr(renderer, 'capture_next_frame_rp_resource_to_file'): renderer.capture_next_frame_rp_resource_to_file(filepath=self.__file_path, resource=viewport_rp_resource, format_desc=self.__format_desc) return carb.log_error('Format description provided to capture, but not honored') renderer.capture_next_frame_rp_resource(filepath=self.__file_path, resource=viewport_rp_resource) async def wait_for_result(self, completion_frames: int = 2): await self.__future import omni.kit.app app = omni.kit.app.get_app() while completion_frames: await app.next_update_async() completion_frames = completion_frames - 1 return self.__future.result() def capture_viewport_to_buffer(viewport_api, on_capture_fn: Callable, is_hdr: bool = False): '''Capture the provided viewport and send it to a callback.''' if hasattr(viewport_api, 'legacy_window'): return _CaptureHelper(viewport_api.legacy_window, is_hdr=is_hdr, on_capture_fn=on_capture_fn) from omni.kit.widget.viewport.capture import ByteCapture return viewport_api.schedule_capture(ByteCapture(on_capture_fn, aov_name='HdrColor' if is_hdr else 'LdrColor')) def capture_viewport_to_file(viewport_api, file_path: str = None, is_hdr: bool = False, render_product_path: str = None, format_desc: dict = None): '''Capture the provided viewport to a file.''' file_path = str(file_path) if hasattr(viewport_api, 'legacy_window'): return _CaptureHelper(viewport_api.legacy_window, is_hdr=is_hdr, file_path=file_path, render_product_path=render_product_path, format_desc=format_desc) from omni.kit.widget.viewport.capture import MultiAOVFileCapture class HdrCaptureHelper(MultiAOVFileCapture): def __init__(self, file_path: str, is_hdr: bool, format_desc: dict = None): super().__init__(['HdrColor' if is_hdr else 'LdrColor'], [file_path]) # Setup RenderProduct for Hdr def __del__(self): # Setdown RenderProduct for Hdr pass def capture_aov(self, file_path, aov): if render_product_path: self.save_product_to_file(file_path, render_product_path) else: self.save_aov_to_file(file_path, aov, format_desc=format_desc) return viewport_api.schedule_capture(HdrCaptureHelper(file_path, is_hdr)) def get_num_viewports(usd_context_name: str = None): num_viewports = 0 try: from omni.kit.viewport.window import get_viewport_window_instances num_viewports += sum(1 for _ in get_viewport_window_instances(usd_context_name)) except ImportError: pass try: import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() for viewport_handle in vp_iface.get_instance_list(): if usd_context_name and (usd_context_name != vp_iface.get_viewport_window(viewport_handle).get_usd_context_name()): continue num_viewports += 1 except ImportError: pass return num_viewports def create_viewport_window(name: str = None, usd_context_name: str = '', width: int = 1280, height: int = 720, position_x: int = 0, position_y: int = 0, camera_path: Sdf.Path = None, **kwargs): window = None try: from omni.kit.viewport.window import get_viewport_window_instances, ViewportWindow if name is None: name = f"Viewport {get_num_viewports()}" window = ViewportWindow(name, usd_context_name, width=width, height=height, **kwargs) return window except ImportError: pass if window is None: try: import omni.kit.viewport_legacy as vp_legacy from .legacy_viewport_window import LegacyViewportWindow vp_iface = vp_legacy.get_viewport_interface() vp_handle = vp_iface.create_instance() assigned_name = vp_iface.get_viewport_window_name(vp_handle) if name and (name != assigned_name): carb.log_warn('omni.kit.viewport_legacy does not support explicit Window names, using assigned name "{assigned_name}"') window = LegacyViewportWindow(assigned_name, **kwargs) window.width = width window.height = height except ImportError: pass if window: window.setPosition(position_x, position_y) if camera_path: window.viewport_api.camera_path = camera_path return window class ViewportPrimReferencePoint: BOUND_BOX_CENTER = 0 BOUND_BOX_LEFT = 1 BOUND_BOX_RIGHT = 2 BOUND_BOX_TOP = 3 BOUND_BOX_BOTTOM = 4 def get_ui_position_for_prim(viewport_window, prim_path: str, alignment: ViewportPrimReferencePoint = ViewportPrimReferencePoint.BOUND_BOX_CENTER, force_legacy_api: bool = False): if isinstance(viewport_window, str): window_name = str(viewport_window) viewport_window = get_active_viewport_window(window_name=window_name) if viewport_window is None: carb.log_error('No ViewportWindow found with name "{window_name}"') return (0, 0), False # XXX: omni.ui constants needed import omni.ui dpi = omni.ui.Workspace.get_dpi_scale() if dpi <= 0.0: dpi = 1 # XXX: kit default dock splitter size (4) dock_splitter_size = 4 * dpi tab_bar_height = 0 if viewport_window.dock_tab_bar_visible or not (viewport_window.flags & omni.ui.WINDOW_FLAGS_NO_TITLE_BAR): tab_bar_height = 22 * dpi # Force legacy Viewport code path if requested if force_legacy_api and hasattr(viewport_window, 'legacy_window'): import omni.ui import omni.kit.viewport_legacy as vp_legacy legacy_window = viewport_window.legacy_window alignment = { ViewportPrimReferencePoint.BOUND_BOX_LEFT: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_LEFT, ViewportPrimReferencePoint.BOUND_BOX_RIGHT: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_RIGHT, ViewportPrimReferencePoint.BOUND_BOX_TOP: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_TOP, ViewportPrimReferencePoint.BOUND_BOX_BOTTOM: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_BOTTOM, }.get(alignment, vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_CENTER) success, x, y, z = legacy_window.get_prim_clipping_pos(str(prim_path), alignment) if not success: return (0, 0), False # Changing xy to match the window coord system. x = (x + 1.0) / 2.0 # x to [0, 1] y = 1 - (y + 1.0) / 2.0 # y to [0, 1] and reverse its direction. min_x, min_y, max_x, max_y = legacy_window.get_viewport_rect() prim_window_pos_x = (max_x - min_x) * x + min_x - dock_splitter_size prim_window_pos_y = (max_y - min_y) * y + min_y - tab_bar_height - dock_splitter_size else: from pxr import UsdGeom, Gf viewport_api = viewport_window.viewport_api usd_context = viewport_window.viewport_api.usd_context stage = usd_context.get_stage() usd_prim = stage.GetPrimAtPath(prim_path) if stage else False if usd_prim: xformable_prim = UsdGeom.Xformable(usd_prim) else: xformable_prim = None if (not stage) or (not xformable_prim): return (0, 0), False # Get bounding box from prim aabb_min, aabb_max = usd_context.compute_path_world_bounding_box(str(prim_path)) gf_range = Gf.Range3d(Gf.Vec3d(aabb_min[0], aabb_min[1], aabb_min[2]), Gf.Vec3d(aabb_max[0], aabb_max[1], aabb_max[2])) if gf_range.IsEmpty(): # May be empty (UsdGeom.Xform for example), so build a scene-scaled constant box world_units = UsdGeom.GetStageMetersPerUnit(stage) if Gf.IsClose(world_units, 0.0, 1e-6): world_units = 0.01 # XXX: compute_path_world_transform is identity in this case if False: world_xform = Gf.Matrix4d(*usd_context.compute_path_world_transform(str(prim_path))) else: import omni.timeline time = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond() world_xform = xformable_prim.ComputeLocalToWorldTransform(time) ref_position = world_xform.ExtractTranslation() extent = Gf.Vec3d(0.2 / world_units) # 20cm by default gf_range.SetMin(ref_position - extent) gf_range.SetMax(ref_position + extent) # Computes the extent in clipping pos mvp = viewport_api.world_to_ndc min_x, min_y, min_z = 2.0, 2.0, 2.0 max_x, max_y, max_z = -2.0, -2.0, -2.0 for i in range(8): corner = gf_range.GetCorner(i) pos = mvp.Transform(corner) min_x = min(min_x, pos[0]) min_y = min(min_y, pos[1]) min_z = min(min_z, pos[2]) max_x = max(max_x, pos[0]) max_y = max(max_y, pos[1]) max_z = max(max_z, pos[2]) min_point = Gf.Vec3d(min_x, min_y, min_z) max_point = Gf.Vec3d(max_x, max_y, max_z) mid_point = (min_point + max_point) / 2 # Map to reference point in screen space if alignment == ViewportPrimReferencePoint.BOUND_BOX_LEFT: ndc_pos = mid_point - Gf.Vec3d((max_x - min_x) / 2, 0, 0) elif alignment == ViewportPrimReferencePoint.BOUND_BOX_RIGHT: ndc_pos = mid_point + Gf.Vec3d((max_x - min_x) / 2, 0, 0) elif alignment == ViewportPrimReferencePoint.BOUND_BOX_TOP: ndc_pos = mid_point + Gf.Vec3d(0, (max_y - min_y) / 2, 0) elif alignment == ViewportPrimReferencePoint.BOUND_BOX_BOTTOM: ndc_pos = mid_point - Gf.Vec3d(0, (max_y - min_y) / 2, 0) else: ndc_pos = mid_point # Make sure its not clipped if (ndc_pos[2] < 0) or (ndc_pos[0] < -1) or (ndc_pos[0] > 1) or (ndc_pos[1] < -1) or (ndc_pos[1] > 1): return (0, 0), False ''' XXX: Simpler world calculation world_pos = gf_range.GetMidpoint() dir_sel = (0, 1) up_axis = UsdGeom.GetStageUpAxis(stage) if up_axis == UsdGeom.Tokens.z: dir_sel = (0, 2) if up_axis == UsdGeom.Tokens.x: dir_sel = (2, 1) if alignment == ViewportPrimReferencePoint.BOUND_BOX_LEFT: world_pos[dir_sel[0]] = gf_range.GetMin()[dir_sel[0]] elif alignment == ViewportPrimReferencePoint.BOUND_BOX_RIGHT: world_pos[dir_sel[0]] = gf_range.GetMax()[dir_sel[0]] elif alignment == ViewportPrimReferencePoint.BOUND_BOX_TOP: world_pos[dir_sel[1]] = gf_range.GetMax()[dir_sel[1]] elif alignment == ViewportPrimReferencePoint.BOUND_BOX_BOTTOM: world_pos[dir_sel[1]] = gf_range.GetMin()[dir_sel[1]] ndc_pos = viewport_api.world_to_ndc.Transform(world_pos) ''' x = (ndc_pos[0] + 1.0) / 2.0 # x to [0, 1] y = 1 - (ndc_pos[1] + 1.0) / 2.0 # y to [0, 1] and reverse its direction. frame = viewport_window.frame prim_window_pos_x = dpi * (frame.screen_position_x + x * frame.computed_width) - dock_splitter_size prim_window_pos_y = dpi * (frame.screen_position_y + y * frame.computed_height) - tab_bar_height - dock_splitter_size return (prim_window_pos_x, prim_window_pos_y), True def frame_viewport_prims(viewport_api=None, prims: List[str] = None): if not prims: return False return __frame_viewport_objects(viewport_api, prims=prims, force_legacy_api=False) def frame_viewport_selection(viewport_api=None, force_legacy_api: bool = False): return __frame_viewport_objects(viewport_api, prims=None, force_legacy_api=force_legacy_api) def __frame_viewport_objects(viewport_api=None, prims: Optional[List[str]] = None, force_legacy_api: bool = False): if not viewport_api: viewport_api = get_active_viewport() if not viewport_api: return False if force_legacy_api and hasattr(viewport_api, "legacy_window"): viewport_api.legacy_window.focus_on_selected() return # This is new CODE if prims is None: # Get current selection prims = viewport_api.usd_context.get_selection().get_selected_prim_paths() # Pass None to underlying command to signal "frame all" if selection is empty prims = prims if prims else None stage = viewport_api.stage cam_path = viewport_api.camera_path if not stage or not cam_path: return False cam_prim = stage.GetPrimAtPath(cam_path) if not cam_prim: return False import omni.kit.undo import omni.kit.commands from pxr import UsdGeom look_through = None # Loop over all targets (should really be only one) and see if we can get a valid UsdGeom.Imageable for target in cam_prim.GetRelationship('omni:kit:viewport:lookThrough:target').GetForwardedTargets(): target_prim = stage.GetPrimAtPath(target) if not target_prim: continue if UsdGeom.Imageable(target_prim): look_through = target_prim break try: omni.kit.undo.begin_group() resolution = viewport_api.resolution omni.kit.commands.execute( 'FramePrimsCommand', prim_to_move=cam_path if not look_through else look_through.GetPath(), prims_to_frame=prims, time_code=viewport_api.time, usd_context_name=viewport_api.usd_context_name, aspect_ratio=resolution[0] / resolution[1] ) finally: omni.kit.undo.end_group() return True def toggle_global_visibility(force_legacy_api: bool = False): # Forward to omni.kit.viewport.actions and propogate an errors so caller should update code carb.log_warn("omni.kit.viewport.utility.toggle_global_visibility is deprecated, use omni.kit.viewport.actions.toggle_global_visibility") import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() action_registry.get_action("omni.kit.viewport.actions", "toggle_global_visibility").execute() async def next_viewport_frame_async(viewport, n_frames: int = 0): """ Waits until frames have been delivered to the Viewport. Args: viewport: the Viewport to wait for a frame on. n_frames: the number of rendered frames to wait for. """ import omni.kit.app app = omni.kit.app.get_app() # Make sure at least one frame has been delivered viewport_handle = viewport.frame_info.get('viewport_handle') while viewport_handle is None: await app.next_update_async() viewport_handle = viewport.frame_info.get('viewport_handle') # Now wait for any additional frames usd_context = viewport.usd_context while n_frames: await usd_context.next_frame_async(viewport_handle) n_frames = n_frames - 1 def create_drop_helper(*args, **kwargs): try: from omni.kit.viewport.window.dragdrop.legacy import create_drop_helper return create_drop_helper(*args, **kwargs) except (ImportError, ModuleNotFoundError): try: import omni.kit.viewport_legacy as vp_legacy return vp_legacy.get_viewport_interface().create_drop_helper(*args, **kwargs) except (ImportError, ModuleNotFoundError): pass class _DisableViewportWindowLayer: def __init__(self, viewport_or_window, layers_and_categories): self.__layers = [] # Find the omni.ui.Window for this Viewport to disable selection manipulator viewport_window = None from omni.kit.viewport.window import ViewportWindow, get_viewport_window_instances if not isinstance(viewport_or_window, ViewportWindow): viewport_id = viewport_or_window.id for window_instance in get_viewport_window_instances(viewport_or_window.usd_context_name): viewport_window_viewport = window_instance.viewport_api if viewport_window_viewport.id == viewport_id: viewport_window = window_instance break else: viewport_window = viewport_or_window if viewport_window: for layer, category in layers_and_categories: found_layer = viewport_window._find_viewport_layer(layer, category) if found_layer: self.__layers.append((found_layer, found_layer.visible)) found_layer.visible = False def __del__(self): for layer, visible in self.__layers: layer.visible = visible self.__layers = tuple() def disable_selection(viewport_or_window, disable_click: bool = True): '''Disable selection rect and possible the single click selection on a Viewport or ViewportWindow. Returns an object that resets selection when it goes out of scope.''' # First check if the Viewport is a legacy Viewport from .legacy_viewport_window import LegacyViewportWindow legacy_window = None if hasattr(viewport_or_window, 'legacy_window'): legacy_window = viewport_or_window.legacy_window elif isinstance(viewport_or_window, LegacyViewportWindow): legacy_window = viewport_or_window.legacy_window if legacy_window: class LegacySelectionState: def __init__(self, viewport_window, disable_click): self.__viewport_window = viewport_window self.__restore_picking = viewport_window.is_enabled_picking() if disable_click: self.__viewport_window.set_enabled_picking(False) self.__viewport_window.disable_selection_rect(True) def __del__(self): self.__viewport_window.set_enabled_picking(self.__restore_picking) return LegacySelectionState(legacy_window, disable_click) disable_items = [('Selection', 'manipulator')] if disable_click: disable_items.append(('ObjectClick', 'manipulator')) return _DisableViewportWindowLayer(viewport_or_window, disable_items) def disable_context_menu(viewport_or_window=None): '''Disable context menu on a Viewport or ViewportWindow. Returns an object that resets context menu visibility when it goes out of scope.''' if viewport_or_window: # Check if the Viewport is a legacy Viewport, s can only operate on all Viewportwindows in that case from .legacy_viewport_window import LegacyViewportWindow if hasattr(viewport_or_window, 'legacy_window') or isinstance(viewport_or_window, LegacyViewportWindow): carb.log_warn("Cannot disable context menu on an individual Viewport, disabling it for all") viewport_or_window = None if viewport_or_window is None: class _DisableAllContextMenus: def __init__(self): # When setting is initially unset, then context menu is enabled self.__settings = carb.settings.get_settings() enabled = self.__settings.get('/exts/omni.kit.window.viewport/showContextMenu') self.__settings.set('/exts/omni.kit.window.viewport/showContextMenu', False) self.__restore = enabled if (enabled is not None) else True def __del__(self): self.__settings.set('/exts/omni.kit.window.viewport/showContextMenu', self.__restore) return _DisableAllContextMenus() return _DisableViewportWindowLayer(viewport_or_window, [('ContextMenu', 'manipulator')]) def get_ground_plane_info(viewport, ortho_special: bool = True) -> Tuple[Gf.Vec3d, List[str]]: """For a given Viewport returns a tuple representing the ground plane. @param viewport: ViewportAPI to use for ground plane info @param ortho_special: bool Use an alternate ground plane for orthographic cameras that are looking down a single axis @return: A tuple of type (normal: Gf.Vec3d, planes: List[str]), where planes is a list of axis' occupied (x, y, z) """ stage = viewport.stage cam_path = viewport.camera_path from pxr import UsdGeom up_axis = UsdGeom.GetStageUpAxis(stage) if stage else UsdGeom.Tokens.y if up_axis == UsdGeom.Tokens.y: normal = Gf.Vec3d.YAxis() planes = ['x', 'z'] elif up_axis == UsdGeom.Tokens.z: normal = Gf.Vec3d.ZAxis() planes = ['x', 'y'] else: normal = Gf.Vec3d.XAxis() planes = ['y', 'z'] if ortho_special: cam_prim = stage.GetPrimAtPath(cam_path) if stage else None if cam_prim: usd_camera = UsdGeom.Camera(cam_prim) if usd_camera and usd_camera.GetProjectionAttr().Get(viewport.time) == UsdGeom.Tokens.orthographic: orthoEpsilon = 0.0001 viewNormal = viewport.transform.TransformDir(Gf.Vec3d(0, 0, -1)) if Gf.IsClose(abs(viewNormal[1]), 1.0, orthoEpsilon): normal = Gf.Vec3d.YAxis() planes = ['x', 'z'] elif Gf.IsClose(abs(viewNormal[2]), 1.0, orthoEpsilon): normal = Gf.Vec3d.ZAxis() planes = ['x', 'y'] elif Gf.IsClose(abs(viewNormal[0]), 1.0, orthoEpsilon): normal = Gf.Vec3d.XAxis() planes = ['y', 'z'] return normal, planes
34,909
Python
42.528678
193
0.63783
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/legacy_viewport_window.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['LegacyViewportWindow'] import omni.ui import carb import weakref # Wrap a legacy viewport Window in an object that poses as a new omni.kit.viewport.window.ViewportWindow (omni.ui.Window) class class LegacyViewportWindow(omni.ui.Window): def __init__(self, window_name: str, viewport_api = None, **kwargs): kwargs.update({ 'window_flags': omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE }) super().__init__(window_name, **kwargs) self.__z_stack = None with self.frame: self.__z_stack = omni.ui.ZStack() self.__window_name = window_name if not viewport_api: from .legacy_viewport_api import LegacyViewportAPI viewport_api = LegacyViewportAPI(window_name) self.__viewport_api = viewport_api self.__added_frames = {} @property def name(self): return self.__window_name @property def viewport_api(self): return weakref.proxy(self.__viewport_api) def get_frame(self, name: str): frame = self.__added_frames.get(name) if frame is None: with self.__z_stack: frame = omni.ui.Frame(horizontal_clipping=True) self.__added_frames[name] = frame return frame @property def legacy_window(self): return self.__get_legacy_window() @property def width(self): return super().width @property def height(self): return super().height @width.setter def width(self, width: float): width = int(width) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_size(width, int(self.height)) super(LegacyViewportWindow, self.__class__).width.fset(self, width) @height.setter def height(self, height: float): height = int(height) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_size(int(self.width), height) super(LegacyViewportWindow, self.__class__).height.fset(self, height) @property def position_x(self): pos_x = super().position_x # Workaround omni.ui reporting massive position_y unless laid out ? return pos_x if pos_x != 340282346638528859811704183484516925440 else 0 @property def position_y(self): pos_y = super().position_y # Workaround omni.ui reporting massive position_y unless laid out ? return pos_y if pos_y != 340282346638528859811704183484516925440 else 0 @position_x.setter def position_x(self, position_x: float): position_x = int(position_x) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_pos(position_x, int(self.position_y)) super(LegacyViewportWindow, self.__class__).position_x.fset(self, position_x) @position_y.setter def position_y(self, position_y: float): position_y = int(position_y) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_pos(int(self.position_x), position_y) super(LegacyViewportWindow, self.__class__).position_y.fset(self, position_y) def setPosition(self, x: float, y: float): return self.set_position(x, y) def set_position(self, x: float, y: float): x, y = int(x), int(y) legacy_window = self.legacy_window if legacy_window: legacy_window.set_window_pos(x, y) super().setPosition(x, y) @property def visible(self): legacy_window = self.legacy_window if legacy_window: return legacy_window.is_visible() return super().visible @visible.setter def visible(self, visible: bool): visible = bool(visible) legacy_window = self.legacy_window if legacy_window: legacy_window.set_visible(visible) super(LegacyViewportWindow, self.__class__).visible.fset(self, visible) def __del__(self): self.destroy() def destroy(self): self.__viewport_api = None if self.__z_stack: self.__z_stack.clear() self.__z_stack.destroy() self.__z_stack = None if self.__added_frames: for name, frame in self.__added_frames.items(): try: frame.destroy() except Exception: import traceback carb.log_error(f"Error destroying {self.__window_name}. Traceback:\n{traceback.format_exc()}") self.__added_frames = None super().destroy() def _post_toast_message(self, message: str, message_id: str = None): legacy_window = self.legacy_window if legacy_window: return legacy_window.post_toast(message) def __get_legacy_window(self): import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() viewport_handle = vp_iface.get_instance(self.__window_name) return vp_iface.get_viewport_window(viewport_handle)
5,623
Python
33.716049
130
0.624755
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/camera_state.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__ = ['ViewportCameraState'] from pxr import Gf, Sdf, Usd, UsdGeom class ViewportCameraState: def __init__(self, camera_path: str = None, viewport = None, time: Usd.TimeCode = None, force_legacy_api: bool = False): if viewport is None: from omni.kit.viewport.utility import get_active_viewport viewport = get_active_viewport() if viewport is None: raise RuntimeError('No default or provided Viewport') self.__viewport_api = viewport self.__camera_path = str(camera_path if camera_path else viewport.camera_path) self.__time = Usd.TimeCode.Default() if time is None else time self.__legacy_window = viewport.legacy_window if (force_legacy_api and hasattr(viewport, 'legacy_window')) else None def get_world_camera_up(self, stage) -> Gf.Vec3d: up_axis = UsdGeom.GetStageUpAxis(stage) if stage else UsdGeom.Tokens.y if up_axis == UsdGeom.Tokens.y: return Gf.Vec3d(0, 1, 0) if up_axis == UsdGeom.Tokens.z: return Gf.Vec3d(0, 0, 1) if up_axis == UsdGeom.Tokens.x: return Gf.Vec3d(1, 0, 0) return Gf.Vec3d(0, 1, 0) @property def usd_camera(self) -> Usd.Prim: camera_prim = self.__viewport_api.stage.GetPrimAtPath(self.__camera_path) usd_camera = UsdGeom.Camera(camera_prim) if camera_prim else None if usd_camera: return usd_camera raise RuntimeError(f'"{self.__camera_path}" is not a valid Usd.Prim or UsdGeom.Camera') @property def position_world(self): if self.__legacy_window: success, x, y, z = self.__legacy_window.get_camera_position(self.__camera_path) if success: return Gf.Vec3d(x, y, z) return self.usd_camera.ComputeLocalToWorldTransform(self.__time).Transform(Gf.Vec3d(0, 0, 0)) @property def target_world(self): if self.__legacy_window: success, x, y, z = self.__legacy_window.get_camera_target(self.__camera_path) if success: return Gf.Vec3d(x, y, z) local_coi = self.usd_camera.GetPrim().GetAttribute('omni:kit:centerOfInterest').Get(self.__time) return self.usd_camera.ComputeLocalToWorldTransform(self.__time).Transform(local_coi) def set_position_world(self, world_position: Gf.Vec3d, rotate: bool): if self.__legacy_window: self.__legacy_window.set_camera_position(self.__camera_path, world_position[0], world_position[1], world_position[2], rotate) return usd_camera = self.usd_camera world_xform = usd_camera.ComputeLocalToWorldTransform(self.__time) parent_xform = usd_camera.ComputeParentToWorldTransform(self.__time) iparent_xform = parent_xform.GetInverse() initial_local_xform = world_xform * iparent_xform pos_in_parent = iparent_xform.Transform(world_position) if rotate: cam_prim = usd_camera.GetPrim() coi_attr = cam_prim.GetAttribute('omni:kit:centerOfInterest') prev_local_coi = coi_attr.Get(self.__time) coi_in_parent = iparent_xform.Transform(world_xform.Transform(prev_local_coi)) cam_up = self.get_world_camera_up(cam_prim.GetStage()) new_local_transform = Gf.Matrix4d(1).SetLookAt(pos_in_parent, coi_in_parent, cam_up).GetInverse() else: coi_attr, prev_local_coi = None, None new_local_transform = Gf.Matrix4d(initial_local_xform) new_local_transform = new_local_transform.SetTranslateOnly(pos_in_parent) import omni.kit.commands omni.kit.commands.create( 'TransformPrimCommand', path=self.__camera_path, new_transform_matrix=new_local_transform, old_transform_matrix=initial_local_xform, time_code=self.__time, usd_context_name=self.__viewport_api.usd_context_name ).do() if coi_attr and prev_local_coi: prev_world_coi = world_xform.Transform(prev_local_coi) new_local_coi = (new_local_transform * parent_xform).GetInverse().Transform(prev_world_coi) omni.kit.commands.create( 'ChangePropertyCommand', prop_path=coi_attr.GetPath(), value=new_local_coi, prev=prev_local_coi, timecode=self.__time, usd_context_name=self.__viewport_api.usd_context_name, type_to_create_if_not_exist=Sdf.ValueTypeNames.Vector3d ).do() def set_target_world(self, world_target: Gf.Vec3d, rotate: bool): if self.__legacy_window: self.__legacy_window.set_camera_target(self.__camera_path, world_target[0], world_target[1], world_target[2], rotate) return usd_camera = self.usd_camera world_xform = usd_camera.ComputeLocalToWorldTransform(self.__time) parent_xform = usd_camera.ComputeParentToWorldTransform(self.__time) iparent_xform = parent_xform.GetInverse() initial_local_xform = world_xform * iparent_xform cam_prim = usd_camera.GetPrim() coi_attr = cam_prim.GetAttribute('omni:kit:centerOfInterest') prev_local_coi = coi_attr.Get(self.__time) pos_in_parent = iparent_xform.Transform(initial_local_xform.Transform(Gf.Vec3d(0, 0, 0))) if rotate: # Rotate camera to look at new target, leaving it where it is cam_up = self.get_world_camera_up(cam_prim.GetStage()) coi_in_parent = iparent_xform.Transform(world_target) new_local_transform = Gf.Matrix4d(1).SetLookAt(pos_in_parent, coi_in_parent, cam_up).GetInverse() new_local_coi = (new_local_transform * parent_xform).GetInverse().Transform(world_target) else: # Camera keeps orientation and distance relative to target # Calculate movement of center-of-interest in parent's space target_move = iparent_xform.Transform(world_target) - iparent_xform.Transform(world_xform.Transform(prev_local_coi)) # Copy the camera's local transform new_local_transform = Gf.Matrix4d(initial_local_xform) # And move it by the delta new_local_transform.SetTranslateOnly(pos_in_parent + target_move) import omni.kit.commands if rotate: omni.kit.commands.create( 'ChangePropertyCommand', prop_path=coi_attr.GetPath(), value=new_local_coi, prev=prev_local_coi, timecode=self.__time, usd_context_name=self.__viewport_api.usd_context_name, type_to_create_if_not_exist=Sdf.ValueTypeNames.Vector3d ).do() omni.kit.commands.create( 'TransformPrimCommand', path=self.__camera_path, new_transform_matrix=new_local_transform, old_transform_matrix=initial_local_xform, time_code=self.__time, usd_context_name=self.__viewport_api.usd_context_name ).do()
7,593
Python
45.588957
137
0.629
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/legacy_viewport_api.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['LegacyViewportAPI'] import carb import omni.ui import omni.usd import omni.timeline import omni.kit.app from pxr import Gf, Sdf, Usd, UsdGeom, CameraUtil from typing import Callable, List, Tuple, Sequence # Wrap a legacy viewport Window in an object that poses as a new ViewportAPI class LegacyViewportAPI: def __init__(self, window_name: str): self.__window_name = window_name self.__settings = carb.settings.get_settings() # All legacy Viewports are locked to timeline time self.__timeline = None self.__saved_resolution = None self.__fill_frame = None @property def camera_path(self) -> Sdf.Path: '''Return an Sdf.Path to the active rendering camera''' path_str = self.legacy_window.get_active_camera() return Sdf.Path(path_str) if path_str else Sdf.Path() @camera_path.setter def camera_path(self, camera_path: Sdf.Path): '''Set the active rendering camera from an Sdf.Path''' self.legacy_window.set_active_camera(str(camera_path)) @property def render_product_path(self) -> str: '''Return a string to the UsdRender.Product used by the Viewport''' return self.legacy_window.get_render_product_path() @render_product_path.setter def render_product_path(self, product_path: str): '''Set the UsdRender.Product used by the Viewport with a string''' self.legacy_window.set_render_product_path(str(product_path)) @property def resolution(self) -> Tuple[float]: '''Return a tuple of (resolution_x, resolution_y) this Viewport is rendering at.''' # Legacy Viewport applies scale internally, so returned value accounts for scale factor. return self.legacy_window.get_texture_resolution() @resolution.setter def resolution(self, value: Tuple[float]): '''Set the resolution to render with (resolution_x, resolution_y).''' # Legacy Viewport applies scale internally based on single carb setting, so just use that self.legacy_window.set_texture_resolution(value[0], value[1]) @property def resolution_scale(self) -> float: '''Get the scaling factor for the Viewport's render resolution.''' # Legacy Viewport applies scale internally based on single carb setting, so just use that or fallback to 1 return self.__settings.get("/app/renderer/resolution/multiplier") or 1.0 @resolution_scale.setter def resolution_scale(self, value: float): '''Set the scaling factor for the Viewport's render resolution.''' value = float(value) if value <= 0: raise ValueError("Viewport resolution scale must be greater than 0.") self.__settings.set("/app/renderer/resolution/multiplier", value) @property def full_resolution(self) -> Tuple[float]: '''Return a tuple of the full (full_resolution_x, full_resolution_y) this Viewport is rendering at, not accounting for scale.''' # Legacy Viewport applies scale internally, so undo any scaling factor resolution = self.resolution resolution_scale = self.resolution_scale return (resolution[0] / resolution_scale, resolution[1] / resolution_scale) # Legacy methods that we also support def get_active_camera(self) -> Sdf.Path: '''Return an Sdf.Path to the active rendering camera''' return self.camera_path def set_active_camera(self, camera_path: Sdf.Path): '''Set the active rendering camera from an Sdf.Path''' self.camera_path = camera_path def get_render_product_path(self) -> str: '''Return a string to the UsdRender.Product used by the Viewport''' return self.render_product_path def set_render_product_path(self, product_path: str): '''Set the UsdRender.Product used by the Viewport with a string''' self.render_product_path = product_path def get_texture_resolution(self) -> Tuple[float]: '''Return a tuple of (resolution_x, resolution_y)''' return self.resolution def set_texture_resolution(self, value: Tuple[float]): '''Set the resolution to render with (resolution_x, resolution_y)''' self.resolution = value def get_texture_resolution_scale(self) -> float: '''Get the scaling factor for the Viewport's render resolution.''' return self.resolution_scale def set_texture_resolution_scale(self, value: float): '''Set the scaling factor for the Viewport's render resolution.''' self.resolution_scale = value def get_full_texture_resolution(self) -> Tuple[float]: '''Return a tuple of (full_resolution_x, full_resolution_y)''' return self.full_resolution @property def fill_frame(self) -> bool: if self.__fill_frame is None: settings = carb.settings.get_settings() width, height = settings.get('/app/renderer/resolution/width') or 0, settings.get('/app/renderer/resolution/height') or 0 self.__fill_frame = (width <= 0) or (height <= 0) return self.__fill_frame @fill_frame.setter def fill_frame(self, value: bool): settings = carb.settings.get_settings() legacy_window = self.legacy_window self.__fill_frame = bool(value) if self.__fill_frame: self.__saved_resolution = legacy_window.get_texture_resolution() legacy_window.set_texture_resolution(-1, -1) settings.set('/app/renderer/resolution/width', -1) settings.set('/app/renderer/resolution/height', -1) else: if self.__saved_resolution is None: width, height = settings.get('/app/renderer/resolution/width') or 0, settings.get('/app/renderer/resolution/height') or 0 self.__saved_resolution = (width, height) if (width > 0 and height > 0) else (1280, 720) legacy_window.set_texture_resolution(self.__saved_resolution[0], self.__saved_resolution[1]) @property def fps(self) -> float: '''Return the frames-per-second this Viewport is running at''' return self.legacy_window.get_fps() @property def id(self): '''Return a hashable value for the Viewport''' return self.legacy_window.get_id() @property def frame_info(self): return { 'viewport_handle' : self.legacy_window.get_id() } @property def usd_context_name(self) -> str: '''Return the name of the omni.usd.UsdContext this Viewport is attached to''' return self.legacy_window.get_usd_context_name() @property def usd_context(self): '''Return the omni.usd.UsdContext this Viewport is attached to''' return omni.usd.get_context(self.usd_context_name) @property def stage(self): '''Return the Usd.Stage of the omni.usd.UsdContext this Viewport is attached to''' return self.usd_context.get_stage() @property def projection(self): '''Return the projection of the UsdCamera in terms of the ui element it sits in.''' # Check if there are cached values from the ScenView subscriptions legacy_subs = _LegacySceneView.get(self.__window_name) if legacy_subs: projection = legacy_subs.projection if projection: return projection # Get the info from USD stage = self.stage cam_prim = stage.GetPrimAtPath(self.camera_path) if stage else None if cam_prim: usd_camera = UsdGeom.Camera(cam_prim) if usd_camera: image_aspect, canvas_aspect = self._aspect_ratios return self._conform_projection(self._conform_policy(), usd_camera, image_aspect, canvas_aspect) return Gf.Matrix4d(1) @property def transform(self) -> Gf.Matrix4d: '''Return the world-space transform of the UsdGeom.Camera being used to render''' # Check if there are cached values from the ScenView subscriptions legacy_subs = _LegacySceneView.get(self.__window_name) if legacy_subs: view = legacy_subs.view if view: return view.GetInverse() # Get the info from USD stage = self.stage cam_prim = stage.GetPrimAtPath(self.camera_path) if stage else None if cam_prim: imageable = UsdGeom.Imageable(cam_prim) if imageable: return imageable.ComputeLocalToWorldTransform(self.time) return Gf.Matrix4d(1) @property def view(self) -> Gf.Matrix4d: '''Return the inverse of the world-space transform of the UsdGeom.Camera being used to render''' # Check if there are cached values from the ScenView subscriptions legacy_subs = _LegacySceneView.get(self.__window_name) if legacy_subs: view = legacy_subs.view if view: return view # Get the info from USD return self.transform.GetInverse() @property def world_to_ndc(self): return self.view * self.projection @property def ndc_to_world(self): return self.world_to_ndc.GetInverse() @property def time(self) -> Usd.TimeCode: '''Return the Usd.TimeCode this Viewport is using''' if self.__timeline is None: self.__timeline = omni.timeline.get_timeline_interface() time = self.__timeline.get_current_time() return Usd.TimeCode(omni.usd.get_frame_time_code(time, self.stage.GetTimeCodesPerSecond())) def map_ndc_to_texture(self, mouse: Sequence[float]): image_aspect, canvas_aspect = self._aspect_ratios if image_aspect < canvas_aspect: ratios = (image_aspect / canvas_aspect, 1) else: ratios = (1, canvas_aspect / image_aspect) # Move into viewport's NDC-space: [-1, 1] bound by viewport mouse = (mouse[0] / ratios[0], mouse[1] / ratios[1]) # Move from NDC space to texture-space [-1, 1] to [0, 1] def check_bounds(coord): return coord >= -1 and coord <= 1 return tuple((x + 1.0) * 0.5 for x in mouse), self if (check_bounds(mouse[0]) and check_bounds(mouse[1])) else None def map_ndc_to_texture_pixel(self, mouse: Sequence[float]): # Move into viewport's uv-space: [0, 1] mouse, viewport = self.map_ndc_to_texture(mouse) # Then scale by resolution flipping-y resolution = self.resolution return (int(mouse[0] * resolution[0]), int((1.0 - mouse[1]) * resolution[1])), viewport def request_query(self, pixel: Sequence[int], callback: Callable, *args): # TODO: This can't be made 100% compatible without changes to legacy Viewport # New Viewport will query based on a pixel co-ordinate, regardless of mouse-state; with object and world-space-position # Legacy Viewport will invoke callback on mouse-click only; with world-space-position info only self.legacy_window.query_next_picked_world_position(lambda pos: callback(True, pos) if pos else callback(False, None)) carb.log_warn("request_query not full implemented, will only receive a position from a Viewport click") @property def hydra_engine(self) -> str: '''Get the name of the active omni.hydra.engine for this Viewport''' return self.legacy_window.get_active_hydra_engine() @hydra_engine.setter def hydra_engine(self, hd_engine: str) -> str: '''Set the name of the active omni.hydra.engine for this Viewport''' return self.set_hd_engine(hd_engine) @property def render_mode(self): '''Get the render-mode for the active omni.hydra.engine used in this Viewport''' hd_engine = self.hydra_engine if bool(hd_engine): return self.__settings.get(self.__render_mode_setting(hd_engine)) @render_mode.setter def render_mode(self, render_mode: str): '''Set the render-mode for the active omni.hydra.engine used in this Viewport''' hd_engine = self.hydra_engine if bool(hd_engine): self.__settings.set_string(self.__render_mode_setting(hd_engine), str(render_mode)) def set_hd_engine(self, hd_engine: str, render_mode: str = None): '''Set the active omni.hydra.engine for this Viewport, and optionally its render-mode''' # self.__settings.set_string("/renderer/active", hd_engine) if bool(hd_engine) and bool(render_mode): self.__settings.set_string(self.__render_mode_setting(hd_engine), render_mode) self.legacy_window.set_active_hydra_engine(hd_engine) async def wait_for_rendered_frames(self, additional_frames: int = 0) -> bool: '''Asynchrnously wait until the renderer has delivered an image''' app = omni.kit.app.get_app_interface() legacy_window = self.legacy_window if legacy_window: viewport_ldr_rp = None while viewport_ldr_rp is None: await app.next_update_async() viewport_ldr_rp = legacy_window.get_drawable_ldr_resource() while additional_frames > 0: additional_frames = additional_frames - 1 await app.next_update_async() return True def add_scene_view(self, scene_view): window_name = self.__window_name legacy_subs = _LegacySceneView.get(self.__window_name, self.legacy_window) if not legacy_subs: raise RuntimeError('Could not create _LegacySceneView subscriptions') legacy_subs.add_scene_view(scene_view, self.projection, self.view) def remove_scene_view(self, scene_view): if not scene_view: raise RuntimeError('Provided scene_view is invalid') _LegacySceneView.remove_scene_view_for_window(self.__window_name, scene_view) ### Everything below is NOT part of the new Viewport-API @property def legacy_window(self): '''Expose the underlying legacy viewport for access if needed (not a real ViewportAPI method)''' import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() return vp_iface.get_viewport_window(vp_iface.get_instance(self.__window_name)) @property def _aspect_ratios(self) -> Tuple[float]: return _LegacySceneView.aspect_ratios(self.__window_name, self.legacy_window) def _conform_projection(self, policy, camera: UsdGeom.Camera, image_aspect: float, canvas_aspect: float, projection: Sequence[float] = None): '''For the given camera (or possible incoming projection) return a projection matrix that matches the rendered image but keeps NDC co-ordinates for the texture bound to [-1, 1]''' if projection is None: # If no projection is provided, conform the camera based on settings # This wil adjust apertures on the gf_camera gf_camera = camera.GetCamera(self.time) if policy == CameraUtil.DontConform: # For DontConform, still have to conform for the final canvas if image_aspect < canvas_aspect: gf_camera.horizontalAperture = gf_camera.horizontalAperture * (canvas_aspect / image_aspect) else: gf_camera.verticalAperture = gf_camera.verticalAperture * (image_aspect / canvas_aspect) else: CameraUtil.ConformWindow(gf_camera, policy, image_aspect) projection = gf_camera.frustum.ComputeProjectionMatrix() else: projection = Gf.Matrix4d(*projection) # projection now has the rendered image projection # Conform again based on canvas size so projection extends with the Viewport sits in the UI if image_aspect < canvas_aspect: policy2 = CameraUtil.MatchVertically else: policy2 = CameraUtil.MatchHorizontally if policy != CameraUtil.DontConform: projection = CameraUtil.ConformedWindow(projection, policy2, canvas_aspect) return projection def _conform_policy(self): conform_setting = self.__settings.get("/app/hydra/aperture/conform") if (conform_setting is None) or (conform_setting == 1) or (conform_setting == 'horizontal'): return CameraUtil.MatchHorizontally if (conform_setting == 0) or (conform_setting == 'vertical'): return CameraUtil.MatchVertically if (conform_setting == 2) or (conform_setting == 'fit'): return CameraUtil.Fit if (conform_setting == 3) or (conform_setting == 'crop'): return CameraUtil.Crop if (conform_setting == 4) or (conform_setting == 'stretch'): return CameraUtil.DontConform return CameraUtil.MatchHorizontally def __render_mode_setting(self, hd_engine: str) -> str: return f'/{hd_engine}/rendermode' if hd_engine != 'iray' else '/rtx/iray/rendermode' class _LegacySceneView: __g_legacy_subs = {} @staticmethod def aspect_ratios(window_name: str, legacy_window): canvas_aspect = 1 viewport_window = omni.ui.Workspace.get_window(window_name) if viewport_window: # XXX: Why do some windows have no frame !? if hasattr(viewport_window, 'frame'): canvas = viewport_window.frame canvas_size = (canvas.computed_width, canvas.computed_height) else: canvas_size = (1, 1) canvas_aspect = canvas_size[0] / canvas_size[1] if canvas_size[1] else 1 resolution = legacy_window.get_texture_resolution() image_aspect = resolution[0] / resolution[1] if resolution[1] else 1 return image_aspect, canvas_aspect @staticmethod def get(window_name: str, legacy_window = None): legacy_subs = _LegacySceneView.__g_legacy_subs.get(window_name) if legacy_subs is None and legacy_window: legacy_subs = _LegacySceneView(window_name, legacy_window) _LegacySceneView.__g_legacy_subs[window_name] = legacy_subs return legacy_subs @staticmethod def remove_scene_view_for_window(window_name: str, scene_view): if not scene_view: raise RuntimeError('Provided scene_view is invalid') legacy_subs = _LegacySceneView.__g_legacy_subs.get(window_name) if not legacy_subs: raise RuntimeError('Removing a SceneView for Viewport that is not trakcing any') if legacy_subs.remove_scene_view(scene_view): return legacy_subs.destroy() del _LegacySceneView.__g_legacy_subs[window_name] def __init__(self, window_name: str, legacy_window): self.__window_name = window_name self.__draw_sub, self.__update_sub = None, None self.__scene_views = [] self.__projection = None self.__view = None events = legacy_window.get_ui_draw_event_stream() self.__draw_sub = events.create_subscription_to_pop(self.__on_draw, name=f'omni.kit.viewport.utility.LegacyViewportAPI.{window_name}.draw') events = omni.kit.app.get_app().get_update_event_stream() self.__update_sub = events.create_subscription_to_pop(self.__on_update, name='omni.kit.viewport.utility.LegacyViewportAPI.{window_name}.update') @property def projection(self) -> Gf.Matrix4d: # Return a copy as the reference would be mutable return Gf.Matrix4d(self.__projection) if self.__projection else None @property def view(self) -> Gf.Matrix4d: # Return a copy as the reference would be mutable return Gf.Matrix4d(self.__view) if self.__view else None def __del__(self): self.destroy() def destroy(self): self.__scene_views = [] if self.__draw_sub: self.__draw_sub = None if self.__update_sub: self.__update_sub = None self.__save_position = None self.__scene_views = [] @staticmethod def _flatten_matrix(m: Gf.Matrix4d) -> List[float]: m0, m1, m2, m3 = m[0], m[1], m[2], m[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]] def __get_legacy_window(self): import omni.kit.viewport_legacy as vp_legacy vp_iface = vp_legacy.get_viewport_interface() window_name = self.__window_name viewport_handle = vp_iface.get_instance(window_name) viewport_window = vp_iface.get_viewport_window(viewport_handle) if not viewport_window: self.destroy() del _LegacySceneView.__g_legacy_subs[window_name] return window_name, viewport_window def __on_update(self, *args): window_name, legacy_window = self.__get_legacy_window() visible = legacy_window.is_visible() if legacy_window else False viewport_window = omni.ui.Workspace.get_window(window_name) if viewport_window and (visible != viewport_window.visible): pruned_views = [] for sv in self.__scene_views: scene_view = sv() if scene_view: scene_view.visible = visible pruned_views.append(sv) self.__scene_views = pruned_views omni.ui.Workspace.show_window(window_name, visible) # viewport_window.visible = visible # if not visible: # self.__save_position = viewport_window.position_x, viewport_window.position_y # viewport_window.position_x = omni.ui.Workspace.get_main_window_width() # viewport_window.position_y = omni.ui.Workspace.get_main_window_height() # elif self.__save_position: # viewport_window.position_x = self.__save_position[0] # viewport_window.position_y = self.__save_position[1] # self.__save_position = None def __on_draw(self, event, *args): vm = event.payload["viewMatrix"] pm = event.payload["projMatrix"] # Conform the Projection to the layout of the texture in the Window window_name, legacy_window = self.__get_legacy_window() image_aspect, canvas_aspect = _LegacySceneView.aspect_ratios(window_name, legacy_window) if image_aspect < canvas_aspect: policy = CameraUtil.MatchVertically else: policy = CameraUtil.MatchHorizontally proj_matrix = Gf.Matrix4d(pm[0], pm[1], pm[2], pm[3], pm[4], pm[5], pm[6], pm[7], pm[8], pm[9], pm[10], pm[11], pm[12], pm[13], pm[14], pm[15]) # Fix up RTX projection Matrix for omni.ui.scene...ultimately this should be passed without any compensation if pm[15] == 0.0: proj_matrix = Gf.Matrix4d(1.0, 0.0, -0.0, 0.0, 0.0, 1.0, 0.0, -0.0, -0.0, 0.0, 1.0, -1.0, 0.0, -0.0, 0.0, -2.0) * proj_matrix proj_matrix = CameraUtil.ConformedWindow(proj_matrix, policy, canvas_aspect) # Cache these for lokkup later self.__projection = proj_matrix self.__view = Gf.Matrix4d(vm[0], vm[1], vm[2], vm[3], vm[4], vm[5], vm[6], vm[7], vm[8], vm[9], vm[10], vm[11], vm[12], vm[13], vm[14], vm[15]) # Flatten into list for model pm = _LegacySceneView._flatten_matrix(proj_matrix) pruned_views = [] for sv in self.__scene_views: scene_view = sv() if scene_view: model = scene_view.model model.set_floats("projection", pm) model.set_floats("view", vm) pruned_views.append(sv) self.__scene_views = pruned_views def add_scene_view(self, scene_view, projection: Gf.Matrix4d, view: Gf.Matrix4d): # Sync the model once now model = scene_view.model model.set_floats("projection", _LegacySceneView._flatten_matrix(projection)) model.set_floats("view", _LegacySceneView._flatten_matrix(view)) # And save it for subsequent synchrnoizations import weakref self.__scene_views.append(weakref.ref(scene_view)) def remove_scene_view(self, scene_view) -> bool: for sv in self.__scene_views: if sv() == scene_view: self.__scene_views.remove(sv) break # Return whether this sub is needed anymore return True if self.__scene_views else False
24,854
Python
43.147424
152
0.634948
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/tests/capture.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__ = [ 'DEFAULT_THRESHOLD', 'capture_viewport_and_compare' ] import carb import omni.kit.app import omni.renderer_capture from omni.kit.test_helpers_gfx import compare, CompareError from omni.kit.test.teamcity import teamcity_log_fail, teamcity_publish_image_artifact import pathlib import traceback DEFAULT_THRESHOLD = 10.0 def viewport_capture(image_name: str, output_img_dir: str, viewport=None, use_log: bool = True): """ Captures a Viewport texture into a file. Args: image_name: the image name of the image and golden image. output_img_dir: the directory path that the capture will be saved to. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. use_log: whether to log the comparison image path """ from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file image1 = str(pathlib.Path(output_img_dir).joinpath(image_name)) if use_log: carb.log_info(f"[tests.compare] Capturing {image1}") if viewport is None: viewport = get_active_viewport() return capture_viewport_to_file(viewport, file_path=image1) def finalize_capture_and_compare(image_name: str, output_img_dir: str, golden_img_dir: str, threshold: float = DEFAULT_THRESHOLD): """ Finalizes capture and compares it with the golden image. Args: image_name: the image name of the image and golden image. threshold: the max threshold to collect TC artifacts. output_img_dir: the directory path that the capture will be saved to. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. Returns: A value that indicates the maximum difference between pixels. 0 is no difference in the range [0-255]. """ image1 = pathlib.Path(output_img_dir).joinpath(image_name) image2 = pathlib.Path(golden_img_dir).joinpath(image_name) image_diffmap_name = f"{pathlib.Path(image_name).stem}.diffmap.png" image_diffmap = pathlib.Path(output_img_dir).joinpath(image_diffmap_name) carb.log_info(f"[tests.compare] Comparing {image1} to {image2}") try: diff = compare(image1, image2, image_diffmap) if diff >= threshold: # TODO pass specific test name here instead of omni.rtx.tests teamcity_log_fail("omni.rtx.tests", f"Reference image {image_name} differ from golden.") teamcity_publish_image_artifact(image2, "golden", "Reference") teamcity_publish_image_artifact(image1, "results", "Generated") teamcity_publish_image_artifact(image_diffmap, "results", "Diff") return diff except CompareError as e: carb.log_error(f"[tests.compare] Failed to compare images for {image_name}. Error: {e}") exc = traceback.format_exc() carb.log_error(f"[tests.compare] Traceback:\n{exc}") async def capture_viewport_and_wait(image_name: str, output_img_dir: str, viewport = None): viewport_capture(image_name, output_img_dir, viewport) app = omni.kit.app.get_app() capure_iface = omni.renderer_capture.acquire_renderer_capture_interface() for i in range(3): capure_iface.wait_async_capture() await app.next_update_async() async def capture_viewport_and_compare(image_name: str, output_img_dir: str, golden_img_dir: str, threshold: float = DEFAULT_THRESHOLD, viewport = None, test_caller: str = None): """ Captures frame and compares it with the golden image. Args: image_name: the image name of the image and golden image. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. threshold: the max threshold to collect TC artifacts. viewport: the viewport to capture or None for the active Viewport Returns: A value that indicates the maximum difference between pixels. 0 is no difference in the range [0-255]. """ await capture_viewport_and_wait(image_name=image_name, output_img_dir=output_img_dir, viewport=viewport) diff = finalize_capture_and_compare(image_name=image_name, output_img_dir=output_img_dir, golden_img_dir=golden_img_dir, threshold=threshold) if diff is not None and diff < DEFAULT_THRESHOLD: return True, '' carb.log_warn(f"[{image_name}] the generated image has difference {diff}") if test_caller is None: import os.path test_caller = os.path.splitext(image_name)[0] return False, f"The image for test '{test_caller}' doesn't match the golden one. Difference of {diff} is is not less than threshold of {threshold}."
5,144
Python
39.511811
178
0.700428
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/tests/__init__.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 .capture import * from .test_suite import * async def setup_viewport_test_window(resolution_x: int, resolution_y: int, position_x: int = 0, position_y: int = 0): from omni.kit.viewport.utility import get_active_viewport_window viewport_window = get_active_viewport_window() if viewport_window: viewport_window.position_x = position_x viewport_window.position_y = position_y viewport_window.width = resolution_x viewport_window.height = resolution_y viewport_window.viewport_api.resolution = (resolution_x, resolution_y) return viewport_window
1,043
Python
42.499998
117
0.744966
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/tests/test_suite.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__ = ['TestViewportUtility'] import omni.kit.test from omni.kit.test import AsyncTestCase import omni.kit.viewport.utility import omni.kit.renderer_capture import omni.kit.app import omni.usd import omni.ui as ui from pathlib import Path from pxr import Gf, UsdGeom, Sdf, Usd TEST_OUTPUT = Path(omni.kit.test.get_test_output_path()).resolve().absolute() TEST_WIDTH, TEST_HEIGHT = (500, 500) class TestViewportUtility(AsyncTestCase): # Before running each test async def setUp(self): super().setUp() await omni.usd.get_context().new_stage_async() async def tearDown(self): super().tearDown() # Legacy Viewport needs some time to adopt the resolution changes async def wait_for_resolution_change(self, viewport_api): await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) for i in range(3): await omni.kit.app.get_app().next_update_async() async def test_get_viewport_from_window_name(self): '''Test getting a default Viewport from a Window without a name''' viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name() self.assertIsNotNone(viewport_window) async def test_get_viewport_from_window_name_with_name(self): '''Test getting a default Viewport from a Window name''' viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name(window_name='Viewport') self.assertIsNotNone(viewport_window) async def test_get_active_viewport(self): '''Test getting a default Viewport''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) viewport_api = omni.kit.viewport.utility.get_active_viewport(usd_context_name='') self.assertIsNotNone(viewport_api) async def test_get_viewport_from_non_existant_window_name_with_name(self): '''Test getting a non-existent Viewport via Window name''' viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name(window_name='NotExisting') self.assertIsNone(viewport_window) async def test_get_non_existant_viewport(self): '''Test getting a non-existent Viewport via UsdContext name''' viewport_api = omni.kit.viewport.utility.get_active_viewport(usd_context_name='NotExisting') self.assertIsNone(viewport_api) async def test_get_camera_path_api(self): '''Test camera access API''' # Test camera-path as an Sdf.Path cam_path = omni.kit.viewport.utility.get_viewport_window_camera_path() self.assertTrue(bool(cam_path)) self.assertTrue(isinstance(cam_path, Sdf.Path)) cam_path = omni.kit.viewport.utility.get_viewport_window_camera_path(window_name='Viewport') self.assertTrue(bool(cam_path)) self.assertTrue(isinstance(cam_path, Sdf.Path)) cam_path = omni.kit.viewport.utility.get_viewport_window_camera_path(window_name='NO_Viewport') self.assertIsNone(cam_path) cam_path = omni.kit.viewport.utility.get_active_viewport_camera_path() self.assertTrue(bool(cam_path)) self.assertTrue(isinstance(cam_path, Sdf.Path)) cam_path = omni.kit.viewport.utility.get_active_viewport_camera_path(usd_context_name='') self.assertTrue(bool(cam_path)) self.assertTrue(isinstance(cam_path, Sdf.Path)) cam_path = omni.kit.viewport.utility.get_active_viewport_camera_path(usd_context_name='DoesntExist') self.assertIsNone(cam_path) # Test camera-path as a string cam_path_str = omni.kit.viewport.utility.get_viewport_window_camera_string() self.assertTrue(bool(cam_path_str)) self.assertTrue(isinstance(cam_path_str, str)) cam_path_str = omni.kit.viewport.utility.get_viewport_window_camera_string(window_name='Viewport') self.assertTrue(bool(cam_path_str)) self.assertTrue(isinstance(cam_path_str, str)) cam_path_str = omni.kit.viewport.utility.get_viewport_window_camera_string(window_name='NO_Viewport') self.assertIsNone(cam_path_str) cam_path_str = omni.kit.viewport.utility.get_active_viewport_camera_string() self.assertTrue(bool(cam_path_str)) self.assertTrue(isinstance(cam_path_str, str)) cam_path_str = omni.kit.viewport.utility.get_active_viewport_camera_string(usd_context_name='') self.assertTrue(bool(cam_path_str)) self.assertTrue(isinstance(cam_path_str, str)) cam_path_str = omni.kit.viewport.utility.get_active_viewport_camera_string(usd_context_name='DoesntExist') self.assertIsNone(cam_path_str) viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) # Test property and method accessors are equal self.assertEqual(viewport_api.get_active_camera(), viewport_api.camera_path) async def test_setup_viewport_test_window(self): '''Test the test-suite utility setup_viewport_test_window''' from omni.kit.viewport.utility.tests import setup_viewport_test_window viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) resolution = viewport_api.resolution # Test the keywords arguments for the function await setup_viewport_test_window(resolution_x=128, resolution_y=128, position_x=10, position_y=10) # Test the arguments for the function and restore Viewport resolution await setup_viewport_test_window(resolution[0], resolution[1], 0, 0) async def test_viewport_resolution(self): '''Test the test-suite utility setup_viewport_test_window''' from omni.kit.viewport.utility.tests import setup_viewport_test_window viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) # Legacy Viewport needs some time to adopt the resolution changes try: resolution = viewport_api.resolution self.assertIsNotNone(resolution) full_resolution = viewport_api.full_resolution self.assertEqual(resolution, full_resolution) resolution_scale = viewport_api.resolution_scale # Resolution scale factor should be 1 by default self.assertEqual(resolution_scale, 1.0) viewport_api.resolution_scale = 0.5 await self.wait_for_resolution_change(viewport_api) # Resolution scale factor should stick self.assertEqual(viewport_api.resolution_scale, 0.5) # Full resolution should still be the same self.assertEqual(viewport_api.full_resolution, full_resolution) # New resolution should now be half of the original self.assertEqual(viewport_api.resolution, (resolution[0] * 0.5, resolution[1] * 0.5)) finally: viewport_api.resolution_scale = 1.0 self.assertEqual(viewport_api.resolution_scale, 1.0) async def test_testsuite_capture_helpers(self): '''Test the API exposed to assist other extensions testing/capturing Viewport''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) from omni.kit.viewport.utility.tests.capture import viewport_capture, capture_viewport_and_wait # Test keyword arguments with an explicit Viewport await capture_viewport_and_wait(image_name='test_testsuite_capture_helper_01', output_img_dir=str(TEST_OUTPUT), viewport = viewport_api) # Test arguments with an implicit Viewport await capture_viewport_and_wait('test_testsuite_capture_helper_02', str(TEST_OUTPUT)) async def test_legacy_as_new_api(self): '''Test the new API against a new or legacy Viewport''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) self.assertEqual(viewport_api.camera_path.pathString, '/OmniverseKit_Persp') # Test camera property setter viewport_api.camera_path = '/OmniverseKit_Top' self.assertEqual(viewport_api.camera_path.pathString, '/OmniverseKit_Top') # Test camera method setter viewport_api.set_active_camera('/OmniverseKit_Persp') resolution = viewport_api.resolution self.assertIsNotNone(resolution) # Test access via legacy method-name self.assertEqual(resolution, viewport_api.get_texture_resolution()) # Test setting via property viewport_api.resolution = (128, 128) await self.wait_for_resolution_change(viewport_api) self.assertEqual(viewport_api.resolution, (128, 128)) # Test setting via method viewport_api.set_texture_resolution((256, 256)) await self.wait_for_resolution_change(viewport_api) self.assertEqual(viewport_api.get_texture_resolution(), (256, 256)) # Test matrix access self.assertIsNotNone(viewport_api.projection) self.assertIsNotNone(viewport_api.transform) self.assertIsNotNone(viewport_api.view) # Test world-NDC matrix convertor access self.assertIsNotNone(viewport_api.world_to_ndc) self.assertIsNotNone(viewport_api.ndc_to_world) # Test UsdContext and Stage access self.assertIsNotNone(viewport_api.usd_context_name) self.assertIsNotNone(viewport_api.usd_context) self.assertIsNotNone(viewport_api.stage) render_product_path = viewport_api.render_product_path self.assertIsNotNone(render_product_path) # Test access via legacy method-name self.assertEqual(render_product_path, viewport_api.get_render_product_path()) # Test setting via property viewport_api.render_product_path = render_product_path # Test setting via method viewport_api.set_render_product_path(render_product_path) # Should have an id property self.assertIsNotNone(viewport_api.id) # Should have a frame_info dictionary self.assertIsNotNone(viewport_api.frame_info) # Test the NDC to texture-uv mapping API uv, valid = viewport_api.map_ndc_to_texture((0, 0)) self.assertTrue(bool(valid)) self.assertEqual(uv, (0.5, 0.5)) # Test the NDC to texture-pixel mapping API pixel, valid = viewport_api.map_ndc_to_texture_pixel((0, 0)) self.assertTrue(bool(valid)) # Test API to set fill-frame resolution self.assertFalse(viewport_api.fill_frame) viewport_api.fill_frame = True await self.wait_for_resolution_change(viewport_api) self.assertTrue(viewport_api.fill_frame) viewport_api.fill_frame = False await self.wait_for_resolution_change(viewport_api) self.assertFalse(viewport_api.fill_frame) async def test_viewport_window_api(self): '''Test the legacy API exposure into the omni.ui window wrapper''' viewport_window = omni.kit.viewport.utility.get_active_viewport_window() self.assertIsNotNone(viewport_window) # Test the get_frame API frame_1 = viewport_window.get_frame('omni.kit.viewport.utility.test_frame_1') self.assertIsNotNone(frame_1) frame_2 = viewport_window.get_frame('omni.kit.viewport.utility.test_frame_1') self.assertEqual(frame_1, frame_2) frame_3 = viewport_window.get_frame('omni.kit.viewport.utility.test_frame_3') self.assertNotEqual(frame_1, frame_3) # Test setting visible attribute on Window viewport_window.visible = True self.assertTrue(viewport_window.visible) # Test utility function for legacy usage only if viewport_window and hasattr(viewport_window.viewport_api, 'legacy_window'): viewport_window.setPosition(0, 0) viewport_window.set_position(0, 0) async def test_toggle_global_visibility(self): """Test the expected setting change for omni.kit.viewport.utility.toggle_global_visibility""" import carb settings = carb.settings.get_settings() viewport_api = omni.kit.viewport.utility.get_active_viewport() if hasattr(viewport_api, 'legacy_window'): def collect_settings(settings): return settings.get('/persistent/app/viewport/displayOptions') else: def collect_settings(settings): setting_keys = [ "/persistent/app/viewport/Viewport/Viewport0/guide/grid/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/deviceMemory/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/hostMemory/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/renderFPS/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/renderProgress/visible", "/persistent/app/viewport/Viewport/Viewport0/hud/renderResolution/visible", "/persistent/app/viewport/Viewport/Viewport0/scene/cameras/visible", "/persistent/app/viewport/Viewport/Viewport0/scene/lights/visible", "/persistent/app/viewport/Viewport/Viewport0/scene/skeletons/visible", ] return {k: settings.get(k) for k in setting_keys} omni.kit.viewport.utility.toggle_global_visibility() options_1 = collect_settings(settings) omni.kit.viewport.utility.toggle_global_visibility() options_2 = collect_settings(settings) self.assertNotEqual(options_1, options_2) omni.kit.viewport.utility.toggle_global_visibility() options_3 = collect_settings(settings) self.assertEqual(options_1, options_3) omni.kit.viewport.utility.toggle_global_visibility() options_4 = collect_settings(settings) self.assertEqual(options_2, options_4) async def test_ui_scene_view_model_sync(self): '''Test API to autmoatically set view and projection on a SceneView model''' class ModelPoser: def __init__(model_self): model_self.set_items = set() def get_item(model_self, name: str): if name == 'view' or name == 'projection': return name self.assertTrue(False) def set_floats(model_self, item, floats): self.assertEqual(len(floats), 16) self.assertTrue(item == model_self.get_item(item)) model_self.set_items.add(item) class SceneViewPoser: def __init__(model_self): model_self.model = ModelPoser() viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) scene_view = SceneViewPoser() # Test add_scene_view API viewport_api.add_scene_view(scene_view) # Test both view and projection have been set into self.assertTrue('view' in scene_view.model.set_items) self.assertTrue('projection' in scene_view.model.set_items) # Test remove_scene_view API viewport_api.remove_scene_view(scene_view) async def test_legacy_drag_drop_helper(self): pickable = False add_outline = False def on_drop_accepted_fn(url): pass def on_drop_fn(url, prim_path, unused_viewport_name, usd_context_name): pass def on_pick_fn(payload, prim_path, usd_context_name): pass dd_from_args = omni.kit.viewport.utility.create_drop_helper( pickable, add_outline, on_drop_accepted_fn, on_drop_fn, on_pick_fn ) self.assertIsNotNone(dd_from_args) dd_from_kw = omni.kit.viewport.utility.create_drop_helper( pickable=pickable, add_outline=add_outline, on_drop_accepted_fn=on_drop_accepted_fn, on_drop_fn=on_drop_fn, on_pick_fn=on_pick_fn ) self.assertIsNotNone(dd_from_kw) async def test_capture_file(self): '''Test the capture_viewport_to_file capture to a file''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertTrue(bool(viewport_api)) # Make sure renderer is rendering images (also a good place to up the coverage %) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) file = TEST_OUTPUT.joinpath('capture_01.png') cap_obj = omni.kit.viewport.utility.capture_viewport_to_file(viewport_api, file_path=str(file)) # API should return an object we can await on self.assertIsNotNone(cap_obj) # Test that we can in fact wait on that object result = await cap_obj.wait_for_result(completion_frames=30) self.assertTrue(result) # File should exists by now omni.kit.renderer_capture.acquire_renderer_capture_interface().wait_async_capture() self.assertTrue(file.exists()) async def test_capture_file_with_exr_compression(self): '''Test the capture_viewport_to_file capture to a file''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertTrue(bool(viewport_api)) # Make sure renderer is rendering images (also a good place to up the coverage %) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) format_desc = {} format_desc["format"] = "exr" format_desc["compression"] = "b44" file = TEST_OUTPUT.joinpath(f'capture_{format_desc["compression"]}.{format_desc["format"]}') cap_obj = omni.kit.viewport.utility.capture_viewport_to_file(viewport_api, file_path=str(file), format_desc=format_desc) # API should return an object we can await on self.assertIsNotNone(cap_obj) # Test that we can in fact wait on that object result = await cap_obj.wait_for_result(completion_frames=30) self.assertTrue(result) # File should exists by now omni.kit.renderer_capture.acquire_renderer_capture_interface().wait_async_capture() self.assertTrue(file.exists()) async def test_capture_file_str_convert(self): '''Test the capture_viewport_to_file capture to a file when passed an path-like object''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertTrue(bool(viewport_api)) # Make sure renderer is rendering images (also a good place to up the coverage %) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) file = TEST_OUTPUT.joinpath('capture_02.png') cap_obj = omni.kit.viewport.utility.capture_viewport_to_file(viewport_api, file_path=file) # API should return an object we can await on self.assertIsNotNone(cap_obj) # Test that we can in fact wait on that object result = await cap_obj.wait_for_result(completion_frames=15) self.assertTrue(result) # File should exists by now # self.assertTrue(file.exists()) async def test_capture_to_buffer(self): '''Test the capture_viewport_to_file capture to a callback function''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertTrue(bool(viewport_api)) # Make sure renderer is rendering images (also a good place to up the coverage %) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) callback_called = False def capture_callback(*args, **kwargs): nonlocal callback_called callback_called = True cap_obj = omni.kit.viewport.utility.capture_viewport_to_buffer(viewport_api, capture_callback) # API should return an object we can await on self.assertIsNotNone(cap_obj) # Test that we can in fact wait on that object result = await cap_obj.wait_for_result() self.assertTrue(result) # Callback should have been called self.assertTrue(callback_called) async def test_new_viewport_api(self): '''Test the ability to create a new Viewport and retrieve the number of Viewports open''' num_vp_1 = omni.kit.viewport.utility.get_num_viewports() self.assertEqual(num_vp_1, 1) # Test Window creation, but that would require a renderer other than Storm which can only be created once # Which would make the tests run slower and in L2 # new_window = omni.kit.viewport.utility.create_viewport_window('TEST WINDOW', width=128, height=128, camera_path='/OmniverseKit_Top') # self.assertEqual(new_window.viewport_api.camera_path.pathString, '/OmniverseKit_Top') # num_vp_2 = omni.kit.viewport.utility.get_num_viewports() # self.assertEqual(num_vp_2, 2) async def test_post_toast_api(self): # Post a message with a Viewport only viewport_api = omni.kit.viewport.utility.get_active_viewport() omni.kit.viewport.utility.post_viewport_message(viewport_api, "Message from ViewportAPI") # Post a message with the same API, but a Window viewport_window = omni.kit.viewport.utility.get_active_viewport_window() omni.kit.viewport.utility.post_viewport_message(viewport_window, "Message from ViewportWindow") # Post a message with the same API, but with a method viewport_window._post_toast_message("Message from ViewportWindow method") async def test_disable_picking(self): '''Test ability to disable picking on a Viewport or ViewportWindow''' from omni.kit import ui_test viewport_window = omni.kit.viewport.utility.get_active_viewport_window() self.assertIsNotNone(viewport_window) # viewport_window.position_x = 0 # viewport_window.position_y = 0 # viewport_window.width = TEST_WIDTH # viewport_window.height = TEST_HEIGHT viewport_api = viewport_window.viewport_api self.assertIsNotNone(viewport_api) usd_cube = UsdGeom.Cube.Define(viewport_window.viewport_api.stage, "/cube") usd_cube.GetSizeAttr().Set(100) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) async def test_selection_rect(wait_frames: int = 5): selection = viewport_api.usd_context.get_selection() self.assertIsNotNone(selection) selection.set_selected_prim_paths([], False) selected_prims = selection.get_selected_prim_paths() self.assertFalse(bool(selected_prims)) for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() await ui_test.emulate_mouse_drag_and_drop(ui_test.Vec2(100, 100), ui_test.Vec2(400, 400)) for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() return selection.get_selected_prim_paths() # Test initial selection works as expected selection = await test_selection_rect() self.assertTrue(len(selection) == 1) self.assertTrue(selection[0] == '/cube') # Test disabling selection on the Window leads to no selection picking_disabled = omni.kit.viewport.utility.disable_selection(viewport_window) selection = await test_selection_rect() self.assertTrue(len(selection) == 0) del picking_disabled # Test restore of selection works as expected selection = await test_selection_rect() self.assertTrue(len(selection) == 1) self.assertTrue(selection[0] == '/cube') # Test disabling selection on the Viewport leads to no selection picking_disabled = omni.kit.viewport.utility.disable_selection(viewport_api) selection = await test_selection_rect() self.assertTrue(len(selection) == 0) del picking_disabled async def test_frame_viewport(self): time = Usd.TimeCode.Default() def set_camera(cam_path: str, camera_pos=None, target_pos=None): from omni.kit.viewport.utility.camera_state import ViewportCameraState camera_state = ViewportCameraState(cam_path) camera_state.set_position_world(camera_pos, True) camera_state.set_target_world(target_pos, True) def test_camera_position(cam_path: str, expected_pos: Gf.Vec3d): prim = viewport_api.stage.GetPrimAtPath(cam_path) camera = UsdGeom.Camera(prim) if prim else None world_xform = camera.ComputeLocalToWorldTransform(time) world_pos = world_xform.Transform(Gf.Vec3d(0, 0, 0)) for w_pos, ex_pos in zip(world_pos, expected_pos): self.assertAlmostEqual(float(w_pos), float(ex_pos), 4) viewport_window = omni.kit.viewport.utility.get_active_viewport_window() self.assertIsNotNone(viewport_window) viewport_api = viewport_window.viewport_api usd_cube1 = UsdGeom.Cube.Define(viewport_window.viewport_api.stage, "/cube1") #usd_cube1.GetSizeAttr().Set(10) usd_cube1_xformable = UsdGeom.Xformable(usd_cube1.GetPrim()) usd_cube1_xformable.AddTranslateOp() attr = usd_cube1.GetPrim().GetAttribute("xformOp:translate") attr.Set((200, 800, 4)) usd_cube2 = UsdGeom.Cube.Define(viewport_window.viewport_api.stage, "/cube2") #usd_cube2.GetSizeAttr().Set(100) await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api) selection = viewport_api.usd_context.get_selection() self.assertIsNotNone(selection) camera_path = '/OmniverseKit_Persp' test_camera_position(camera_path, Gf.Vec3d(500, 500, 500)) # select cube1 selection.set_selected_prim_paths(["/cube1"], True) # frame to the selection omni.kit.viewport.utility.frame_viewport_selection(viewport_api=viewport_api) # test test_camera_position(camera_path, Gf.Vec3d(202.49306, 802.49306, 6.49306)) # select cube2 selection.set_selected_prim_paths(["/cube2"], True) # frame to the selection omni.kit.viewport.utility.frame_viewport_selection(viewport_api=viewport_api) # test test_camera_position(camera_path, Gf.Vec3d(2.49306, 2.49306, 2.49306)) # unselect selection.set_selected_prim_paths([], True) # reset camera position set_camera(camera_path, (500, 500, 500), (0, 0, 0)) test_camera_position(camera_path, Gf.Vec3d(500, 500, 500)) # frame. Because nothing is selected, it should frame to all. omni.kit.viewport.utility.frame_viewport_selection(viewport_api=viewport_api) test_camera_position(camera_path, Gf.Vec3d(522.65586, 822.65585, 424.65586)) # unselect selection.set_selected_prim_paths([], True) # reset camera position set_camera(camera_path, (500, 500, 500), (0, 0, 0)) test_camera_position(camera_path, Gf.Vec3d(500, 500, 500)) # no frame on cube2 without to select it omni.kit.viewport.utility.frame_viewport_prims(viewport_api=viewport_api, prims=["/cube2"]) # should be the same as when we select test_camera_position(camera_path, Gf.Vec3d(2.49306, 2.49306, 2.49306)) # reset camera position set_camera(camera_path, (500, 500, 500), (0, 0, 0)) test_camera_position(camera_path, Gf.Vec3d(500, 500, 500)) # try on cube1 omni.kit.viewport.utility.frame_viewport_prims(viewport_api=viewport_api, prims=["/cube1"]) test_camera_position(camera_path, Gf.Vec3d(202.49306, 802.49306, 6.49306)) # call frame on prims with no list given omni.kit.viewport.utility.frame_viewport_prims(viewport_api=viewport_api) # camera should not move test_camera_position(camera_path, Gf.Vec3d(202.49306, 802.49306, 6.49306)) async def test_disable_context_menu(self): '''Test ability to disable context-menu on a Viewport or ViewportWindow''' from omni.kit import ui_test ctx_menu_wait = 50 # # Initial checks about assumption that objects are reachable and that no context manu is visible # ui_viewport = ui_test.find("Viewport") self.assertIsNotNone(ui_viewport) self.assertIsNone(ui.Menu.get_current()) # # Test context-menu is working by default # await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNotNone(ui.Menu.get_current()) # # Test disabling context-menu with a ViewportWindow # viewport_window = omni.kit.viewport.utility.get_active_viewport_window() self.assertIsNotNone(viewport_window) context_menu_disabled = omni.kit.viewport.utility.disable_context_menu(viewport_window) await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNone(ui.Menu.get_current()) del context_menu_disabled # Context menu should work again await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNotNone(ui.Menu.get_current()) # # Test disabling context-menu with a Viewport instance # viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) context_menu_disabled = omni.kit.viewport.utility.disable_context_menu(viewport_api) await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNone(ui.Menu.get_current()) del context_menu_disabled # Context menu should work again await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNotNone(ui.Menu.get_current()) # # Test disabling context-menu globally # context_menu_disabled = omni.kit.viewport.utility.disable_context_menu() await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNone(ui.Menu.get_current()) del context_menu_disabled # Context menu should work again await ui_viewport.right_click(human_delay_speed=ctx_menu_wait) self.assertIsNotNone(ui.Menu.get_current()) async def testget_ground_plane_info(self): '''Test results from get_ground_plane_info''' viewport_api = omni.kit.viewport.utility.get_active_viewport() self.assertIsNotNone(viewport_api) async def get_camera_ground_plane(path: str, ortho_special: bool = True, wait_frames: int = 3): app = omni.kit.app.get_app() viewport_api.camera_path = path for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() return omni.kit.viewport.utility.get_ground_plane_info(viewport_api, ortho_special) def test_results(results, normal, planes): self.assertTrue(Gf.IsClose(results[0], normal, 1e-5)) self.assertEqual(results[1], planes) # Test ground plane info against Y-up stage UsdGeom.SetStageUpAxis(viewport_api.stage, UsdGeom.Tokens.y) persp_info = await get_camera_ground_plane('/OmniverseKit_Persp') front_info = await get_camera_ground_plane('/OmniverseKit_Front') top_info = await get_camera_ground_plane('/OmniverseKit_Top') right_info = await get_camera_ground_plane('/OmniverseKit_Right') right_info_world = await get_camera_ground_plane('/OmniverseKit_Right', False) test_results(persp_info, Gf.Vec3d(0, 1, 0), ['x', 'z']) test_results(front_info, Gf.Vec3d(0, 0, 1), ['x', 'y']) test_results(top_info, Gf.Vec3d(0, 1, 0), ['x', 'z']) test_results(right_info, Gf.Vec3d(1, 0, 0), ['y', 'z']) test_results(right_info_world, Gf.Vec3d(0, 1, 0), ['x', 'z']) # Test ground plane info against Z-up stage UsdGeom.SetStageUpAxis(viewport_api.stage, UsdGeom.Tokens.z) persp_info = await get_camera_ground_plane('/OmniverseKit_Persp') front_info = await get_camera_ground_plane('/OmniverseKit_Front') top_info = await get_camera_ground_plane('/OmniverseKit_Top') right_info = await get_camera_ground_plane('/OmniverseKit_Right') right_info_world = await get_camera_ground_plane('/OmniverseKit_Right', False) test_results(persp_info, Gf.Vec3d(0, 0, 1), ['x', 'y']) test_results(front_info, Gf.Vec3d(1, 0, 0), ['y', 'z']) test_results(top_info, Gf.Vec3d(0, 0, 1), ['x', 'y']) test_results(right_info, Gf.Vec3d(0, 1, 0), ['x', 'z']) test_results(right_info_world, Gf.Vec3d(0, 0, 1), ['x', 'y'])
33,188
Python
43.789474
144
0.664578
omniverse-code/kit/exts/omni.kit.viewport.utility/docs/CHANGELOG.md
# CHANGELOG The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.14] - 2023-01-25 ### Added - get_ground_plane_info API call. ## [1.0.13] - 2022-12-09 ### Added - Be able to pass a prim path to focus on ## [1.0.12] - 2022-10-17 ### Added - disable_context_menu API to disable contet menu for single or all Viewport. - Support legacy global disabling of context-menu by carb-setting. - Ability to also disable object-click (or not) when disabling selection-rect. ### Fixed - A few typos. ## [1.0.11] - 2022-09-27 ### Added - Use new ViewportWindow.active_window API. ### Fixed - Possibly import error from omni.usd.editor ## [1.0.10] - 2022-09-10 ### Added - disable_selection API to disable Viewport selection. ## [1.0.9] - 2022-08-25 ### Fixed - Convert to Gf.Camera at Viewport time. ## [1.0.8] - 2022-08-22 ### Added - Re-enable possibility of more than one Viewport. ## [1.0.7] - 2022-08-10 ### Added - Ability to specify format_desc dictionary to new capture-file API. ## [1.0.6] - 2022-07-28 ### Added - Accept a ViewportWindow or ViewportAPI for toast-message API. - Add _post_toast_message method to LegacyViewportWindow ## [1.0.5] - 2022-07-06 ### Added - Add resolution and scaling API to mirror new Viewport ## [1.0.4] - 2022-06-22 ### Added - Add capture_viewport_to_buffer function ### Changed - Return an object from capture_viewport_to_file and capture_viewport_to_buffer. - Get test-suite coverage above 70%. ### Fixed - Query of fill_frame atribute after toggling with legacy Viewport ## [1.0.3] - 2022-06-16 ### Added - Add create_drop_helper function ## [1.0.2] - 2022-05-25 ### Added - Add framing and toggle-visibility function for edit menu. ## [1.0.1] - 2022-05-25 ### Added - Fix issue with usage durring startup with only Legacy viewport ## [1.0.0] - 2022-04-29 ### Added - Initial release
1,867
Markdown
23.578947
80
0.688806
omniverse-code/kit/exts/omni.kit.viewport.utility/docs/README.md
# Overview Utility functions to access [active] Viewport information
70
Markdown
16.749996
57
0.814286
omniverse-code/kit/exts/omni.kit.viewport.utility/docs/Overview.md
# Overview Utility functions to access [active] Viewport information
70
Markdown
16.749996
57
0.814286
omniverse-code/kit/exts/omni.kit.example.toolbar_button/PACKAGE-LICENSES/omni.kit.example.toolbar_button-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.example.toolbar_button/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Kit Toolbar Button Example" desciption="Extension to demostrate how to add and remove custom button to Omniverse Kit Toolbar." category = "Example" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" # We only depend on testing framework currently: [dependencies] "omni.ui" = {} "omni.kit.window.toolbar" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.kit.example.toolbar_button" [[test]] waiver = "an example extension"
1,061
TOML
29.342856
107
0.745523
omniverse-code/kit/exts/omni.kit.example.toolbar_button/omni/kit/example/toolbar_button/__init__.py
from .toolbar_button import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.kit.example.toolbar_button/omni/kit/example/toolbar_button/toolbar_button.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.ext import omni.kit.app import omni.kit.window.toolbar import omni.ui import os from carb.input import KeyboardInput as Key from omni.kit.widget.toolbar import SimpleToolButton, WidgetGroup class ExampleSimpleToolButton(SimpleToolButton): """ Example of how to use SimpleToolButton """ def __init__(self, icon_path): super().__init__( name="example_simple", tooltip="Example Simple ToolButton", icon_path=f"{icon_path}/plus.svg", icon_checked_path=f"{icon_path}/plus.svg", hotkey=Key.L, toggled_fn=lambda c: carb.log_warn(f"Example button toggled {c}"), ) class ExampleToolButtonGroup(WidgetGroup): """ Example of how to create two ToolButton in one WidgetGroup """ def __init__(self, icon_path): super().__init__() self._icon_path = icon_path def clean(self): super().clean() def get_style(self): style = { "Button.Image::example1": {"image_url": f"{self._icon_path}/plus.svg"}, "Button.Image::example1:checked": {"image_url": f"{self._icon_path}/minus.svg"}, "Button.Image::example2": {"image_url": f"{self._icon_path}/minus.svg"}, "Button.Image::example2:checked": {"image_url": f"{self._icon_path}/plus.svg"}, } return style def create(self, default_size): def on_clicked(): # example of getting a button by name from toolbar toolbar = omni.kit.window.toolbar.get_instance() button = toolbar.get_widget("scale_op") if button is not None: button.enabled = not button.enabled button1 = omni.ui.ToolButton( name="example1", tooltip="Example Button 1", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: on_clicked(), ) button2 = omni.ui.ToolButton( name="example2", tooltip="Example Button 2", width=default_size, height=default_size ) # return a dictionary of name -> widget if you want to expose it to other widget_group return {"example1": button1, "example2": button2} class ToolbarButtonExample(omni.ext.IExt): def on_startup(self, ext_id): ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) icon_path = os.path.join(ext_path, "icons") self._toolbar = omni.kit.window.toolbar.get_instance() self._widget_simple = ExampleSimpleToolButton(icon_path) self._widget = ExampleToolButtonGroup(icon_path) self._toolbar.add_widget(self._widget, -100) self._toolbar.add_widget(self._widget_simple, -200) def on_shutdown(self): self._toolbar.remove_widget(self._widget) self._toolbar.remove_widget(self._widget_simple) self._widget.clean() self._widget = None self._widget_simple.clean() self._widget_simple = None self._toolbar = None
3,501
Python
33.673267
96
0.630963
omniverse-code/kit/exts/omni.kit.example.toolbar_button/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [0.1.0] - 2020-07-23 ### Added - Initial implementation
156
Markdown
18.624998
80
0.673077
omniverse-code/kit/exts/omni.kit.example.toolbar_button/docs/index.rst
omni.kit.example.toolbar_button ############################### Omniverse Kit Toolbar Button Example .. toctree:: :maxdepth: 1 CHANGELOG
150
reStructuredText
9.785714
36
0.56
omniverse-code/kit/exts/omni.kit.window.preferences/PACKAGE-LICENSES/omni.kit.window.preferences-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.preferences/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.3.8" category = "Internal" feature = true # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Preferences Window" description="Preferences Window" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "ui", "preferences"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" [ui] name = "Python preferences Window" [dependencies] "omni.usd" = {} "omni.kit.context_menu" = {} "omni.client" = {} "omni.ui" = {} "omni.kit.audiodeviceenum" = {} "omni.kit.window.filepicker" = {} "omni.kit.menu.utils" = {} "omni.kit.widget.settings" = {} "omni.kit.actions.core" = {} [[python.module]] name = "omni.kit.window.preferences" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/file/ignoreUnsavedOnExit=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/persistent/app/omniverse/filepicker/options_menu/show_details=false", "--/persistent/app/stage/dragDropImport='reference'", "--/persistent/app/material/dragDropMaterialPath='Absolute'", "--no-window" ] dependencies = [ "omni.hydra.pxr", "omni.kit.mainwindow", "omni.usd", "omni.kit.ui_test", "omni.kit.test_suite.helpers", ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop "*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available ]
2,222
TOML
28.64
122
0.69757
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/__init__.py
from .scripts import *
23
Python
10.999995
22
0.73913
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/preference_builder.py
import asyncio import os from typing import List, Callable, Union from typing import List, Callable, Union import carb import omni.kit.menu.utils import omni.ui as ui from omni.ui import color as cl from functools import partial from omni.kit.widget.settings import create_setting_widget, create_setting_widget_combo, SettingType from omni.kit.widget.settings import get_style, get_ui_style_name # Base class for a preference builder class PreferenceBuilder: WINDOW_NAME = "Preferences" def __init__(self, title): self._title = title carb.settings.get_settings().set_default_string("/placeholder", "missing setting") def __del__(self): pass def label(self, name: str, tooltip: str=None): """ Create a UI widget label. Args: name: Name to be in label tooltip: The Tooltip string to be displayed when mouse hovers on the label Returns: :class:`ui.Widget` connected with the setting on the path specified. """ if tooltip: ui.Label(name, word_wrap=True, name="title", width=ui.Percent(50), tooltip=tooltip) else: ui.Label(name, word_wrap=True, name="title", width=ui.Percent(50)) def create_setting_widget_combo(self, name: str, setting_path: str, list: List[str], setting_is_index=False, **kwargs) -> ui.Widget: """ Creating a Combo Setting widget. This function creates a combo box that shows a provided list of names and it is connected with setting by path specified. Underlying setting values are used from values of `items` dict. Args: setting_path: Path to the setting to show and edit. items: Can be either :py:obj:`dict` or :py:obj:`list`. For :py:obj:`dict` keys are UI displayed names, values are actual values set into settings. If it is a :py:obj:`list` UI displayed names are equal to setting values. setting_is_index: True - setting_path value is index into items list False - setting_path value is string in items list (default) """ with ui.HStack(height=24): self.label(name) widget, model = create_setting_widget_combo(setting_path, list, setting_is_index=setting_is_index, **kwargs) return widget def create_setting_widget( self, label_name: str, setting_path: str, setting_type: SettingType, **kwargs ) -> ui.Widget: """ Create a UI widget connected with a setting. If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`. Args: setting_path: Path to the setting to show and edit. setting_type: Type of the setting to expect. range_from: Limit setting value lower bound. range_to: Limit setting value upper bound. Returns: :class:`ui.Widget` connected with the setting on the path specified. """ if carb.settings.get_settings().get(setting_path) is None: return self.create_setting_widget(label_name, "/placeholder", SettingType.STRING) clicked_fn = None if "clicked_fn" in kwargs: clicked_fn = kwargs["clicked_fn"] del kwargs["clicked_fn"] # omni.kit.widget.settings.create_drag_or_slider won't use min/max unless hard_range is set to True if 'range_from' in kwargs and 'range_to' in kwargs: kwargs['hard_range'] = True vheight = 24 vpadding = 0 if setting_type == SettingType.FLOAT or setting_type == SettingType.INT or setting_type == SettingType.STRING: vheight = 20 vpadding = 3 with ui.HStack(height=vheight): tooltip = kwargs.pop('tooltip', '') self.label(label_name, tooltip) widget, model = create_setting_widget(setting_path, setting_type, **kwargs) if clicked_fn: ui.Button( style={"image_url": "resources/icons/folder.png"}, clicked_fn=partial(clicked_fn, widget), width=24 ) ui.Spacer(height=vpadding) return widget def add_frame(self, name: str) -> ui.CollapsableFrame: """ Create a UI collapsable frame. Args: name: Name to be in frame Returns: :class:`ui.Widget` connected with the setting on the path specified. """ return ui.CollapsableFrame(title=name, identifier=f"preferences_builder_{name}") def spacer(self) -> ui.Spacer: """ Create a UI spacer. Args: None Returns: :class:`ui.Widget` connected with the setting on the path specified. """ return ui.Spacer(height=10) def get_title(self) -> str: """ Gets the page title Args: None Returns: str name of the page """ return self._title def cleanup_slashes(self, path: str, is_directory: bool = False) -> str: """ Makes path/slashes uniform Args: path: path is_directory is path a directory, so final slash can be added Returns: path """ path = os.path.normpath(path) if is_directory: if path[-1] != "/": path += "/" return path.replace("\\", "/") class PageItem(ui.AbstractItem): """Single item of the model""" def __init__(self, pages): super().__init__() self.name = pages[0].get_title() self.name_model = ui.SimpleStringModel(self.name) self.pages = pages class PageModel(ui.AbstractItemModel): def __init__(self, page_list: List[str]): super().__init__() self._pages = [] for key in page_list: page = page_list[key] self._pages.append(PageItem(page)) self._item_changed(None) def get_item_children(self, item: PageItem) -> List[PageItem]: if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._pages def get_item_value_model_count(self, item: PageItem) -> int: """The number of columns""" return 1 def get_item_value_model(self, item: PageItem, column_id: int) -> ui.SimpleStringModel: if item and isinstance(item, PageItem): return item.name_model class PreferenceBuilderUI: def __init__(self, visibility_changed_fn: Callable): self._visibility_changed_fn = visibility_changed_fn self._active_page = "" self._treeview = None def destroy(self): ui.Workspace.set_show_window_fn(PreferenceBuilder.WINDOW_NAME, None) self._page_list = None self._pages_model = None self._visibility_changed_fn = None self._treeview = None del self._window def __del__(self): pass def update_page_list(self, page_list: List) -> None: """ Updates page list Args: page_list: list of pages Returns: None """ self._page_list = {} self._page_header = [] for page in page_list: if isinstance(page, PreferenceBuilder): if not page._title: self._page_header.append(page) elif not page._title in self._page_list: self._page_list[page.get_title()] = [page] else: self._page_list[page.get_title()].append(page) def create_window(self): """ Create omni.ui.window Args: None Returns: None """ def set_window_state(v): self._show_window(None, v) if v: self.rebuild_pages() self._treeview = None self._window = None ui.Workspace.set_show_window_fn(PreferenceBuilder.WINDOW_NAME, set_window_state) def _show_window(self, menu, value): if value: self._window = ui.Window(PreferenceBuilder.WINDOW_NAME, width=1000, height=600, dockPreference=ui.DockPreference.LEFT_BOTTOM) self._window.set_visibility_changed_fn(self._on_visibility_changed_fn) self._window.frame.set_style(get_style()) self._window.deferred_dock_in("Content") elif self._window: self._treeview = None self._window.destroy() self._window = None def rebuild_pages(self) -> None: """ Rebuilds window pages using current page list Args: None Returns: None """ self._pages_model = PageModel(self._page_list) full_list = self._pages_model.get_item_children(None) if not full_list or not self._window: return elif not self._active_page in self._page_list: self._active_page = next(iter(self._page_list)) def treeview_clicked(treeview): async def get_selection(): await omni.kit.app.get_app().next_update_async() if treeview.selection: selection = treeview.selection[0] self.set_active_page(selection.name) asyncio.ensure_future(get_selection()) with self._window.frame: prefs_style = {"ScrollingFrame::header": {"background_color": 0xFF444444}, "ScrollingFrame::header:hovered": {"background_color": 0xFF444444}, "ScrollingFrame::header:pressed": {"background_color": 0xFF444444}, "Button::global": {"color": cl("#34C7FF"), "margin": 0, "margin_width": 0, "padding": 5}, "Button.Label::global": {"color": cl("#34C7FF")}, "Button::global:hovered": {"background_color": 0xFF545454}, "Button::global:pressed": {"background_color": 0xFF555555}, } with ui.VStack(style=prefs_style, name="header"): if self._page_header: with ui.HStack(width=0, height=10): for page in self._page_header: page.build() ui.Spacer(height=3) with ui.HStack(): with ui.ScrollingFrame( width=175, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF ): if get_ui_style_name() == "NvidiaLight": FIELD_BACKGROUND = 0xFF545454 FIELD_TEXT_COLOR = 0xFFD6D6D6 else: FIELD_BACKGROUND = 0xFF23211F FIELD_TEXT_COLOR = 0xFFD5D5D5 self._treeview = ui.TreeView( self._pages_model, root_visible=False, header_visible=False, style={ "TreeView.Item": {"margin": 4}, "margin_width": 0.5, "margin_height": 0.5, "background_color": FIELD_BACKGROUND, "color": FIELD_TEXT_COLOR, }, ) if not self._treeview.selection and len(full_list) > 0: for page in full_list: if page.name == self._active_page: self._treeview.selection = [page] break selection = self._treeview.selection self._treeview.set_mouse_released_fn(lambda x, y, b, c, tv=self._treeview: treeview_clicked(tv)) with ui.VStack(): ui.Spacer(height=7) self._page_frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED ) if selection: self._build_page(selection[0].pages) def set_active_page(self, page_index: Union[int, str]) -> None: """ Set the given page index as the active one. Args: page_index: Index of page of the page list to set as the active one. Returns: None """ if isinstance(page_index, str): self._active_page = page_index else: for index, key in enumerate(self._page_list): if index == page_index: self._active_page = self._page_list[key].get_title() break # Build and display the list of preference widgets on the right-hand column of the panel: async def rebuild(): await omni.kit.app.get_app().next_update_async() self._build_page(self._page_list[self._active_page]) asyncio.ensure_future(rebuild()) # Select the title of the page on the left-hand column of the panel, acting as navigation tabs between the # Preference pages: if self._pages_model and self._treeview: for page in self._pages_model.get_item_children(None): if page.name == self._active_page: self._treeview.selection = [page] break def select_page(self, page: PreferenceBuilder) -> bool: """ If found, display the given Preference page and select its title in the TreeView. Args: page: One of the page from the list of pages. Returns: bool: A flag indicating if the given page was successfully selected. """ for key in self._page_list: items = self._page_list[key] for item in items: if item == page: self.set_active_page(item.get_title()) return True return False def _build_page(self, pages: List[PreferenceBuilder]) -> None: with self._page_frame: with ui.VStack(): for page in pages: page.build() if len(pages) > 1: ui.Spacer(height=7) def show_window(self) -> None: """ show window Args: None Returns: None """ if not self._window: self._show_window(None, True) self.rebuild_pages() def hide_window(self) -> None: """ hide window Args: None Returns: None """ if self._window: self._show_window(None, False) def _on_visibility_changed_fn(self, visible) -> None: self._visibility_changed_fn(visible) omni.kit.menu.utils.rebuild_menus()
15,348
Python
33.804989
137
0.537464
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/__init__.py
from .preferences_window import *
34
Python
16.499992
33
0.794118
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/preferences_window.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 typing import Callable import asyncio import carb import omni.ext from enum import IntFlag from .preference_builder import PreferenceBuilder, PreferenceBuilderUI, SettingType from .preferences_actions import register_actions, deregister_actions _extension_instance = None _preferences_page_list = [] PERSISTENT_SETTINGS_PREFIX = "/persistent" DEVELOPER_PREFERENCE_PATH = "/app/show_developer_preference_section" GLOBAL_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_globals" AUDIO_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_audio" RENDERING_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_rendering" RESOURCE_MONITOR_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_resource_monitor" TAGGING_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_tagging" class PreferencesExtension(omni.ext.IExt): class PreferencesState(IntFlag): Invalid = 0 Created = 1 def on_startup(self, ext_id): global _extension_instance _extension_instance = self self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name, PreferencesExtension, lambda: _extension_instance) self._hooks = [] self._ready_state = PreferencesExtension.PreferencesState.Invalid self._window = PreferenceBuilderUI(self._on_visibility_changed_fn) self._window.update_page_list(get_page_list()) self._window.create_window() self._window_is_visible = False self._create_menu() self._register_pages() self._resourcemonitor_preferences = None manager = omni.kit.app.get_app().get_extension_manager() if carb.settings.get_settings().get(RESOURCE_MONITOR_PREFERENCES_PATH): self._hooks.append( manager.subscribe_to_extension_enable( on_enable_fn=lambda _: self._register_resourcemonitor_preferences(), on_disable_fn=lambda _: self._unregister_resourcemonitor_preferences(), ext_name="omni.resourcemonitor", hook_name="omni.kit.window.preferences omni.resourcemonitor listener", ) ) # set app started trigger. refresh_menu_items & rebuild_menus won't do anything until self._ready_state is MenuState.Created self._app_ready_sub = ( omni.kit.app.get_app() .get_startup_event_stream() .create_subscription_to_pop_by_type( omni.kit.app.EVENT_APP_READY, self._rebuild_after_loading, name="omni.kit.menu.utils app started trigger" ) ) def on_shutdown(self): self._hooks = None deregister_actions(self._ext_name) self._window.destroy() del self._window self._window = None self._remove_menu() self._unregister_resourcemonitor_preferences() for page in self._created_preferences: unregister_page(page, rebuild=False) self._created_preferences = None # clear globals global _preferences_page_list _preferences_page_list = None global _extension_instance _extension_instance = None def _rebuild_after_loading(self, event): self._ready_state = PreferencesExtension.PreferencesState.Created self.rebuild_pages() def _register_pages(self): from .pages.stage_page import StagePreferences from .pages.rendering_page import RenderingPreferences from .pages.screenshot_page import ScreenshotPreferences from .pages.thumbnail_generation_page import ThumbnailGenerationPreferences from .pages.audio_page import AudioPreferences from .pages.tagging_page import TaggingPreferences from .pages.datetime_format_page import DatetimeFormatPreferences from .pages.globals import GlobalPreferences self._developer_preferences = None self._created_preferences = [] for page in [ ScreenshotPreferences(), ThumbnailGenerationPreferences(), StagePreferences(), DatetimeFormatPreferences(), ]: self._created_preferences.append(register_page(page)) if carb.settings.get_settings().get(GLOBAL_PREFERENCES_PATH): self._created_preferences.append(register_page(GlobalPreferences())) if carb.settings.get_settings().get(AUDIO_PREFERENCES_PATH): self._created_preferences.append(register_page(AudioPreferences())) if carb.settings.get_settings().get(RENDERING_PREFERENCES_PATH): self._created_preferences.append(register_page(RenderingPreferences())) if carb.settings.get_settings().get(TAGGING_PREFERENCES_PATH): self._created_preferences.append(register_page(TaggingPreferences())) # developer options self._hooks.append(carb.settings.get_settings().subscribe_to_node_change_events( DEVELOPER_PREFERENCE_PATH, self._on_developer_preference_section_changed )) self._on_developer_preference_section_changed(None, None) def _on_developer_preference_section_changed(self, item, event_type): if event_type == carb.settings.ChangeEventType.CHANGED: if carb.settings.get_settings().get(DEVELOPER_PREFERENCE_PATH): if not self._developer_preferences: from .pages.developer_page import DeveloperPreferences self._developer_preferences = register_page(DeveloperPreferences()) elif self._developer_preferences: self._developer_preferences = unregister_page(self._developer_preferences) def _register_resourcemonitor_preferences(self): from .pages.resourcemonitor_page import ResourceMonitorPreferences self._resourcemonitor_preferences = register_page(ResourceMonitorPreferences()) def _unregister_resourcemonitor_preferences(self): if self._resourcemonitor_preferences: unregister_page(self._resourcemonitor_preferences) self._resourcemonitor_preferences = None def rebuild_pages(self): if self._ready_state == PreferencesExtension.PreferencesState.Invalid: return if self._window: self._window.update_page_list(get_page_list()) self._window.rebuild_pages() def select_page(self, page): if self._window: if self._window.select_page(page): return True return False async def _refresh_menu_async(self): omni.kit.menu.utils.refresh_menu_items("Edit") self._refresh_menu_task = None def _on_visibility_changed_fn(self, visible): self._window_is_visible = visible if visible: self._window.show_window() else: self._window.hide_window() def _create_menu(self): from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder self._edit_menu_list = None self._refresh_menu_task = None self._edit_menu_list = [ MenuItemDescription( name="Preferences", glyph="cog.svg", appear_after=["Capture Screenshot", MenuItemOrder.LAST], ticked=True, ticked_fn=lambda: self._window_is_visible, onclick_action=("omni.kit.window.preferences", "toggle_preferences_window"), ), MenuItemDescription( appear_after=["Capture Screenshot", MenuItemOrder.LAST], ), ] omni.kit.menu.utils.add_menu_items(self._edit_menu_list, "Edit", -9) def _remove_menu(self): if self._refresh_menu_task: self._refresh_menu_task.cancel() self._refresh_menu_task = None # remove menu omni.kit.menu.utils.remove_menu_items(self._edit_menu_list, "Edit") def _toggle_preferences_window(self): self._window_is_visible = not self._window_is_visible async def show_windows(): if self._window_is_visible: self._window.show_window() else: self._window.hide_window() asyncio.ensure_future(show_windows()) asyncio.ensure_future(self._refresh_menu_async()) def show_preferences_window(self): """Show the Preferences window to the User.""" if not self._window_is_visible: self._toggle_preferences_window() def hide_preferences_window(self): """Hide the Preferences window from the User.""" if self._window_is_visible: self._toggle_preferences_window() def get_instance(): global _extension_instance return _extension_instance def show_preferences_window(): """Show the Preferences window to the User.""" get_instance().show_preferences_window() def hide_preferences_window(): """Hide the Preferences window from the User.""" get_instance().hide_preferences_window() def get_page_list(): global _preferences_page_list return _preferences_page_list def register_page(page): global _preferences_page_list _preferences_page_list.append(page) _preferences_page_list = sorted(_preferences_page_list, key=lambda page: page._title) get_instance().rebuild_pages() return page def select_page(page): return get_instance().select_page(page) def rebuild_pages(): get_instance().rebuild_pages() def unregister_page(page, rebuild: bool=True): global _preferences_page_list if hasattr(page, 'destroy'): page.destroy() # Explicitly clear properties, that helps to release some C++ objects page.__dict__.clear() if _preferences_page_list: _preferences_page_list.remove(page) preferences = get_instance() if preferences and rebuild: preferences.rebuild_pages() def show_file_importer( title: str, file_exts: list = [("All Files(*)", "")], filename_url: str = None, click_apply_fn: Callable = None, show_only_folders: bool = False, ): from functools import partial from omni.kit.window.file_importer import get_file_importer def on_import(click_fn: Callable, filename: str, dirname: str, selections=[]): dirname = dirname.strip() if dirname and not dirname.endswith("/"): dirname += "/" fullpath = f"{dirname}{filename}" if click_fn: click_fn(fullpath) file_importer = get_file_importer() if file_importer: file_importer.show_window( title=title, import_button_label="Select", import_handler=partial(on_import, click_apply_fn), file_extension_types=file_exts, filename_url=filename_url, # OM-96626: Add show_only_folders option to file importer show_only_folders=show_only_folders, )
11,373
Python
35.107936
132
0.652686
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/material_config_widget.py
import os import carb.settings import omni.kit.notification_manager as nm import omni.ui as ui from omni.ui import color as cl from . import material_config_utils class EditableListItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) class EditableListItemDelegate(ui.AbstractItemDelegate): _ITEM_LABEL_STYLE = { "margin": 3, "font_size": 16.0, ":selected": { "color": cl("#333333") } } _DELETE_BUTTON_STYLE = { "margin": 2, "padding": 0, "": { "image_url": "", "alignment": ui.Alignment.CENTER, "background_color": 0x00000000 }, ":hovered": { "image_url": "resources/glyphs/trash.svg", "color": cl("#cccccc"), "background_color": 0x00000000 }, ":selected": { "image_url": "resources/glyphs/trash.svg", "color": cl("#cccccc"), "background_color": 0x00000000 } } def build_widget(self, model, item, column_id, level, expanded): with ui.ZStack(height=20): value_model = model.get_item_value_model(item, column_id) if column_id == 0: # entry text label = ui.Label(value_model.as_string, style=self._ITEM_LABEL_STYLE) field = ui.StringField() field.model = value_model field.visible = False label.set_mouse_double_clicked_fn( lambda x, y, b, m, f=field, l=label: self.on_label_double_click(b, f, l) ) elif column_id == 1: # remove button with ui.HStack(): ui.Spacer() button = ui.Button(width=20, style=self._DELETE_BUTTON_STYLE) button.set_clicked_fn(lambda i=item, m=model: self.on_button_clicked(i, m)) ui.Spacer(width=5) else: pass def on_label_double_click(self, mouse_button, field, label): if mouse_button != 0: return field.visible = True field.focus_keyboard() self.subscription = field.model.subscribe_end_edit_fn( lambda m, f=field, l=label: self.on_field_end_edit(m, f, l) ) def on_field_end_edit(self, model, field, label): field.visible = False if model.as_string: # avoid empty string label.text = model.as_string self.subscription = None def on_button_clicked(self, item, model): model.remove_item(item) class EditableListModel(ui.AbstractItemModel): def __init__( self, item_class=EditableListItem, setting_path=None ): super().__init__() self._settings = carb.settings.get_settings() self._setting_path = setting_path self._item_class = item_class self._items = [] self.populate_items() def populate_items(self): entries = self._settings.get(self._setting_path) if not entries: entries = [] self._items.clear() for entry in entries: if not entry: continue self._items.append(self._item_class(entry)) self._item_changed(None) def get_item_children(self, item): if item is not None: return [] return self._items def get_item_value_model_count(self, item): return 2 def get_item_value_model(self, item, column_id): if item and isinstance(item, self._item_class): if column_id == 0: return item.name_model else: return None def get_drag_mime_data(self, item): return item.name_model.as_string def drop_accepted(self, target_item, source, drop_location=1): return not target_item and drop_location >= 0 def drop(self, target_item, source, drop_location=-1): try: source_id = self._items.index(source) except ValueError: return if source_id == drop_location: return self._items.remove(source) if drop_location > len(self._items): self._items.append(source) else: if source_id < drop_location: drop_location = drop_location - 1 self._items.insert(drop_location, source) self._item_changed(None) def add_entry(self, text): self._items.insert(0, self._item_class(text)) self._item_changed(None) def remove_item(self, item): self._items.remove(item) self._item_changed(None) def save_entries_to_settings(self): entries = [item.name_model.as_string for item in self._items] self._settings.set(self._setting_path, entries) def save_to_material_config_file(self): material_config_utils.save_live_config_to_file() class EditableListWidget(ui.Widget): _ADD_BUTTON_STYLE = { "image_url": "resources/glyphs/plus.svg", "color": cl("#cccccc") } def __init__( self, model_class=EditableListModel, item_delegate_class=EditableListItemDelegate, setting_path=None, list_height=100 ): super(EditableListWidget).__init__() self._model = model_class(setting_path=setting_path) self._delegate = item_delegate_class() # build UI with ui.VStack(): with ui.HStack(): # list widget with ui.ScrollingFrame(height=list_height): ui.Spacer(height=5) self._view = ui.TreeView( self._model, delegate=self._delegate, header_visible=False, root_visible=False, column_widths=[ui.Percent(95)], drop_between_items=True ) self._view.set_selection_changed_fn(self.on_item_selection_changed) ui.Spacer(width=5) # "+" button self._add_new_entry_button = ui.Button( width=20, height=20, style=self._ADD_BUTTON_STYLE, clicked_fn=self.on_add_new_entry_button_clicked ) ui.Spacer(height=5) with ui.HStack(): ui.Spacer() # save button self._save_button = ui.Button( "Save", width=100, height=0, clicked_fn=self.on_save_button_clicked ) ui.Spacer(width=5) # reset button self._reset_button = ui.Button( "Reset", width=100, height=0, clicked_fn=self.on_reset_button_clicked ) ui.Spacer(width=25) def on_add_new_entry_button_clicked(self): self._view.clear_selection() self._model.add_entry("New Entry") def on_item_selection_changed(self, items): # not to allow multi-selection num_items = len(items) if num_items > 1: for i in range(1, num_items): self._view.toggle_selection(items[i]) def on_save_button_clicked(self): self._model.save_entries_to_settings() config_file = material_config_utils.get_config_file_path() if not os.path.exists(config_file): ok_button = nm.NotificationButtonInfo( "OK", on_complete=self._model.save_to_material_config_file ) cancel_button = nm.NotificationButtonInfo( "Cancel", on_complete=None ) nm.post_notification( f"Material config file does not exist. Create?\n\n{config_file}", status=nm.NotificationStatus.INFO, button_infos=[ok_button, cancel_button], hide_after_timeout=False ) else: self._model.save_to_material_config_file() def on_reset_button_clicked(self): self._view.clear_selection() self._model.populate_items()
8,497
Python
29.134752
95
0.520184
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/preferences_actions.py
import omni.kit.actions.core def register_actions(extension_id, cls, get_self_fn): action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "Window Preferences Actions" # actions action_registry.register_action( extension_id, "show_preferences_window", get_self_fn().show_preferences_window, display_name="Show Preferences Window", description="Show Preferences Window", tag=actions_tag, ) action_registry.register_action( extension_id, "hide_preferences_window", get_self_fn().hide_preferences_window, display_name="Hide Preferences Window", description="Hide Preferences Window", tag=actions_tag, ) action_registry.register_action( extension_id, "toggle_preferences_window", get_self_fn()._toggle_preferences_window, display_name="Toggle Preferences Window", description="Toggle Preferences Window", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
1,202
Python
29.074999
70
0.666389
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/material_path_widget.py
import os import pathlib import carb import carb.settings import omni.kit.notification_manager as nm import omni.ui as ui from omni.kit.window.filepicker import FilePickerDialog from omni.mdl import pymdlsdk from omni.ui import color as cl from . import material_config_utils from . material_config_widget import EditableListItemDelegate, EditableListModel, EditableListWidget class MdlPathItem(ui.AbstractItem): def __init__(self, text): super().__init__() text = pathlib.PurePath(text).as_posix() self.name_model = ui.SimpleStringModel(text) class MdlDefaultPathListModel(ui.AbstractItemModel): SOURCE_MDL_SYSTEM_PATH = 0 SOURCE_MDL_USER_PATH = 1 SOURCE_ADDITIONAL_SYSTEM_PATHS = 2 SOURCE_ADDITIONAL_USER_PATHS = 3 SOURCE_RENDERER_REQUIRED = 4 SOURCE_RENDERER_TEMPLATES = 5 def __init__(self, mode): super().__init__() self._SETTING_NAME_MAP = { self.SOURCE_ADDITIONAL_SYSTEM_PATHS: "/app/mdl/additionalSystemPaths", self.SOURCE_ADDITIONAL_USER_PATHS: "/app/mdl/additionalUserPaths", self.SOURCE_RENDERER_REQUIRED: "/renderer/mdl/searchPaths/required", self.SOURCE_RENDERER_TEMPLATES: "/renderer/mdl/searchPaths/templates" } _FN_MAP = { self.SOURCE_MDL_SYSTEM_PATH: self._get_paths_from_mdl_config, self.SOURCE_MDL_USER_PATH: self._get_paths_from_mdl_config, self.SOURCE_ADDITIONAL_SYSTEM_PATHS: self._get_paths_from_setting, self.SOURCE_ADDITIONAL_USER_PATHS: self._get_paths_from_setting, self.SOURCE_RENDERER_REQUIRED: self._get_paths_from_setting, self.SOURCE_RENDERER_TEMPLATES: self._get_paths_from_setting } self._items = [] paths = _FN_MAP[mode](mode) for path in paths: self._items.append(MdlPathItem(path)) def _get_omni_neuray_api(self): import omni.mdl.neuraylib neuraylib = omni.mdl.neuraylib.get_neuraylib() ineuray = neuraylib.getNeurayAPI() neuray = pymdlsdk.attach_ineuray(ineuray) return neuray def _get_paths_from_mdl_config(self, mode): neuray = self._get_omni_neuray_api() paths = [] with neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg: if mode == self.SOURCE_MDL_SYSTEM_PATH: num_paths = cfg.get_mdl_system_paths_length() if num_paths: for i in range(0, num_paths): paths.append(cfg.get_mdl_system_path(i)) elif mode == self.SOURCE_MDL_USER_PATH: num_paths = cfg.get_mdl_user_paths_length() if num_paths: for i in range(0, num_paths): paths.append(cfg.get_mdl_user_path(i)) else: pass return paths def _get_paths_from_setting(self, mode): settings = carb.settings.get_settings() pathStr = settings.get(self._SETTING_NAME_MAP[mode]) paths = [] if pathStr: paths = pathStr.split(";") return paths def get_item_children(self, item): if item is not None: return [] return self._items def get_item_value_model_count(self, item): return 1 def get_item_value_model(self, item, column_id): if item and isinstance(item, MdlPathItem): return item.name_model def get_items(self): return self._items class MdlDefaultPathListWidget(ui.Widget): _TREEVIEW_STYLE = { "TreeView.Item": { "margin": 3, "font_size": 16.0, "color": cl("#777777") } } _FRAME_STYLE = { "CollapsableFrame": { "margin": 0, "padding": 3, "border_width": 0, "border_radius": 0, "secondary_color": cl("#2c2e2e") } } def __init__(self, **kwargs): super(MdlDefaultPathListWidget).__init__() self._models = {} entries = [ ["Standard System Paths", MdlDefaultPathListModel.SOURCE_MDL_SYSTEM_PATH], ["Additional System Paths", MdlDefaultPathListModel.SOURCE_ADDITIONAL_SYSTEM_PATHS], ["Standard User Paths", MdlDefaultPathListModel.SOURCE_MDL_USER_PATH], ["Additional User Paths", MdlDefaultPathListModel.SOURCE_ADDITIONAL_USER_PATHS], ["Renderer Required", MdlDefaultPathListModel.SOURCE_RENDERER_REQUIRED], ["Renderer Templates", MdlDefaultPathListModel.SOURCE_RENDERER_TEMPLATES] ] with ui.VStack(height=0): for entry in entries: model = MdlDefaultPathListModel(entry[1]) if not model.get_items(): continue # do not add widget if it is empty self._add_path_list_widget(entry[0], model) self._models[entry[1]] = model def _add_path_list_widget(self, title, model): with ui.CollapsableFrame(title, collapsed=True, style=self._FRAME_STYLE): with ui.ScrollingFrame(height=100): view = ui.TreeView( model, header_visible=False, root_visible=False, style=self._TREEVIEW_STYLE ) # do not allow select items view.set_selection_changed_fn(lambda i: view.clear_selection()) class MdlLocalPathListModel(EditableListModel): def __init__(self, setting_path): super().__init__( MdlPathItem, setting_path ) def populate_items(self): pathStr = self._settings.get(self._setting_path) paths = pathStr.split(";") if pathStr else [] self._items.clear() for path in paths: if not path: continue self._items.append(self._item_class(path)) self._item_changed(None) def find_path(self, path): pp = pathlib.PurePath(path) for item in self._items: ip = pathlib.PurePath(item.name_model.as_string) if pp == ip: return ip.as_posix() return "" def sanity_check_paths(self): bad_paths = [] for item in self._items: path = item.name_model.as_string if not os.path.exists(path): bad_paths.append(path) return bad_paths def save_entries_to_settings(self): pathStrs = [item.name_model.as_string for item in self._items] pathStr = ";".join(pathStrs) self._settings.set(self._setting_path, pathStr) def save_to_material_config_file(self): material_config_utils.save_carb_setting_to_config_file( "/app/mdl/nostdpath", "/options/noStandardPath" ) material_config_utils.save_carb_setting_to_config_file( self._setting_path, "/searchPaths/local", is_paths=True ) class MdlLocalPathListWidget(EditableListWidget): def __init__(self): super().__init__( MdlLocalPathListModel, EditableListItemDelegate, "/renderer/mdl/searchPaths/local", 150 ) self._file_picker_selection = None self._file_picker = FilePickerDialog( "Add New Search Path", allow_multi_selection=False, apply_button_label="Select", selection_changed_fn=self.on_file_picker_selection_changed, click_apply_handler=lambda f, d: self.on_file_picker_apply_clicked(), click_cancel_handler=None ) self._file_picker.hide() def on_file_picker_selection_changed(self, items): # this is a workaround for that FilePickerDialog has a bug that # the selection does not get updated if user select a directory if items: self._file_picker_selection = items[0].path def on_file_picker_apply_clicked(self): if self._model.find_path(self._file_picker_selection): nm.post_notification( "Path already exists in the list.", status=nm.NotificationStatus.INFO, hide_after_timeout=False ) return self._model.add_entry(self._file_picker_selection) self._file_picker.hide() def on_add_new_entry_button_clicked(self): self._view.clear_selection() self._file_picker.show() def on_save_button_clicked(self): bad_paths = self._model.sanity_check_paths() if bad_paths: paths = "\n".join(bad_paths) ok_button = nm.NotificationButtonInfo( "OK", on_complete=lambda: self.save_settings_and_config_file() ) cancel_button = nm.NotificationButtonInfo( "Cancel", on_complete=None ) nm.post_notification( f"Path(s) below do not exist. Continue?\n\n{paths}", status=nm.NotificationStatus.WARNING, button_infos=[ok_button, cancel_button], hide_after_timeout=False ) else: self.save_settings_and_config_file() def save_settings_and_config_file(self): self._model.save_entries_to_settings() config_file = material_config_utils.get_config_file_path() if not os.path.exists(config_file): ok_button = nm.NotificationButtonInfo( "OK", on_complete=self._model.save_to_material_config_file ) cancel_button = nm.NotificationButtonInfo( "Cancel", on_complete=None ) nm.post_notification( f"Material config file does not exist. Create?\n\n{config_file}", status=nm.NotificationStatus.INFO, button_infos=[ok_button, cancel_button], hide_after_timeout=False ) else: self._model.save_to_material_config_file() carb.log_info(f"Material config file saved: {config_file}")
10,259
Python
32.420195
100
0.573253
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/material_config_utils.py
import os import posixpath # import platform import pathlib import copy import toml import carb import carb.settings SETTING_BUILTINALLOWLIST = "/materialConfig/materialGraph/builtInAllowList" SETTING_BUILTINBLOCKLIST = "/materialConfig/materialGraph/builtInBlockList" SETTING_USERALLOWLIST = "/materialConfig/materialGraph/userAllowList" SETTING_USERBLOCKLIST = "/materialConfig/materialGraph/userBlockList" def _key_value_to_dict(key, value): # "/path/to/key", <value> -> {"path": {"to": {"key": <value>}}} tokens = key.split('/') tokens = list(filter(None, tokens)) # filter empty strings dct = value for token in reversed(tokens): dct = {token: dct} return dct def _merge_dict(dict1, dict2): merged = copy.deepcopy(dict1) for k2, v2 in dict2.items(): v1 = merged.get(k2) if isinstance(v1, dict) and isinstance(v2, dict): merged[k2] = _merge_dict(v1, v2) else: merged[k2] = copy.deepcopy(v2) return merged def get_default_config_file_path(): try: home_dir = pathlib.Path.home() except Exception as e: carb.log_error(str(e)) return "" config_file_path = home_dir / "Documents/Kit/shared" / "material.config.toml" config_file_path = config_file_path.as_posix() return str(config_file_path) def get_config_file_path(): settings = carb.settings.get_settings() file_path = settings.get('/materialConfig/configFilePath') if not file_path or not os.path.exists(file_path): file_path = get_default_config_file_path() return file_path def load_config_file(file_path): config = {} try: if os.path.exists(file_path): config = toml.load(file_path) except Exception as e: carb.log_error(str(e)) return config def save_config_file(config, file_path): # this setting should not be saved in file config.pop("configFilePath", None) try: toml_str = toml.dumps(config) # least prettify format toml_str = toml_str.replace(",", ",\n") toml_str = toml_str.replace("[ ", "[\n ") with open(file_path, "w") as f: f.write(toml_str) except Exception as e: carb.log_error(str(e)) return False return True def save_carb_setting_to_config_file(carb_setting_key, config_key, is_paths=False, non_standard_path=None): try: # get value from carb setting settings = carb.settings.get_settings() value = settings.get(carb_setting_key) if is_paths: value = value.split(";") if value else [] value = list(filter(None, value)) # remove empty strings # load config from file file_path = pathlib.Path(non_standard_path if non_standard_path else get_config_file_path()) if not file_path.exists(): file_path.touch() config = load_config_file(file_path) # deep merge configs new_config = _key_value_to_dict(config_key, value) merged_config = _merge_dict(config, new_config) # save config to file save_config_file(merged_config, file_path) except Exception as e: carb.log_error(str(e)) return False return True def save_live_config_to_file(non_standard_path=None): try: # get live material config from carb setting settings = carb.settings.get_settings() live_config = settings.get("/materialConfig") # save config to file file_path = pathlib.Path(non_standard_path if non_standard_path else get_config_file_path()) save_config_file(live_config, file_path) except Exception as e: carb.log_error(str(e)) return False return True
3,771
Python
25.194444
107
0.631132
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/screenshot_page.py
import os import carb.settings import omni.ui as ui from ..preferences_window import PreferenceBuilder, show_file_importer, PERSISTENT_SETTINGS_PREFIX, SettingType class ScreenshotPreferences(PreferenceBuilder): def __init__(self): super().__init__("Capture Screenshot") self._settings = carb.settings.get_settings() # setup captureFrame paths template_path = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path") if template_path is None or template_path == "./": template_path = self._settings.get("/app/captureFrame/path") if template_path[-1] != "/": template_path += "/" self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path", template_path) # 3D viewport self._settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/viewport", False) # ansel defaults if self._is_ansel_enabled(): ansel_quality_path = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/quality" self._settings.set_default_string(ansel_quality_path, "Medium") ansel_super_resolution_size_path = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/superResolution/size" self._settings.set_default_string(ansel_super_resolution_size_path, "2x") # create captureFrame directory original_umask = os.umask(0) if not os.path.isdir(template_path): try: os.makedirs(template_path) except Exception: carb.log_error(f"Failed to create directory {template_path}") os.umask(original_umask) def build(self): """ Capture Screenshot """ # The path widget. It's not standard because it has the button browse. Since the main layout has two columns, # we need to create another layout and put it to the main one. with ui.VStack(height=0): with self.add_frame("Capture Screenshot"): with ui.VStack(): self._settings_widget = self.create_setting_widget( "Path to save screenshots", PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path", SettingType.STRING, clicked_fn=self._on_browse_button_fn, ) self.create_setting_widget( "Capture only the 3D viewport", PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/viewport", SettingType.BOOL, ) # Show Ansel super resolution configuration, only when Ansel enabled self._create_ansel_super_resolution_settings() def _add_ansel_settings(self): # check if Ansel enabled. If not, do not show Ansel settings if not self._is_ansel_enabled(): return self.create_setting_widget_combo( "Quality", PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/quality", ["Low", "Medium", "High"] ) def _create_ansel_super_resolution_settings(self): # check if Ansel enabled. If not, do not show Ansel settings if not self._is_ansel_enabled(): return self.spacer() with self.add_frame("Super Resolution"): with ui.VStack(): self.create_setting_widget_combo( "Size", PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/superResolution/size", ["2x", "4x", "8x", "16x", "32x"], ) self._add_ansel_settings() def _is_ansel_enabled(self): return self._settings.get("/exts/omni.ansel/enable") def _on_browse_button_fn(self, owner): """ Called when the user picks the Browse button. """ navigate_to = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path") show_file_importer("Select Screenshot Directory", click_apply_fn=self._on_dir_pick, filename_url=navigate_to, show_only_folders=True) def _on_dir_pick(self, real_path): """ Called when the user accepts directory in the Select Directory dialog. """ directory = self.cleanup_slashes(real_path, is_directory=True) self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path", directory) self._settings_widget.model.set_value(directory)
4,486
Python
42.990196
117
0.596745
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/globals.py
import asyncio import carb.settings import omni.kit.app import omni.ui as ui from ..preferences_window import PreferenceBuilder class GlobalPreferences(PreferenceBuilder): def __init__(self): super().__init__("") def build(self): async def on_ok_clicked(dialog): import sys import carb.events import omni.kit.app dialog.hide() def run_process(args): import subprocess import platform kwargs = {"close_fds": False} if platform.system().lower() == "windows": kwargs["creationflags"] = subprocess.CREATE_NEW_CONSOLE | subprocess.CREATE_NEW_PROCESS_GROUP subprocess.Popen(args, **kwargs) # pylint: disable=consider-using-with def on_event(e: carb.events.IEvent): if e.type == omni.kit.app.PRE_SHUTDOWN_EVENT_TYPE: run_process(sys.argv + ["--reset-user"]) self._shutdown_sub = omni.kit.app.get_app().get_shutdown_event_stream().create_subscription_to_pop(on_event, name="preferences re-start", order=0) await omni.kit.app.get_app().next_update_async() omni.kit.app.get_app().post_quit() def reset_clicked(): from omni.kit.window.popup_dialog import MessageDialog if omni.usd.get_context().has_pending_edit(): dialog = MessageDialog( title= f"{omni.kit.ui.get_custom_glyph_code('${glyphs}/exclamation.svg')} Reset to Default Settings", width=400, message=f"This application will restart to remove all custom settings and restore the application to the installed state.\n\nYou will be prompted to save any unsaved changes.", ok_handler=lambda dialog: asyncio.ensure_future(on_ok_clicked(dialog)), ok_label="Continue", cancel_label="Cancel", ) else: dialog = MessageDialog( title= f"{omni.kit.ui.get_custom_glyph_code('${glyphs}/exclamation.svg')} Reset to Default Settings", width=400, message=f"This application will restart to remove all custom settings and restore the application to the installed state.", ok_handler=lambda dialog: asyncio.ensure_future(on_ok_clicked(dialog)), ok_label="Restart", cancel_label="Cancel", ) dialog.show() ui.Button("Reset to Default", clicked_fn=reset_clicked, name="global", tooltip="This will reset all settings back to the installed state after the application is restarted") def __del__(self): super().__del__()
2,806
Python
42.859374
196
0.581254
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/thumbnail_generation_page.py
import carb.settings import omni.ui as ui from ..preferences_window import PreferenceBuilder, show_file_importer, PERSISTENT_SETTINGS_PREFIX, SettingType MDL_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_thumbnail_generation_mdl" def set_default_usd_thumbnail_generator_settings(): """Setup default value for the setting of the USD Thumbnail Generator""" settings = carb.settings.get_settings() settings.set_default_int("/app/thumbnailsGenerator/usd/width", 256) settings.set_default_int("/app/thumbnailsGenerator/usd/height", 256) settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/renderer", "RayTracing") settings.set_default_int(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/iterations", 8) settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.thumbnails.usd/thumbnail_on_save", True) def set_default_mdl_thumbnail_generator_settings(): """Setup default value for the setting of the MDL Thumbnail Generator""" settings = carb.settings.get_settings() settings.set_default_int("/app/thumbnailsGenerator/mdl/width", 256) settings.set_default_int("/app/thumbnailsGenerator/mdl/height", 256) settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/renderer", "PathTracing") settings.set_default_int(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/iterations", 512) template_url = "/Library/AEC/Materials/Library_Default.thumbnail.usd" settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/usd_template_path", template_url ) settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/standin_usd_path", "/Stage/ShaderKnob" ) class ThumbnailGenerationPreferences(PreferenceBuilder): def __init__(self): super().__init__("Thumbnail Generation") self._settings = carb.settings.get_settings() # default_settings set_default_usd_thumbnail_generator_settings() set_default_mdl_thumbnail_generator_settings() def build(self): """Thumbnail Generation""" with ui.VStack(height=0): if carb.settings.get_settings().get(MDL_PREFERENCES_PATH): with self.add_frame("MDL Thumbnail Generation Settings"): with ui.VStack(): self._settings_widget = self.create_setting_widget( "Path usd template to render MDL Thumnail", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/usd_template_path", SettingType.STRING, clicked_fn=self._on_browse_button_fn, ) self.create_setting_widget( "Name of the standin Prim", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/standin_usd_path", SettingType.STRING, ) self.create_setting_widget_combo( "Renderer Type", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/renderer", ["RayTracing", "PathTracing"], ) self.create_setting_widget( "Rendering Samples", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/iterations", SettingType.INT, ) self.spacer() with self.add_frame("USD Thumbnail Generation Settings"): with ui.VStack(): self.create_setting_widget_combo( "Renderer Type", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/renderer", ["RayTracing", "PathTracing"], ) self.create_setting_widget( "Rendering Samples", PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/iterations", SettingType.INT, ) self.create_setting_widget( "Save usd thumbnail on save", PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.thumbnails.usd/thumbnail_on_save", SettingType.BOOL, ) def _on_browse_button_fn(self, owner): """Called when the user picks the Browse button.""" path = self._settings_widget.model.get_value_as_string() show_file_importer(title="Select Template", click_apply_fn=self._on_file_pick, filename_url=path) def _on_file_pick(self, full_path): """Called when the user accepts directory in the Select Directory dialog.""" self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/usd_template_path", full_path) self._settings_widget.model.set_value(full_path)
5,142
Python
48.932038
116
0.6021
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/usdskel_page.py
import carb.settings import omni.kit.app from functools import partial from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType class UsdSkelPreferences(PreferenceBuilder): def __init__(self): super().__init__("UsdSkel") self._update_setting = {} settings = carb.settings.get_settings() if settings.get(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter", True ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape", True ) def build(self): import omni.ui as ui with ui.VStack(height=0): with self.add_frame("UsdSkel"): with ui.VStack(): self.create_setting_widget( "Enable BlendShape", PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape", SettingType.BOOL, tooltip="Enable BlendShape. Will be effective on the next stage load.", ) def _on_enable_blendshape_change(item, event_type, owner): if event_type == carb.settings.ChangeEventType.CHANGED: settings = carb.settings.get_settings() if settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape"): if not settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter"): settings.set_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter", True) self._update_setting["Enable BlendShape"] = omni.kit.app.SettingChangeSubscription( PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape", partial(_on_enable_blendshape_change, owner=self), ) def __del__(self): super().__del__() self._update_setting = {}
2,310
Python
40.267856
120
0.577056
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/material_page.py
import carb.settings import omni.kit.app import omni.ui as ui from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType from ..material_config_utils import SETTING_USERALLOWLIST, SETTING_USERBLOCKLIST from ..material_config_widget import EditableListWidget from ..material_path_widget import MdlDefaultPathListWidget from ..material_path_widget import MdlLocalPathListWidget class MaterialPreferences(PreferenceBuilder): def __init__(self): super().__init__("Material") settings = carb.settings.get_settings() self._sub_render_context = omni.kit.app.SettingChangeSubscription( PERSISTENT_SETTINGS_PREFIX + "/app/hydra/material/renderContext", self._on_render_context_changed ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath") is None: settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "Relative") if settings.get("/app/mdl/nostdpath") is None: settings.set_default_bool("/app/mdl/nostdpath", False) PreferenceBuilder.__init__(self, "Material") def build(self): """ Material """ with ui.VStack(height=0): """ Material """ with self.add_frame("Material"): with ui.VStack(): self.create_setting_widget_combo( "Binding Strength", PERSISTENT_SETTINGS_PREFIX + "/app/stage/materialStrength", ["weakerThanDescendants", "strongerThanDescendants"], ) self.create_setting_widget_combo( "Drag/Drop Path", PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", ["Absolute", "Relative"], ) self.create_setting_widget_combo( "Render Context / Material Network (Requires Stage Reload)", PERSISTENT_SETTINGS_PREFIX + "/app/hydra/material/renderContext", {"default": "", "mdl": "mdl"}, ) self.spacer() """ Material Search Path """ with self.add_frame("Material Search Path"): with ui.VStack(height=0): """ Default Paths """ default_path_frame = self.add_frame("Default Paths") # default_path_frame.collapsed = True default_path_frame.collapsed = False with default_path_frame: with ui.VStack(): self.create_setting_widget( "Ignore Standard Paths", "/app/mdl/nostdpath", SettingType.BOOL ) self.spacer() with ui.HStack(): ui.Spacer(width=5) self._mdl_default_paths = MdlDefaultPathListWidget() self.spacer() """ Local Paths """ with self.add_frame("Local Paths"): self._mdl_local_paths = MdlLocalPathListWidget() self.spacer() """ Material Graph """ if self._isExtensionEnabled("omni.kit.window.material_graph"): with self.add_frame("Material Graph"): with ui.VStack(height=0): """ User Allow List """ user_allow_list_frame = self.add_frame("User Allow List") with user_allow_list_frame: self._user_allow_list_widget = EditableListWidget(setting_path=SETTING_USERALLOWLIST) self.spacer() """ User Block List """ user_block_list_frame = self.add_frame("User Block List") with user_block_list_frame: self._user_block_list_widget = EditableListWidget(setting_path=SETTING_USERBLOCKLIST) def _isExtensionEnabled(self, name): manager = omni.kit.app.get_app().get_extension_manager() for ext in manager.get_extensions(): if ext["name"] == name and ext["enabled"] == True: return True return False def _on_render_context_changed(self, value: str, event_type: carb.settings.ChangeEventType): import omni.usd if event_type == carb.settings.ChangeEventType.CHANGED: stage = omni.usd.get_context().get_stage() if not stage or stage.GetRootLayer().anonymous: return msg = "Material render context has been changed. You will need to reload your stage for this to take effect." try: import asyncio import omni.kit.notification_manager import omni.kit.app async def show_msg(): await omni.kit.app.get_app().next_update_async() omni.kit.notification_manager.post_notification(msg, hide_after_timeout=False) asyncio.ensure_future(show_msg()) except: carb.log_warn(msg)
5,435
Python
42.488
121
0.529899
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/resourcemonitor_page.py
import omni.ui as ui from ..preferences_window import PreferenceBuilder, SettingType class ResourceMonitorPreferences(PreferenceBuilder): def __init__(self): super().__init__("Resource Monitor") def build(self): """ Resource Monitor """ try: import omni.resourcemonitor as rm with ui.VStack(height=0): with self.add_frame("Resource Monitor"): with ui.VStack(): self.create_setting_widget( "Time Between Queries", rm.timeBetweenQueriesSettingName, SettingType.FLOAT, ) self.create_setting_widget( "Send Device Memory Warnings", rm.sendDeviceMemoryWarningSettingName, SettingType.BOOL, ) self.create_setting_widget( "Device Memory Warning Threshold (MB)", rm.deviceMemoryWarnMBSettingName, SettingType.INT, ) self.create_setting_widget( "Device Memory Warning Threshold (Fraction)", rm.deviceMemoryWarnFractionSettingName, SettingType.FLOAT, range_from=0., range_to=1., ) self.create_setting_widget( "Send Host Memory Warnings", rm.sendHostMemoryWarningSettingName, SettingType.BOOL ) self.create_setting_widget( "Host Memory Warning Threshold (MB)", rm.hostMemoryWarnMBSettingName, SettingType.INT, ) self.create_setting_widget( "Host Memory Warning Threshold (Fraction)", rm.hostMemoryWarnFractionSettingName, SettingType.FLOAT, range_from=0., range_to=1., ) except ImportError: pass
2,435
Python
41.736841
73
0.420534
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/datetime_format_page.py
import carb.settings import omni.kit.app from functools import partial from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX class DatetimeFormatPreferences(PreferenceBuilder): def __init__(self): super().__init__("Datetime Format") settings = carb.settings.get_settings() if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/datetime/format") is None: settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/datetime/format", "MM/DD/YYYY") def build(self): import omni.ui as ui # OM-38343: allow user to switching between different date formats with ui.VStack(height=0): with self.add_frame("Datetime Format"): self.create_setting_widget_combo( "Display Date As", PERSISTENT_SETTINGS_PREFIX + "/app/datetime/format", [ "MM/DD/YYYY", "DD.MM.YYYY", "DD-MM-YYYY", "YYYY-MM-DD", "YYYY/MM/DD", "YYYY.MM.DD" ] ) def __del__(self): super().__del__()
1,232
Python
32.324323
106
0.529221
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/developer_page.py
import carb import carb.settings import omni.kit.app import omni.ui as ui from ..preferences_window import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX from typing import Any from typing import Dict from typing import Optional THREAD_SYNC_PRESETS = [ ( "No Pacing", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 120, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": False, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 120, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 120, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": False, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 120, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": False, "/app/runLoopsGlobal/syncToPresent": False, "/app/vsync": False, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": False, "/persistent/app/viewport/defaults/tickRate": 120, "/rtx-transient/dlssg/enabled": True, }, ), ( "30x2", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 60, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": True, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 60, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 30, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": True, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 30, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": True, "/app/runLoopsGlobal/syncToPresent": True, "/app/vsync": True, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": True, "/persistent/app/viewport/defaults/tickRate": 30, "/rtx-transient/dlssg/enabled": True, }, ), ( "60", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 60, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": True, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 60, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 60, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": True, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 60, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": True, "/app/runLoopsGlobal/syncToPresent": True, "/app/vsync": True, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": True, "/persistent/app/viewport/defaults/tickRate": 60, "/rtx-transient/dlssg/enabled": False, }, ), ( "60x2", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 60, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": True, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 120, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 60, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": True, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 60, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": True, "/app/runLoopsGlobal/syncToPresent": True, "/app/vsync": True, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": True, "/persistent/app/viewport/defaults/tickRate": 60, "/rtx-transient/dlssg/enabled": True, }, ), ( "120", { "/app/runLoops/main/rateLimitEnabled": True, "/app/runLoops/main/rateLimitFrequency": 120, "/app/runLoops/main/rateLimitUsePrecisionSleep": True, "/app/runLoops/main/syncToPresent": True, "/app/runLoops/present/rateLimitEnabled": True, "/app/runLoops/present/rateLimitFrequency": 120, "/app/runLoops/present/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/rateLimitEnabled": True, "/app/runLoops/rendering_0/rateLimitFrequency": 120, "/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_0/syncToPresent": True, "/app/runLoops/rendering_1/rateLimitEnabled": True, "/app/runLoops/rendering_1/rateLimitFrequency": 120, "/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True, "/app/runLoops/rendering_1/syncToPresent": True, "/app/runLoopsGlobal/syncToPresent": True, "/app/vsync": True, "/exts/omni.kit.renderer.core/present/enabled": True, "/exts/omni.kit.renderer.core/present/presentAfterRendering": True, "/persistent/app/viewport/defaults/tickRate": 120, "/rtx-transient/dlssg/enabled": False, }, ), ] class ThreadSyncPresets: def __init__(self): # Get all the settings to watch names = [] paths = set() for name, setting in THREAD_SYNC_PRESETS: names.append(name) for key, default in setting.items(): paths.add(key) self._settings = carb.settings.get_settings() self._subscriptions = [] for path in paths: self._subscriptions.append(self._settings.subscribe_to_node_change_events(path, self._on_setting_changed)) combo = ui.ComboBox(*([0, ""] + names), height=0) self._model = combo.model self._sub = self._model.subscribe_item_changed_fn(self._on_model_changed) def _on_setting_changed(self, item, event_type): for name, setting in THREAD_SYNC_PRESETS: all_is_good = True for key, default in setting.items(): if self._settings.get(key) != default: all_is_good = False break if all_is_good: self._on_preset_changed(name) return self._on_preset_changed(None) def _on_preset_changed(self, preset: Optional[str]): # Find ID for i, child_item in enumerate(self._model.get_item_children()): if self._model.get_item_value_model(child_item).as_string == preset: self._set_preset_id(i) def _set_preset_id(self, preset_id: int): self._model.get_item_value_model().as_int = preset_id def _on_model_changed(self, model: ui.AbstractItemModel, item: ui.AbstractItem): preset_id = self._model.get_item_value_model().as_int child_item = self._model.get_item_children()[preset_id] child_name = self._model.get_item_value_model(child_item).as_string if not child_name: return # Find prest for name, setting in THREAD_SYNC_PRESETS: if name == child_name: self._set_settings(setting) break def _set_settings(self, batch: Dict[str, Any]): for key, value in batch.items(): if self._settings.get(key) != value: self._settings.set(key, value) carb.log_info(f"Present Sets Setting {key} -> {value}") class DeveloperPreferences(PreferenceBuilder): def __init__(self): super().__init__("Developer") def build(self): with ui.VStack(height=0): """ Throttle Rendering """ with self.add_frame("Throttle Rendering"): with ui.VStack(): with ui.HStack(): self.label("Global Thread Synchronization Preset") self.__presets = ThreadSyncPresets() self.create_setting_widget("Async Rendering", "/app/asyncRendering", SettingType.BOOL) self.create_setting_widget( "Skip Rendering While Minimized", "/app/renderer/skipWhileMinimized", SettingType.BOOL ) self.create_setting_widget( "Yield 'ms' while in focus", "/app/renderer/sleepMsOnFocus", SettingType.INT, range_from=0, range_to=50, ) self.create_setting_widget( "Yield 'ms' while not in focus", "/app/renderer/sleepMsOutOfFocus", SettingType.INT, range_from=0, range_to=200, ) self.create_setting_widget( "Enable UI FPS Limit", "/app/runLoops/main/rateLimitEnabled", SettingType.BOOL ) self.create_setting_widget( "UI FPS Limit uses Busy Loop", "/app/runLoops/main/rateLimitUseBusyLoop", SettingType.BOOL ) self.create_setting_widget( "UI FPS Limit", "/app/runLoops/main/rateLimitFrequency", SettingType.FLOAT, range_from=10, range_to=360, ) self.create_setting_widget( "Use Fixed Time Stepping", "/app/player/useFixedTimeStepping", SettingType.BOOL ) # Present thread self.create_setting_widget( "Use Present Thread", "/exts/omni.kit.renderer.core/present/enabled", SettingType.BOOL ) self.create_setting_widget( "Sync Threads and Present Thread", "/app/runLoopsGlobal/syncToPresent", SettingType.BOOL ) self.create_setting_widget( "Present Thread FPS Limit", "/app/runLoops/present/rateLimitFrequency", SettingType.FLOAT, range_from=10, range_to=360, ) self.create_setting_widget( "Sync Present Thread to Present After Rendering", "/exts/omni.kit.renderer.core/present/presentAfterRendering", SettingType.BOOL ) self.create_setting_widget( "Vsync", "/app/vsync", SettingType.BOOL )
12,661
Python
44.060498
118
0.564647
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/stage_page.py
import carb.settings import omni.kit.app from functools import partial from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType class StagePreferences(PreferenceBuilder): def __init__(self): super().__init__("Stage") self._update_setting = {} settings = carb.settings.get_settings() if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodeRange") is None: settings.set_float_array(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodeRange", [0, 100]) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodesPerSecond") is None: settings.set_default_float(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodesPerSecond", 60.0) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps", True ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType") is None: settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType", "Scale, Rotate, Translate" ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder") is None: settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder", "XYZ") # OM-47905: Default camera rotation order should be YXZ. if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultCameraRotationOrder") is None: settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultCameraRotationOrder", "YXZ") if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder") is None: settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:translate, xformOp:rotate, xformOp:scale", ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision") is None: settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision", "Double" ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/dragDropImport") is None: settings.set_default_string( PERSISTENT_SETTINGS_PREFIX + "/app/stage/dragDropImport", "payload" ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/nestedGprimsAuthoring") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/app/stage/nestedGprimsAuthoring", False ) if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/movePrimInPlace") is None: settings.set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/app/stage/movePrimInPlace", True ) def build(self): import omni.ui as ui """ New Stage """ with ui.VStack(height=0): with self.add_frame("New Stage"): with ui.VStack(): self.create_setting_widget_combo( "Default Up Axis", PERSISTENT_SETTINGS_PREFIX + "/app/stage/upAxis", ["Y", "Z"] ) self.create_setting_widget( "Default Animation Rate (TimeCodesPerSecond)", PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodesPerSecond", SettingType.FLOAT ) self.create_setting_widget( "Default Meters Per Unit", PERSISTENT_SETTINGS_PREFIX + "/simulation/defaultMetersPerUnit", SettingType.FLOAT, range_from=0.001, range_to=1.0, speed=0.001, identifier="default_meters_per_unit" ) self.create_setting_widget( "Default Time Code Range", PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodeRange", SettingType.DOUBLE2, ) self.create_setting_widget( "Default DefaultPrim Name", PERSISTENT_SETTINGS_PREFIX + "/app/stage/defaultPrimName", SettingType.STRING, ) self.create_setting_widget_combo( "Interpolation Type", PERSISTENT_SETTINGS_PREFIX + "/app/stage/interpolationType", ["Linear", "Held"], ) self.create_setting_widget( "Enable Static Material Network Topology", "/omnihydra/staticMaterialNetworkTopology", SettingType.BOOL, ) self._create_prim_creation_settings_widgets() self.spacer() """ Authoring """ with self.add_frame("Authoring"): with ui.VStack(): self.create_setting_widget( "Keep Prim World Transfrom When Reparenting", PERSISTENT_SETTINGS_PREFIX + "/app/stage/movePrimInPlace", SettingType.BOOL, ) self.create_setting_widget( 'Set "Instanceable" When Creating Reference', PERSISTENT_SETTINGS_PREFIX + "/app/stage/instanceableOnCreatingReference", SettingType.BOOL, ) self.create_setting_widget( "Transform Gizmo Manipulates Scale/Rotate/Translate Separately (New)", PERSISTENT_SETTINGS_PREFIX + "/app/transform/gizmoUseSRT", SettingType.BOOL, ) self.create_setting_widget( "Camera Controller Manipulates Scale/Rotate/Translate Separately (New)", PERSISTENT_SETTINGS_PREFIX + "/app/camera/controllerUseSRT", SettingType.BOOL, ) self.create_setting_widget( "Allow nested gprims authoring", PERSISTENT_SETTINGS_PREFIX + "/app/stage/nestedGprimsAuthoring", SettingType.BOOL, ) self.spacer() """ Import """ with self.add_frame("Import"): with ui.VStack(): self.create_setting_widget_combo( "Drag & Drop USD Method", PERSISTENT_SETTINGS_PREFIX + "/app/stage/dragDropImport", ["payload", "reference"], ) self.spacer() """ Logging """ with self.add_frame("Logging"): with ui.VStack(): self.create_setting_widget( "Mute USD Coding Error from USD Diagnostic Manager", PERSISTENT_SETTINGS_PREFIX + "/app/usd/muteUsdCodingError", SettingType.BOOL, ) self.spacer() """ Compatibility """ with self.add_frame("Compatibility"): with ui.VStack(): self.create_setting_widget( "Support unprefixed UsdLux attributes (USD <= 20.11)", PERSISTENT_SETTINGS_PREFIX + "/app/usd/usdLuxUnprefixedCompat", SettingType.BOOL, ) def __del__(self): super().__del__() self._update_setting = {} def _create_prim_creation_settings_widgets(self): self.create_setting_widget( "Start with Transform Op on Prim Creation", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps", SettingType.BOOL, ) def _on_prim_creation_with_default_xform_ops_change(item, event_type, owner): if event_type == carb.settings.ChangeEventType.CHANGED: owner._update_prim_creation_with_default_xform_ops() self._update_setting["PrimCreationWithDefaultXformOps"] = omni.kit.app.SettingChangeSubscription( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps", partial(_on_prim_creation_with_default_xform_ops_change, owner=self), ) widget = self.create_setting_widget_combo( " Default Transform Op Type", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType", ["Scale, Rotate, Translate", "Scale, Orient, Translate", "Transform"], ) def _on_default_xform_op_type_change(item, event_type, owner): if event_type == carb.settings.ChangeEventType.CHANGED: owner._update_prim_creation_with_default_xform_ops() self._update_setting["DefaultXformOpType"] = omni.kit.app.SettingChangeSubscription( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType", partial(_on_default_xform_op_type_change, owner=self), ) self._widget_default_xform_op_type = widget widget = self.create_setting_widget_combo( " Default Camera Rotation Order", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultCameraRotationOrder", ["XYZ", "XZY", "YZX", "YXZ", "ZXY", "ZYX"], ) self._widget_default_camera_rotation_order = widget widget = self.create_setting_widget_combo( " Default Rotation Order", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder", ["XYZ", "XZY", "YZX", "YXZ", "ZXY", "ZYX"], ) self._widget_default_rotation_order = widget widget = self.create_setting_widget_combo( " Default Xform Op Order", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", [ "xformOp:translate, xformOp:rotate, xformOp:scale", "xformOp:translate, xformOp:orient, xformOp:scale", "xformOp:transform", ], ) self._widget_default_xform_op_order = widget widget = self.create_setting_widget_combo( " Default Xform Precision", PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision", ["Float", "Double"], ) self._widget_default_xform_op_precision = widget self._update_prim_creation_with_default_xform_ops() def _update_prim_creation_with_default_xform_ops(self): settings = carb.settings.get_settings() if settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps"): self._widget_default_xform_op_type.enabled = True default_xform_ops = settings.get_as_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType" ) if default_xform_ops == "Scale, Orient, Translate": self._widget_default_rotation_order.enabled = False self._widget_default_camera_rotation_order.enabled = False settings.set_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:translate, xformOp:orient, xformOp:scale", ) elif default_xform_ops == "Transform": self._widget_default_rotation_order.enabled = False self._widget_default_camera_rotation_order.enabled = False settings.set_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:transform" ) else: self._widget_default_rotation_order.enabled = True self._widget_default_camera_rotation_order.enabled = True settings.set_string( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:translate, xformOp:rotate, xformOp:scale", ) self._widget_default_xform_op_order.enabled = False self._widget_default_xform_op_precision.enabled = True else: self._widget_default_xform_op_type.enabled = False self._widget_default_rotation_order.enabled = False self._widget_default_camera_rotation_order.enabled = False self._widget_default_xform_op_order.enabled = False self._widget_default_xform_op_precision.enabled = False
13,140
Python
44.787456
123
0.563775
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/rendering_page.py
import carb import carb.settings import omni.kit.app import omni.ui as ui from ..preferences_window import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX from .developer_page import THREAD_SYNC_PRESETS # kit-extensions/kit-scene extension access this from typing import Any from typing import Dict from typing import Optional class RenderingPreferences(PreferenceBuilder): def post_notification(message: str, info: bool = False, duration: int = 3): import omni.kit.notification_manager as nm if info: type = nm.NotificationStatus.INFO else: type = nm.NotificationStatus.WARNING nm.post_notification(message, status=type, duration=duration) def __init__(self): super().__init__("Rendering") self._persistentDistillMaterialPath = PERSISTENT_SETTINGS_PREFIX + "/rtx/mdltranslator/distillMaterial" self._persistentMultiGPUPath = PERSISTENT_SETTINGS_PREFIX + "/renderer/multiGpu/enabled" self._persistentOpacityMicromapPath = PERSISTENT_SETTINGS_PREFIX + "/renderer/raytracingOmm/enabled" settings = carb.settings.get_settings() if settings.get(self._persistentDistillMaterialPath) is None: settings.set_default_bool(self._persistentDistillMaterialPath, False) self._sub_material_distilling_changed = omni.kit.app.SettingChangeSubscription( self._persistentDistillMaterialPath, self._on_material_distilling_changed ) self._sub_opacity_micromap_changed = omni.kit.app.SettingChangeSubscription( self._persistentOpacityMicromapPath, self._on_opacity_micromap_changed ) self._persistentPlaceholderTextureColorPath = PERSISTENT_SETTINGS_PREFIX + "/rtx/resourcemanager/placeholderTextureColor" if settings.get(self._persistentPlaceholderTextureColorPath) is None: settings.set_float_array(self._persistentPlaceholderTextureColorPath, [0,1,1]) # Note: No SettingChangeSubscription because it shows the same popup like 6 times when the color is changed self._enableFabricSceneDelegatePath = "/app/useFabricSceneDelegate" self._sub_fabric_delegate_changed = omni.kit.app.SettingChangeSubscription( self._enableFabricSceneDelegatePath, self._on_fabric_delegate_changed ) self._fabricMemBudgetPath = "/app/usdrt/scene_delegate/gpuMemoryBudgetPercent" if settings.get(self._fabricMemBudgetPath) is None: settings.set_default_float(self._fabricMemBudgetPath, 90) self._fabricEnableGeometryStreaming = "/app/usdrt/scene_delegate/geometryStreaming/enabled" if settings.get(self._fabricEnableGeometryStreaming) is None: settings.set_default_bool(self._fabricEnableGeometryStreaming, True) self._fabricEnableGeometryStreamingMinSize = "/app/usdrt/scene_delegate/geometryStreaming/solidAngleLimit" if settings.get(self._fabricEnableGeometryStreamingMinSize) is None: settings.set_default_float(self._fabricEnableGeometryStreamingMinSize, 0.) self._fabricEnableProxyCubes = "/app/usdrt/scene_delegate/enableProxyCubes" if settings.get(self._fabricEnableProxyCubes) is None: settings.set_default_bool(self._fabricEnableProxyCubes, False) self._fabricMergeSubcomponents = "/app/usdrt/population/utils/mergeSubcomponents" if settings.get(self._fabricMergeSubcomponents) is None: settings.set_default_bool(self._fabricMergeSubcomponents, False) self._fabricMergeInstances = "/app/usdrt/population/utils/mergeInstances" if settings.get(self._fabricMergeInstances) is None: settings.set_default_bool(self._fabricMergeInstances, False) self._fabricMergeMaterials = "/app/usdrt/population/utils/mergeMaterials" if settings.get(self._fabricMergeMaterials) is None: settings.set_default_bool(self._fabricMergeMaterials, True) self._fabricReadMaterials = "/app/usdrt/population/utils/readMaterials" if settings.get(self._fabricReadMaterials) is None: settings.set_default_bool(self._fabricReadMaterials, True) self._fabricReadLights = "/app/usdrt/population/utils/readLights" if settings.get(self._fabricReadLights) is None: settings.set_default_bool(self._fabricReadLights, True) self._fabricReadPrimvars = "/app/usdrt/population/utils/readPrimvars" if settings.get(self._fabricReadPrimvars) is None: settings.set_default_bool(self._fabricReadPrimvars, True) self._fabricInferDisplayColorFromMaterial = "/app/usdrt/population/utils/inferDisplayColorFromMaterial" if settings.get(self._fabricInferDisplayColorFromMaterial) is None: settings.set_default_bool(self._fabricInferDisplayColorFromMaterial, False) self._fabricHandleSceneGraphInstances = "/app/usdrt/population/utils/handleSceneGraphInstances" if settings.get(self._fabricHandleSceneGraphInstances) is None: settings.set_default_bool(self._fabricHandleSceneGraphInstances, True) self._fabricUseHydraBlendShape = "/app/usdrt/scene_delegate/useHydraBlendShape" if settings.get(self._fabricUseHydraBlendShape) is None: settings.set_default_bool(self._fabricUseHydraBlendShape, False) def build(self): with ui.VStack(height=0): """ Hydra Scene Delegate """ with self.add_frame("Fabric Scene Delegate"): with ui.VStack(): self.create_setting_widget("Enable Fabric delegate (preview feature, requires scene reload)", self._enableFabricSceneDelegatePath, SettingType.BOOL, tooltip="Enable Fabric Hydra scene delegate for faster load times on large scenes.\n" "This is a preview release of this new feature and some scene interactions will be limited.\n" "You should expect faster load times with geometry streaming, faster playback of USD animation, " "and GPU memory staying under a predefined budget.") self.create_setting_widget("Fabric delegate GPU memory budget %", self._fabricMemBudgetPath, SettingType.FLOAT, range_from=0, range_to=100, tooltip="Fabric Scene Delegate will stop loading geometry when this threshold of available GPU memory is reached.") with ui.CollapsableFrame(title="Advanced Fabric Scene Delegate Settings", collapsed=True): with ui.VStack(): self.create_setting_widget("Enable Geometry Streaming in Fabric Scene Delegate", self._fabricEnableGeometryStreaming, SettingType.BOOL, tooltip="This enables the progressive and sorted loading of geometry, as well as the device memory limit checks.") self.create_setting_widget("Geo Streaming Minimum Size", self._fabricEnableGeometryStreamingMinSize, SettingType.FLOAT, range_from=0, range_to=1, range_step=0.0001, tooltip="This sets a minimum relative size on screen for objects to be loaded, 0 loads everything.") self.create_setting_widget("Enable proxy cubes for unloaded prims", self._fabricEnableProxyCubes, SettingType.BOOL, tooltip="This helps visualizing scene content when having low device memory, but can have performance impact for very large scenes.") self.create_setting_widget("Merge subcomponents", self._fabricMergeSubcomponents, SettingType.BOOL, tooltip="Fabric Scene Delegate will merge all meshes within USD subcomponents.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Merge instances", self._fabricMergeInstances, SettingType.BOOL, tooltip="Fabric Scene Delegate will merge all meshes within USD scene graph instances.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Merge materials", self._fabricMergeMaterials, SettingType.BOOL, tooltip="Fabric Scene Delegate will identify unique materials and drop all duplicates.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Read materials", self._fabricReadMaterials, SettingType.BOOL, tooltip="When off, Fabric Scene Delegate will not read any material from USD, which can speed up load time.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Infer displayColor from material", self._fabricInferDisplayColorFromMaterial, SettingType.BOOL, tooltip="When on, Fabric Scene Delegate will read material info to infer mesh displayColor.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Read lights", self._fabricReadLights, SettingType.BOOL, tooltip="When off, Fabric Scene Delegate will not read any lights from USD.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Read primvars", self._fabricReadPrimvars, SettingType.BOOL, tooltip="When off, Fabric Scene Delegate will not read any mesh primvar from USD.\n" "This does NOT affect the USD stage, only the Fabric representation.") self.create_setting_widget("Use Fabric Scene Graph Instancing", self._fabricHandleSceneGraphInstances, SettingType.BOOL, tooltip="When off, Fabric Scene Delegate will ignore USD Scene Graph Instances.\n" "Each instanced geometry will be duplicated in Fabric.") self.create_setting_widget("Use Hydra BlendShape", self._fabricUseHydraBlendShape, SettingType.BOOL, tooltip="Fabric Scene Delegate will compute hydra BlendShape.\n" "This will be effective after next stage loading.") #define USDRT_POPULATION_UTILS_INFERDISPLAYCOLORFROMMATERIAL "/app/usdrt/population/utils/" self.spacer() """ White Mode """ with self.add_frame("White Mode"): with ui.VStack(): widget = self.create_setting_widget("Material", "/rtx/debugMaterialWhite", SettingType.STRING) widget.enabled = False self.create_setting_widget( "Exceptions (Requires Scene Reload)", PERSISTENT_SETTINGS_PREFIX + "/app/rendering/whiteModeExceptions", SettingType.STRING, ) self.spacer() """ MDL """ with self.add_frame("MDL"): with ui.VStack(): self.create_setting_widget( "Material Distilling (Experimental, requires app restart)", self._persistentDistillMaterialPath, SettingType.BOOL, tooltip="Enables transforming MDL materials of arbitrary complexity to predefined target material models, which can improve material rendering fidelity in RTX Real-Time mode." "\nImproves rendering fidelity of complex materials such as Clear Coat in RTX Real-Time mode." "\nRequires app restart to take effect." ) self.spacer() """ Texture Streaming """ with self.add_frame("Texture Streaming"): with ui.VStack(): self.create_setting_widget( "Placeholder Texture Color (requires app restart)", self._persistentPlaceholderTextureColorPath, SettingType.COLOR3, tooltip="Sets the color of the placeholder texture which is used while actual textures are loaded." "\nRequires app restart to take effect." ) self.spacer() """ Multi-GPU """ with self.add_frame("Multi-GPU"): with ui.VStack(): with ui.HStack(height=24): self.label("Multi-GPU") settings = carb.settings.get_settings() mgpu = str(settings.get(self._persistentMultiGPUPath)) index = 0 if mgpu == "True": index = 1 elif mgpu == "False": index = 2 widget = ui.ComboBox(index, "Auto", "True", "False") widget.model.add_item_changed_fn(self._on_multigpu_changed) self.spacer() """ Opacity MicroMap """ with self.add_frame("Opacity MicroMap"): with ui.VStack(): self.create_setting_widget( "Enable Opacity MicroMap", self._persistentOpacityMicromapPath, SettingType.BOOL, tooltip="Opacity MicroMaps improve efficiency of rendering translucent objects." "\nThis feature requires an Ada Lovelace architecture GPU." "\nRequires app restart to take effect." ) def _on_opacity_micromap_changed(self, value: bool, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: msg = "Opacity MicroMap settings has been changed. You will need to restart Omniverse for this to take effect." try: import asyncio import omni.kit.notification_manager import omni.kit.app async def show_msg(): await omni.kit.app.get_app().next_update_async() omni.kit.notification_manager.post_notification(msg, hide_after_timeout=False) asyncio.ensure_future(show_msg()) except: carb.log_warn(msg) def _on_material_distilling_changed(self, value: bool, event_type: carb.settings.ChangeEventType): if event_type == carb.settings.ChangeEventType.CHANGED: msg = "Material distilling settings has been changed. You will need to restart Omniverse for this to take effect." try: import asyncio import omni.kit.notification_manager import omni.kit.app async def show_msg(): await omni.kit.app.get_app().next_update_async() omni.kit.notification_manager.post_notification(msg, hide_after_timeout=False) asyncio.ensure_future(show_msg()) except: carb.log_warn(msg) def _on_fabric_delegate_changed(self, value: str, event_type: carb.settings.ChangeEventType): import omni.usd if event_type == carb.settings.ChangeEventType.CHANGED: stage = omni.usd.get_context().get_stage() if not stage or stage.GetRootLayer().anonymous: return msg = "Hydra scene delegate changed. You will need to reload your stage for this to take effect." try: import asyncio import omni.kit.notification_manager import omni.kit.app async def show_msg(): await omni.kit.app.get_app().next_update_async() omni.kit.notification_manager.post_notification(msg, hide_after_timeout=True, duration=2) asyncio.ensure_future(show_msg()) except: carb.log_warn(msg) def _on_multigpu_changed(self, model, item): current_index = model.get_item_value_model().as_int settings = carb.settings.get_settings() if current_index == 0: # this is a string not a bool and will have no effect settings.set_string(self._persistentMultiGPUPath, "auto") elif current_index == 1: settings.set_bool(self._persistentMultiGPUPath, True) elif current_index == 2: settings.set_bool(self._persistentMultiGPUPath, False) # print restart message RenderingPreferences.post_notification(f"You need to restart {omni.kit.app.get_app().get_app_name()} for changes to take effect", info=True)
18,315
Python
54.335347
199
0.583347
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/audio_page.py
import os import platform import carb.settings import omni.kit.app import omni.kit.audiodeviceenum import omni.usd.audio from functools import partial import omni.ui as ui from omni.kit.audiodeviceenum import Direction, SampleType from ..preferences_window import PreferenceBuilder, show_file_importer, PERSISTENT_SETTINGS_PREFIX, SettingType class AudioPreferences(PreferenceBuilder): def __init__(self): super().__init__("Audio") self._settings = carb.settings.get_settings() self._enum = omni.kit.audiodeviceenum.acquire_audio_device_enum_interface() self._audio = omni.usd.audio.get_stage_audio_interface() carb.settings.get_settings().set_default_bool( PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop", False ) carb.settings.get_settings().set_default_float(PERSISTENT_SETTINGS_PREFIX + "/audio/context/uiVolume", 1.0) def build(self): devices = self.get_device_list(Direction.PLAYBACK) capture_devices = self.get_device_list(Direction.CAPTURE) speaker_list = [ "auto-detect", "mono", "stereo", "2.1", "quad", "4.1 surround", "5.1 surround", "7.1 surround", "7.1.4 surround", "9.1 surround", "9.1.4 surround", "9.1.6 surround", ] """ Audio Device """ with ui.VStack(height=0): with self.add_frame("Audio Output"): with ui.VStack(): self._device_widget = self.create_setting_widget_combo( "Output Device", PERSISTENT_SETTINGS_PREFIX + "/audio/context/deviceName", devices ) self._capture_device_widget = self.create_setting_widget_combo( "Input Device", PERSISTENT_SETTINGS_PREFIX + "/audio/context/captureDeviceName", capture_devices ) self.create_setting_widget_combo( "Speaker Configuration", PERSISTENT_SETTINGS_PREFIX + "/audio/context/speakerMode", speaker_list ) with ui.HStack(height=24): ui.Button("Refresh", clicked_fn=partial(self._on_refresh_button_fn)) ui.Spacer(width=10) ui.Button("Apply", clicked_fn=partial(self._on_apply_button_fn)) self.spacer() """ Audio Parameters """ with self.add_frame("Audio Parameters"): with ui.VStack(): self.create_setting_widget( "Auto Stream Threshold (in Kilobytes)", PERSISTENT_SETTINGS_PREFIX + "/audio/context/autoStreamThreshold", SettingType.INT, range_from=0, range_to=10240, speed=10, ) self.spacer() """ Audio Player Parameters """ with self.add_frame("Audio Player Parameters"): with ui.VStack(): self.create_setting_widget( "Auto Stream Threshold (in Kilobytes)", PERSISTENT_SETTINGS_PREFIX + "/audio/context/audioPlayerAutoStreamThreshold", SettingType.INT, range_from=0, range_to=10240, speed=10, ) self.create_setting_widget( "Close Audio Player on Stop", PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop", SettingType.BOOL, ) self.spacer() """ Volume Levels """ with self.add_frame("Volume Levels"): with ui.VStack(): self.create_setting_widget( "Master Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/masterVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.create_setting_widget( "USD Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/usdVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.create_setting_widget( "Spatial Voice Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/spatialVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.create_setting_widget( "Non-spatial Voice Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/nonSpatialVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.create_setting_widget( "UI Audio Volume", PERSISTENT_SETTINGS_PREFIX + "/audio/context/uiVolume", SettingType.FLOAT, range_from=0.0, range_to=1.0, speed=0.01, ) self.spacer() """ Debug """ with self.add_frame("Debug"): with ui.VStack(): self.create_setting_widget( "Stream Dump Filename", PERSISTENT_SETTINGS_PREFIX + "/audio/context/streamerFile", SettingType.STRING, clicked_fn=self._on_browse_button_fn, ) # checkbox to enable stream dumping. Note that the setting path for # this is *intentionally* not persistent. This forces the stream # dumping to need to be toggled on at each launch instead of just # enabling it on startup and filling up everyone's harddrives. self.create_setting_widget("Enable Stream Dump", "/audio/context/enableStreamer", SettingType.BOOL) def _on_browse_button_fn(self, origin): """ Called when the user picks the Browse button. """ full_path = origin.model.get_value_as_string() path = os.path.dirname(full_path) if path == "": path = "/" if platform.system().lower() == "windows": path = "C:/" filename = os.path.basename(full_path) if filename == "": filename = "stream_dump" # NOTE: navigate_to doesn't work if target file doesn't exist... navigate_to = self.cleanup_slashes(os.path.join(path, filename)) if not os.path.exists(navigate_to): navigate_to = self.cleanup_slashes(path) show_file_importer( title="Select Filename (Local Files Only)", file_exts=[("RIFF Files(*.wav)", ""), ("All Files(*)", "")], click_apply_fn=self._on_file_pick, filename_url=navigate_to ) def _on_file_pick(self, full_path): """ Called when the user accepts filename in the Select Filename dialog. """ path = os.path.dirname(full_path) if path == "": path = "/" if platform.system().lower() == "windows": path = "C:/" filename = os.path.basename(full_path) if filename == "": filename = "stream_dump.bin" self._settings.set( PERSISTENT_SETTINGS_PREFIX + "/audio/context/streamerFile", self.cleanup_slashes(os.path.join(path, filename)), ) def _on_refresh_button_fn(self): """ Called when the user clicks on the 'Refresh' button. """ devices = self.get_device_list(Direction.PLAYBACK) self._device_widget.model.set_items(devices) devices = self.get_device_list(Direction.CAPTURE) self._capture_device_widget.model.set_items(devices) def _on_apply_button_fn(self): """ Called when the user clicks on the 'Apply' button. """ deviceId = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/audio/context/deviceName") self._audio.set_device(deviceId) def get_device_list(self, direction): device_count = self._enum.get_device_count(direction) default_device = self._enum.get_device_name(direction, 0) if default_device is None: return {"No audio device is connected": ""} devices = {"Default Device (" + self._enum.get_device_name(direction, 0) + ")": ""} for i in range(device_count): dev_name = self._enum.get_device_description(direction, i) dev_id = self._enum.get_device_id(direction, i) if dev_name == None or dev_id == None: continue devices[dev_name] = dev_id return devices
9,404
Python
39.891304
120
0.507656
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/tagging_page.py
import carb.settings import omni.kit.app from functools import partial import omni.ui as ui from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType class TaggingPreferences(PreferenceBuilder): def __init__(self): super().__init__("Tagging") self._showAdvanced = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/showAdvancedTagView" self._showHidden = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/showHiddenTags" self._modifyHidden = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/modifyHiddenTags" carb.settings.get_settings().set_default_bool(self._showAdvanced, False) carb.settings.get_settings().set_default_bool(self._showHidden, False) carb.settings.get_settings().set_default_bool(self._modifyHidden, False) def build(self): # update on setting change def _on_change(item, event_type, owner): if event_type == carb.settings.ChangeEventType.CHANGED: owner._update_visibility() self._update_setting = omni.kit.app.SettingChangeSubscription( self._showAdvanced, partial(_on_change, owner=self) ) self._update_setting2 = omni.kit.app.SettingChangeSubscription( self._showHidden, partial(_on_change, owner=self) ) """ Tagging """ with ui.VStack(height=0): with self.add_frame("Tagging"): with ui.VStack(): self.create_setting_widget("Allow advanced tag view", self._showAdvanced, SettingType.BOOL) self._showHiddenWidget = self.create_setting_widget( "Show hidden tags in advanced view", self._showHidden, SettingType.BOOL ) self._modifyHiddenWidget = self.create_setting_widget( "Allow adding and modifying hidden tags directly", self._modifyHidden, SettingType.BOOL ) self._update_visibility() def _update_visibility(self): settings = carb.settings.get_settings() if settings.get_as_bool(self._showAdvanced): self._showHiddenWidget.enabled = True self._modifyHiddenWidget.enabled = settings.get_as_bool(self._showHidden) else: self._showHiddenWidget.enabled = False self._modifyHiddenWidget.enabled = False
2,442
Python
42.624999
111
0.643735
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_material_config.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import carb import omni.usd import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.kit.window.preferences.scripts.material_config_utils as mc_utils import os from pathlib import Path import posixpath import shutil import tempfile import toml TEST_PATH_STRS = [ "C:/some/project/materials", "omniverse://another/project/materials", "/my/own/materials" ] def _compare_toml_files(file1, file2): # the toml module does not preserve the item order in files so can't use # simple line comparison. needs to compare them as dicts toml1 = toml.load(file1) toml2 = toml.load(file2) return (toml1 == toml2) class PreferencesTestMaterialConfigUtils(AsyncTestCase): # run only once at the beginning @classmethod def setUpClass(cls): # test config file path ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) data_tests_dir = Path(ext_path) / "data/tests" test_config_file_path = data_tests_dir / "material.config.toml" test_config_carb_file_path = data_tests_dir / "material.config.carb.toml" # create temp home dir cls._temp_home = Path(tempfile.mkdtemp()) cls._temp_home = cls._temp_home.as_posix() # copy test config files to the temp home cls._temp_kit_shared_dir = posixpath.join(cls._temp_home, "Documents/Kit/shared") if not os.path.exists(cls._temp_kit_shared_dir): os.makedirs(cls._temp_kit_shared_dir) shutil.copy(test_config_file_path, cls._temp_kit_shared_dir) shutil.copy(test_config_carb_file_path, cls._temp_kit_shared_dir) # temporary wipe out material config in settings settings = carb.settings.get_settings() cls._curr_material_config = settings.get("/materialConfig") settings.set("/materialConfig", {}) # run only once at the end @classmethod def tearDownClass(cls): # remove settings used in tests settings = carb.settings.get_settings() settings.destroy_item("/materialConfigTests") # restore material config in settings settings.set("/materialConfig", {}) settings.set("/materialConfig", cls._curr_material_config) # delete temp home dir if os.path.exists(cls._temp_home): shutil.rmtree(cls._temp_home) # before running each test async def setUp(self): # temporary set home path # replace both variables since Path.home() looks for different env var on Windows # depends on the Python version self._curr_profile = os.environ.get("USERPROFILE", "") if self._curr_profile: os.environ["USERPROFILE"] = str(self._temp_home) self._curr_home = os.environ.get("HOME", "") if self._curr_home: os.environ["HOME"] = str(self._temp_home) # after running each test async def tearDown(self): # restore env vars if self._curr_profile: os.environ["USERPROFILE"] = self._curr_profile if self._curr_home: os.environ["HOME"] = self._curr_home async def test_get_config_file_path(self): expect = Path(self._temp_home) / "Documents/Kit/shared" / "material.config.toml" expect = expect.as_posix() self.assertEqual(expect, mc_utils.get_config_file_path()) async def test_load_config_file(self): config_file_path = mc_utils.get_config_file_path() config = mc_utils.load_config_file(config_file_path) expect = ["my_materials", "my_maps"] self.assertEqual(expect, config["materialGraph"]["userAllowList"]) expect = ["foo_materials", "bar_maps"] self.assertEqual(expect, config["materialGraph"]["userBlockList"]) expect = False self.assertEqual(expect, config["options"]["noStandardPath"]) expect = TEST_PATH_STRS self.assertEqual(expect, config["searchPaths"]["local"]) async def test_save_config_file(self): config = {} config["materialGraph"] = {} config["materialGraph"]["userAllowList"] = ["my_materials", "my_maps"] config["materialGraph"]["userBlockList"] = ["foo_materials", "bar_maps"] config["options"] = {} config["options"]["noStandardPath"] = False config["searchPaths"] = {} config["searchPaths"]["local"] = TEST_PATH_STRS config["configFilePath"] = "/dummy/path/material.config.toml" # save new file new_config_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.saved.toml") self.assertTrue(mc_utils.save_config_file(config, new_config_file_path)) # compare to the original file orig_config_file_path = mc_utils.get_config_file_path() self.assertTrue(_compare_toml_files(new_config_file_path, orig_config_file_path)) async def test_save_carb_setting_to_config_file(self): test_settings = ( ("string", "coffee", False), ("float", 24.0, False), ("bool", True, False), ("paths", ";".join(TEST_PATH_STRS), True) ) # assign to carb settings settings = carb.settings.get_settings() for i in test_settings: setting_key = posixpath.join("/materialConfigTests", i[0]) settings.set(setting_key, i[1]) # save new file new_config_carb_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.carb.saved.toml") for i in test_settings: carb_key = posixpath.join("/materialConfigTests", i[0]) config_key = posixpath.join("tests", i[0]) mc_utils.save_carb_setting_to_config_file( carb_key, config_key, is_paths=i[2], non_standard_path=new_config_carb_file_path ) # compare to the original file orig_config_carb_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.carb.toml") self.assertTrue(_compare_toml_files(new_config_carb_file_path, orig_config_carb_file_path)) async def test_save_live_config_to_file(self): test_settings = ( ("materialGraph/userAllowList", ["my_materials", "my_maps"]), ("materialGraph/userBlockList", ["foo_materials", "bar_maps"]), ("options/noStandardPath", False), ("searchPaths/local", TEST_PATH_STRS) ) # assign to /materialConfig carb settings settings = carb.settings.get_settings() for i in test_settings: setting_key = posixpath.join("/materialConfig", i[0]) settings.set(setting_key, i[1]) # save new file new_config_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.saved2.toml") mc_utils.save_live_config_to_file(non_standard_path=new_config_file_path) # compare to the original file orig_config_file_path = mc_utils.get_config_file_path() self.assertTrue(_compare_toml_files(new_config_file_path, orig_config_file_path))
7,577
Python
37.467005
112
0.637455
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_pages.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import carb import omni.usd import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test class PreferencesTestPages(AsyncTestCase): # Before running each test async def setUp(self): omni.kit.window.preferences.show_preferences_window() # After running each test async def tearDown(self): omni.kit.window.preferences.hide_preferences_window() carb.settings.get_settings().set("/app/show_developer_preference_section", False) async def _change_values(self): # toggle checkboxes widgets = ui_test.find_all("Preferences//Frame/**/CheckBox[*]") if widgets: for w in widgets: # don't change audio as it causes exceptions on TC if not "audio" in w.widget.identifier: ov = w.model.get_value_as_bool() w.model.set_value(not ov) await ui_test.human_delay(10) w.model.set_value(ov) async def test_show_pages(self): pages = omni.kit.window.preferences.get_page_list() page_names = [page._title for page in pages] # is list alpha sorted. Don't compare with fixed list as members can change self.assertEqual(page_names, sorted(page_names)) for page in pages: omni.kit.window.preferences.select_page(page) await ui_test.human_delay(10) await self._change_values() async def test_developer_page(self): carb.settings.get_settings().set("/app/show_developer_preference_section", True) await ui_test.human_delay(10) omni.kit.window.preferences.select_page(omni.kit.window.preferences.get_instance()._developer_preferences) await ui_test.human_delay(10) await self._change_values()
2,284
Python
40.545454
114
0.672067
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/__init__.py
from .test_preferences import * from .test_stage import * from .test_pages import *
84
Python
20.249995
31
0.75
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_preferences.py
import os import unittest import carb import omni.kit.test from omni.kit.window.preferences.scripts.preferences_window import ( PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, ) class TestPreferencesWindow(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_new_preferences_window(self): called_init = False called_del = False class TestPreferences(PreferenceBuilder): def __init__(self): super().__init__("Test") def build(self): nonlocal called_init called_init = True def __del__(self): super().__del__() nonlocal called_del called_del = True self.assertFalse(called_init) self.assertFalse(called_del) called_init = False called_del = False page = omni.kit.window.preferences.register_page(TestPreferences()) omni.kit.window.preferences.select_page(page) omni.kit.window.preferences.rebuild_pages() prefs = omni.kit.window.preferences.get_instance() self.assertTrue(called_init) self.assertFalse(called_del) called_init = False called_del = False omni.kit.window.preferences.unregister_page(page) del page self.assertFalse(called_init) self.assertTrue(called_del)
1,450
Python
25.381818
75
0.608276
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_material.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb import omni.usd import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase class PreferencesTestDragDropImport(AsyncTestCase): # Before running each test async def setUp(self): from omni.kit import ui_test carb.settings.get_settings().set("/persistent/app/material/dragDropMaterialPath", "Absolute") omni.kit.window.preferences.show_preferences_window() for page in omni.kit.window.preferences.get_page_list(): if page.get_title() == "Material": omni.kit.window.preferences.select_page(page) await ui_test.human_delay(50) break # After running each test async def tearDown(self): carb.settings.get_settings().set("/persistent/app/material/dragDropMaterialPath", "Absolute") async def test_l1_app_materla_drag_drop_path(self): from omni.kit import ui_test frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_Material'") import_combo = frame.find("**/ComboBox[*].identifier=='/persistent/app/material/dragDropMaterialPath'") index_model = import_combo.model.get_item_value_model(None, 0) import_list = import_combo.model.get_item_children(None) for index, item in enumerate(import_list): index_model.set_value(item.model.value) await ui_test.human_delay(50) self.assertEqual(carb.settings.get_settings().get('/persistent/app/material/dragDropMaterialPath'), item.model.as_string)
2,000
Python
42.499999
133
0.706
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_stage.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb import omni.usd import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase class PreferencesTestDragDropImport(AsyncTestCase): # Before running each test async def setUp(self): from omni.kit import ui_test carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference") omni.kit.window.preferences.show_preferences_window() for page in omni.kit.window.preferences.get_page_list(): if page.get_title() == "Stage": omni.kit.window.preferences.select_page(page) await ui_test.human_delay(50) break # After running each test async def tearDown(self): carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference") async def test_l1_app_stage_drag_drop_import(self): from omni.kit import ui_test frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_Import'") import_combo = frame.find("**/ComboBox[*]") import_combo.widget.scroll_here_y(0.5) await ui_test.human_delay(50) index_model = import_combo.model.get_item_value_model(None, 0) import_list = import_combo.model.get_item_children(None) for index, item in enumerate(import_list): index_model.set_value(item.model.value) await ui_test.human_delay(50) self.assertEqual(carb.settings.get_settings().get('/persistent/app/stage/dragDropImport'), item.model.as_string) async def test_default_meters_zero(self): from omni.kit import ui_test # get widgets await ui_test.human_delay(10) frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_New Stage'") widget = frame.find("**/FloatSlider[*].identifier=='default_meters_per_unit'") # set to 0.5 widget.model.set_value(0.5) await ui_test.human_delay(10) # set to 0.0 - This is not allowed as minimum if 0.01 widget.model.set_value(0.0) await ui_test.human_delay(10) # verify self.assertAlmostEqual(widget.model.get_value_as_float(), 0.5)
2,667
Python
38.820895
124
0.674541
omniverse-code/kit/exts/omni.kit.window.preferences/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.3.8] - 2023-01-12 ### Changed - Fixed `create_setting_widget_combo` to support `setting_is_index` - Pages with same name to be grouped into same page ## [1.3.7] - 2022-09-13 ### Changed - Prevented "Material render context has been changed" message when stage not saved ## [1.3.6] - 2022-08-23 ### Changed - Alpha sorted page names ## [1.3.4] - 2022-07-27 ### Changed - Added "/omnihydra/staticMaterialNetworkTopology" to stage page ## [1.3.3] - 2022-06-22 ### Changed - Added "/persistent/app/material/dragDropMaterialPath" to materials page ## [1.3.2] - 2022-06-08 ### Changed - Updated menus to use actions ## [1.3.1] - 2022-06-06 ### Changed - Removed omni.kit.ui support ## [1.2.2] - 2022-02-22 ### Changed - Added stage import usd method payload/reference - Added identifier to `ui.CollapsableFrame` in `add_frame` ## [1.2.1] - 2022-02-22 ### Changed - Changed implementation on label function ## [1.2.0] - 2022-02-16 ### Added - Allow widgets to display tooltip information ## [1.1.5] - 2021-10-20 ### Changes - Cleans up on shutdown, including releasing handle to FilePickerDialog. ## [1.1.4] - 2021-10-18 ### Changes - Use float type for rateLimitFrequency in preferences. ## [1.1.3] - 2021-07-10 ### Added - Added support for "deep linking" of specific Preference pages from external components. ## [1.1.2] - 2021-05-19 ### Changes - Force "Preferences" to always at the bottom of the edit menu ## [1.1.1] - 2021-05-06 ### Changes - Added feeback when user changes `/app/hydra/material/renderContext` ## [1.1.0] - 2021-03-25 ### Changes - Added `PreferenceBuilder` for new `omni.ui` - Updated existing Pages to use `PreferenceBuilder` - Updated `PreferencePage` it still works, but now depricated ## [1.0.3] - 2021-03-02 ### Changes - Added test ## [1.0.2] - 2020-12-17 ### Changes - Updated menu to use `omni.kit.menu.utils` ## [1.0.1] - 2020-10-17 ### Changes - Added filepicker API - Updated pages to use new filepicker API ## [1.0.0] - 2020-08-13 ### Changes - Converted to extension 2.0
2,122
Markdown
22.853932
89
0.682846
omniverse-code/kit/exts/omni.kit.window.preferences/docs/index.rst
omni.kit.window.preferences ########################### Preferences Window .. toctree:: :maxdepth: 1 CHANGELOG .. automodule:: omni.kit.window.preferences :platform: Windows-x86_64, Linux-x86_64, Linux-aarch64 :members: :undoc-members: :imported-members:
283
reStructuredText
14.777777
58
0.621908
omniverse-code/kit/exts/omni.kit.window.preferences/data/tests/material.config.carb.toml
[tests] paths = [ "C:/some/project/materials", "omniverse://another/project/materials", "/my/own/materials", ] string = "coffee" float = 24.0 bool = true
157
TOML
14.799999
41
0.66879
omniverse-code/kit/exts/omni.kit.window.preferences/data/tests/material.config.toml
[materialGraph] userAllowList = [ "my_materials", "my_maps", ] userBlockList = [ "foo_materials", "bar_maps", ] [options] noStandardPath = false [searchPaths] local = [ "C:/some/project/materials", "omniverse://another/project/materials", "/my/own/materials", ]
271
TOML
12.599999
41
0.678967
omniverse-code/kit/exts/omni.rtx.tests/PACKAGE-LICENSES/omni.rtx.tests-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.tests/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.4" # 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 tests" description="Extension for RTX renderer python tests." # 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", "tests"] # Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content # of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" [dependencies] "omni.kit.commands" = {} "omni.kit.renderer.capture" = {} "omni.kit.test_helpers_gfx" = {} "omni.kit.window.property" = {} "omni.kit.viewport.utility" = {} "omni.usd" = {} # Temporary until we can move the tetmesh imaging # logic and test cases into the physics repo. "omni.usd.schema.physx" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.rtx.tests" [[test]] pythonTests.unreliable = [ "*UNSTABLE*" ] args = [ "--/renderer/enabled=rtx", "--/renderer/active=rtx", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", "--/app/asyncRendering=false", "--/app/captureFrame/setAlphaTo1=true", "--/omni.kit.plugin/syncUsdLoads=true", "--/rtx-transient/resourcemanager/texturestreaming/async=false", "--/rtx/materialDb/syncLoads=true", "--/rtx/hydra/materialSyncLoads=true", "--/rtx/pathtracing/lightcache/cached/enabled=false", "--/rtx/raytracing/lightcache/spatialCache/enabled=false", "--/rtx/post/aa/op=0", "--/rtx-defaults/post/aa/op=0", "--/app/viewport/forceHideFps=true", "--/persistent/app/viewport/displayOptions=0", "--/persistent/app/primCreation/PrimCreationWithDefaultXformOps=true", "--/app/window/hideUi=true", "--/app/docks/disabled=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/window/width=512", "--/app/window/height=512", "--no-window", ] # Aftermath in lightmode (Windows only right now) "filter:platform"."windows-x86_64"."args" = [ "--/renderer/debug/aftermath/enabled=true", "--/renderer/debug/aftermath/useLightMode=true", ] dependencies = [ "omni.usd", "omni.kit.commands", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.hydra.rtx", "omni.kit.viewport.utility", "omni.kit.window.viewport", "omni.volume" # Tests use volume rendering ] profiling = false # RTX regression OM-51983 timeout = 700
2,936
TOML
28.969387
117
0.690395
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_common.py
## Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.appwindow import omni.kit.app import omni.kit.test import omni.kit.commands import omni.timeline import omni.usd import carb import carb.settings import carb.windowing import inspect import pathlib from omni.kit.test_helpers_gfx.compare_utils import finalize_capture_and_compare, ComparisonMetric from omni.kit.viewport.utility import get_active_viewport_window, next_viewport_frame_async from omni.kit.viewport.utility.tests.capture import capture_viewport_and_wait from pxr import Sdf, Gf, Usd, UsdGeom, UsdLux # This settings should be set before stage opening/creation testSettings = { "/app/window/hideUi": True, "/app/asyncRendering": False, "/app/docks/disabled": True, "/app/window/scaleToMonitor": False, "/app/viewport/forceHideFps": True, "/app/captureFrame/setAlphaTo1": True, "/rtx/materialDb/syncLoads": True, "/omni.kit.plugin/syncUsdLoads": True, "/rtx/hydra/materialSyncLoads": True, "/renderer/multiGpu/autoEnable": False, "/persistent/app/viewport/displayOptions": 0, "/app/viewport/grid/enabled": False, "/app/viewport/show/lights": False, "/persistent/app/primCreation/PrimCreationWithDefaultXformOps": True, "/rtx-transient/resourcemanager/texturestreaming/async": False, "/app/viewport/outline/enabled": True } # Settings that should override settings that was set on stage opening/creation postLoadTestSettings = { "/rtx/post/aa/op": 0, "/rtx/pathtracing/lightcache/cached/enabled": False, "/rtx/raytracing/lightcache/spatialCache/enabled": False, "/rtx/sceneDb/ambientLightIntensity": 1.0, "/rtx/indirectDiffuse/enabled": False, } postLoadSkelTestSettings = { "/rtx/post/aa/op": 0, "/rtx/shadows/enabled": False, "/rtx/reflections/enabled": False, "/rtx/ambientOcclusion/enabled": False, "/rtx/post/tonemap/op": 1, "/renderer/multiGpu/autoEnable": False, } RENDER_WIDTH_SETTING = "/app/renderer/resolution/width" RENDER_HEIGHT_SETTING = "/app/renderer/resolution/height" OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path()) EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("data/golden") USD_DIR = EXTENSION_FOLDER_PATH.joinpath("data/usd") VOLUMES_DIR = EXTENSION_FOLDER_PATH.joinpath("data/volumes") async def next_resize_async(): """ Wait for the next event in the resize event stream of IAppWindow::getWindowResizeEventStream. We need it because the window resize event stream is independent of IApp::getUpdateEventStream. Without this function it's possible that resize happens several updates after. It's reproducable on Linux Release build. """ return await omni.appwindow.get_default_app_window().get_window_resize_event_stream().next_event() async def wait_for_update(usd_context=omni.usd.get_context(), wait_frames=10): max_loops = 0 while max_loops < wait_frames: _, files_loaded, total_files = usd_context.get_stage_loading_status() await omni.kit.app.get_app().next_update_async() if files_loaded or total_files: continue max_loops = max_loops + 1 def set_cursor_position(pos): app_window = omni.appwindow.get_default_app_window() windowing = carb.windowing.acquire_windowing_interface() os_window = app_window.get_window() windowing.set_cursor_position(os_window, pos) def set_transform_helper( prim_path, translate=Gf.Vec3d(0, 0, 0), euler=Gf.Vec3d(0, 0, 0), scale=Gf.Vec3d(1, 1, 1), ): rotation = ( Gf.Rotation(Gf.Vec3d.ZAxis(), euler[2]) * Gf.Rotation(Gf.Vec3d.YAxis(), euler[1]) * Gf.Rotation(Gf.Vec3d.XAxis(), euler[0]) ) xform = Gf.Matrix4d().SetScale(scale) * Gf.Matrix4d().SetRotate(rotation) * Gf.Matrix4d().SetTranslate(translate) omni.kit.commands.execute( "TransformPrimCommand", path=prim_path, new_transform_matrix=xform, ) async def setup_viewport_test_window(resolution_x: int, resolution_y: int, position_x: int = 0, position_y: int = 0): from omni.kit.viewport.utility import get_active_viewport_window viewport_window = get_active_viewport_window() if viewport_window: viewport_window.position_x = position_x viewport_window.position_y = position_y viewport_window.width = resolution_x viewport_window.height = resolution_y viewport_window.viewport_api.resolution = (resolution_x, resolution_y) return viewport_window class RtxTest(omni.kit.test.AsyncTestCase): THRESHOLD = 1e-5 WINDOW_SIZE = (640, 480) def __init__(self, tests=()): super().__init__(tests) self._saved_width = None self._saved_height = None self._savedSettings = {} self._failedImages = [] @property def __test_name(self) -> str: """ The full name of the test. It has the name of the module, class and the current test function. We use the stack to get the name of the test function and since it's only called from create_test_window and finalize_test, we get the third member. """ return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" async def create_test_area(self, width: int = 256, height: int = 256): """Resize the main window""" app_window = omni.appwindow.get_default_app_window() await omni.usd.get_context().new_stage_async() viewport_window = await setup_viewport_test_window(width, height) self.assertTrue(viewport_window is not None, "No active viewport window found.") # Current main window size current_width = app_window.get_width() current_height = app_window.get_height() # If the main window is already has requested size, do nothing if width == current_width and height == current_height: self._saved_width = None self._saved_height = None else: # Save the size of the main window to be able to restore it at the end of the test self._saved_width = current_width self._saved_height = current_height app_window.resize(width, height) # Wait for getWindowResizeEventStream await next_resize_async() # Wait until the Viewport has delivered some frames await next_viewport_frame_async(viewport_window.viewport_api, 0) async def screenshot_and_diff(self, golden_img_dir: pathlib.Path, output_subdir=None, golden_img_name=None, threshold=THRESHOLD): """ Capture the current frame and compare it with the golden image. Assert if the diff is more than given threshold. This method differs from capture_and_compare in that it lets callers outside omni.rtx.tests capture and compare images in their own directories. The screen captures will be placed in a common place with the rtx.tests output, either in a subdirectory passed in as output_subdir, or in a directory named for the test module. Golden images will be found in the directory passed in as golden_img_dir, this is the only required parameter. """ if not golden_img_dir: self.assertTrue(golden_img_dir, "A valid golden image dir is a required parameter") if not output_subdir: output_subdir = f"{self.__module__}" output_img_dir = OUTPUTS_DIR.joinpath(output_subdir) if not golden_img_name: golden_img_name = f"{self.__test_name}.png" return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir) async def capture_and_compare(self, img_subdir: pathlib.Path = None, golden_img_name=None, threshold=THRESHOLD, metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED): """ Capture current frame and compare it with the golden image. Assert if the diff is more than given threshold. """ golden_img_dir = GOLDEN_DIR.joinpath(img_subdir) output_img_dir = OUTPUTS_DIR.joinpath(img_subdir) if not golden_img_name: golden_img_name = f"{self.__test_name}.png" return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric) async def _capture_and_compare(self, golden_img_name, threshold, output_img_dir: pathlib.Path, golden_img_dir: pathlib.Path, metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED): # Capture directly from the Viewport's texture, not from UI swapchain await capture_viewport_and_wait(golden_img_name, output_img_dir) # Do the image comparison now diff = finalize_capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric=metric) if diff != 0: carb.log_warn(f"[{self.__test_name}] the generated image {golden_img_name} has max difference {diff}") if (diff is not None) and diff >= threshold: self._failedImages.append(golden_img_name) return diff def add_dir_light(self): omni.kit.commands.execute( "CreatePrimCommand", prim_path="/World/Light", prim_type="DistantLight", select_new_prim=False, # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 attributes={UsdLux.Tokens.inputsAngle: 1.0, UsdLux.Tokens.inputsIntensity: 3000} if hasattr(UsdLux.Tokens, 'inputsIntensity') else {UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.intensity: 3000}, create_default_xform=True, ) def add_floor(self): floor_path = "/World/Floor" omni.kit.commands.execute( "CreatePrimCommand", prim_path=floor_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100}, ) floor_prim = self.ctx.get_stage().GetPrimAtPath(floor_path) floor_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(25, 0.1, 25)) floor_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) def open_usd(self, usdSubpath: pathlib.Path): path = USD_DIR.joinpath(usdSubpath) omni.usd.get_context().open_stage(str(path)) def get_volumes_path(self, volumeSubPath: pathlib.Path): return Sdf.AssetPath(str(VOLUMES_DIR.joinpath(volumeSubPath))) def set_settings(self, newSettings): settingsAPI = carb.settings.get_settings() for s, v in newSettings.items(): if s not in self._savedSettings: # Remember old setting only when it was changed first time self._savedSettings[s] = settingsAPI.get(s) if v is None: # hideUi sometimes is None and it hangs kit v = False settingsAPI.set(s, v) def set_camera(self, cameraPos=None, targetPos=None): from omni.kit.viewport.utility.camera_state import ViewportCameraState camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world(cameraPos, True) camera_state.set_target_world(targetPos, True) async def setUp_internal(self): self.ctx = omni.usd.get_context() await self.create_test_area(self.WINDOW_SIZE[0], self.WINDOW_SIZE[1]) async def setUp(self): await self.setUp_internal() async def tearDown(self): # Restore main window resolution if it was saved if self._saved_width is not None and self._saved_height is not None: app_window = omni.appwindow.get_default_app_window() app_window.resize(self._saved_width, self._saved_height) # Wait for getWindowResizeEventStream await next_resize_async() self.set_settings(self._savedSettings) self.ctx.close_stage() for imgName in self._failedImages: carb.log_warn(f"[{self.__test_name}] The image {imgName} doesn't match the golden") hasFailed = len(self._failedImages) self._failedImages = [] self.assertEqual(hasFailed, 0)
12,851
Python
41.415841
142
0.668897
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_domelight.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom, UsdLux, Gf, Sdf class TestRtxDomelight(RtxTest): TEST_PATH = "domelight" DOMELIGHT_PRIM_PATH = "/World/DomeLight" def create_mesh(self): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), "/World/box") box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box def create_dome_light(self, name=DOMELIGHT_PRIM_PATH): omni.kit.commands.execute( "CreatePrim", prim_path=name, prim_type="DomeLight", select_new_prim=False, # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 attributes={ UsdLux.Tokens.inputsIntensity: 1, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.inputsTextureFile: "daytime.hdr", UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited, } if hasattr(UsdLux.Tokens, 'inputsIntensity') else { UsdLux.Tokens.intensity: 1, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.textureFile: "daytime.hdr", UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited, }, create_default_xform=True, ) dome_light_prim = self.ctx.get_stage().GetPrimAtPath(name) return dome_light_prim async def setUp(self): await self.setUp_internal() print("RTX DomeLight Tests Setup") self.set_settings(testSettings) super().open_usd("hydra/dome_materials.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) my_settings = { "/rtx/pathtracing/lightcache/cached/enabled": False, "/rtx/raytracing/lightcache/spatialCache/enabled" : False, "/rtx-transient/resourcemanager/genMipsForNormalMaps" : False, "/rtx-transient/resourcemanager/texturestreaming/async" : False, "/rtx-transient/samplerFeedbackTileSize" : 1, "/rtx/post/aa/op" : 0, # 0 = None, 2 = FXAA "/rtx/directLighting/sampledLighting/enabled" : False, "/rtx/reflections/sampledLighting/enabled" : False, # LTC gives consistent lighting # perMaterialSyncLoads: Very important, otherwise the material updates for the domelight # materials (MDLs) are not sync-ed and updated properly. "/rtx/hydra/perMaterialSyncLoads" : True, } self.set_settings(my_settings) async def test_domelight_material_assignment(self): """ Test Domelight material assignment """ looksPath = "/World/Looks/" # Scene Setup self.set_settings({"/rtx/domeLight/baking/resolution": "1024"}) # We could show some minimal mesh but that might create false positives in the lighting. #self.create_mesh() dome_prim = self.create_dome_light() # The loaded domelight had a texture assigned check it: # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): dome_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(100) else: dome_prim.GetAttribute(UsdLux.Tokens.intensity).Set(100) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_texture_assigned.png") # Bind a material to the domelight # This material shows the emission direction in a color-coded way. omni.kit.commands.execute('BindMaterial', material_path=looksPath + "dome_emission_direction", prim_path=[self.DOMELIGHT_PRIM_PATH], strength=['weakerThanDescendants']) # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): dome_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(1) else: dome_prim.GetAttribute(UsdLux.Tokens.intensity).Set(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_emission_direction_mat.png") # Bind a different material to the domelight omni.kit.commands.execute('BindMaterial', material_path='/World/Looks/dome_gridspherejulia', prim_path=['/World/DomeLight'], strength=['weakerThanDescendants']) # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): dome_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(1) else: dome_prim.GetAttribute(UsdLux.Tokens.intensity).Set(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_gridspherejulia_mat.png") # Set a different baking resolution self.set_settings({"/rtx/domeLight/baking/resolution": "256"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_baking_resolution.png") # Testing domelight per pixel evaluation: # JIRA OM-49492 self.set_settings({ "/rtx/pathtracing/domeLight/primaryRaysEvaluateDomelightMdlDirectly" : True, "/rtx/rendermode" : 'PathTracing', "/rtx/pathtracing/spp" : 1, "/rtx/pathtracing/totalSpp" : 1, }) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04a_mdl_direct_evaluation.png") # Create another domelight (JIRA OM-19501) # The visible domelight can be any domelight if multiple domelights are in the scene. # Internally it depends which one is in the domelight buffer[0]. # Therefore, we need to explicitly disable the first one to see the result of the second. self.set_settings({ "/rtx/rendermode" : 'RaytracedLighting', }) dome2_path = "/World/DomeLight_2" dome_prim2 = self.create_dome_light(dome2_path) # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): dome_prim2.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(100) else: dome_prim2.GetAttribute(UsdLux.Tokens.intensity).Set(100) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/DomeLight_2.xformOp:rotateXYZ'), value=Gf.Vec3d(270.0, -90.0, 0.0), prev=Gf.Vec3d(270.0, 0.0, 0.0)) # Disable the first dome light dome_prim.GetAttribute(UsdGeom.Tokens.visibility).Set(UsdGeom.Tokens.invisible) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_second_domelight.png")
7,828
Python
47.030675
113
0.646525
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_material_distilling_toggle.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update class TestMaterialDistillingToggle(RtxTest): """ rtx test running renderer with material distilling toggle on to ensure renderer correctly loads in neuraylib plugins, compiles shader cache, inserts preprocessor macro (DISTILLED_MTL_MODE) """ async def setUp(self): await super().setUp() self.set_settings(testSettings) self.open_usd("material_distilling.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_material_distilling_toggle(self): await wait_for_update() await self.capture_and_compare("material_distilling_toggle", "material_distilling_toggle.png", 1e-3)
1,315
Python
42.866665
121
0.752091
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_skel.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. ## #TODO 02: omnihydra does not support dynamically switch animationsource on skelroot prim bindingAPI (should be a repopulate in this case) #TODO 03: omnihydra does not support joints/blendshapes change in skelanimation prim #TODO 04: omnihydra does not support blendshapes (target name) change in skelanimation prim (not in test) #TODO 05 when skelanimation become invalid, skinning result should retrive restTransform #TODO 06: after added time ranged control, the render result does not work correct for the specific animation source import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline import carb.settings from .test_hydra_common import RtxHydraTest from .test_common import testSettings, postLoadSkelTestSettings, set_transform_helper, wait_for_update from pxr import Gf, Sdf, Usd, UsdGeom, UsdSkel, UsdShade def _update_animation(animation : UsdSkel.Animation, animation_static : UsdSkel.Animation, timecode : Usd.TimeCode): trans = animation.GetTranslationsAttr().Get(timecode) rots = animation.GetRotationsAttr().Get(timecode) scales = animation.GetScalesAttr().Get(timecode) bsWeights = animation.GetBlendShapeWeightsAttr().Get(timecode) animation_static.GetTranslationsAttr().Set(trans) animation_static.GetRotationsAttr().Set(rots) animation_static.GetScalesAttr().Set(scales) animation_static.GetBlendShapeWeightsAttr().Set(bsWeights) class TestRtxHydraSkel(RtxHydraTest): TEST_PATH = "hydra/skel" async def setUp(self): await super().setUp() timeline = omni.timeline.get_timeline_interface() timeline.set_fast_mode(True) await omni.kit.app.get_app().next_update_async() async def test_01_skel_anim(self): """ Test hydra skel - skel anim """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelroot_path = "/Root/group1" skelroot_prim = stage.GetPrimAtPath(skelroot_path) skelroot = UsdSkel.Root(skelroot_prim) skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() # pure skeleton test await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_0_skeleton_0.png") #Test animation skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_1.png") timeline.set_current_time(1.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_2.png") skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_3.png") #Test animation in session layer (resync) with Usd.EditContext(stage, session_layer): skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_1.png") timeline.set_current_time(1.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_2.png") stage.RemovePrim(skeleton_path) self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_3.png") await wait_for_update() self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) #Test animation switch skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_1.png") skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_2.png") #Test animation switch in session layer with Usd.EditContext(stage, session_layer): skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path]) timeline.set_current_time(0.0) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_sessionlayer_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_sessionlayer_1.png") #TODO 06: after added time ranged control, the render result does not work correct for the specific animation source stage.RemovePrim(skeleton_path) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_sessionlayer_2.png") #Test animation switch to outside root animation await wait_for_update() self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_outside_path]) await wait_for_update() self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_outside_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_1.png") skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path]) await wait_for_update() self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) #Test animation switch to outside root animation in session layer with Usd.EditContext(stage, session_layer): skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_outside_path]) await wait_for_update() self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_outside_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_sessionlayer_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_sessionlayer_1.png") stage.RemovePrim(skeleton_path) ##TODO 02: omnihydra does not support dynamically switch animationsource on skelroot prim bindingAPI (should be a repopulate in this case) ##Test animation switch to at skelroot prim #skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #await wait_for_update() #self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) #skelroot_bindingAPI = UsdSkel.BindingAPI.Apply(skelroot_prim) #skelroot_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path]) #await wait_for_update() #self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim) #timeline.set_current_time(0.0) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_0.png") #timeline.set_current_time(0.5) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_1.png") #skelroot_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #self.assertTrue(not skelroot_bindingAPI.GetInheritedAnimationSource()) ##Test animation switch to outside root animation in session layer #with Usd.EditContext(stage, session_layer): # skelroot_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path]) # await wait_for_update() # self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_sessionlayer_0.png") # timeline.set_current_time(0.5) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_sessionlayer_1.png") # stage.RemovePrim(skeleton_path) timeline.set_auto_update(True) timeline.stop() async def test_02_skel_anim_update(self): """ Test hydra skel - skel animation update """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() #Test SRT/bsweights update skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_static_path]) self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_static_prim) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_0.png") timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond()) with Sdf.ChangeBlock(): _update_animation(animation, animation_static, timecode) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_1.png") #non play test timeline.play() timeline.set_auto_update(False) timeline.set_current_time(1.0) await omni.kit.app.get_app().next_update_async() timecode = Usd.TimeCode(timeline.get_current_time() * stage.GetTimeCodesPerSecond()) with Sdf.ChangeBlock(): _update_animation(animation, animation_static, timecode) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_2.png") # play test timeline.set_auto_update(True) timeline.stop() timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() with Sdf.ChangeBlock(): _update_animation(animation, animation_static, Usd.TimeCode.Default()) #Test SRT/bsweights update in session layer with Usd.EditContext(stage, session_layer): self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_static_prim) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_sessionlayer_0.png") timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond()) with Sdf.ChangeBlock(): _update_animation(animation, animation_static, timecode) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_sessionlayer_1.png") #non play test stage.RemovePrim(animation_static_path) timeline.set_current_time(1.0) await omni.kit.app.get_app().next_update_async() timecode = Usd.TimeCode(timeline.get_current_time() * stage.GetTimeCodesPerSecond()) with Sdf.ChangeBlock(): _update_animation(animation, animation_static, timecode) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_2_animation_update_sessionlayer_2.png") # play test timeline.set_auto_update(True) timeline.stop() await omni.kit.app.get_app().next_update_async() stage.RemovePrim(animation_static_path) ###Test joint change ##TODO 03: omnihydra does not support joints/blendshapes change in skelanimation prim ##TODO 04: omnihydra does not support blendshapes (target name) change in skelanimation prim (not in test) #with Sdf.ChangeBlock(): #_update_animation(animation, animation_static, Usd.TimeCode.Default()) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_0.png") #timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) #trans = animation.GetTranslationsAttr().Get(timecode) #rots = animation.GetRotationsAttr().Get(timecode) #scales = animation.GetScalesAttr().Get(timecode) #joints = animation.GetJointsAttr().Get() #new_joints = joints.__getitem__(slice(0,3,1)) #new_trans = trans.__getitem__(slice(0,3,1)) #new_rots = rots.__getitem__(slice(0,3,1)) #new_scales = scales.__getitem__(slice(0,3,1)) #animation_static.GetJointsAttr().Set(new_joints) #animation_static.GetTranslationsAttr().Set(new_trans) #animation_static.GetRotationsAttr().Set(new_rots) #animation_static.GetScalesAttr().Set(new_scales) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_1.png") #new_joints = joints.__getitem__(slice(0,2,1)) #new_trans = trans.__getitem__(slice(0,2,1)) #new_rots = rots.__getitem__(slice(0,2,1)) #new_scales = scales.__getitem__(slice(0,2,1)) #animation_static.GetJointsAttr().Set(new_joints) #animation_static.GetTranslationsAttr().Set(new_trans) #animation_static.GetRotationsAttr().Set(new_rots) #animation_static.GetScalesAttr().Set(new_scales) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_2.png") #animation_static.GetJointsAttr().Set(joints) #animation_static.GetTranslationsAttr().Set(trans) #animation_static.GetRotationsAttr().Set(rots) #animation_static.GetScalesAttr().Set(scales) #await wait_for_update() ###Test joint change in session layer #animation_static.GetJointsAttr().Set(joints) #with Sdf.ChangeBlock(): #_update_animation(animation, animation_static, Usd.TimeCode.Default()) #await wait_for_update() #await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_sessionlayer_0.png") #with Usd.EditContext(stage, session_layer): # timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) # trans = animation.GetTranslationsAttr().Get(timecode) # rots = animation.GetRotationsAttr().Get(timecode) # scales = animation.GetScalesAttr().Get(timecode) # joints = animation.GetJointsAttr().Get() # new_joints = joints.__getitem__(slice(0,3,1)) # new_trans = trans.__getitem__(slice(0,3,1)) # new_rots = rots.__getitem__(slice(0,3,1)) # new_scales = scales.__getitem__(slice(0,3,1)) # animation_static.GetJointsAttr().Set(new_joints) # animation_static.GetTranslationsAttr().Set(new_trans) # animation_static.GetRotationsAttr().Set(new_rots) # animation_static.GetScalesAttr().Set(new_scales) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_sessionlayer_1.png") # new_joints = joints.__getitem__(slice(0,2,1)) # new_trans = trans.__getitem__(slice(0,2,1)) # new_rots = rots.__getitem__(slice(0,2,1)) # new_scales = scales.__getitem__(slice(0,2,1)) # animation_static.GetJointsAttr().Set(new_joints) # animation_static.GetTranslationsAttr().Set(new_trans) # animation_static.GetRotationsAttr().Set(new_rots) # animation_static.GetScalesAttr().Set(new_scales) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_sessionlayer_2.png") # animation_static.GetJointsAttr().Set(joints) # animation_static.GetTranslationsAttr().Set(trans) # animation_static.GetRotationsAttr().Set(rots) # animation_static.GetScalesAttr().Set(scales) # await wait_for_update() # stage.RemovePrim(animation_static_path) async def test_03_skel_anim_create_delete(self): """ Test hydra skel - skel animation update """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) trans = animation.GetTranslationsAttr().Get(timecode) rots = animation.GetRotationsAttr().Get(timecode) scales = animation.GetScalesAttr().Get(timecode) joints = animation.GetJointsAttr().Get() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_0_animation_create_0.png") animation_new_path = "/ZAnimation_New" animation_new = UsdSkel.Animation.Define(stage, animation_new_path) animation_new_prim = animation_new.GetPrim() await wait_for_update() self.assertTrue(animation_new_prim) with Sdf.ChangeBlock(): animation_new.GetJointsAttr().Set(joints) animation_new.GetTranslationsAttr().Set(trans) animation_new.GetRotationsAttr().Set(rots) animation_new.GetScalesAttr().Set(scales) skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_new_path]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_0_animation_create_1.png") stage.RemovePrim(animation_new_path) skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #This line should supposed not to be needed #TODO 05 when skelanimation become invalid, skinning result should retrive restTransform await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_1_animation_delete_0.png") with Usd.EditContext(stage, session_layer): animation_new = UsdSkel.Animation.Define(stage, animation_new_path) animation_new_prim = animation_new.GetPrim() await wait_for_update() self.assertTrue(animation_new_prim) with Sdf.ChangeBlock(): animation_new.GetJointsAttr().Set(joints) animation_new.GetTranslationsAttr().Set(trans) animation_new.GetRotationsAttr().Set(rots) animation_new.GetScalesAttr().Set(scales) skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_new_path]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_2_animation_create_sessionlayer_0.png") with Sdf.ChangeBlock(): stage.RemovePrim(animation_new_path) skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #This line should supposed not to be needed #TODO 05 when skelanimation become invalid, skinning result should retrive restTransform skel_root_prim = stage.GetPrimAtPath("/Root/group1") skel_root = UsdSkel.Root(skel_root_prim) visible = skel_root.GetVisibilityAttr().Set("invisible") await wait_for_update() # test repopulate crash due to resync by update visibility in skelroot. skel_root.GetVisibilityAttr().Set("inherited") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_3_animation_delete_with_root_recync_sessionlayer_0.png") #This test is temporarily since we cannot dynamically update animation source on skelroot's bindAPI in omnihydra yet. async def test_04_skel_anim_on_skel_root(self): """ Test hydra skel - skel anim on root """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder_root.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelroot_path = "/Root/group1" skelroot_prim = stage.GetPrimAtPath(skelroot_path) skelroot = UsdSkel.Root(skelroot_prim) skelroot_bindingAPI = UsdSkel.BindingAPI(skelroot_prim) skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() # pure skeleton test await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_0_skeleton_0.png") #Test animation self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_1_animation_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_1_animation_1.png") timeline.set_current_time(1.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_1_animation_2.png") timeline.set_auto_update(True) timeline.stop() await omni.kit.app.get_app().next_update_async() async def test_05_skel_anim_update_restTransforms(self): """ Test hydra skel - update restTransforms """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder.usda") # self.set_settings(postLoadSkelTestSettings) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelroot_path = "/Root/group1" skelroot_prim = stage.GetPrimAtPath(skelroot_path) skelroot = UsdSkel.Root(skelroot_prim) skelroot_bindingAPI = UsdSkel.BindingAPI(skelroot_prim) skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() # pure skeleton test await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_0_skeleton_0.png") #Test animation self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource()) timecode = Usd.TimeCode.Default() poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_0.png") timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond()) poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_1.png") timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_2.png") with Usd.EditContext(stage, session_layer): timecode = Usd.TimeCode.Default() poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_session_layer_0.png") timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond()) poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_session_layer_1.png") timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond()) poses = animation.GetTransforms(timecode) skeleton.GetRestTransformsAttr().Set(poses) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_session_layer_2.png") timeline.set_auto_update(True) timeline.stop() await omni.kit.app.get_app().next_update_async() async def test_06_skel_anim_reference(self): """ Test hydra skel - skel anim reference """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder_ref.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelroot_path = "/Root/group1" skelroot_prim = stage.GetPrimAtPath(skelroot_path) skelroot = UsdSkel.Root(skelroot_prim) skelroot_bindingAPI = UsdSkel.BindingAPI(skelroot_prim) skeleton_path = "/Root/group1/joint1" skeleton_prim = stage.GetPrimAtPath(skeleton_path) skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim) skeleton = UsdSkel.Skeleton(skeleton_prim) animation_static_path = "/Root/group1/joint1/Animation_Static" animation_static_prim = stage.GetPrimAtPath(animation_static_path) animation_static = UsdSkel.Animation(animation_static_prim) animation_path = "/Root/group1/joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) animation = UsdSkel.Animation(animation_prim) animation_flat_path = "/Root/group1/joint1/Animation_Flat" animation_flat_prim = stage.GetPrimAtPath(animation_flat_path) aniamtion_flat = UsdSkel.Animation(animation_flat_prim) animation_outside_path = "/ZAnimation" animation_outside_prim = stage.GetPrimAtPath(animation_outside_path) aniamtion_outside = UsdSkel.Animation(animation_outside_prim) session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await omni.kit.app.get_app().next_update_async() # pure skeleton tests await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_0_skeleton_0.png") # Test animation self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim) refs = animation_prim.GetReferences() refs.SetReferences([Sdf.Reference(assetPath="./assets/skelcylinder_anim_flat.usda")]) timeline.set_current_time(0.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_1_animation_reference_0.png") timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_1_animation_reference_1.png") timeline.set_current_time(1.0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_1_animation_reference_2.png") timeline.set_auto_update(True) timeline.stop() async def test_07_skel_mesh_material_switch(self): """ Test hydra skel - skel anim reference """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder_material_test.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelmesh1_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder1" skelmesh1_prim = stage.GetPrimAtPath(skelmesh1_path) skelmesh2_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder2" skelmesh2_prim = stage.GetPrimAtPath(skelmesh2_path) print(skelmesh2_prim) material_red_path = "/Root/Looks/PreviewSurface_Red" material_blue_path = "/Root/Looks/PreviewSurface_Blue" session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await wait_for_update() # pure skeleton tests timeline.set_current_time(0.1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_0.png") # Test animations omni.kit.commands.execute( "BindMaterial", prim_path=Sdf.Path(skelmesh1_path), material_path=Sdf.Path(material_blue_path), strength=UsdShade.Tokens.weakerThanDescendants, ) timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_1.png") omni.kit.commands.execute( "BindMaterial", prim_path=Sdf.Path(skelmesh2_path), material_path=Sdf.Path(material_red_path), strength=UsdShade.Tokens.weakerThanDescendants, ) timeline.set_current_time(0.6) await wait_for_update() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_2.png") imageable = UsdGeom.Imageable(skelmesh2_prim) imageable.MakeInvisible() timeline.set_current_time(0.7) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_3.png") timeline.set_auto_update(True) timeline.stop() async def test_08_skel_mesh_animation_rename(self): """ Test hydra skel - skel anim reference """ self.set_settings(testSettings) super().open_usd("hydra/skel/skelcylinder_material_test.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadSkelTestSettings) stage = self.ctx.get_stage() skelmesh1_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder1" skelmesh1_prim = stage.GetPrimAtPath(skelmesh1_path) skelmesh2_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder2" skelmesh2_prim = stage.GetPrimAtPath(skelmesh2_path) animation_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_joint1/Animation" animation_prim = stage.GetPrimAtPath(animation_path) new_animation_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_joint1/Animation2" session_layer = stage.GetSessionLayer() timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) timeline.set_current_time(0.0) await wait_for_update() # pure skeleton tests timeline.set_current_time(0.5) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_0.png") old_prim_name = Sdf.Path(animation_path) move_dict = {old_prim_name: new_animation_path} omni.kit.commands.execute("MovePrims", paths_to_move=move_dict, destructive=False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_1.png") omni.kit.undo.undo() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_2.png") # Test animations omni.kit.commands.execute( "DeletePrims", paths=[Sdf.Path(animation_path)] ) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_3.png") omni.kit.undo.undo() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_4.png") timeline.set_auto_update(True) timeline.stop()
40,592
Python
50.448669
212
0.674985
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_light_collections.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.kit.commands import omni.kit.undo from .test_hydra_common import RtxHydraTest from .test_common import wait_for_update class TestRtxHydraLightCollections(RtxHydraTest): """ To run: from omni.kit.test import unittests from omni.rtx.tests import test_hydra_light_collections unittests.run_tests_in_modules([test_hydra_light_collections]) """ TEST_PATH = "hydra/lightCollections" LIGHT_PATH = "/World/defaultLight" LIGHT_VIS_PATH = LIGHT_PATH + ".visibility" LIGHT_SHADOW_EXCLUDE_PATH = LIGHT_PATH + ".collection:shadowLink:excludes" LIGHT_LINK_INCLUDE_PATH = LIGHT_PATH + ".collection:lightLink:includeRoot" CUBE_PATH = "/World/Cube" SHADOW_LINK_INCLUDE_PATH = LIGHT_PATH + ".collection:shadowLink:includeRoot" async def test_UNSTABLE_light_collection_undo(self): """ Regression test for usdImaging refresh issue when undoing light deletion """ self.open_usd("hydra/LightLink.usda") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-4) omni.kit.commands.execute("DeletePrims", paths=[self.LIGHT_PATH]) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionBlack.png", 1e-4) omni.kit.undo.undo() await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-4) # OM-56283, CI-1655 - Sporadic crash/unreliable image output async def test_UNSTABLE_light_collection_toggle_crash_UNSTABLE(self): """ Regression test for crash in Light Collection toggle """ self.open_usd("hydra/LightLink.usda") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=True, prev=False) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionInactive.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.SHADOW_LINK_INCLUDE_PATH, value=False, prev=True) await wait_for_update(wait_frames=1) omni.kit.commands.execute("ChangeProperty", prop_path=self.SHADOW_LINK_INCLUDE_PATH, value=True, prev=False) await wait_for_update(wait_frames=1) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=False, prev=True) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3) async def test_UNSTABLE_light_collection_lightvistoggle(self): """ Regression test for refresh issue when toggling light visibility """ self.open_usd("hydra/LightLink.usda") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_VIS_PATH, value="invisible", prev="inherited") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionBlack.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_VIS_PATH, value="inherited", prev="invisible") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3) # OM-53278 - occasionally produces pitch black image async def test_UNSTABLE_light_collection_refresh_issue_when_light_and_shadow_are_the_same_UNSTABLE(self): """ Regression test for refresh issue when the light and shadow collections become the same This is a regression test for OM-48040 Light Linking: light goes off after toggling Include Root on/off """ self.open_usd("hydra/LightLinkSimple.usda") await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionSimpleCubeNoLight.png", 1e-3) omni.kit.commands.execute( "AddRelationshipTarget", relationship=omni.usd.get_context().get_stage().GetPropertyAtPath(self.LIGHT_SHADOW_EXCLUDE_PATH), target=self.CUBE_PATH ) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionSimpleCubeNoShadow.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=False, prev=True) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionBlack.png", 1e-3) omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=True, prev=False) await wait_for_update(wait_frames=25) await self.capture_and_compare(self.TEST_PATH, "lightCollectionSimpleCubeNoShadow.png", 1e-3)
5,550
Python
43.766129
119
0.709369
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_postprocessing_tonemapper.py
## Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test import omni.kit.commands import carb import pathlib from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from .test_common import USD_DIR, EXTENSION_FOLDER_PATH from pxr import Gf, Sdf, Usd from pxr import UsdGeom, UsdLux class TestRtxPostprocessingTonemapper(RtxTest): TEST_PATH = "tonemapping" def open_usd_scene(self, path : pathlib.Path): omni.usd.get_context().open_stage(str(path)) def create_dome_light(self, name="/Xform/DomeLight"): omni.kit.commands.execute( "CreatePrim", prim_path=name, prim_type="DomeLight", select_new_prim=False, attributes={ UsdLux.Tokens.inputsIntensity: 1, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.inputsTextureFile: str(EXTENSION_FOLDER_PATH.joinpath("data/usd/hydra/daytime.hdr")), UsdGeom.Tokens.visibility: "inherited", } if hasattr(UsdLux.Tokens, 'inputsIntensity') else { UsdLux.Tokens.intensity: 1, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.textureFile: str(EXTENSION_FOLDER_PATH.joinpath("data/usd/hydra/daytime.hdr")), UsdGeom.Tokens.visibility: "inherited", }, create_default_xform=True, ) dome_light_prim = self.ctx.get_stage().GetPrimAtPath(name) return dome_light_prim async def setUp(self): await self.setUp_internal() carb.log_info("Setting up scene for RTX postprocessing tonemapping tests.") # Setting that should be set before opening a new stage self.set_settings(testSettings) rtxDataPath = EXTENSION_FOLDER_PATH.joinpath("../../../../../data/usd/tests") self.open_usd_scene(rtxDataPath.joinpath("BallCluster/ballcluster_stage.usda")) # Settings that should be set after opening a new stage self.set_settings(postLoadTestSettings) # camera setup: omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_path='/Ballcluster_set/Camera', prim_type='Camera', attributes={'focusDistance': 400, 'focalLength': 24, 'clippingRange': (1, 10000000)}, create_default_xform=False) omni.kit.commands.execute('TransformPrimCommand', path=Sdf.Path('/Ballcluster_set/Camera'), new_transform_matrix=Gf.Matrix4d(-0.6550639249522971, 0.7555734605093614, 6.112664085837494e-16, 0.0, 0.008064090705444693, 0.006991371699474781, 0.9999430439594318, 0.0, 0.7555304260366915, 0.6550266151048126, -0.010672808306432642, 0.0, 543.7716131933593, 536.4127523809548, 92.10006955095595, 1.0), old_transform_matrix=Gf.Matrix4d(-0.7071067811865474, 0.7071067811865478, 5.551115215516806e-17, 0.0, -0.4082482839677534, -0.4082482839677533, 0.8164965874238357, 0.0, 0.5773502737830692, 0.5773502737830688, 0.5773502600027394, 0.0, 500.0, 500.0, 500.0, 1.0), time_code=Usd.TimeCode.Default(), had_transform_at_key=False, usd_context_name='') # Create a domelight to get some high dynamic range going: self.domelight_prim = self.create_dome_light() # Disable this object so that the dome light is actually visible: omni.kit.commands.execute('DeletePrims', paths=['/Xform/sky_sphere_emiss'], destructive=False) await wait_for_update() # Activate the new camera: viewport_api = omni.kit.viewport.utility.get_active_viewport() viewport_api.set_active_camera("/Ballcluster_set/Camera") await omni.kit.app.get_app().next_update_async() my_settings = { "/app/hydraEngine/waitIdle" : True, "/app/renderer/waitIdle" : True, "/app/asyncRenderingLowLatency" : False, "/rtx-transient/resourcemanager/genMipsForNormalMaps" : False, "/rtx-transient/resourcemanager/texturestreaming/async" : False, "/rtx-transient/samplerFeedbackTileSize" : 1, "/rtx/hydra/perMaterialSyncLoads" : True, "/rtx/post/aa/op" : 0, # 0 = None, 2 = FXAA "/renderer/multiGpu/maxGpuCount" : 1, "/rtx/gatherColorToDisplayDevice" : True, "/rtx/rendermode" : 'PathTracing', "/rtx/raytracing/lightcache/spatialCache/enabled" : False, "/rtx/pathtracing/lightcache/cached/enabled" : False, "/rtx/pathtracing/cached/enabled" : False, "/rtx/pathtracing/optixDenoiser/enabled" : False, "/rtx/pathtracing/spp" : 1, "/rtx/pathtracing/totalSpp" : 1, "/rtx/pathtracing/maxBounces" : 2, "/rtx/hydra/perMaterialSyncLoads" : True, } self.set_settings(my_settings) await wait_for_update() # Marking unstable due to OM-86613 async def test_UNSTABLE_postprocessing_tonemappers_UNSTABLE(self): """ Test RTX Postprocessing Tonemappers """ self.set_settings({"/rtx/post/tonemap/op" : "0"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "0_tonemapper_test_clamp.png") # Make the domelight 'visible' for all non-clamp tonemappers # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 if hasattr(UsdLux.Tokens, 'inputsIntensity'): self.domelight_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(200) else: self.domelight_prim.GetAttribute(UsdLux.Tokens.intensity).Set(200) self.set_settings({"/rtx/post/tonemap/op" : "1"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "1_tonemapper_test_linear.png") self.set_settings({"/rtx/post/tonemap/op" : "2"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "2_tonemapper_test_reinhard.png") self.set_settings({"/rtx/post/tonemap/op" : "3"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "3_tonemapper_test_reinhard_modified.png") self.set_settings({"/rtx/post/tonemap/op" : "4"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "4_tonemapper_test_hejlhablealu.png") self.set_settings({"/rtx/post/tonemap/op" : "5"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "5_tonemapper_test_hableuc2.png") self.set_settings({"/rtx/post/tonemap/op" : "6"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "6_tonemapper_test_aces.png") self.set_settings({"/rtx/post/tonemap/op" : "7"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "7_tonemapper_test_iray.png")
7,492
Python
44.689024
115
0.645889
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/__init__.py
import sys if sys.platform == "win32": from .test_example import TestRtxExample1, TestRtxExample2 from .test_selectionoutline import TestRtxSelectionOutline from .test_hydra_mesh import * from .test_hydra_points import * from .test_hydra_basis_curves import * from .test_hydra_skel import * from .test_hydra_materials import * from .test_scenedb import TestRtxSceneDb from .test_hydra_light_collections import * from .test_hydra_volume import * from .test_domelight import TestRtxDomelight from .test_postprocessing_tonemapper import * from .test_light_toggling import * from .test_usdlux_schema_compat import * from .test_hydra_scene_delegate_omni_imaging import * from .test_picking import * from .test_material_distilling_toggle import * # Enable other extensions to use these test classes from .test_common import RtxTest, testSettings, postLoadTestSettings, OUTPUTS_DIR
944
Python
40.086955
81
0.745763
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_light_toggling.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test import omni.kit.commands import carb import pathlib from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from .test_common import EXTENSION_FOLDER_PATH from pxr import Gf, Sdf, Usd class TestRtxLightToggling(RtxTest): TEST_PATH = "light_toggling" def open_usd_scene(self, path : pathlib.Path): omni.usd.get_context().open_stage(str(path)) async def setUp(self): await self.setUp_internal() carb.log_info("Setting up scene for RTX postprocessing tonemapping tests.") self.set_settings(testSettings) rtxDataPath = EXTENSION_FOLDER_PATH.joinpath("../../../../../data/usd/tests") self.open_usd_scene(rtxDataPath.joinpath("KitchenSet/Kitchen_set.usda")) # camera setup: omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_path='/Kitchen_set/Camera', prim_type='Camera', attributes={'focusDistance': 400, 'focalLength': 24, 'clippingRange': (1, 10000000)}, create_default_xform=False) omni.kit.commands.execute('TransformPrimCommand', path=Sdf.Path('/Kitchen_set/Camera'), new_transform_matrix=Gf.Matrix4d( 0.929103525371008, 0.36981973871491086, 9.165845166192454e-16, 0.0, -0.07453993201486002, 0.18726775876424714, 0.9794766893921647, 0.0, 0.3622298133483562, -0.9100352451329841, 0.201557473037752, 0.0, 273.5074607559941, -621.0054603487383, 221.75447008156692, 1.0), old_transform_matrix=Gf.Matrix4d( 0.9305632067779971, 0.36613128545789503, 9.159340032886883e-16, 0.0, -0.09015111941855866, 0.22912905319151347, 0.9692123877928621, 0.0, 0.35485897742431627, -0.9019133876334855, 0.24622621174208614, 0.0, 328.2529492634561, -760.1471818173628, 259.74075506441545, 1.0), time_code=Usd.TimeCode.Default(), had_transform_at_key=False, usd_context_name='') # remove any selection, not sure why this happens, but otherwise weird bounding # boxes appear selection = omni.usd.get_context().get_selection() selection.clear_selected_prim_paths() await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) my_settings = { "/rtx/pathtracing/lightcache/cached/enabled": False, "/rtx/raytracing/lightcache/spatialCache/enabled" : False, "/rtx-transient/resourcemanager/genMipsForNormalMaps" : False, "/rtx-transient/resourcemanager/texturestreaming/async" : False, "/rtx-transient/samplerFeedbackTileSize" : 1, "/rtx/post/aa/op" : 0, # 0 = None, 2 = FXAA "/rtx/directLighting/sampledLighting/enabled" : False, # LTC gives consistent lighting "/rtx/reflections/enabled" : False, # Disabling reflections. "/rtx/reflections/sampledLighting/enabled" : False, # LTC gives consistent lighting "/rtx/sceneDb/ambientLightIntensity" : float(0.0), "/rtx/ambientOcclusion/enabled" : False, "/rtx/indirectDiffuse/enabled" : False, "/app/viewport/grid/enabled" : False, # Disable Kit Grid "/app/viewport/grid/showOrigin" : False, # Disable Kit Origin "/app/viewport/outline/enabled" : False, # Disable Selection drawing } self.set_settings(my_settings) async def test_light_toggling(self): """ Test RTX Light Toggling """ LIGHT_VIS_PATH = ".visibility" # Activate the main camera: viewport_api = omni.kit.viewport.utility.get_active_viewport() viewport_api.set_active_camera("/Kitchen_set/Camera") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "0_all_light_sources.png") # Disable SphereLight omni.kit.commands.execute("ChangeProperty", prop_path="/SphereLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "1_spherelight_off.png") # Disable DiskLight omni.kit.commands.execute("ChangeProperty", prop_path="/DiskLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "2_disklight_off.png") # Disable DistantLight # Disable RectLightLight omni.kit.commands.execute("ChangeProperty", prop_path="/DistantLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") omni.kit.commands.execute("ChangeProperty", prop_path="/RectLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") omni.kit.commands.execute("ChangeProperty", prop_path="/DiskLight" + LIGHT_VIS_PATH, value="inherited", prev="invisible") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "3_two_lights_off_one_light_on.png") # Enable Sphere Light # Enable Rect Light # Disable Cylinder Light omni.kit.commands.execute("ChangeProperty", prop_path="/SphereLight" + LIGHT_VIS_PATH, value="inherited", prev="invisible") omni.kit.commands.execute("ChangeProperty", prop_path="/RectLight" + LIGHT_VIS_PATH, value="inherited", prev="invisible") omni.kit.commands.execute("ChangeProperty", prop_path="/CylinderLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "4_one_light_off_two_lights_on.png")
6,132
Python
48.861788
133
0.664547
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_picking.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.usd import carb from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update class TestRtxPicking(RtxTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings and stage. await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) async def test_picking_queue(self): """ Verify picking/query requests are successfully queued """ super().add_floor() await wait_for_update() # OM-80470: Verify all picking requests requested in consecutive frames are all queued and executed successfully counter = 0 def query_complete(path, pos, *args, **kwargs): nonlocal counter counter += 1 import omni.kit.viewport viewport = omni.kit.viewport.utility.get_active_viewport() if hasattr(viewport, 'legacy_window'): return # Queue multiple query requests interrupted by a pick center = [int(v * 0.5) for v in viewport.resolution] viewport.request_query(center, query_complete, query_name="test_1") viewport.request_query(center, query_complete, query_name="test_2") viewport.request_pick(center, center, omni.usd.PickingMode.RESET_AND_SELECT) viewport.request_query(center, query_complete, query_name="test_3") viewport.request_query(center, query_complete, query_name="test_4") await wait_for_update(wait_frames=40) # All queries should complete self.assertEqual(counter, 4)
2,268
Python
39.517856
130
0.694444
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_materials.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 sys import path import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline import carb.settings from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest from .test_common import testSettings, postLoadTestSettings, wait_for_update, USD_DIR from pxr import Gf, Sdf, UsdGeom, UsdRender, UsdShade import shutil, os, pathlib class RtxHydraMaterialTest(RtxHydraTest): TEST_PATH = "hydra/materials" PRIM_PATH = "/World/box" DATA_PATH = "hydra/materials/reload" TEST_CLASS = "" # need to use the real path in order to have the filewatching work properly # -> client library ticket: https://nvidia-omniverse.atlassian.net/browse/CC-168 def getDataPath(self, relativePath) -> str: data_path : str = USD_DIR.joinpath(self.DATA_PATH, relativePath) return pathlib.Path(os.path.normpath(data_path)).resolve() # helper to override the test files # in case we want to do more or use another function def copyTestFile(self, source : str, target : str): shutil.copy(self.getDataPath(source), self.getDataPath(target)) # delete the temporary file created def cleanupTestFile(self, target : str): os.remove(self.getDataPath(target)) # basic structure of a test case init async def initTest(self, caseName: str): goldenImage = f"reload-{self.TEST_CLASS}-{caseName}.png" # compare await wait_for_update(wait_frames=10) await self.capture_and_compare(self.TEST_PATH, goldenImage) # basic structure of a test case async def changeMdlAndTest(self, caseName: str, moduleToChange: str, threshold=None): sourceFile = f"{self.TEST_CLASS}/{caseName}.mdl" targetFile = f"{self.TEST_CLASS}/{moduleToChange}.mdl" goldenImage = f"reload-{self.TEST_CLASS}-{caseName}.png" if threshold is None: threshold = self.THRESHOLD # change MDL self.copyTestFile(sourceFile, targetFile) # compare await wait_for_update(wait_frames=10) await self.capture_and_compare(self.TEST_PATH, goldenImage, threshold) class TestRtxHydraMaterialsReloadBasic(RtxHydraMaterialTest): MEDIUM_THRESHOLD = 3.0e-5 async def setUp(self): self.TEST_CLASS = "basic" await self.setUp_internal() self.set_settings(testSettings) # prepare initial MDL module self.copyTestFile("basic/A_init.mdl", "basic/A.mdl") # load the test scene scenePath = self.getDataPath("basic/XYZ.usda") print(f"Scene Path: {scenePath}") super().open_usd(scenePath) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_touch_no_change(self): """ Test hydra materials - reload basic - touch, no change """ # make sure we start with the right material await self.initTest("A_init") # touch the file by copying the same file again await self.changeMdlAndTest("A_init", "A", self.MEDIUM_THRESHOLD) # remove the temp file self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl") async def test_change_body(self): """ Test hydra materials - reload basic - change body """ # make sure we start with the right material await self.initTest("A_init") # make multiple changes in a row await self.changeMdlAndTest("A_change_body_1", "A", self.MEDIUM_THRESHOLD) await self.changeMdlAndTest("A_change_body_2", "A", self.MEDIUM_THRESHOLD) # remove the temp file self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl") class TestRtxHydraMaterialsReloadSignature(RtxHydraMaterialTest): async def setUp(self): self.TEST_CLASS = "signature" await self.setUp_internal() self.set_settings(testSettings) # prepare initial MDL module self.copyTestFile("signature/A_init.mdl", "signature/A.mdl") # load the test scene scenePath = self.getDataPath("signature/A.usda") print(f"Scene Path: {scenePath}") super().open_usd(scenePath) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_change_signature(self): """ Test hydra materials - reload signature - change signature """ # make sure we start with the right material await self.initTest("A_init") # run test cases await self.changeMdlAndTest("A_add_parameter", "A") await self.changeMdlAndTest("A_rename_parameter", "A") await self.changeMdlAndTest("A_move_parameter", "A") await self.changeMdlAndTest("A_change_parameter_default", "A") await self.changeMdlAndTest("A_change_parameter_type", "A") await self.changeMdlAndTest("A_remove_parameter", "A") # remove the temp file self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl") class TestRtxHydraMaterialsReloadGraph(RtxHydraMaterialTest): async def setUp(self): self.TEST_CLASS = "graph" await self.setUp_internal() self.set_settings(testSettings) # prepare initial MDL module self.copyTestFile("graph/A_init.mdl", "graph/A.mdl") # load the test scene scenePath = self.getDataPath("graph/GraphA.usda") print(f"Scene Path: {scenePath}") super().open_usd(scenePath) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) # Unstable via OM-53607 async def test_UNSTABLE_change_function_body_UNSTABLE(self): """ Test hydra materials - reload graph - change function body """ # make sure we start with the right material await self.initTest("A_init") # run test cases await self.changeMdlAndTest("A_change_function_body", "A") await self.changeMdlAndTest("A_change_function_param_defaults", "A") await self.changeMdlAndTest("A_add_function_param", "A") await self.changeMdlAndTest("A_move_function_param", "A") await self.changeMdlAndTest("A_remove_function_param", "A") # remove the temp file self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl") class TestRtxHydraMaterialsDebugMode(RtxHydraMaterialTest): async def setUp(self): self.TEST_CLASS = "debugMode" await self.setUp_internal() self.set_settings(testSettings) async def test_whiteMode(self): """ Test hydra materials - toggling white mode """ super().open_usd("hydra/materials/two_spheres.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_off.png", 1e-4) self.set_settings({"/rtx/debugMaterialType": 0}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_on.png", 1e-4) shader = self.ctx.get_stage().GetPrimAtPath("/World/Looks/PreviewSurface/Shader") attr = shader.GetAttribute("inputs:excludeFromWhiteMode") attr.Set(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_on_withExclude.png", 1e-4) attr.Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_on_withoutExclude.png", 1e-4) self.set_settings({"/rtx/debugMaterialType": -1}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_off_again.png", 1e-4) class TestRtxHydraMaterialStdModules(RtxHydraTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) super().open_usd("hydra/materials/stdmodules/test_std_modules.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_load_stdmodules(self): await wait_for_update(wait_frames=10) await self.capture_and_compare("hydra/materials", "stdmodules.png")
8,611
Python
37.446428
105
0.66926
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_basis_curves.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.timeline from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest from .test_common import wait_for_update, postLoadTestSettings from pxr import Sdf, Vt, UsdGeom, UsdShade simplePts = [(0, -100, 0), (50, -50, 0), (-50, 50, 0), (0, 100, 0)] simpleCnt = len(simplePts) linearPts = [(0, -100, 0), (50, 0, 0), (0, 100, 0)] linearCnt = len(linearPts) bezierPts = [(0, -100, 0), (25, -25, 0), (50, 0, 0), (0, 25, 0), (-50, 50, 0), (-25, 75, 0), (0, 100, 0)] bezierCnt = len(bezierPts) bsplinePts = [(0, -200, 0), (25, -25, 0), (-25, 0, 0), (50, 25, 0), (0, 200, 0)] bsplineCnt = len(bsplinePts) catromPts = [(0, -200, 0), (25, -50, 0), (-25, -15, 0), (-25, 15, 0), (50, 50, 0), (0, 200, 0)] catromCnt = len(catromPts) periodicPts = [(-200, -200, 0), (200, -200, 0), (200, 200, 0), (-200, 200, 0)] periodicCnt = len(periodicPts) bezierPeriodicPts = [(0, -200, 0), (-100, -200, 0), (-200, -100, 0), (-200, 0, 0), (-200, 100, 0), (-100, 200, 0), (0, 200, 0), (100, 200, 0), (200, 100, 0)] bezierPeriodicCnt = len(bezierPeriodicPts) class TestRtxHydraBasisCurves(RtxHydraTest): TEST_PATH = "hydra/basisCurves" PRIM_PATH = "/World/curve" async def setUp(self): await super().setUp() timeline = omni.timeline.get_timeline_interface() self.set_settings({"/rtx/hydra/curves/enabled": True, "/rtx/hydra/curves/splits": 1}) def _create_geometry(self, cnt, v, widthInterpolation="constant", width=None, basis="bezier", type="cubic", wrap="nonperiodic", name=PRIM_PATH): curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), name) curve.CreateCurveVertexCountsAttr(cnt) curve.CreatePointsAttr(v) curve.SetWidthsInterpolation(widthInterpolation) curve.CreateWidthsAttr(width if width else [20]) curve.CreateBasisAttr(basis) curve.CreateTypeAttr(type) curve.CreateWrapAttr(wrap) return curve async def create_geometry_and_test(self, golden, *args, **kwargs): self._create_geometry(*args, **kwargs) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, golden) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def create_geometry_and_test_primvar(self, golden, pvName, pvType, pvInterp, pvData, *args, **kwargs): self._create_geometry(*args, **kwargs) prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) attr = UsdGeom.PrimvarsAPI(prim).CreatePrimvar(pvName, pvType, pvInterp) attr.Set(pvData) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, golden) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) def create_geometry(self, name=PRIM_PATH): curve = self._create_geometry([simpleCnt], simplePts, name=name) return curve async def test_visibility(self): """ Test hydra basis curves - visibility """ await self.visibility() async def test_doNotCastShadow(self): """ Test hydra basis curves - doNotCastShadow toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "doNotCastShadows") async def test_matteObject(self): """ Test hydra basis curves - isMatteObject toggle """ self.create_geometry_with_floor() await self.matte() async def test_hideForCamera(self): """ Test hydra basis curves - hideForCamera toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "hideForCamera") async def test_transform(self): """ Test hydra basis curves - tranform """ await self.transform_all() async def test_display_color(self): """ Test hydra basis curves - change display color """ # Constant geom = self.create_geometry() geom.CreateDisplayColorPrimvar("constant").Set([(0, 1, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorConstant.png") return geom async def test_widths(self): """ Test hydra basis curves - change width """ await self.create_geometry_and_test("bezier.png", [bezierCnt], bezierPts, "constant", [20, 19]) await self.create_geometry_and_test("widthDefault.png", [bezierCnt], bezierPts, "constant", []) await self.create_geometry_and_test("widthLinear.png", [linearCnt], linearPts, "vertex", [0, 30, 0], type="linear") await self.create_geometry_and_test("widthVertex.png", [bezierCnt], bezierPts, "vertex", [0, 10, 20, 30, 20, 10, 0]) await self.create_geometry_and_test("widthBsplineVertex.png", [bsplineCnt], bsplinePts, "vertex", [0, 10, 30, 10, 0], "bspline") await self.create_geometry_and_test("widthLinear.png", [linearCnt], linearPts, "varying", [0, 30, 0], type="linear") await self.create_geometry_and_test("widthVarying.png", [bezierCnt], bezierPts, "varying", [10, 30, 50]) await self.create_geometry_and_test("widthBsplineVarying.png", [bsplineCnt], bsplinePts, "varying", [10, 30, 10], "bspline") pts2 = bezierPts + [(p[0], p[1], 50) for p in bezierPts] await self.create_geometry_and_test("widthConstant.png", [bezierCnt, bezierCnt], pts2, "constant", [30]) await self.create_geometry_and_test("widthUniform.png", [bezierCnt, bezierCnt], pts2, "uniform", [10, 30]) lPts2 = linearPts + [(p[0], p[1], 50) for p in linearPts] await self.create_geometry_and_test("widthLinear2.png", [linearCnt, linearCnt], lPts2, "varying", [10, 30, 50, 5, 35, 5], type="linear") await self.create_geometry_and_test("widthVarying2.png", [bezierCnt, bezierCnt], pts2, "varying", [10, 30, 50, 5, 35, 5]) bsPts2 = bsplinePts + [(p[0], p[1], 50) for p in bsplinePts] await self.create_geometry_and_test("widthBsplineVarying2.png", [bsplineCnt, bsplineCnt], bsPts2, "varying", [10, 30, 50, 5, 35, 5], "bspline") async def test_points(self): """ Test hydra basis curves - update points """ pts = [simplePts, simplePts.copy()] pts[1][1] = (-50, -50, 0) pts[1][2] = (50, 50, 0) await self.attribute_test_case(self.create_geometry, "points", Sdf.ValueTypeNames.Point3f, pts, ["geom.png", "points.png"]) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # TODO fix curves for delayed points assignments # curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), self.PRIM_PATH) # curve.CreateWidthsAttr([20]) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "empty.png") # curve.CreateCurveVertexCountsAttr([simpleCnt]) # curve.CreatePointsAttr(simplePts) # await wait_for_update() # await self.capture_and_compare(self.TEST_PATH, "empty.png") async def test_skip_processing(self): """ Test hydra basis curves - skipProcessing attribute """ geom = self.create_geometry() geom.GetPrim().CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool).Set(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "empty.png") async def test_topology_wrap(self): """ Test hydra basis curves - wrap """ # bspline: await self.create_geometry_and_test("bsplinePinned.png", [bsplineCnt], bsplinePts, "constant", [20], "bspline", "cubic", "pinned") await self.create_geometry_and_test("bsplinePinned2.png", [bsplineCnt, bsplineCnt], bsplinePts + [(p[0], p[1], 50) for p in bsplinePts], "constant", [20], "bspline", "cubic", "pinned") # catmullRom await self.create_geometry_and_test("catmullRomPinned.png", [catromCnt], catromPts, "constant", [20], "catmullRom", "cubic", "pinned") await self.create_geometry_and_test("catmullRomPinned2.png", [catromCnt, catromCnt], catromPts + [(p[0], p[1], 50) for p in catromPts], "constant", [20], "catmullRom", "cubic", "pinned") # bspline: await self.create_geometry_and_test("bsplinePeriodic.png", [periodicCnt], periodicPts, "constant", [20], "bspline", "cubic", "periodic") await self.create_geometry_and_test("bsplinePeriodic2.png", [periodicCnt, periodicCnt], periodicPts + [(p[0], p[1], 50) for p in periodicPts], "constant", [20], "bspline", "cubic", "periodic") # catmullRom await self.create_geometry_and_test("catmullRomPeriodic.png", [periodicCnt], periodicPts, "constant", [20], "catmullRom", "cubic", "periodic") await self.create_geometry_and_test("catmullRomPeriodic2.png", [periodicCnt, periodicCnt], periodicPts + [(p[0], p[1], 50) for p in periodicPts], "constant", [20], "catmullRom", "cubic", "periodic") # bezier await self.create_geometry_and_test("bezierPeriodic.png", [bezierPeriodicCnt], bezierPeriodicPts, "constant", [20], "bezier", "cubic", "periodic") # linear await self.create_geometry_and_test("linearPeriodic.png", [periodicCnt], periodicPts, type="linear", wrap="periodic") async def test_topology_basis(self): """ Test hydra basis curves - topology basis """ # linear: 2 + (n - 1) await self.create_geometry_and_test("linear.png", [linearCnt], linearPts, type="linear") await self.create_geometry_and_test("linear2.png", [linearCnt, linearCnt], linearPts + [(p[0], p[1], 50) for p in linearPts], type="linear", wrap="nonperiodic") # bezier: 4 + 3 * (n - 1) pts await self.create_geometry_and_test("bezier.png", [bezierCnt], bezierPts, "constant", [20], "bezier", "cubic", "nonperiodic") # # more points than needed, but this is ok await self.create_geometry_and_test("bezier.png", [bezierCnt], bezierPts + [(0, 0, 0)]) # # indices - ibychkov: is this supported? How it can be set? # bspline: 4 + (n - 1) pts await self.create_geometry_and_test("bspline.png", [bsplineCnt], bsplinePts, "constant", [20], "bspline", "cubic", "nonperiodic") # catmullRom await self.create_geometry_and_test("catmullRom.png", [catromCnt], catromPts, "constant", [20], "catmullRom", "cubic", "nonperiodic") # Ribbons - Not supported - OM-36882 async def test_topology_incorrect(self): """ Test hydra basis curves - incorrect topology """ efn = "empty.png" # test incorrect number of points # linear await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], type="linear") await self.create_geometry_and_test(efn, [2], [(0, -100, 0), (-100, 0, 0)], type="linear", wrap="periodic") # bezier await self.create_geometry_and_test(efn, [0], []) await self.create_geometry_and_test(efn, [4], []) await self.create_geometry_and_test(efn, [1], [(0, -100, 0), (50, -50, 0), (0, 0, 0), (-50, 50, 0), (0, 100, 0)]) await self.create_geometry_and_test(efn, [1], [(0, -100, 0)]) await self.create_geometry_and_test(efn, [2], [(0, -100, 0), (50, -50, 0)]) await self.create_geometry_and_test(efn, [3], [(0, -100, 0), (50, -50, 0), (0, 0, 0)]) await self.create_geometry_and_test(efn, [4], [(0, -100, 0)]) await self.create_geometry_and_test(efn, [5], [(0, -100, 0), (50, -50, 0), (0, 0, 0), (-50, 50, 0), (0, 100, 0), (50, 150, 0)]) await self.create_geometry_and_test(efn, [7], [(0, -100, 0), (25, -25, 0), (50, 0, 0), (0, 25, 0), (-50, 50, 0), (-25, 75, 0), (0, 100, 0)], "constant", [20], "bezier", "cubic", "periodic") await self.create_geometry_and_test(efn, [7, 7], [(0, -100, 0), (25, -25, 0), (50, 0, 0), (0, 25, 0), (-50, 50, 0), (-25, 75, 0), (0, 100, 0)]) # bspline await self.create_geometry_and_test(efn, [3], [(0, -100, 0), (50, -50, 0), (0, 0, 0)], basis="bspline") await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "bspline", "cubic", "periodic") await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "bspline", "cubic", "pinned") # catmullRom await self.create_geometry_and_test(efn, [3], [(0, -100, 0), (50, -50, 0), (0, 0, 0)], basis="catmullRom") await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "catmullRom", "cubic", "periodic") await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "catmullRom", "cubic", "pinned") # pinned wrap, bezier await self.create_geometry_and_test("empty.png", [bezierCnt], bezierPts, "constant", [20], "bezier", "cubic", "pinned") # test incorrect number of widths pts2 = bezierPts + [(p[0], p[1], 50) for p in bezierPts] await self.create_geometry_and_test(efn, [bezierCnt], bezierPts, "vertex", [0, 10, 20, 30, 20, 10]) await self.create_geometry_and_test(efn, [bezierCnt], bezierPts, "varying", [20]) await self.create_geometry_and_test(efn, [bezierCnt, bezierCnt], pts2, "uniform", [20]) # test incorrect number of display color async def test_normal_and_tangents(self): """ Test hydra basis curves - normal and tangents """ self.set_settings({"/rtx/debugView/target": "normal"}) await self.create_geometry_and_test("normalLinear.png", [linearCnt], linearPts, "constant", [40], type="linear") await self.create_geometry_and_test("normal.png", [bezierCnt], bezierPts, "constant", [40]) await self.create_geometry_and_test("normalBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline") await self.create_geometry_and_test("normalCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom") self.set_settings({"/rtx/debugView/target": "tangentu"}) await self.create_geometry_and_test("tangentuLinear.png", [linearCnt], linearPts, "constant", [40], type="linear") await self.create_geometry_and_test("tangentu.png", [bezierCnt], bezierPts, "constant", [40]) await self.create_geometry_and_test("tangentuBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline") await self.create_geometry_and_test("tangentuCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom") self.set_settings({"/rtx/debugView/target": "tangentv"}) await self.create_geometry_and_test("tangentvLinear.png", [linearCnt], linearPts, "constant", [40], type="linear") await self.create_geometry_and_test("tangentv.png", [bezierCnt], bezierPts, "constant", [40]) await self.create_geometry_and_test("tangentvBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline") await self.create_geometry_and_test("tangentvCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom") async def test_texCoords(self): """ Test hydra basis curves - texCoords (UVs) """ self.set_settings({"/rtx/debugView/target": "texcoord0"}) await self.create_geometry_and_test("texCoordsLinear.png", [linearCnt], linearPts, "vertex", [10, 30, 50], type="linear") await self.create_geometry_and_test("texCoords.png", [bezierCnt], bezierPts, "varying", [10, 30, 50]) await self.create_geometry_and_test("texCoordsBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline") await self.create_geometry_and_test("texCoordsCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom") async def test_texCoords2(self): """ Test hydra basis curves - texCoords (UVs) set 2. Defined by asset. """ self.set_settings({"/rtx/debugView/target": "texcoord1"}) await self.create_geometry_and_test_primvar("texCoords2Vertex.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex, [(0, 0), (0.15, 0), (0.3, 0), (0.5, 0), (0.7, 0), (0.85, 0), (1, 0)], [bezierCnt], bezierPts, "varying", [10, 30, 50]) await self.create_geometry_and_test_primvar("texCoords2Uniform.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.uniform, [(0, 0.5), (1, 0)], [bezierCnt, bezierCnt], bezierPts + [(p[0], p[1], 50) for p in bezierPts]) # Pinned wrap await self.create_geometry_and_test_primvar("texCoords2VertexPinned.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex, [(0, 0), (0.3, 0), (0.5, 0), (0.7, 0), (1, 0)], [bsplineCnt], bsplinePts, "constant", [30], "bspline", "cubic", "pinned") await self.create_geometry_and_test_primvar("texCoords2UniformPinned.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.uniform, [(0, 0.5), (1, 0)], [bsplineCnt, bsplineCnt], bsplinePts + [(p[0], p[1], 50) for p in bsplinePts], "constant", [20], "bspline", "cubic", "pinned") # Peropdic wrap await self.create_geometry_and_test_primvar("texCoords2VertexPeriodic.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex, [(0, 0), (0.3, 0), (0.5, 0), (1, 0)], [periodicCnt], periodicPts, "constant", [30], "bspline", "cubic", "periodic") await self.create_geometry_and_test_primvar("texCoords2UniformPeriodic.png", "uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.uniform, [(0, 0.5), (1, 0)], [periodicCnt, periodicCnt], periodicPts + [(p[0], p[1], 50) for p in periodicPts], "constant", [20], "bspline", "cubic", "periodic") async def test_endcaps(self): """ Test hydra basis curves - endcaps. For cubic curves - flat and open For linear curves - only round """ self._create_geometry([bezierCnt], bezierPts, "varying", [30, 30, 50]) prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) pv = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("endcaps", Sdf.ValueTypeNames.Int) # Flat pv.Set(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "endcapFlat.png") # Open pv.Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "endcapOpen.png") # OM-55978: Discontinuity along curves or hair fibers when the endcaps option set to open self.set_camera((1.25, 1.25, 1.25), (0, 0, 0)) self.set_settings({"/rtx/debugView/target": "normal"}) self._create_geometry([4], [(0, -10, 0), (0, 0, 0), (0, 10, 0), (0, 20, 0)], "constant", [1], "bspline", "cubic", "pinned") prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) pv = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("endcaps", Sdf.ValueTypeNames.Int) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "om55978.png") async def test_numsplits(self): """ Test hydra basis curves - numSplits. For cubic curves only """ self.set_settings({"/rtx/wireframe/enabled": True}) self.set_settings({"/rtx/wireframe/wireframeThickness": 5}) self.set_settings({"/rtx/wireframe/mode": 2}) # Global setting self._create_geometry([bezierCnt], bezierPts, "constant", [20]) self.set_settings({"/rtx/hydra/curves/splits": 4}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bezier4Splits.png") # Update global setting self.set_settings({"/rtx/hydra/curves/splits": 1}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bezier1Splits.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Primvar with overrided self._create_geometry([bezierCnt], bezierPts, "constant", [20]) prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplitsOverride", Sdf.ValueTypeNames.Bool).Set(True) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplits", Sdf.ValueTypeNames.Int).Set(2) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bezier2Splits.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Primvar without override (it should get num splits from global setting == 1) self._create_geometry([bezierCnt], bezierPts, "constant", [20]) prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplits", Sdf.ValueTypeNames.Int).Set(2) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bezier1Splits.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Bspline self._create_geometry([bsplineCnt], bsplinePts, "constant", [20], "bspline") prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplits", Sdf.ValueTypeNames.Int).Set(2) UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplitsOverride", Sdf.ValueTypeNames.Bool).Set(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "bspline2Splits.png") async def test_timeSampled(self): """ Test hydra basis curves - verify time sample animation works. """ super().open_usd("hydra/curves_timeSampled_001.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) timeline = omni.timeline.get_timeline_interface() # Regression test for OM-96462, where time-sampled xform was impairing update of time-sampled points await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "curves_timeSampled_frame0.png") # Advance a few frames and capture another frame for t in range(12): timeline.forward_one_frame() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "curves_timeSampled_frame12.png") class TestRtxHydraBasisCurvesInstancer(RtxHydraInstancerTest): # TODO full cover scene instancer with tests TEST_PATH = "hydra/basisCurves/instancer" GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/curve" def create_geometry(self, name=GEOM_PATH): curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), name) curve.CreateCurveVertexCountsAttr([simpleCnt]) curve.CreatePointsAttr(simplePts) curve.CreateWidthsAttr([0, 20, 20, 0]) return curve async def test_sceneInstancer(self): """ Test hydra basis curves - scene instancer """ await self.si_all() async def test_pointInstancer(self): """ Test hydra basis curves - point instancer """ await self.pi_all() class TestRtxHydraBasisCurvesMaterials(RtxHydraMaterialsTest): TEST_PATH = "hydra/basisCurves/material" PRIM_PATH = "/World/curve" def create_geometry(self, name=PRIM_PATH): curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), name) curve.CreateCurveVertexCountsAttr([simpleCnt]) curve.CreatePointsAttr(simplePts) curve.CreateWidthsAttr([10, 30, 30, 10]) return curve # Unstable via OM-53604 async def test_UNSTABLE_materials_UNSTABLE(self): """ Test hydra basis curves - materials """ materials = ["Green", "Red"] looksPath = "/World/Looks/" # Set and change material geomPrim = self.create_geometry().GetPrim() for m in materials: self.bind_material(geomPrim, looksPath + m) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_{}.png".format(m)) # Unbind material it should fallback to basic material UsdShade.MaterialBindingAPI(geomPrim).UnbindAllBindings() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_base.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
24,695
Python
50.665272
197
0.626443
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_common.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline from .test_common import RtxTest, testSettings, postLoadTestSettings, set_transform_helper, wait_for_update from pxr import Sdf, Gf, UsdGeom, UsdShade class RtxHydraTest(RtxTest): """ Base class for hydra tests """ # override resolution WINDOW_SIZE = (512, 512) TEST_PATH = "hydra" PRIM_PATH = "" async def setUp(self): await self.setUp_internal() self.set_settings(testSettings) omni.usd.get_context().new_stage() self.add_dir_light() await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) def create_geometry(self, name=PRIM_PATH): pass def create_geometry_with_floor(self): self.add_floor() self.create_geometry() set_transform_helper(self.PRIM_PATH, translate=Gf.Vec3d(0, 100, 0)) async def geometry_with_attribute(self, attrName, attrType, attrVal, shouldWait=False): geom = self.create_geometry() if shouldWait: await wait_for_update() attr = geom.GetPrim().CreateAttribute(attrName, attrType) self.assertTrue(attr) attr.Set(attrVal) await wait_for_update() return geom async def set_attribute_timesampled(self, geom, attrName, attrType, attrVals, goldens): attr = geom.GetPrim().CreateAttribute(attrName, attrType) self.assertTrue(attr) for i, v in enumerate(attrVals): attr.Set(v, i) self.assertTrue(len(attrVals) == len(goldens)) timeline = omni.timeline.get_timeline_interface() timeline.set_target_framerate(timeline.get_time_codes_per_seconds()) timeline.play() timeline.set_auto_update(False) for i, g in enumerate(goldens): timeline.set_current_time(i) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, g) timeline.set_auto_update(True) timeline.stop() async def attribute_test_case(self, createGeom, attrName, attrType, attrVals, goldens): self.assertTrue(len(attrVals) > 1) self.assertTrue(len(attrVals) == len(goldens)) geom = createGeom() attr = geom.GetPrim().CreateAttribute(attrName, attrType) self.assertTrue(attr) # Test updating attribute for i, g in enumerate(goldens): attr.Set(attrVals[i]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, g) # Test timesampled attribute self.ctx.get_stage().RemovePrim(self.PRIM_PATH) geom = createGeom() await self.set_attribute_timesampled(geom, attrName, attrType, attrVals, goldens) async def toggle_primvar(self, geomPath, primvarName, primvarType=Sdf.ValueTypeNames.Bool, primvarVal=True, baseGoldenName="boxAndFloor.png", threshould=1e-5): prim = self.ctx.get_stage().GetPrimAtPath(geomPath) attr = UsdGeom.PrimvarsAPI(prim).CreatePrimvar(primvarName, primvarType) self.assertTrue(attr) await wait_for_update() self.assertFalse(attr.Get() == primvarVal) await self.capture_and_compare(self.TEST_PATH, baseGoldenName) attr.Set(primvarVal) await wait_for_update() self.assertTrue(attr.Get() == primvarVal) await self.capture_and_compare(self.TEST_PATH, primvarName + ".png", threshould) async def visibility(self): prim = self.create_geometry() attr = prim.GetVisibilityAttr() self.assertTrue(attr) for i in range(2): attr.Set(UsdGeom.Tokens.inherited) await wait_for_update() self.assertTrue(attr.Get() == UsdGeom.Tokens.inherited) await self.capture_and_compare(self.TEST_PATH, "geom.png") attr.Set(UsdGeom.Tokens.invisible) await wait_for_update() self.assertTrue(attr.Get() == UsdGeom.Tokens.invisible) await self.capture_and_compare(self.TEST_PATH, "empty.png") async def cull_style(self): # Not yet supported by hydra pass async def double_sided(self): pass async def single_sided(self): self.set_settings({"/rtx/debugView/target": "normal", "/rtx/hydra/faceCulling/enabled": True}) geom = self.create_geometry() attr = geom.GetPrim().CreateAttribute("singleSided", Sdf.ValueTypeNames.Bool) self.assertTrue(attr) self.set_camera(cameraPos=(0, 0, 0), targetPos=(-500, -500, -500)) await wait_for_update() self.assertFalse(attr.Get()) await self.capture_and_compare(self.TEST_PATH, "doubleSided.png") attr.Set(True) await wait_for_update() self.assertTrue(attr.Get()) await self.capture_and_compare(self.TEST_PATH, "singleSided.png") async def matte(self): self.set_settings({"/rtx/matteObject/enabled": True, "/rtx/post/backgroundZeroAlpha/enabled": True, "/rtx/post/backgroundZeroAlpha/backgroundComposite": True, "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor": (0, 0, 0)}) await self.toggle_primvar("/World/Floor", "isMatteObject") async def is_picked(self): # This is not worked when kit is not focused. Skip tests while solution wouldn't be found self.skipTest("Test is not worked correctly yet!") #viewport = omni.kit.viewport_legacy.acquire_viewport_interface().get_viewport_window(None) #isPicked = False # for i in range(10): # set_cursor_position((int(self.WINDOW_SIZE[0] / 2), int(self.WINDOW_SIZE[1] / 2))) # await omni.kit.app.get_app().next_update_async() # ret = viewport.get_hovered_world_position() # isPicked |= ret[0] #return isPicked async def pickable(self): geom = self.create_geometry() self.assertTrue(await self.is_picked()) self.ctx.set_pickable(self.PRIM_PATH, False) # set_pickable is not catched correctly by hydra yet. So we need to update any primvar to force update instance attr = geom.GetPrim().CreateAttribute("singleSided", Sdf.ValueTypeNames.Bool) attr.Set(True) await wait_for_update() self.assertFalse(await self.is_picked()) async def transform_translate(self): self.create_geometry() set_transform_helper(self.PRIM_PATH, translate=Gf.Vec3d(0, 0, 150)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "translateZ.png") async def transform_rotate(self): self.create_geometry() set_transform_helper(self.PRIM_PATH, euler=Gf.Vec3d(0, 45, 0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "rotateY.png") async def transform_scale(self): self.create_geometry() set_transform_helper(self.PRIM_PATH, scale=Gf.Vec3d(2, 1, 1)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "scaleX.png") async def transform_combined(self, shouldWait=False): self.create_geometry() if shouldWait: await wait_for_update() set_transform_helper(self.PRIM_PATH, translate=Gf.Vec3d(0, 0, 150), euler=Gf.Vec3d(0, 45, 0), scale=Gf.Vec3d(2, 1, 1)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tranlateZrotateYscaleX.png") async def transform_all(self): await self.transform_translate() self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await self.transform_rotate() self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await self.transform_scale() self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await self.transform_combined(shouldWait=True) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await wait_for_update() await self.transform_combined(shouldWait=False) class RtxHydraMaterialsTest(RtxHydraTest): TEST_PATH = "" PRIM_PATH = "" async def setUp(self): await self.setUp_internal() self.set_settings(testSettings) super().open_usd("hydra/UsdShade.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) def create_geometry(self, name): pass def bind_material(self, geom, material_path): binding_api = UsdShade.MaterialBindingAPI(geom) material_prim = self.ctx.get_stage().GetPrimAtPath(material_path) material = UsdShade.Material(material_prim) binding_api.Bind(material, UsdShade.Tokens.weakerThanDescendants) class RtxHydraInstancerTest(RtxHydraTest): # TODO full cover scene instancer with tests TEST_PATH = "" GEOM_PATH = "" PRIM_PATH = "/World/instance" PRIM1_PATH = "/World/instance1" PRIM2_PATH = "/World/instance2" def create_geometry(self, name): pass def create_scene_instancer(self): prim = UsdGeom.Xform.Define(self.ctx.get_stage(), self.PRIM_PATH).GetPrim() self.create_geometry(self.GEOM_PATH) prim1 = UsdGeom.Xform.Define(self.ctx.get_stage(), self.PRIM1_PATH).GetPrim() prim1.GetReferences().AddInternalReference(self.PRIM_PATH) prim1.SetInstanceable(True) omni.kit.commands.execute("CopyPrimCommand", path_from=self.PRIM1_PATH, path_to=self.PRIM2_PATH) self.ctx.get_selection().clear_selected_prim_paths() prim2 = self.ctx.get_stage().GetPrimAtPath(self.PRIM2_PATH) set_transform_helper(self.PRIM2_PATH, translate=Gf.Vec3d(0, 200, 0)) return prim, prim2 def remove_scene_instancer(self): # Teardown in reverse order of creation, to avoid temporarily leaving dangling references. # Alternatively, we could implement this in Sdf with a change block to batch all the removals. self.ctx.get_stage().RemovePrim(self.PRIM2_PATH) self.ctx.get_stage().RemovePrim(self.PRIM1_PATH) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) self.ctx.get_stage().RemovePrim(self.GEOM_PATH) def create_point_instancer(self): instancer = UsdGeom.PointInstancer.Define(self.ctx.get_stage(), self.PRIM_PATH) instancer.CreatePositionsAttr([(-150, 0, 0), (150, 0, 0)]) instancer.CreateProtoIndicesAttr([0, 0]) self.create_geometry(self.GEOM_PATH) attr = instancer.CreatePrototypesRel() attr.AddTarget(self.GEOM_PATH) return instancer def remove_point_instancer(self): self.ctx.get_stage().RemovePrim(self.GEOM_PATH) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def si_create(self): self.create_scene_instancer() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "sceneinstancer.png", 1e-4) async def si_rotate(self): self.create_scene_instancer() set_transform_helper(self.GEOM_PATH, euler=Gf.Vec3d(0, 0, 45)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "si_rotate_mesh.png", 1e-4) async def si_all(self): await self.si_create() self.remove_scene_instancer() await self.si_rotate() self.remove_scene_instancer() async def pi_create(self): self.create_point_instancer() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pointinstancer.png", 1e-4) async def pi_protoIndices(self): instancer = self.create_point_instancer() sphere = UsdGeom.Sphere.Define(self.ctx.get_stage(), self.PRIM_PATH + "/sphere") sphere.CreateRadiusAttr(50) instancer.GetPrototypesRel().AddTarget(self.PRIM_PATH + "/sphere") instancer.GetProtoIndicesAttr().Set([1, 0]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_2meshes.png", 1e-4) # Regression test for OM-32503 instancer.GetProtoIndicesAttr().Set([1, 0, 1]) instancer.GetPositionsAttr().Set([(-150, 0, 0), (0, 0, 0), (150, 0, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_3meshes.png", 1e-4) async def pi_invisibleIds(self): instancer = self.create_point_instancer() attr = instancer.CreateInvisibleIdsAttr() attr.Set([0]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_invisibleIds.png", 1e-4) attr.Set([]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pointinstancer.png", 1e-4) async def pi_orientations(self): instancer = self.create_point_instancer() attr = instancer.CreateOrientationsAttr() attr.Set([Gf.Quath(0., 0., 0.5, 1), Gf.Quath(0., 0.5, 0., 1)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_orientations.png", 1e-4) async def pi_scales(self): instancer = self.create_point_instancer() attr = instancer.CreateScalesAttr() attr.Set([(1., 2., 1), (1., 1., 2)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_scales.png", 1e-4) # OM-30814 - verify proper refresh when authoring xforms on prototype gprims and ancestors async def pi_protoXform(self): instancer = self.create_point_instancer() await wait_for_update() # TODO: Figure out why the bug does not repro via scripting, only via TransformGizmo; # even scripting the entire operation within an Sdf.ChangeBlock does not trigger the # bug, with the fixes reverted. set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(2, 1, 2)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_protoXform.png", 1e-4) set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(1, 1, 1)) await wait_for_update() geomPath = Sdf.Path(self.GEOM_PATH) xformPath = geomPath.GetParentPath().AppendChild('Xform') UsdGeom.Xform.Define(self.ctx.get_stage(), xformPath) newGeomPath = xformPath.AppendChild(geomPath.name) omni.kit.commands.execute("MovePrimCommand", path_from=self.GEOM_PATH, path_to=newGeomPath) instancer.GetPrototypesRel().ClearTargets(removeSpec=True) instancer.GetPrototypesRel().AddTarget(xformPath) await wait_for_update() set_transform_helper(xformPath, scale=Gf.Vec3d(1, 2, 1)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_ancestralProtoXform.png", 1e-4) omni.kit.commands.execute("MovePrimCommand", path_from=newGeomPath, path_to=self.GEOM_PATH) instancer.GetPrototypesRel().ClearTargets(removeSpec=True) instancer.GetPrototypesRel().AddTarget(geomPath) self.ctx.get_stage().RemovePrim(xformPath) # OM-81682 - verify the prototype transform does not include the transform above the prototype root set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(1, 1, 1)) await wait_for_update() parentXformPath = geomPath.GetParentPath().AppendChild('Parent') UsdGeom.Xform.Define(self.ctx.get_stage(), parentXformPath) newXformPath = parentXformPath.AppendChild('Xform') UsdGeom.Xform.Define(self.ctx.get_stage(), newXformPath) newGeomPath = newXformPath.AppendChild(geomPath.name) omni.kit.commands.execute("MovePrimCommand", path_from=self.GEOM_PATH, path_to=newGeomPath) set_transform_helper(newXformPath, scale=Gf.Vec3d(1, 2, 1)) set_transform_helper(parentXformPath, scale=Gf.Vec3d(2, 2, 2)) instancer.GetPrototypesRel().ClearTargets(removeSpec=True) instancer.GetPrototypesRel().AddTarget(newXformPath) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pi_ancestralProtoXform.png") omni.kit.commands.execute("MovePrimCommand", path_from=newGeomPath, path_to=self.GEOM_PATH) self.ctx.get_stage().RemovePrim(parentXformPath) set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(2, 1, 2)) instancer.GetPrototypesRel().ClearTargets(removeSpec=True) instancer.GetPrototypesRel().AddTarget(self.GEOM_PATH) async def pi_all(self): await self.pi_create() self.remove_point_instancer() await self.pi_protoIndices() self.remove_point_instancer() await self.pi_invisibleIds() self.remove_point_instancer() # Transforms await self.pi_orientations() self.remove_point_instancer() await self.pi_scales() self.remove_point_instancer() self.create_point_instancer() await self.transform_translate() self.remove_point_instancer() self.create_point_instancer() await self.transform_rotate() self.remove_point_instancer() self.create_point_instancer() await self.transform_scale() self.remove_point_instancer() await self.pi_protoXform() self.remove_point_instancer()
17,803
Python
41.901205
119
0.652587
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_points.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.timeline from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest from .test_common import wait_for_update, postLoadTestSettings from pxr import Sdf, UsdGeom, UsdShade DEFAULT_POINTS = [(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)] class TestRtxHydraPoints(RtxHydraTest): TEST_PATH = "hydra/points" PRIM_PATH = "/World/pts" async def display_color(self): # Constant geom = self.create_geometry() geom.CreateDisplayColorPrimvar("constant").Set([(0, 1, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorConstant.png") return geom async def widths(self): # Default geom = self.create_geometry() geom.GetWidthsAttr().Clear() self.set_settings({"/persistent/rtx/hydra/points/defaultWidth": 35}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "widthDefault.png") self.set_settings({"/persistent/rtx/hydra/points/defaultWidth": 45}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "widthDefault2.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Constant geom = self.create_geometry() geom.SetWidthsInterpolation("constant") geom.CreateWidthsAttr().Set([20]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "widthConstant.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Vertex geom = self.create_geometry() geom.CreateWidthsAttr().Set([20, 15, 10, 25, 30, 35, 40, 45]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "widthVertex.png") async def points(self): pts = [DEFAULT_POINTS, [(-50, -50, -50), (150, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]] await self.attribute_test_case(self.create_geometry, "points", Sdf.ValueTypeNames.Point3f, pts, ["geom.png", "points.png"]) async def skipProcessing(self): geom = self.create_geometry() geom.GetPrim().CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool).Set(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "empty.png") class TestRtxHydraPrimitiveDrawingPoints(TestRtxHydraPoints): TEST_PATH = "hydra/points/primitivedrawing" PRIM_PATH = "/World/pts" def create_geometry(self, name=PRIM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr(DEFAULT_POINTS) pts.CreateWidthsAttr([10, 10, 10, 10, 5, 5, 15, 15]) UsdGeom.PrimvarsAPI(pts).CreatePrimvar("usePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True) UsdGeom.PrimvarsAPI(pts).CreatePrimvar("screenSpacePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True) return pts async def test_visibility(self): """ Test hydra points - visibility """ await self.visibility() async def test_transform(self): """ Test hydra points - tranform """ await self.transform_all() async def test_displayColor(self): """ Test hydra points - change display color """ geom = await self.display_color() # Vertex geom.CreateDisplayColorPrimvar("vertex").Set([(0, 1, 0), (1, 1, 0), (0, 1, 1), (1, 0, 1), (1, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorVertex.png") async def test_widths(self): """ Test hydra points - change widths """ await self.widths() async def test_points(self): """ Test hydra points - update points """ await self.points() async def test_skipProcessing(self): """ Test hydra points - skipProcessing attribute """ await self.skipProcessing() class TestRtxHydraPrimitiveDrawingPointsInstancer(RtxHydraInstancerTest): # TODO full cover scene instancer with tests TEST_PATH = "hydra/points/primitivedrawing/instancer" GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/pts" def create_geometry(self, name=GEOM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr(DEFAULT_POINTS) pts.CreateWidthsAttr([10, 10, 10, 10, 5, 5, 15, 15]) UsdGeom.PrimvarsAPI(pts).CreatePrimvar("usePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True) UsdGeom.PrimvarsAPI(pts).CreatePrimvar("screenSpacePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True) return pts async def test_sceneInstancer(self): """ Test hydra points scene instancer """ await self.si_all() async def test_pointInstancer(self): """ Test hydra points point instancer """ await self.pi_all() class UNSTABLE_TestRtxHydraProceduralPoints_UNSTABLE(TestRtxHydraPoints): TEST_PATH = "hydra/points/procedural" PRIM_PATH = "/World/pts" def create_geometry(self, name=PRIM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr(DEFAULT_POINTS) pts.CreateWidthsAttr([40, 30, 30, 20, 15, 15, 35, 35]) return pts async def test_visibility(self): """ Test hydra points - visibility """ await self.visibility() async def test_doNotCastShadow(self): """ Test hydra points - doNotCastShadow toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "doNotCastShadows") async def test_matteObject(self): """ Test hydra points - isMatteObject toggle """ self.create_geometry_with_floor() await self.matte() async def test_hideForCamera(self): """ Test hydra points - hideForCamera toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "hideForCamera") async def test_transform(self): """ Test hydra points - tranform """ await self.transform_all() async def test_displayColor(self): """ Test hydra points - change display color """ await self.display_color() async def test_widths(self): """ Test hydra points - change widths """ await self.widths() async def test_points(self): """ Test hydra points - update points """ await self.points() self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # OM-45604, OM-43655 # Delayed points assignment geom = UsdGeom.Points.Define(self.ctx.get_stage(), self.PRIM_PATH) geom.CreateWidthsAttr([40, 30, 30, 20, 15, 15, 35, 35]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "empty.png", 1e-4) attr = geom.CreatePointsAttr(DEFAULT_POINTS) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "geom.png", 1e-4) # OM-43655 - remove point attr.Set(DEFAULT_POINTS[:-1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "pointsRemovedOne.png", 1e-4) async def test_skip_processing(self): """ Test hydra points - skipProcessing attribute """ await self.skipProcessing() async def test_texCoords(self): self.set_settings({"/rtx/debugView/target": "texcoord1"}) self.create_geometry() prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) attr = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex) uvVertexSet = [(1, 0), (0.15, 0.5), (0.3, 0.5), (0.5, 0.5), (0.7, 0.5), (0.85, 0.5), (1, 0.5), (1, 1)] attr.Set(uvVertexSet) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "texCoords.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def test_timeSampled(self): """ Test hydra points - verify time sample animation works. """ super().open_usd("hydra/points_timeSampled_001.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) timeline = omni.timeline.get_timeline_interface() # Regression test for OM-96462, where time-sampled xform was impairing update of time-sampled points await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "points_timeSampled_frame0.png") # Advance a few frames and capture another frame for t in range(12): timeline.forward_one_frame() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "points_timeSampled_frame12.png") class UNSTABLE_TestRtxHydraProceduralPointsInstancer_UNSTABLE(RtxHydraInstancerTest): # TODO full cover scene instancer with tests TEST_PATH = "hydra/points/procedural/instancer" GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/pts" def create_geometry(self, name=GEOM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr(DEFAULT_POINTS) pts.CreateWidthsAttr([40, 30, 30, 20, 15, 15, 35, 35]) return pts async def test_sceneInstancer(self): """ Test hydra points - scene instancer """ await self.si_all() async def test_pointInstancer(self): """ Test hydra points - point instancer """ await self.pi_all() class UNSTABLE_TestRtxHydraProceduralPointsMaterials_UNSTABLE(RtxHydraMaterialsTest): TEST_PATH = "hydra/points/procedural/material" PRIM_PATH = "/World/pts" def create_geometry(self, name=PRIM_PATH): pts = UsdGeom.Points.Define(self.ctx.get_stage(), name) pts.CreatePointsAttr([(-50, 0, 0), (50, 0, 0)]) pts.CreateWidthsAttr([50, 25]) return pts async def test_materials(self): """ Test hydra points - materials """ materials = ["Green", "Red"] looksPath = "/World/Looks/" # Set and change material geomPrim = self.create_geometry().GetPrim() for m in materials: self.bind_material(geomPrim, looksPath + m) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_{}.png".format(m)) # Unbind material it should fallback to basic material UsdShade.MaterialBindingAPI(geomPrim).UnbindAllBindings() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_base.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
11,487
Python
35.820513
142
0.630278
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_volume.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .test_hydra_common import RtxHydraTest from .test_common import set_transform_helper, wait_for_update from pxr import Gf, UsdVol class TestRtxHydraVolume(RtxHydraTest): TEST_PATH = "hydra/volume" PRIM_PATH = "/World/volume" def create_geometry(self, name=PRIM_PATH): open_vdb_asset = UsdVol.OpenVDBAsset.Define(self.ctx.get_stage(), name + "/OpenVDBAsset") open_vdb_asset.GetFilePathAttr().Set(self.get_volumes_path("sphere.vdb")) open_vdb_asset.GetFieldNameAttr().Set("density") volume = UsdVol.Volume.Define(self.ctx.get_stage(), name) volume.CreateFieldRelationship("density", open_vdb_asset.GetPath()) set_transform_helper(volume.GetPath(), translate=Gf.Vec3d(0, 150, 0), scale=Gf.Vec3d(20.0, 20.0, 20.0)) return volume # simple test, create a volume with a OpenVDB asset # Unstable via OM-54845 async def test_UNSTABLE_create_UNSTABLE(self): self.add_floor() self.create_geometry() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "create_sphere.png", threshold=1e-3) # test changing the OpenVDBAsset file path # Unstable via OM-54845 async def test_UNSTABLE_change_to_torus_UNSTABLE(self): self.add_floor() self.create_geometry() open_vdb_asset = UsdVol.OpenVDBAsset(self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH + "/OpenVDBAsset")) open_vdb_asset.GetFilePathAttr().Set(self.get_volumes_path("torus.vdb")) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "change_to_torus.png", threshold=1e-3)
2,088
Python
44.413043
114
0.70977
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_example.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom class TestRtxExample1(RtxTest): """ Example of rtx test which creates box and capture screenshot Hints: for python debug insert line below and attach to kit process in VS Code omni.kit.debug.python.breakpoint() """ # override resolution WINDOW_SIZE = (512, 512) async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings and stage. self.add_dir_light() await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) def create_mesh(self): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), "/World/box") box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box # Unstable via OM-58681 async def test_UNSTABLE_rtx_example_create_mesh_UNSTABLE(self): """ Test example - create mesh """ self.create_mesh() await wait_for_update() await self.capture_and_compare("example", "mesh.png") async def test_rtx_example_check_mesh(self): """ Test example - check mesh """ box = self.create_mesh() points = box.GetPointsAttr().Get() face_indices = box.GetFaceVertexIndicesAttr().Get() unique_indices = set(face_indices) self.assertTrue(len(points) == len(unique_indices)) class TestRtxExample2(RtxTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) self.open_usd("bunny.obj.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) self.set_camera((6.969233739993722, 6.969233739993723, 6.969233739993719), (0, 0, 0)) async def test_UNSTABLE_rtx_example_open_usd_UNSTABLE(self): """ Test example - open usd file """ await wait_for_update() await self.capture_and_compare("example", "usd.png", 1e-4)
3,058
Python
37.721519
130
0.642904
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_usdlux_schema_compat.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom, UsdLux class TestUsdLuxSchemaCompat(RtxTest): TEST_PATH = "hydra/usdlux" async def test_usdlux_inputs_prefix(self): """ Test that the compatibility workaround for UsdLux schema changes that requires an inputs: prefix on attributes works. """ test_file_path = "hydra/simpleSphereLightUnprefixed.usda" super().open_usd(test_file_path) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "lightAttributes.png") async def test_usdlux_light_with_both_attributes(self): """ Test that the delegate chooses inputs: attributes when both inputs and non-inputs are authored. The usda for this test has these properties defined: float inputs:intensity = 30000 float intensity = 90000000 """ test_file_path = "hydra/simpleSphereLightBothAttributes.usda" super().open_usd(test_file_path) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "lightAttributes.png")
1,633
Python
44.388888
125
0.71831
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_mesh.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline import carb.settings from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest from .test_common import postLoadTestSettings, set_transform_helper, wait_for_update from pxr import Vt, Gf, Sdf, UsdGeom, UsdShade cubePts = [(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)] cubeFaceVCount = [4, 4, 4, 4, 4, 4] cubeIndices = [0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5] class TestRtxHydraMesh(RtxHydraTest): TEST_PATH = "hydra/mesh" PRIM_PATH = "/World/box" async def setUp(self): await super().setUp() timeline = omni.timeline.get_timeline_interface() timeline.set_target_framerate(timeline.get_time_codes_per_seconds()) def create_geometry(self, name=PRIM_PATH): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) box.CreatePointsAttr(cubePts) box.CreateFaceVertexCountsAttr(cubeFaceVCount) box.CreateFaceVertexIndicesAttr(cubeIndices) box.CreateSubdivisionSchemeAttr("none") return box # # Common tests for mesh # async def test_visibility(self): """ Test hydra mesh - visibility """ await self.visibility() # OM-34158 # Verify proper refresh when points are moved while the mesh is invisible. prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) mesh = UsdGeom.Mesh(prim) points = mesh.GetPointsAttr().Get() for idx, p in enumerate(points): points[idx] = p + Gf.Vec3f(100, 0, 0) mesh.GetPointsAttr().Set(points) await wait_for_update() mesh.GetVisibilityAttr().Set(UsdGeom.Tokens.inherited) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "boxPtsMovedWhileInvisible.png") async def test_doNotCastShadow(self): """ Test hydra mesh - doNotCastShadow toggle """ self.create_geometry_with_floor() # OM-58993: Properly cast shadows. await self.toggle_primvar(self.PRIM_PATH, "doNotCastShadows") # TODO setup scene which shows the difference # async def test_shadowTerminatorFix(self): # """ # Test hydra mesh - enableShadowTerminatorFix toggle # """ # self.create_geometry_with_floor() # await self.toggle_primvar(self.PRIM_PATH, "enableShadowTerminatorFix") async def test_matteObject(self): """ Test hydra mesh - isMatteObject toggle """ self.create_geometry_with_floor() await self.matte() async def test_hideForCamera(self): """ Test hydra mesh - hideForCamera toggle """ self.create_geometry_with_floor() await self.toggle_primvar(self.PRIM_PATH, "hideForCamera") async def test_wireframe(self): """ Test hydra mesh - wireframe toggle """ self.create_geometry() self.set_settings({"/rtx/wireframe/wireframeThickness": 10}) await self.toggle_primvar(self.PRIM_PATH, "wireframe", baseGoldenName="geom.png", threshould=1e-7) async def test_singleSided(self): """ Test hydra mesh - singleSided toggle """ await self.single_sided() async def test_pickable(self): """ Test hydra mesh - pickable flag toggle """ await self.pickable() # OM-3262 Verify proper refresh when authoring purpose async def test_purpose(self): """ Test hydra mesh - purpose toggle """ self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False}) self.create_geometry() geom = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) UsdGeom.Imageable(geom).CreatePurposeAttr().Set(UsdGeom.Tokens.guide) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "purpose.png") # OM-62070 # Verify mesh visibility updates when changing global setting self.set_settings({'/persistent/app/hydra/displayPurpose/guide': True}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "guideVisEnable.png") self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "guideVisDisable.png") # Verify inherited purpose authoring self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False}) super().open_usd("hydra/inheritedPurpose.usda") scope = self.ctx.get_stage().GetPrimAtPath('/World/Scope') UsdGeom.Imageable(scope).CreatePurposeAttr().Set(UsdGeom.Tokens.guide) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "inheritedGuidePurpose.png") UsdGeom.Imageable(scope).GetPurposeAttr().Clear() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "inheritedDefaultPurpose.png", 5e-5) # OM-32623 # Verify proper population of new repr when toggling saved guide purpose to default. self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False}) super().open_usd("hydra/guideRepr.usda") geom = self.ctx.get_stage().GetPrimAtPath('/World/Cube') UsdGeom.Imageable(geom).GetPurposeAttr().Clear() await wait_for_update() # Allow for a bit of noise between local run and TC await self.capture_and_compare(self.TEST_PATH, "guideRepr.png", 1e-4) async def test_transform(self): """ Test hydra mesh - tranform """ await self.transform_all() # OM-26055 # Verify that fallback xform values are properly initialized. super().open_usd("hydra/OM-26055_scene.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "OM-26055_scene.png") # OM-34447 # Verify that xforms properly resync when initially present with no value. super().open_usd("hydra/empty_xform_mtx.usda") stage = self.ctx.get_stage() set_transform_helper("/World/Mesh", translate=Gf.Vec3d(200, 0, 0)) await wait_for_update() # Looser threshold, as the test is somewhat noisy on Linux TC await self.capture_and_compare(self.TEST_PATH, "resync-empty_xform_mtx.png", 1e-4) # Verify that ancestral xforms properly affect invisible geometry. super().open_usd("hydra/simpleCubeAncestralXforms.usda") stage = self.ctx.get_stage() await wait_for_update() intermediateXform = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Xform/Xform_01")) intermediateXform.MakeVisible(False) await wait_for_update() ancestralXform = UsdGeom.XformCommonAPI(stage.GetPrimAtPath("/World/Xform")) ancestralXform.SetTranslate((100,0,0)) await wait_for_update() intermediateXform.MakeVisible(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "postVisAncestralXform.png") async def test_backfaceCulling(self): """ Test hydra mesh - verify toggling of backface culling is correctly propagated """ # Scene loads without backface culling: a green place partially covers a gray sphere super().open_usd("hydra/backFaceCulling.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "backfaceCulling_off.png") self.set_settings({"/rtx/hydra/faceCulling/enabled": True}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "backfaceCulling_on.png") stage = self.ctx.get_stage() prim = stage.GetPrimAtPath("/World/Plane") attr = prim.GetAttribute("singleSided") attr.Set(False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "backfaceCulling_doublesided.png") async def test_displayColor(self): """ Test hydra mesh - change display color """ await self.geometry_with_attribute("primvars:displayColor", Sdf.ValueTypeNames.Color3f, [(0, 1, 0)]) await self.capture_and_compare(self.TEST_PATH, "displayColor.png") # OM-58993 - Changing only display color should work prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH) mesh = UsdGeom.Mesh(prim) displayColorAttr = mesh.GetDisplayColorAttr() displayColorAttr.Set([(0, 0, 1)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorChange.png") stage = self.ctx.get_stage() prim = stage.GetPrimAtPath(self.PRIM_PATH) mesh = UsdGeom.Mesh(prim) attr = prim.GetAttribute("primvars:displayColor") primvar = UsdGeom.Primvar(attr) primvar.SetInterpolation(UsdGeom.Tokens.uniform) colors = [(1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 1), (0, 0, 1), (1, 0, 1)] attr.Set(colors) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorUniform.png") primvar.SetInterpolation(UsdGeom.Tokens.vertex) colors = [(1, 0, 0), (1, 0, 1), (1, 1, 1), (1, 1, 0), (0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0)] attr.Set(colors) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "displayColorVertex.png") async def test_primvarBinding(self): """ Test hydra mesh - varify effects of material edits to geometry primvar binding """ # OM-83102 - the file should open with a material lookup pointing to no primvar. It should render # a default magenta color super().open_usd("hydra/primvars_edit.usda") await self.capture_and_compare(self.TEST_PATH, "primvarNotFound_magenta.png") # changing the default lookup color to yellow prim = self.ctx.get_stage().GetPrimAtPath("/World/Looks/mtl_emissive/data_lookup_color") attr = prim.GetAttribute("inputs:default_value") attr.Set((1, 1, 0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarNotFound_yellow.png") # specify an existing primvar to lookup attr = prim.GetAttribute("inputs:name") attr.Set("blue") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarFound_blue.png") # change to a different existing primvar to lookup attr = prim.GetAttribute("inputs:name") attr.Set("green") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarFound_green.png") # change the default value to red now should have no effect attr = prim.GetAttribute("inputs:default_value") attr.Set((1, 0, 0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarFound_still_green.png") # change to a different not-existing primvar to lookup, now it should render the default color set in previous step attr = prim.GetAttribute("inputs:name") attr.Set("foo_bar") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "primvarNotFound_red.png") # # Mesh specific tests # async def test_topology(self): """ Test hydra mesh - topology changes - transform cube to wedge """ box = self.create_geometry() await wait_for_update() # Wait 5 frames to be sure that we update topology box.CreateFaceVertexCountsAttr([4, 3, 4, 3, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 1, 0, 2, 7, 4, 2, 3, 7, 1, 4, 7, 3]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "topology.png") async def subdiv_default(self, shouldWait=False): box = self.create_geometry() if shouldWait: await wait_for_update() subdivAttr = box.GetSubdivisionSchemeAttr() subdivAttr.Set("catmullClark") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivDefault.png") async def test_subdiv(self): """ Test hydra mesh - subdiv """ await self.subdiv_default(shouldWait=True) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) await wait_for_update() await self.subdiv_default(shouldWait=False) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Set refinement level with setting self.set_settings({"/rtx/hydra/subdivision/refinementLevel": 2}) geom = self.create_geometry() subdivAttr = geom.GetSubdivisionSchemeAttr() subdivAttr.Set("catmullClark") geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivRefinementLevel.png", 1e-4) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Set refinement level override from usd self.set_settings({"/rtx/hydra/subdivision/refinementLevel": 0}) geom = self.create_geometry() subdivAttr = geom.GetSubdivisionSchemeAttr() subdivAttr.Set("catmullClark") geom.GetPrim().CreateAttribute("refinementEnableOverride", Sdf.ValueTypeNames.Bool).Set(True) geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(2) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivRefinementLevel.png", 1e-4) # OM-21340 Verify that load of refined geometry does not crash. super().open_usd("hydra/cone_sbdv.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "cone_sbdv.png", 1e-4) async def test_subdiv_toggle(self): """ Test hydra mesh - subdiv toggle on/off, this test verifies that change between regular polygons and subdiv geometry doesn't leave the mesh in a corrupt internal state. """ # OM-88053: toggle on/off sudivision surfaces on a mesh *with authored normals*. # Begin with checking the input geometry: a primitve cube with authored normals. super().open_usd("hydra/cube_subdiv.usda") geom = self.ctx.get_stage().GetPrimAtPath("/World/Cube") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_off.png", 1e-4) # Enabling Catmull-Clark subdivision without changing any other option would simply # discard the authored normals, but still render the polygonal cage. subdivAttr = geom.GetAttribute("subdivisionScheme") subdivAttr.Set("catmullClark") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_smoothNormals.png", 1e-4) # This should produce a subdivided smooth mesh. geom.CreateAttribute("refinementEnableOverride", Sdf.ValueTypeNames.Bool).Set(True) geom.CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(2) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_subdivided.png", 1e-4) # Deform by moving a point. mesh = UsdGeom.Mesh(geom) points = mesh.GetPointsAttr().Get() points[7] = points[7] + Gf.Vec3f(0, 40, 0) mesh.GetPointsAttr().Set(points) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_deformed.png", 1e-4) # Also test bilinear subdivision subdivAttr.Set("bilinear") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_bilinear.png", 1e-4) # Finally this should go back to the original mesh with authored normals. subdivAttr.Set("none") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "subdivToggle_off_again.png", 1e-4) async def test_handedness(self): """ Test hydra mesh - toggle orintation between right and left handed, in a combination of triangulated mesh and quadrangulated mesh, with and without subdivision surfaces. """ # OM-113941: toggle handedness. A custom material front-facing green and back-facing red. super().open_usd("hydra/handedness_001.usda") await wait_for_update() self.set_settings(postLoadTestSettings) # This triangulated mesh is left-handed and has subdivision surface on. It also has broken normals # (a vector of zero entries) that would have resulted in a crash when toggling subdivision surfaces off. geomT = self.ctx.get_stage().GetPrimAtPath("/World/glasst_mod/SH000254198100001_Tube/SH000254198100001_Tube") # This is a mesh made of quads and right-handed geomQ = self.ctx.get_stage().GetPrimAtPath("/World/glassq/SH000254198100001_Tube/SH000254198100001_Tube") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "handedness_001_subdiv_green.png", 1e-4) # Toggle handedness geomT.GetAttribute("orientation").Set("leftHanded") # This edit would not render red in OM-113941 geomQ.GetAttribute("orientation").Set("rightHanded") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "handedness_001_subdiv_red.png", 1e-4) # Toggle subdivision surface geomT.GetAttribute("subdivisionScheme").Set("none") # This edit would crash OM-113941 geomQ.GetAttribute("subdivisionScheme").Set("catmullClark") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "handedness_001_mesh_red.png", 1e-4) # Toggle handedness again geomT.GetAttribute("orientation").Set("rightHanded") geomQ.GetAttribute("orientation").Set("leftHanded") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "handedness_001_mesh_green.png", 1e-4) async def test_points(self): """ Test hydra mesh - update points """ pts = [cubePts, cubePts.copy()] pts[1][1] = (150, -50, -50) await self.attribute_test_case(self.create_geometry, "points", Sdf.ValueTypeNames.Point3f, pts, ["geom.png", "points.png"]) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # OM-76321: this set of tests [interleavedPointsEdit_*] verifies intermittent primvar edits during # regular points edit. Special care is due because of the minimal updates we do to mesh VBs # Interleaved points edit - initial state, this should render a blue cube. geom = self.create_geometry() mesh = UsdGeom.Mesh(geom) displayColorAttr = mesh.GetDisplayColorAttr() displayColorAttr.Set([(0, 0, 1)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_0.png", 1e-4) # Interleaved points edit - first edit, the cube is slightly deformed and still blue. # This first edit goes through full mesh update to create mutable buffers (not deduplicated). pts[1][1] = (60, -50, -50) geom.GetPointsAttr().Set(pts[1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_1.png", 1e-4) # Interleaved points edit - second edit, the cube is deformed again and is now set to green # The second edit goes through meshUpdateVertices and creates a second VB. pts[1][1] = (70, -50, -50) geom.GetPointsAttr().Set(pts[1]) displayColorAttr.Set([(0, 1, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_2.png", 1e-4) # Interleaved points edit - third edit, the cube is more deformed and should still be green # The last edit verifies that the previous edit to primvars need to be propagated to The # VB ping-pong swap. If this fails the cube will be blue (as in previous frame) instead of green. pts[1][1] = (80, -50, -50) geom.GetPointsAttr().Set(pts[1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_3.png", 1e-4) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def test_normals(self): """ Test hydra mesh - update normals """ self.set_settings({"/rtx/debugView/target": "normal"}) # Authored face varying interpolation normals = [[(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1), (1, 0, 0), (1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)], [(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0.5, 0.5, 0), (0.5, 0.5, 0), (0.5, 0.5, 0), (0.5, 0.5, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)]] def createGeom(): geom = self.create_geometry() geom.CreateNormalsAttr() geom.SetNormalsInterpolation("faceVarying") return geom await self.attribute_test_case(createGeom, "normals", Sdf.ValueTypeNames.Point3f, normals, ["normals.png", "normalsAuthoredFaceVarying.png"]) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Authored vertex interpolation geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)]) geom.SetNormalsInterpolation("vertex") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsAuthoredVertex.png", 1e-4) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Authored uniform interpolation geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, -1, 0), (0, 0, -1), (1, 0, 0), (0, 0, 1), (-1, 0, 0), (0, 1, 0)]) geom.SetNormalsInterpolation("uniform") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normals.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Authored constant interpolation geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, 1, 0)]) geom.SetNormalsInterpolation("constant") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsAuthoredConstant.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Generated smooth geom = self.create_geometry() geom.GetSubdivisionSchemeAttr().Set("catmullClark") geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsGeneratedSmooth.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Generated flat self.create_geometry() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normals.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # TBN Frame mode - generate normals on gpu self.set_settings({"/rtx/hydra/TBNFrameMode": 2}) geom = self.create_geometry() geom.GetSubdivisionSchemeAttr().Set("catmullClark") geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(0) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsGeneratedSmooth-gpu.png", 5e-5) self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # OM-94303: Unstable due to golden image mismatch async def test_UNSTABLE_gpu_normals(self): """ Test hydra mesh - gpu normals """ super().open_usd("hydra/normals_gen_001.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) self.set_settings({"/rtx/hydra/TBNFrameMode": 2}) self.set_settings({"/rtx/debugView/target": "materialGeometryNormal"}) await self.capture_and_compare(self.TEST_PATH, "gpu_normals_creation.png") # Generated on GPU with reference normals stage = self.ctx.get_stage() prim = stage.GetPrimAtPath("/World/pSphere2") mesh = UsdGeom.Mesh(prim) points = mesh.GetPointsAttr().Get() # By moving a point we force the generation of normals. Regression test for OM-90364 / MR !24845 points[16] = Gf.Vec3f(0, 11, 0) mesh.GetPointsAttr().Set(points) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "gpu_normals_editing.png") async def test_texCoords(self): """ Test hydra mesh - update tex coords """ self.set_settings({"/rtx/debugView/target": "texcoord0"}) # faceVarying geom = self.create_geometry() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "texCoordsFaceVarying.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # vertex or varying (they are the same for a mesh geometry) geom = self.create_geometry() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set( [(0, 0), (0.1, 0), (0.2, 0), (0.3, 0), (0.4, 0), (0.5, 0), (0.6, 0), (0.7, 0)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "texCoordsVertex.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # uniform geom = self.create_geometry() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.uniform).Set( [(0, 0), (0, 0.1), (0, 0.2), (0, 0.3), (0, 0.4), (0, 0.5)]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "texCoordsUniform.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def test_tangents(self): """ Test hydra mesh - update tangents """ self.set_settings({"/rtx/debugView/target": "tangentu"}) # default - gpu geom = self.create_geometry() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsU.png") self.set_settings({"/rtx/debugView/target": "tangentv"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsV.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # cpu - uniform geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, -1, 0), (0, 0, -1), (1, 0, 0), (0, 0, 1), (-1, 0, 0), (0, 1, 0)]) geom.SetNormalsInterpolation("uniform") # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) self.set_settings({"/rtx/debugView/target": "tangentu"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsU.png") self.set_settings({"/rtx/debugView/target": "tangentv"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsV.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # cpu - vertex geom = self.create_geometry() geom.GetNormalsAttr().Set([(-0.57735, -0.57735, -0.57735), (0.57735, -0.57735, -0.57735), (-0.57735, -0.57735, 0.57735), (0.57735, -0.57735, 0.57735), (-0.57735, 0.57735, -0.57735), (0.57735, 0.57735, -0.57735), (0.57735, 0.57735, 0.57735), (-0.57735, 0.57735, 0.57735)]) geom.SetNormalsInterpolation("vertex") # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) self.set_settings({"/rtx/debugView/target": "tangentu"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsVertexU.png") self.set_settings({"/rtx/debugView/target": "tangentv"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsVertexV.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # cpu - facevarying geom = self.create_geometry() geom.GetNormalsAttr().Set([(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1), (1, 0, 0), (1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)]) geom.SetNormalsInterpolation("faceVarying") # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set( [(1, 0), (0, 0), (0, 1), (1, 1)]) geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set( [0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1]) self.set_settings({"/rtx/debugView/target": "tangentu"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsFacevaryingU.png") self.set_settings({"/rtx/debugView/target": "tangentv"}) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tangentsFacevaryingV.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) async def test_skeleton(self): """ Test hydra mesh - skeleton """ super().open_usd("hydra/skelcylinder.usda") # self.set_settings(postLoadTestSettings) await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) # create timeline = omni.timeline.get_timeline_interface() timeline.play() timeline.set_auto_update(False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "skeleton0.png") timeline.set_current_time(1) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "skeleton1.png") timeline.set_auto_update(True) timeline.stop() # TODO remove, update # create many instances # SkinningMethod: eDualQuaternion, eClassicLinear, eWeightedBlend async def test_mesh_with_api_schemas(self): """ Verify proper population and refresh when apiSchemas are present """ # OM-24223: Verify proper mesh population when duplicating with apiSchemas present stage = self.ctx.get_stage() cube = UsdGeom.Cube.Define(stage, "/Cube") cube.GetSizeAttr().Set(50.0) # Doesn't matter which API schema is applied, just use one from core, to avoid depending on physics. # https://github.com/PixarAnimationStudios/USD/commit/6f0ce585bf5d06ca929584b515cd3bdf05d78eb3 # https://github.com/PixarAnimationStudios/USD/commit/1222ea7cd2478e576f4fc32936f781d2a7f61cd5 # https://github.com/PixarAnimationStudios/USD/commit/61fcc34d8555bb269fae49af90eab5154989392c if hasattr(UsdGeom, 'VisibilityAPI'): UsdGeom.VisibilityAPI.Apply(cube.GetPrim()) else: from pxr import UsdRender UsdRender.SettingsAPI.Apply(cube.GetPrim()) await wait_for_update() omni.kit.commands.execute("CopyPrim", path_from="/Cube", path_to="/DupeCube") self.ctx.get_selection().clear_selected_prim_paths() set_transform_helper("/DupeCube", translate=Gf.Vec3d(200, 0, 0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "dupeWithApiSchema.png") self.ctx.get_stage().RemovePrim("/Cube") self.ctx.get_stage().RemovePrim("/DupeCube") await wait_for_update() # OM-29819: Verify proper normals after applying an API schema super().open_usd("hydra/torus_mesh.usda") await wait_for_update() stage = self.ctx.get_stage() # Doesn't matter which API schema is applied, just use one from core, to avoid depending on physics. # https://github.com/PixarAnimationStudios/USD/commit/6f0ce585bf5d06ca929584b515cd3bdf05d78eb3 # https://github.com/PixarAnimationStudios/USD/commit/1222ea7cd2478e576f4fc32936f781d2a7f61cd5 # https://github.com/PixarAnimationStudios/USD/commit/61fcc34d8555bb269fae49af90eab5154989392c if hasattr(UsdGeom, 'VisibilityAPI'): UsdGeom.VisibilityAPI.Apply(stage.GetPrimAtPath("/World/Torus")) else: from pxr import UsdRender UsdRender.SettingsAPI.Apply(stage.GetPrimAtPath("/World/Torus")) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "normalsWithApiSchema.png", 3e-4) async def test_UNSTABLE_tetMesh_UNSTABLE(self): """ Test hydra tetmesh """ # Eventually this should live in the physics repo, when omni hydra supports plugin adapters. super().open_usd("hydra/tetmesh_teddy.usda") await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "tetmesh_teddy.png", 3e-4) async def test_mesh_dedup(self): """ Verify hash collisions in mesh dedup do not crash """ # OM-64181: Verify hash collisions in mesh dedup do not crash timeline = omni.timeline.get_timeline_interface() timeline.set_current_time(0) super().open_usd("hydra/AlternatingCubePlane.usda") await wait_for_update() N = 50 while N > 0: N = N - 1 timeline.forward_one_frame() await wait_for_update() timeline.rewind_one_frame() await wait_for_update() class TestRtxHydraMeshMaterials(RtxHydraMaterialsTest): TEST_PATH = "hydra/mesh/material" PRIM_PATH = "/World/box" def create_geometry(self, name=PRIM_PATH): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box async def test_materials(self): """ Test hydra mesh - materials """ materials = ["Green", "Red"] looksPath = "/World/Looks/" # Set and change material geomPrim = self.create_geometry().GetPrim() for m in materials: self.bind_material(geomPrim, looksPath + m) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_{}.png".format(m)) # Unbind material it should fallback to basic material UsdShade.MaterialBindingAPI(geomPrim).UnbindAllBindings() await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_base.png") self.ctx.get_stage().RemovePrim(self.PRIM_PATH) # Subsets subsetPath = self.PRIM_PATH + "/subset" geomPrim = self.create_geometry().GetPrim() subset = UsdGeom.Subset.Define(self.ctx.get_stage(), subsetPath) # https://github.com/PixarAnimationStudios/USD/commit/c1cdbbaa8a2dd8ecbb9722de517ef44c1a680352 # Family name required for subset material bindingas as of USD 21.11+; # has been available on subsets from the firsrt public release of USD. subset.CreateFamilyNameAttr().Set(UsdShade.Tokens.materialBind) attr = subset.CreateIndicesAttr() attr.Set([5]) self.bind_material(geomPrim, looksPath + materials[0]) self.bind_material(subset.GetPrim(), looksPath + materials[1]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_subsets.png") # Update subset attr.Set([3]) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_subsets2.png") # Remove subset self.ctx.get_stage().RemovePrim(subsetPath) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "mat_Green.png") class TestRtxHydraMeshInstancer(RtxHydraInstancerTest): # TODO full cover scene instancer with tests TEST_PATH = "hydra/mesh/instancer" GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/box" def create_geometry(self, name=GEOM_PATH): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box async def test_sceneInstancer(self): """ Test hydra mesh scene instancer """ await self.si_all() sgInstSettingsKey = "/persistent/omnihydra/useSceneGraphInstancing" useSceneGraphInstancing = carb.settings.get_settings().get_as_bool(sgInstSettingsKey) try: async def nest_ptinst_in_sginst_test(self, enableOmniHydraScenegraphInstancing): carb.settings.get_settings().set_bool(sgInstSettingsKey, enableOmniHydraScenegraphInstancing) # OM-34669 # Verify that turning on instanceable on a hierarchy that contains # a point instancer does not corrupt parent xforms. super().open_usd("hydra/ptinst_inside_sginst.usda") await wait_for_update() stage = self.ctx.get_stage() instance = stage.GetPrimAtPath('/World/Instance') instance.SetInstanceable(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "ptinst_inside_sginst.png") # Verify that authoring xforms on instances over internal references refreshes properly. set_transform_helper(instance.GetPath(), translate=Gf.Vec3d(200,0,0), euler=Gf.Vec3f(0, 0, -120)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "ptinst_inside_sginst_rotated.png") # Verify that authoring xforms on instances over external references refreshes properly. super().open_usd("hydra/ref_ptinst_inside_sginst.usda") await wait_for_update() stage = self.ctx.get_stage() instance = stage.GetPrimAtPath('/World/Instance') set_transform_helper(instance.GetPath(), euler=Gf.Vec3f(0, 0, -30)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "ref_ptinst_inside_sginst_rotated.png") await nest_ptinst_in_sginst_test(self, False) await nest_ptinst_in_sginst_test(self, True) finally: carb.settings.get_settings().set_bool(sgInstSettingsKey, useSceneGraphInstancing) # OM-35643 # Verify xforms above scenegraph instance roots are honored by omni hydra scenegraph instancing. try: carb.settings.get_settings().set_bool(sgInstSettingsKey, True) super().open_usd("hydra/CubeWorld.usda") await wait_for_update() stage = self.ctx.get_stage() cubeInstance = stage.GetPrimAtPath("/CubeWorld/CubeInstance") cubeInstance.SetInstanceable(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "sginst_parent_xform.png", 1e-4) cubeInstance.SetInstanceable(False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "sginst_parent_xform.png", 1e-4) finally: carb.settings.get_settings().set_bool(sgInstSettingsKey, useSceneGraphInstancing) # OM-36724 # Verify xforms in the presence of nested scenegraph instancing with omni hydra scenegraph instancing enabled for testFile in ["hydra/nestedScenegraphInstances.usda", "hydra/nestedScenegraphInstancesOff.usda"]: try: carb.settings.get_settings().set_bool(sgInstSettingsKey, True) super().open_usd(testFile) await wait_for_update() stage = self.ctx.get_stage() cubeInstance = stage.GetPrimAtPath("/World/threeCubes") cubeInstance.SetInstanceable(True) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "nested_sginst_toggle.png", 1e-4) cubeInstance.SetInstanceable(False) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "nested_sginst_toggle.png", 1e-4) set_transform_helper(cubeInstance.GetPath(), translate=Gf.Vec3d(200,0,0)) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "nested_sginst_xform_refresh.png", 1e-4) finally: carb.settings.get_settings().set_bool(sgInstSettingsKey, useSceneGraphInstancing) async def test_pointInstancer(self): """ Test hydra mesh point instancer """ await self.pi_all() # OM-30658 Verify proper population when prototype is not nested under point instancer super().open_usd("hydra/ptinst_unnested_proto.usda") await wait_for_update() # Raise threshold a bit to account for noise between local runs and TC await self.capture_and_compare(self.TEST_PATH, "ptinst_unnested_proto.png", 3e-4) # OM-32571 Verify proper population after creating an empty instancer. super().open_usd("hydra/cube_ptinst_unpopulated.usda") await wait_for_update() stage = self.ctx.get_stage() p = stage.GetPrimAtPath('/World/output') pos = p.GetAttribute('positions1').Get() ori = p.GetAttribute('orientations1').Get() scl = p.GetAttribute('scales1').Get() pi = p.GetAttribute('protoIndices1').Get() with Sdf.ChangeBlock(): p.GetAttribute('positions').Set(pos) p.GetAttribute('orientations').Set(ori) p.GetAttribute('scales').Set(scl) p.GetAttribute('protoIndices').Set(pi) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "cube_ptinst_unpopulated.png") # OM-35779 Verify proper refresh of nested point instancers super().open_usd("hydra/nested_ptinst.usda") await wait_for_update() stage = self.ctx.get_stage() prim = stage.GetPrimAtPath("/World/PointInstancer_parent") pos = prim.GetAttribute('positions').Get() new_pos = list(pos) new_pos[0] = Gf.Vec3d(300,300,0) prim.GetAttribute('positions').Set(new_pos) await wait_for_update() await self.capture_and_compare(self.TEST_PATH, "nested_ptinst.png") # OM-38291 Verify no crash with full update from Nucleus super().open_usd("hydra/OM-38291-one_ptinst.usda") await wait_for_update() stage = self.ctx.get_stage() # Mock a full update from Nucleus live edit by clearing and reloading the layer. stage.GetRootLayer().Clear() await wait_for_update() stage.GetRootLayer().Reload(True) await wait_for_update() # OM-110897 Verify no crash with nested point instancers with different dimensions super().open_usd("hydra/nested_ptinst_extradim.usda") await wait_for_update() stage = self.ctx.get_stage() await wait_for_update()
47,596
Python
46.980847
158
0.631272
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_selectionoutline.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom spherePath = '/World/Sphere' cylinderPath = '/World/Cylinder' defaultColor0 = [0, 0, 0, 0] defaultColor1 = [0.7, 0.7, 0, 1] defaultColor2 = [0.7, 0, 1, 1] displayOptionSetting = "/persistent/app/viewport/displayOptions" outlineWidthSetting = "/persistent/app/viewport/outline/width" outlineColorSetting = "/persistent/app/viewport/outline/color" shadeColorSetting = "/persistent/app/viewport/outline/shadeColor" intersectionColorSetting = "/persistent/app/viewport/outline/intersection/color" outlineEnabledSetting = "/app/viewport/outline/enabled" class TestRtxSelectionOutline(RtxTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) self.set_settings({displayOptionSetting: (1 << 7)}) omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings # and stage. await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) self.set_settings({ outlineWidthSetting: 2, outlineColorSetting: defaultColor0, shadeColorSetting: defaultColor0, intersectionColorSetting: defaultColor0, "/app/transform/operation": "select" }) self.create_scene() self.ctx.set_selection_group_outline_color(255, defaultColor1) def set_selected(self, path, select=True): self.ctx.get_selection().set_prim_path_selected(path, select, True, False, True) def create_scene(self): stage = self.ctx.get_stage() sphere = UsdGeom.Sphere.Define(stage, spherePath) sphere.CreateRadiusAttr(100) cylinder = UsdGeom.Cylinder.Define(stage, cylinderPath) cylinder.CreateHeightAttr(200) cylinder.CreateRadiusAttr(75) async def test_rtx_selectionoutline_outline1(self): """ Test SelectionOutline - Outline sphere """ self.set_selected(spherePath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Outline1.png") async def test_rtx_selectionoutline_outline2(self): """ Test SelectionOutline - Outline cylinder """ self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Outline2.png") async def test_rtx_selectionoutline_outline12(self): """ Test SelectionOutline - Outline sphere & cylinder """ self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Outline12.png") async def test_rtx_selectionoutline_intersection(self): """ Test SelectionOutline - Intersection """ self.set_settings({intersectionColorSetting: defaultColor2}) self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Intersection.png", 4e-5) async def test_UNSTABLE_rtx_selectionoutline_thick(self): """ Test SelectionOutline - Outline sphere & cylinder, thick """ self.set_settings({outlineWidthSetting: 15}) self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Thick.png") async def test_rtx_selectionoutline_blend(self): """ Test SelectionOutline - Outline cylinder with blended color """ self.set_settings({outlineWidthSetting: 15}) c = defaultColor1[:3] c.append(0.5) self.ctx.set_selection_group_outline_color(255, c) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Blend.png") async def test_rtx_selectionoutline_multicolored(self): """ Test SelectionOutline - Outline sphere & cylinder with different colors """ self.set_settings({outlineWidthSetting: 4}) self.ctx.set_selection_group(1, spherePath) self.ctx.set_selection_group(2, cylinderPath) self.ctx.set_selection_group_outline_color(1, defaultColor1) self.ctx.set_selection_group_outline_color(2, defaultColor2) self.ctx.set_selection_group_shade_color(1, defaultColor0) self.ctx.set_selection_group_shade_color(2, defaultColor0) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Multicolored.png") async def test_rtx_selectionoutline_shade(self): """ Test SelectionOutline - Shade sphere """ self.set_settings({outlineWidthSetting: 4}) self.ctx.set_selection_group(1, spherePath) self.ctx.set_selection_group(2, cylinderPath) self.ctx.set_selection_group_shade_color(1, defaultColor1) self.ctx.set_selection_group_shade_color(2, defaultColor0) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Shade.png") async def test_UNSTABLE_rtx_selectionoutline_shade_multicolored_UNSTABLE(self): """ Test SelectionOutline - Shade sphere & cylinder with different colors """ self.set_settings({outlineWidthSetting: 4}) self.ctx.set_selection_group(1, spherePath) self.ctx.set_selection_group(2, cylinderPath) self.ctx.set_selection_group_shade_color(1, defaultColor1) self.ctx.set_selection_group_shade_color(2, defaultColor2) await wait_for_update() await self.capture_and_compare("SelectionOutline", "ShadeMulticolored.png") async def test_rtx_selectionoutline_disabled(self): """ Test SelectionOutline - Disabled """ self.set_settings({outlineEnabledSetting: False, displayOptionSetting: 0}) self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Disabled.png") # OM-102267 - unreliable in 105.1 branch async def test_UNSTABLE_rtx_selectionoutline_disabledByMetadata_UNSTABLE(self): """ Test SelectionOutline - Disabled by metadata. OM-34048 """ self.ctx.get_stage().GetPrimAtPath(spherePath).SetMetadata('no_selection_outline', True) self.set_selected(spherePath) self.set_selected(cylinderPath) await wait_for_update() await self.capture_and_compare("SelectionOutline", "Outline2.png", 2e-5) # OM-102267 - unreliable in 105.1 branch async def test_UNSTABLE_rtx_selectionoutline_instances_UNSTABLE(self): """ Test Selection Outline - Instances """ self.open_usd("hydra/CubeWorld.usda") PRIM_PATH = '/CubeWorld/CubeInstance' cubeInstance = self.ctx.get_stage().GetPrimAtPath(PRIM_PATH) cubeInstance.SetInstanceable(False) self.set_selected(PRIM_PATH) await wait_for_update() await self.capture_and_compare("SelectionOutline", "InstanceableFalse.png", 4e-5) self.set_selected(PRIM_PATH, False) # Unselect cubeInstance.SetInstanceable(True) self.set_selected(PRIM_PATH) await wait_for_update() await self.capture_and_compare("SelectionOutline", "InstanceableTrue.png", 4e-5) async def test_rtx_selectionoutline_mouse_select(self): """Test mouse selection works in Viewport.""" from omni.kit import ui_test from omni.kit.ui_test.vec2 import Vec2 self.open_usd("hydra/CubeInstance.usda") omni.usd.get_context().get_selection().set_selected_prim_paths([], True) await wait_for_update() await ui_test.emulate_mouse_move_and_click(Vec2(256, 256)) await wait_for_update() await self.capture_and_compare("SelectionOutline", "MouseSelect.png", 4e-5) async def test_rtx_selectionoutline_mouse_select_aov_changed(self): """Test mouse selection works in Viewport before and after AOV change.""" from omni.kit import ui_test from omni.kit.ui_test.vec2 import Vec2 mouse_pos = Vec2(256, 256) self.open_usd("hydra/CubeInstance.usda") usd_context = omni.usd.get_context() usd_context.get_selection().set_selected_prim_paths([], True) await wait_for_update() await ui_test.emulate_mouse_move_and_click(mouse_pos) await wait_for_update() await self.capture_and_compare("SelectionOutline", "MouseSelectAOVA.png", 4e-5) # Reset selection to nothing usd_context.get_selection().set_selected_prim_paths([], True) # Add additional AOVs from omni.kit.viewport.utility import get_active_viewport from pxr import Sdf, Usd, UsdRender stage = usd_context.get_stage() render_product_path = Sdf.Path(get_active_viewport().render_product_path) render_product = UsdRender.Product(stage.GetPrimAtPath(render_product_path)) ordered_vars_rel = render_product.GetOrderedVarsRel() start_aov_len = len(ordered_vars_rel.GetForwardedTargets()) # Targets need to be adde don session-layer as other prims live there with Usd.EditContext(stage, stage.GetSessionLayer()): aov_name = "Depth" render_var = UsdRender.Var.Define(stage, Sdf.Path(f"/Render/Vars/{aov_name}")) render_var.GetSourceNameAttr().Set(aov_name) render_var.GetDataTypeAttr().Set("float") ordered_vars_rel.AddTarget(render_var.GetPath()) end_aov_len = len(render_product.GetOrderedVarsRel().GetForwardedTargets()) self.assertNotEqual(start_aov_len, end_aov_len) # Re-select the object await ui_test.emulate_mouse_move_and_click(mouse_pos) await wait_for_update() await self.capture_and_compare("SelectionOutline", "MouseSelectAOVB.png", 4e-5)
10,699
Python
40.960784
119
0.670904
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_scene_delegate_omni_imaging.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 sys import path import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.kit.test import omni.timeline import carb.settings from .test_hydra_common import RtxHydraTest from .test_common import testSettings, postLoadTestSettings, wait_for_update from pxr import Gf, UsdShade import shutil, os, pathlib class TestRtxHydraSceneDelegateOmniImagingSetEmissionColor(RtxHydraTest): # OM-73180 # Prior to the update in this ticket the OmniImagingDelegate ignored # certain parameters, "emission_color" being one of them. This test # validates that is no longer the case. async def setUp(self): await super().setUp() self.set_settings(testSettings) super().open_usd("hydra/scene_delegate/emission_color/test.usda") await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def test_set_emission_color(self): ''' Test OmniImagingDelegate don't ignore 'emission_color' ''' await wait_for_update(wait_frames=10) prim = self.ctx.get_stage().GetPrimAtPath("/World/Looks/mtl_emission/emission") shader_prim = UsdShade.Shader(prim) shader_prim.GetInput("emission_color").Set(Gf.Vec3f(1.0, 0.0, 0.0)) await wait_for_update(wait_frames=10) await self.capture_and_compare("hydra/scene_delegate", "set_emission_color.png")
1,865
Python
40.466666
88
0.723324
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_scenedb.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update from pxr import UsdGeom, Sdf import numpy as np class TestRtxSceneDb(RtxTest): TEST_PATH = "scenedb" async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings and stage. self.add_dir_light() await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) def create_geometry(self, name): sphere = UsdGeom.Sphere.Define(self.ctx.get_stage(), name) sphere.CreateRadiusAttr(10) def create_instancer(self, name, N): pts = [] indices = [] sp = 250. dx = 500. / N[0] dy = 500. / N[1] dz = 500. / N[2] for i in np.arange(-sp, sp, dx): for j in np.arange(-sp, sp, dy): for k in np.arange(-sp, sp, dz): pts.append((i, j, k)) indices.append(0) print("Generated points: ", len(indices)) lyr = self.ctx.get_stage().GetRootLayer() with Sdf.ChangeBlock(): instancer = lyr.GetPrimAtPath("/World/Instancer") or \ Sdf.PrimSpec(lyr.GetPrimAtPath("/World"), "Instancer", Sdf.SpecifierDef, "PointInstancer") pos = lyr.GetAttributeAtPath("/World/Instancer.positions") or \ Sdf.AttributeSpec(instancer, "positions", Sdf.ValueTypeNames.Point3fArray) pos.default = pts protoIndices = lyr.GetAttributeAtPath("/World/Instancer.protoIndices") or \ Sdf.AttributeSpec(instancer, "protoIndices", Sdf.ValueTypeNames.IntArray) protoIndices.default = indices rel = lyr.GetRelationshipAtPath("/World/Instancer.prototypes") or \ Sdf.RelationshipSpec(instancer, "prototypes") rel.targetPathList.prependedItems = [name] async def test_sphere_PI_1M(self): id = "/World/Sphere" self.create_geometry(id) self.create_instancer(id, (100, 100, 100)) await wait_for_update(self.ctx, 25) # Wait 25 frames before capture. await self.capture_and_compare(self.TEST_PATH, "sphere1M.png", threshold=5e-5) # Unstable due to crashes in SceneDB: OM-49598 async def test_UNSTABLE_sphere_PI_1M_Recreate_UNSTABLE(self): id = "/World/Sphere" self.create_geometry(id) self.create_instancer(id, (100, 100, 100)) await wait_for_update(self.ctx, 25) # Wait 25 frames before capture. self.ctx.get_stage().RemovePrim("/World/instancer") self.create_instancer(id, (100, 100, 100)) await self.capture_and_compare(self.TEST_PATH, "sphere1M.png")
3,313
Python
43.783783
130
0.644431
omniverse-code/kit/exts/omni.rtx.tests/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.rtx.tests`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [Unreleased] ### Added ### Changed ### Removed ## [0.1.4] - 2022-10-19 ### Changed - Flagged test_light_collection_lightvistoggle as UNSTABLE. ## [0.1.3] - 2022-06-05 ### Fixed - Added one missing dependency and a couple small fixes ## [0.1.2] - 2022-06-02 ### Changed - Capture from Viewport texture directly instead of UI / Window ## [0.1.1] - 2022-05-23 ### Changed - Add missing explicit dependencies ## [0.1.0] - 2021-04-20 ### Added - Initial Release
629
Markdown
16.5
74
0.675676
omniverse-code/kit/exts/omni.rtx.tests/docs/README.md
# The RTX Renderer Test Framework [omni.rtx.tests] This extensions contains python tests for RTX renderer. This tests is based on kit python tests. See `omni.kit.tests` documentation. # How-to run tets There is few ways to run tets. 1) Run script `_build/{build}/{config}/tests-omni.rtx.tests.{bat|sh}` 2) Run `kit`. Open `Window -> Test Runner`. Select and run tests you want to run. # How-to add new tests: 1) Create new py file. See `test_example.py` as template. 2) Derive you test class from `class RtxTests` from `test_common.py` 3) Add your test by adding method started from `test_` 4) Improt your test class in __init__.py # How-to write tests You may use any methods from `omni.kit.tests`. For example to assert use `self.assertTrue({condition})`. Default directory for placing usd files is `{ext_path}/data/usd` ## Settings It is not recommended to use `carb.settings` directly as tests might be executed by user in kit and overwrite user's settings config. There is way to deal with it - use next method for settings. ``` self.set_settings({"/app/setting1": "val1", "/app/setting2": (0, 0), "/app/setting3": True})) ``` `set_settings` remembers previous value of setting that changed first time and set this value on `tearDown()` ### Default rtx test settings See `testSettings` and `postLoadTestSettings`. `testSettings` is set on test startup before stage loading. `postLoadTestSettings`is set after stage loading. You can load this settings in your tests without changes or create your own setup based on it. ## Capture and compare screenshots with golden Rendering is drawn screen with few frames delay. So after any changes has done it is needed to wait few frames before capture. Use `wait_for_update(wait_frames=4)` for waiting next few frames. For capturing use `capture_and_compare` function. Generated images are placed in `{kit}/kit/outputs/omni.rtx.tests/{image_subdir}`. Goldens for compare are placed in `{ext_path}/data/goldens/{image_subdir}`. ### Generating goldens Tests is not interrupted if golden is missed in goloden directory. So if it is needed to generate goldens it shold be removed from golden directory. Then run the tests and copy new goldens from output directory. ## Helper functions `set_transform_helper` - set transform for specified prim path `add_dir_light` - add directional light `/World/Light` to scene `add_floor` - add floor plane `/World/Floor` to scene `open_usd` - open usd file `set_camera` - set camera position and target
2,556
Markdown
35.014084
126
0.735915
omniverse-code/kit/exts/omni.rtx.tests/docs/index.rst
omni.rtx.tests ########################### .. toctree:: :maxdepth: 1 CHANGELOG
89
reStructuredText
7.999999
27
0.41573
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/peer_user_shared_data.py
import carb import omni.usd import omni.kit.usd.layers as layers from pxr import Sdf, Usd, Tf, UsdGeom from typing import List from .constants import * from .utils import ( get_user_shared_root_path, get_bound_camera_property_path, get_following_user_property_path, get_selection_property_path ) class PeerUserSharedData: """ Data abstraction to manage peer user data inside presence layer. """ def __init__( self, usd_context: omni.usd.UsdContext, shared_stage: Usd.Stage, user_info: layers.LiveSessionUser ): # Shared stage is the one in the live session folder with name users.live that holds all # shared data for all users. Peer users camera will be replicated into the local session layer # with path self.session_layer_camera_path if peer user is bound to the builtin camera. self.shared_stage = shared_stage self.user_info = user_info self.usd_context = usd_context user_name_identifier = Tf.MakeValidIdentifier(user_info.user_name.split('@')[0]) self.__replication_root_path = LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH.AppendElementString( f"{user_name_identifier}_{user_info.user_id}" ) self.__replication_camera_path = self.__replication_root_path.AppendElementString( f"{user_name_identifier}_Camera_{user_info.user_id}" ) # Creates corresponding replication inside local session layer. stage = self.usd_context.get_stage() target_layer = stage.GetSessionLayer() with Usd.EditContext(stage, target_layer): prim = stage.DefinePrim(self.__replication_root_path, "Scope") omni.usd.editor.set_hide_in_stage_window(prim, True) omni.usd.editor.set_hide_in_ui(prim, True) # Creates user namespace inside shared stage self.shared_root_path = get_user_shared_root_path(self.user_id) prim_spec = Sdf.CreatePrimInLayer(self.shared_stage.GetRootLayer(), SESSION_SHARED_LAYER_ROOT_PATH) prim_spec.specifier = Sdf.SpecifierDef prim_spec = Sdf.CreatePrimInLayer(self.shared_stage.GetRootLayer(), self.shared_root_path) prim_spec.specifier = Sdf.SpecifierDef # The property that can be used to check which camera the user is bound to. # Every user can bind two kinds of cameras: # 1. Builtin cameras. # 2. Cameras in the USD. # If it's builtin cameras, the property value must be in the list of SHARED_BUILT_IN_CAMERA_LIST. # If it's camera in the USD, the property value points to the camera path in the stage. self.__bound_camera_property_path = get_bound_camera_property_path(self.user_id) self.__selections_property_path = get_selection_property_path(self.user_id) self.__following_user_property_path = get_following_user_property_path(self.user_id) self.__shared_stage_builtin_camera_paths = {} for camera_name in SHARED_BUILT_IN_CAMERA_LIST: self.__shared_stage_builtin_camera_paths[camera_name] = self.shared_root_path.AppendElementString(camera_name) self.__current_bound_camera_property_value: str = None self.__current_selection_paths: List[Sdf.Path] = [] self.__current_following_user: str = None self.update_bound_camera() @property def user_id(self): return self.user_info.user_id @property def user_name(self): return self.user_info.user_name def destroy(self): if self.usd_context.get_stage(): layers.LayerUtils.remove_prim_spec( self.usd_context.get_stage().GetSessionLayer(), self.__replication_root_path ) self.shared_stage = None self.usd_context = None def update_bound_camera(self): latest_bound_camera_path = self.__get_bound_camera_path_from_usd() if latest_bound_camera_path != self.__current_bound_camera_property_value: self.__current_bound_camera_property_value = latest_bound_camera_path if not self.is_bound_to_builtin_camera(): layers.LayerUtils.remove_prim_spec( self.usd_context.get_stage().GetSessionLayer(), self.__replication_camera_path ) else: self.replicate_bound_camera_to_local() with Sdf.ChangeBlock(): self.__hide_prim_and_set_display_name() return True return False def update_selections(self): latest_selections = self.__get_selections_from_usd() if latest_selections != self.__current_selection_paths: self.__current_selection_paths = latest_selections return True return False def update_following_user(self): latest_following_user = self.__get_following_user_from_usd() if latest_following_user != self.__current_following_user: self.__current_following_user = latest_following_user return True return False @carb.profiler.profile def replicate_bound_camera_to_local(self, property_names: List[str] = []): builtin_camera_name = self.__bound_camera_property_value path = self.__shared_stage_builtin_camera_paths.get(builtin_camera_name, None) if not path: return shared_data_stage = self.shared_stage stage = self.usd_context.get_stage() bound_camera_prim = self.shared_stage.GetPrimAtPath(path) if not bound_camera_prim: return bound_camera_path = bound_camera_prim.GetPath() target_path = self.__replication_camera_path target_layer = stage.GetSessionLayer() with Sdf.ChangeBlock(): Sdf.CreatePrimInLayer(target_layer, target_path) if property_names: for property_name in property_names: source_property_path = bound_camera_path.AppendProperty(property_name) target_property_path = target_path.AppendProperty(property_name) Sdf.CopySpec( shared_data_stage.GetRootLayer(), source_property_path, target_layer, target_property_path ) else: Sdf.CopySpec(shared_data_stage.GetRootLayer(), bound_camera_path, target_layer, target_path) def is_bound_to_builtin_camera(self): if self.__current_following_user: return False builtin_camera_name = self.__bound_camera_property_value path = self.__shared_stage_builtin_camera_paths.get(builtin_camera_name, None) return path is not None def is_bound_camera_property_affected(self, changed_path: Sdf.Path): changed_path = Sdf.Path(changed_path) return changed_path == self.__bound_camera_property_path def is_selection_property_affected(self, changed_path: Sdf.Path): changed_path = Sdf.Path(changed_path) return changed_path == self.__selections_property_path def is_following_user_property_affected(self, changed_path: Sdf.Path): changed_path = Sdf.Path(changed_path) return changed_path == self.__following_user_property_path def is_builtin_camera_affected(self, changed_path: Sdf.Path): """Checkes if the changes to path will influence the builtin camera prim if user is bound to builtin camera.""" changed_path = Sdf.Path(changed_path) builtin_camera_name = self.__bound_camera_property_value path = self.__shared_stage_builtin_camera_paths.get(builtin_camera_name, None) # Not bound to builtin camera if not path: return False return changed_path.GetPrimPath() == path def get_bound_camera_prim(self) -> Usd.Prim: """Returns the bound camera in the local stage. It will return None if it's following other user.""" if self.__current_following_user: return None if self.is_bound_to_builtin_camera(): camera_path = self.__replication_camera_path elif Sdf.Path.IsValidPathString(self.__bound_camera_property_value): camera_path = Sdf.Path(self.__bound_camera_property_value) else: camera_path = None if not camera_path: return None stage = self.usd_context.get_stage() return stage.GetPrimAtPath(camera_path) @property def __bound_camera_property_value(self) -> str: """ Returns property value of bound camera path in shared stage. In order to support binding to both builtin cameras and non-builtin cameras. The property value can be builtin camera name listed in the SHARED_BUILT_IN_CAMERA_LIST, or the prim path in the local stage. """ if self.__current_bound_camera_property_value is None: self.__current_bound_camera_property_value = self.__get_bound_camera_path_from_usd() return self.__current_bound_camera_property_value @property def following_user_id(self) -> str: """The user id that this user is currently following.""" if self.__current_following_user is None: self.__current_following_user = self.__get_following_user_from_usd() return self.__current_following_user @property def selections(self) -> List[Sdf.Path]: if self.__current_selection_paths is None: self.__current_selection_paths = self.__get_selections_from_usd() return self.__current_selection_paths def __get_following_user_from_usd(self): following_user_property = self.shared_stage.GetRootLayer().GetAttributeAtPath(self.__following_user_property_path) if not following_user_property: return "" return str(following_user_property.default).strip() def __get_bound_camera_path_from_usd(self): camera_path_property = self.shared_stage.GetRootLayer().GetAttributeAtPath(self.__bound_camera_property_path) if not camera_path_property: return "" return str(camera_path_property.default).strip() def __get_selections_from_usd(self): selections_property = self.shared_stage.GetRootLayer().GetAttributeAtPath(self.__selections_property_path) if not selections_property: return [] selections = selections_property.default selections = [Sdf.Path(selection) for selection in selections if Sdf.Path.IsValidPathString(str(selection))] return selections def __hide_prim_and_set_display_name(self): stage = self.usd_context.get_stage() prim = self.get_bound_camera_prim() if not prim: return prim = prim.GetPrim() with Sdf.ChangeBlock(): with Usd.EditContext(stage, stage.GetSessionLayer()): omni.usd.editor.set_hide_in_stage_window(prim, True) omni.usd.editor.set_hide_in_ui(prim, True) omni.usd.editor.set_display_name(prim, self.user_info.user_name) prim.CreateAttribute("omni:kit:cameraLock", Sdf.ValueTypeNames.Bool).Set(True)
11,222
Python
39.225806
122
0.642132
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/event.py
__all__ = ["PresenceLayerEventType", "PresenceLayerEventPayload", "get_presence_layer_event_payload"] import carb from enum import IntEnum from typing import Set, List EVENT_PAYLOAD_KEY = "payload" class PresenceLayerEventType(IntEnum): # Emitted when local user enters/quits follow mode to other peer users. # REMIND: this event only applies to local user. In order to get the following status of other peer user, # you need to listen for BOUND_CAMERA_CHANGED below and PresenceLayerAPI.is_in_following_mode to check # if peer user is following other users. LOCAL_FOLLOW_MODE_CHANGED = carb.events.type_from_string("omni.kit.collaboration.presence_layer@local_follow_mode") # Emitted when peer user switched its bound camera or the the user that is following switches the bound camera. BOUND_CAMERA_CHANGED = carb.events.type_from_string("omni.kit.collaboration.presence_layer@bound_camera") # Emitted when peer user switched its selections. SELECTIONS_CHANGED = carb.events.type_from_string("omni.kit.collaboration.presence_layer@selections") # Emitted when the bound camera if peer user is builtin camera, and its properties are changed. BOUND_CAMERA_PROPERTIES_CHANGED = carb.events.type_from_string( "omni.kit.collaboration.presence_layer@bound_camera_properties" ) # Emitted when the bound camera of peer user is resynced. This is the same as prim resync of USD. BOUND_CAMERA_RESYNCED = carb.events.type_from_string( "omni.kit.collaboration.presence_layer@bound_camera_resynced" ) class PresenceLayerEventPayload: def __init__(self, event: carb.events.IEvent) -> None: carb_dict = carb.dictionary.get_dictionary() if event.type and event.type in iter(PresenceLayerEventType): self.event_type = PresenceLayerEventType(event.type) if self.event_type == PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED: self.__changed_users = carb_dict.get_dict_copy(event.payload) elif EVENT_PAYLOAD_KEY in event.payload: self.__changed_users = {}.fromkeys(event.payload[EVENT_PAYLOAD_KEY]) else: self.__changed_users = {} else: self.event_type = None self.__changed_users = {} @property def changed_user_ids(self) -> List[str]: return self.__changed_users.keys() def get_changed_camera_properties(self, user_id: str) -> Set[str]: """Gets the changed properties of bound builtin camera if event_type is BOUND_CAMERA_PROPERTIES_CHANGED.""" return self.__changed_users.get(user_id, set()) def __str__(self): return f"Event Type: {str(self.event_type)}, Changes: {self.__changed_users}" def get_presence_layer_event_payload(event: carb.events.IEvent) -> PresenceLayerEventPayload: try: return PresenceLayerEventPayload(event) except Exception as e: carb.log_error(f"Failed to convert event: {str(e)}") return None
3,026
Python
42.869565
119
0.697951
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/constants.py
from pxr import Sdf SESSION_SHARED_USER_LAYER = "shared_data/users.live" SESSION_SHARED_LAYER_ROOT_PATH = Sdf.Path("/__session_shared_data__") SESSION_SHARED_PERSPECTIVE_CAMERA_NAME = "perspective" SESSION_SHARED_FRONT_CAMERA_NAME = "front" SESSION_SHARED_LEFT_CAMERA_NAME = "left" SESSION_SHARED_RIGHT_CAMERA_NAME = "right" SESSION_SHARED_BOUND_CAMERA_PROPERTY_NAME = "bound_camera" SESSION_SHARED_FOLLOWING_USER_PROPERTY_NAME = "following_user" SESSION_SHARED_SELECTION_PROPERTY_NAME = "selected_prim_paths" SHARED_BUILT_IN_CAMERA_LIST = [ SESSION_SHARED_PERSPECTIVE_CAMERA_NAME, SESSION_SHARED_FRONT_CAMERA_NAME, SESSION_SHARED_LEFT_CAMERA_NAME, SESSION_SHARED_RIGHT_CAMERA_NAME ] LOCAL_BUILT_IN_CAMERA_PATH_TO_SHARED_NAME = { Sdf.Path("/OmniverseKit_Persp"): SESSION_SHARED_PERSPECTIVE_CAMERA_NAME, Sdf.Path("/OmniverseKit_Top"): SESSION_SHARED_FRONT_CAMERA_NAME, Sdf.Path("/OmniverseKit_Front"): SESSION_SHARED_LEFT_CAMERA_NAME, Sdf.Path("/OmniverseKit_Right"): SESSION_SHARED_RIGHT_CAMERA_NAME, } SHARED_NAME_TO_LOCAL_BUILT_IN_CAMERA_PATH = { SESSION_SHARED_PERSPECTIVE_CAMERA_NAME: Sdf.Path("/OmniverseKit_Persp"), SESSION_SHARED_FRONT_CAMERA_NAME: Sdf.Path("/OmniverseKit_Top"), SESSION_SHARED_LEFT_CAMERA_NAME: Sdf.Path("/OmniverseKit_Front"), SESSION_SHARED_RIGHT_CAMERA_NAME: Sdf.Path("/OmniverseKit_Right"), } LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH = Sdf.Path("/OmniverseLiveSessionSharedData") LAYER_SUBSCRIPTION_ORDER = -1 << 31 # make sure this runs before anything else
1,544
Python
40.756756
87
0.750648
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["PresenceLayerAPI", "get_presence_layer_interface", "PresenceLayerExtension"] import carb import omni.ext import omni.usd from .presence_layer_manager import PresenceLayerManager, PresenceLayerAPI from typing import Dict, Union, List __all_presence_layer_apis: Dict[omni.usd.UsdContext, PresenceLayerAPI] = {} __all_presence_managers: List[PresenceLayerManager] = [] def shutdown_all(): global __all_presence_layer_apis global __all_presence_managers for presence_layer in __all_presence_managers: presence_layer.stop() __all_presence_layer_apis.clear() __all_presence_managers.clear() def get_presence_layer_interface( context_name_or_instance: Union[str, omni.usd.UsdContext] = "" ) -> Union[PresenceLayerAPI, None]: """ Gets PresenceLayerAPI interface bound to the context. For each UsdContext, it has unique PresenceLayerAPI instance, through which, you can access all the interfaces supported. PresenceLayerAPI provides the APIs that serve for easy access to data of presence layer, where presence layer is the transport layer that works for exchange persistent data for all users in the Live Session of the bound UsdContext. It only supports Live Session of root layer for now. """ global __all_presence_layer_apis if not context_name_or_instance: context_name_or_instance = "" if isinstance(context_name_or_instance, str): usd_context = omni.usd.get_context(context_name_or_instance) elif isinstance(context_name_or_instance, omni.usd.UsdContext): usd_context = context_name_or_instance else: carb.log_warn("Failed to get presence layer interface since the param must be name or instance of UsdContext.") return None if not usd_context: carb.log_warn("Failed to query presence layer interface since UsdContext cannot be found.") return None presence_layer_api = __all_presence_layer_apis.get(usd_context, None) if not presence_layer_api: presence_layer = PresenceLayerManager(usd_context) presence_layer.start() __all_presence_managers.append(presence_layer) presence_layer_api = PresenceLayerAPI(presence_layer) __all_presence_layer_apis[usd_context] = presence_layer_api return presence_layer_api class PresenceLayerExtension(omni.ext.IExt): def on_startup(self): # Initialize presence layer for default context. get_presence_layer_interface() def on_shutdown(self): shutdown_all()
2,979
Python
36.25
119
0.728432