file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.viewport.menubar.settings/omni/kit/viewport/menubar/settings/tests/test_ui.py
import omni.kit.test from re import I from omni.ui.tests.test_base import OmniUiTest import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 import omni.usd import omni.kit.app from omni.kit.test.teamcity import is_running_in_teamcity from pathlib import Path import carb.input import asyncio import unittest import sys CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 600 class TestSettingMenuWindow(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await omni.kit.app.get_app().next_update_async() async def test_navigation(self): await self.__show_subitem("menubar_setting_navigation.png", 86) async def test_selection(self): await self.__show_subitem("menubar_setting_selection.png", 106) async def test_grid(self): await self.__show_subitem("menubar_setting_grid.png", 126) async def test_gizmo(self): await self.__show_subitem("menubar_setting_gizmo.png", 146) @unittest.skipIf( (sys.platform == "linux" and is_running_in_teamcity()), "OM-64377: Delegate for RadioMenuCollection does not work in Linux", ) async def test_viewport(self): await self.__show_subitem("menubar_setting_viewport.png", 166) async def test_viewport_ui(self): await self.__show_subitem("menubar_setting_viewport_ui.png", 186) async def test_viewport_manipulate(self): await self.__show_subitem("menubar_setting_viewport_manipulator.png", 206) async def test_reset_item(self): settings = carb.settings.get_settings() cam_vel = settings.get("/persistent/app/viewport/camMoveVelocity") in_enabled = settings.get("/persistent/app/viewport/camInertiaEnabled") settings.set("/persistent/app/viewport/camMoveVelocity", cam_vel * 2) settings.set("/persistent/app/viewport/camInertiaEnabled", not in_enabled) try: await self.__do_ui_test(ui_test.emulate_mouse_click, 225) self.assertEqual(settings.get("/persistent/app/viewport/camMoveVelocity"), cam_vel) self.assertEqual(settings.get("/persistent/app/viewport/camInertiaEnabled"), in_enabled) finally: settings.set("/persistent/app/viewport/camMoveVelocity", cam_vel) settings.set("/persistent/app/viewport/camInertiaEnabled", in_enabled) async def __show_subitem(self, golden_img_name: str, y: int) -> None: async def gloden_compare(): await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.__do_ui_test(gloden_compare, y) async def __do_ui_test(self, test_operation, y: int, frame_wait: int = 3) -> None: # Enable mouse input app = omni.kit.app.get_app() app_window = omni.appwindow.get_default_app_window() for device in [carb.input.DeviceType.MOUSE]: app_window.set_input_blocking_state(device, None) try: await ui_test.emulate_mouse_move(Vec2(20, 46), human_delay_speed=4) await ui_test.emulate_mouse_click() await ui_test.emulate_mouse_move(Vec2(20, y)) for _ in range(frame_wait): await app.next_update_async() await test_operation() finally: for _ in range(frame_wait): await app.next_update_async() await ui_test.emulate_mouse_move(Vec2(300, 26)) await ui_test.emulate_mouse_click() for _ in range(frame_wait): await app.next_update_async()
3,830
Python
36.930693
106
0.661358
omniverse-code/kit/exts/omni.kit.window.status_bar/config/extension.toml
[package] version = "0.1.5" title = "Status Bar" changelog = "docs/CHANGELOG.md" [dependencies] "omni.usd" = {} "omni.ui" = {} "omni.kit.mainwindow" = { optional=true } [[native.plugin]] path = "bin/*.plugin" recursive = false # That will make tests auto-discoverable by test_runner: [[python.module]] name = "omni.kit.window.status_bar.tests" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.capture", "omni.ui", ]
538
TOML
16.966666
56
0.644981
omniverse-code/kit/exts/omni.kit.window.status_bar/omni/kit/window/status_bar/tests/test_status_bar.py
## Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from omni.ui.tests.test_base import OmniUiTest import carb import asyncio class TestStatusBar(OmniUiTest): # Before running each test async def setUp(self): self.name_progress = carb.events.type_from_string("omni.kit.window.status_bar@progress") self.name_activity = carb.events.type_from_string("omni.kit.window.status_bar@activity") self.message_bus = omni.kit.app.get_app().get_message_bus_event_stream() self.message_bus.push(self.name_activity, payload={"text": ""}) self.message_bus.push(self.name_progress, payload={"progress": "-1"}) # After running each test async def tearDown(self): pass async def test_general(self): await self.create_test_area(256, 64) async def log(): # Delayed log because self.finalize_test logs things carb.log_warn("StatusBar test") asyncio.ensure_future(log()) await self.finalize_test() async def test_activity(self): await self.create_test_area(512, 64) async def log(): # Delayed log because self.finalize_test logs things carb.log_warn("StatusBar test") # Test activity name with spaces URL-encoded self.message_bus.push(self.name_activity, payload={"text": "MFC%20For%20NvidiaAnimated.usd"}) self.message_bus.push(self.name_progress, payload={"progress": "0.2"}) asyncio.ensure_future(log()) await self.finalize_test()
1,941
Python
36.346153
101
0.686244
omniverse-code/kit/exts/omni.kit.primitive.mesh/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.8" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] category = "Internal" # The title and description fields are primarly for displaying extension info in UI title = "Kit Mesh Primitives Generator" description="Generators for basic mesh geometry." # Keywords for the extension keywords = ["kit", "mesh primitive"] # URL of the extension source repository. repository = "" # 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" [dependencies] "omni.kit.commands" = {} "omni.usd" = {} "omni.ui" = {optional = true} "omni.kit.menu.utils" = {optional = true} "omni.kit.usd.layers" = {} "omni.kit.actions.core" = {} [[python.module]] name = "omni.kit.primitive.mesh" [[test]] timeout=300 args = [ "--/app/file/ignoreUnsavedOnExit=true", "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.hydra.pxr", "omni.kit.commands", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.test", "omni.ui", "omni.kit.menu.utils" ]
1,473
TOML
24.413793
93
0.691785
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/extension.py
__all__ = ["PrimitiveMeshExtension"] import omni from .mesh_actions import register_actions, deregister_actions from pxr import Usd class PrimitiveMeshExtension(omni.ext.IExt): def __init__(self): super().__init__() def on_startup(self, ext_id): self._ext_name = omni.ext.get_extension_name(ext_id) self._mesh_generator = None try: from .generator import MeshGenerator self._mesh_generator = MeshGenerator() self._mesh_generator.register_menu() except ImportError: pass register_actions(self._ext_name, PrimitiveMeshExtension, lambda: self._mesh_generator) def on_shutdown(self): deregister_actions(self._ext_name) if self._mesh_generator: self._mesh_generator.destroy()
814
Python
27.103447
94
0.635135
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/__init__.py
from .evaluators import get_geometry_mesh_prim_list, AbstractShapeEvaluator from .command import CreateMeshPrimCommand, CreateMeshPrimWithDefaultXformCommand from .extension import PrimitiveMeshExtension
204
Python
50.249987
81
0.887255
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/mesh_actions.py
import omni.usd import omni.kit.commands import omni.kit.actions.core from .evaluators import get_geometry_mesh_prim_list def register_actions(extension_id, cls, get_self_fn): def create_mesh_prim(prim_type): usd_context = omni.usd.get_context() with omni.kit.usd.layers.active_authoring_layer_context(usd_context): omni.kit.commands.execute("CreateMeshPrimWithDefaultXform", prim_type=prim_type, above_ground=True) # actions for prim in get_geometry_mesh_prim_list(): omni.kit.actions.core.get_action_registry().register_action( extension_id, f"create_mesh_prim_{prim.lower()}", lambda p=prim: create_mesh_prim(p), display_name=f"Create Mesh Prim {prim}", description=f"Create Mesh Prim {prim}", tag="Create Mesh Prim", ) if get_self_fn() is not None: omni.kit.actions.core.get_action_registry().register_action( extension_id, "show_setting_window", get_self_fn().show_setting_window, display_name="Show Settings Window", description="Show Settings Window", tag="Show Settings Window", ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
1,391
Python
34.692307
111
0.646298
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/generator.py
import carb.settings import omni import omni.kit from omni import ui from .evaluators import _get_all_evaluators, get_geometry_mesh_prim_list from omni.kit.menu.utils import MenuItemDescription, remove_menu_items, add_menu_items class MeshGenerator: def __init__(self): self._settings = carb.settings.get_settings() self._window = None self._mesh_setting_ui = {} self._current_setting_index = 0 self._mesh_menu_list = [] def destroy(self): self._window = None remove_menu_items(self._mesh_menu_list, "Create") def register_menu(self): sub_menu = [] for prim in get_geometry_mesh_prim_list(): sub_menu.append(MenuItemDescription(name=prim, onclick_action=("omni.kit.primitive.mesh", f"create_mesh_prim_{prim.lower()}"))) sub_menu.append(MenuItemDescription()) sub_menu.append(MenuItemDescription(name="Settings", onclick_action=("omni.kit.primitive.mesh", "show_setting_window"))) self._mesh_menu_list = [ MenuItemDescription(name="Mesh", glyph="menu_prim.svg", sub_menu=sub_menu) ] add_menu_items(self._mesh_menu_list, "Create") def on_primitive_type_selected(self, model, item): names = get_geometry_mesh_prim_list() old_mesh_name = names[self._current_setting_index] if old_mesh_name in self._mesh_setting_ui: self._mesh_setting_ui[old_mesh_name].visible = False idx = model.get_item_value_model().as_int mesh_name = names[idx] if mesh_name in self._mesh_setting_ui: self._mesh_setting_ui[old_mesh_name].visible = False self._mesh_setting_ui[mesh_name].visible = True self._current_setting_index = idx def show_setting_window(self): flags = ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR if not self._window: self._window = ui.Window( "Mesh Generation Settings", ui.DockPreference.DISABLED, width=400, height=260, flags=flags, padding_x=0, padding_y=0, ) with self._window.frame: with ui.VStack(height=0): ui.Spacer(width=0, height=20) with ui.HStack(height=0): ui.Spacer(width=20, height=0) ui.Label("Primitive Type", name="text", height=0) model = ui.ComboBox(0, *get_geometry_mesh_prim_list(), name="primitive_type").model model.add_item_changed_fn(self.on_primitive_type_selected) ui.Spacer(width=20, height=0) ui.Spacer(width=0, height=10) ui.Separator(height=0, name="text") ui.Spacer(width=0, height=10) with ui.ZStack(height=0): mesh_names = get_geometry_mesh_prim_list() for i in range(len(mesh_names)): mesh_name = mesh_names[i] stack = ui.VStack(spacing=0) self._mesh_setting_ui[mesh_name] = stack with stack: ui.Spacer(height=20) evaluator_class = _get_all_evaluators()[mesh_name] evaluator_class.build_setting_ui() ui.Spacer(height=5) if i != 0: stack.visible = False ui.Spacer(width=0, height=20) with ui.HStack(height=0): ui.Spacer() ui.Button( "Create", alignment=ui.Alignment.H_CENTER, name="create", width=120, height=0, mouse_pressed_fn=lambda *args: self._create_shape(), ) ui.Button( "Reset Settings", alignment=ui.Alignment.H_CENTER, name="reset", width=120, height=0, mouse_pressed_fn=lambda *args: self._reset_settings(), ) ui.Spacer() self._current_setting_index = 0 self._window.visible = True def _create_shape(self): names = get_geometry_mesh_prim_list() mesh_type = names[self._current_setting_index] usd_context = omni.usd.get_context() with omni.kit.usd.layers.active_authoring_layer_context(usd_context): omni.kit.commands.execute("CreateMeshPrimWithDefaultXform", prim_type=mesh_type, above_ground=True) def _reset_settings(self): names = get_geometry_mesh_prim_list() mesh_type = names[self._current_setting_index] evaluator_class = _get_all_evaluators()[mesh_type] evaluator_class.reset_setting()
5,205
Python
39.992126
139
0.510086
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/command.py
__all__ = ["CreateMeshPrimWithDefaultXformCommand", "CreateMeshPrimCommand"] import omni import carb.settings from pxr import UsdGeom, Usd, Vt, Kind, Sdf, Gf from .evaluators import _get_all_evaluators PERSISTENT_SETTINGS_PREFIX = "/persistent" class CreateMeshPrimWithDefaultXformCommand(omni.kit.commands.Command): def __init__(self, prim_type: str, **kwargs): """ Creates primitive. Args: prim_type (str): It supports Plane/Sphere/Cone/Cylinder/Disk/Torus/Cube. kwargs: object_origin (Gf.Vec3f): Position of mesh center in stage units. u_patches (int): The number of patches to tessellate U direction. v_patches (int): The number of patches to tessellate V direction. w_patches (int): The number of patches to tessellate W direction. It only works for Cone/Cylinder/Cube. half_scale (float): Half size of mesh in centimeters. Default is None, which means it's controlled by settings. u_verts_scale (int): Tessellation Level of U. It's a multiplier of u_patches. v_verts_scale (int): Tessellation Level of V. It's a multiplier of v_patches. w_verts_scale (int): Tessellation Level of W. It's a multiplier of w_patches. It only works for Cone/Cylinder/Cube. For Cone/Cylinder, it's to tessellate the caps. For Cube, it's to tessellate along z-axis. above_ground (bool): It will offset the center of mesh above the ground plane if it's True, False otherwise. It's False by default. This param only works when param object_origin is not given. Otherwise, it will be ignored. """ self._prim_type = prim_type[0:1].upper() + prim_type[1:].lower() self._usd_context = omni.usd.get_context(kwargs.get("context_name", "")) self._selection = self._usd_context.get_selection() self._stage = self._usd_context.get_stage() self._settings = carb.settings.get_settings() self._default_path = kwargs.get("prim_path", None) self._select_new_prim = kwargs.get("select_new_prim", True) self._prepend_default_prim = kwargs.get("prepend_default_prim", True) self._above_round = kwargs.get("above_ground", False) self._attributes = {**kwargs} # Supported mesh types should have an associated evaluator class self._evaluator_class = _get_all_evaluators()[prim_type] assert isinstance(self._evaluator_class, type) def do(self): self._prim_path = None if self._default_path: path = omni.usd.get_stage_next_free_path(self._stage, self._default_path, self._prepend_default_prim) else: path = omni.usd.get_stage_next_free_path(self._stage, "/" + self._prim_type, self._prepend_default_prim) mesh = UsdGeom.Mesh.Define(self._stage, path) prim = mesh.GetPrim() defaultXformOpType = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType") defaultRotationOrder = self._settings.get( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder" ) defaultXformOpOrder = self._settings.get( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder" ) defaultXformPrecision = self._settings.get( PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision" ) vec3_type = Sdf.ValueTypeNames.Double3 if defaultXformPrecision == "Double" else Sdf.ValueTypeNames.Float3 quat_type = Sdf.ValueTypeNames.Quatd if defaultXformPrecision == "Double" else Sdf.ValueTypeNames.Quatf up_axis = UsdGeom.GetStageUpAxis(self._stage) self._attributes["up_axis"] = up_axis half_scale = self._attributes.get("half_scale", None) if half_scale is None or half_scale <= 0.0: half_scale = self._evaluator_class.get_default_half_scale() object_origin = self._attributes.get("object_origin", None) if object_origin is None and self._above_round: # To move the mesh above the ground. if self._prim_type != "Disk" and self._prim_type != "Plane": if self._prim_type != "Torus": offset = half_scale else: # The tube of torus is half of the half_scale. offset = half_scale / 2.0 # Scale it to make sure it matches stage units. units = UsdGeom.GetStageMetersPerUnit(mesh.GetPrim().GetStage()) if Gf.IsClose(units, 0.0, 1e-6): units = 0.01 scale = 0.01 / units offset = offset * scale if up_axis == "Y": object_origin = Gf.Vec3f(0.0, offset, 0.0) else: object_origin = Gf.Vec3f(0.0, 0.0, offset) else: object_origin = Gf.Vec3f(0.0) elif isinstance(object_origin, list): object_origin = Gf.Vec3f(*object_origin) else: object_origin = Gf.Vec3f(0.0) default_translate = Gf.Vec3d(object_origin) if defaultXformPrecision == "Double" else object_origin default_euler = Gf.Vec3d(0.0, 0.0, 0.0) if defaultXformPrecision == "Double" else Gf.Vec3f(0.0, 0.0, 0.0) default_scale = Gf.Vec3d(1.0, 1.0, 1.0) if defaultXformPrecision == "Double" else Gf.Vec3f(1.0, 1.0, 1.0) default_orient = ( Gf.Quatd(1.0, Gf.Vec3d(0.0, 0.0, 0.0)) if defaultXformPrecision == "Double" else Gf.Quatf(1.0, Gf.Vec3f(0.0, 0.0, 0.0)) ) mat4_type = Sdf.ValueTypeNames.Matrix4d # there is no Matrix4f in SdfValueTypeNames if defaultXformOpType == "Scale, Rotate, Translate": attr_translate = prim.CreateAttribute("xformOp:translate", vec3_type, False) attr_translate.Set(default_translate) attr_rotate_name = "xformOp:rotate" + defaultRotationOrder attr_rotate = prim.CreateAttribute(attr_rotate_name, vec3_type, False) attr_rotate.Set(default_euler) attr_scale = prim.CreateAttribute("xformOp:scale", vec3_type, False) attr_scale.Set(default_scale) attr_order = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.TokenArray, False) attr_order.Set(["xformOp:translate", attr_rotate_name, "xformOp:scale"]) if defaultXformOpType == "Scale, Orient, Translate": attr_translate = prim.CreateAttribute("xformOp:translate", vec3_type, False) attr_translate.Set(default_translate) attr_rotate = prim.CreateAttribute("xformOp:orient", quat_type, False) attr_rotate.Set(default_orient) attr_scale = prim.CreateAttribute("xformOp:scale", vec3_type, False) attr_scale.Set(default_scale) attr_order = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.TokenArray, False) attr_order.Set(["xformOp:translate", "xformOp:orient", "xformOp:scale"]) if defaultXformOpType == "Transform": attr_matrix = prim.CreateAttribute("xformOp:transform", mat4_type, False) attr_matrix.Set(Gf.Matrix4d(1.0)) attr_order = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.TokenArray, False) attr_order.Set(["xformOp:transform"]) self._prim_path = path if self._select_new_prim: self._selection.set_prim_path_selected(path, True, False, True, True) self._define_mesh(mesh) return self._prim_path def undo(self): if self._prim_path: self._stage.RemovePrim(self._prim_path) def _define_mesh(self, mesh): evaluator = self._evaluator_class(self._attributes) points = [] normals = [] sts = [] point_indices = [] face_vertex_counts = [] points, normals, sts, point_indices, face_vertex_counts = evaluator.eval(**self._attributes) units = UsdGeom.GetStageMetersPerUnit(mesh.GetPrim().GetStage()) if Gf.IsClose(units, 0.0, 1e-6): units = 0.01 # Scale points to make sure it's already in centimeters scale = 0.01 / units points = [point * scale for point in points] mesh.GetPointsAttr().Set(Vt.Vec3fArray(points)) mesh.GetNormalsAttr().Set(Vt.Vec3fArray(normals)) mesh.GetFaceVertexIndicesAttr().Set(point_indices) mesh.GetFaceVertexCountsAttr().Set(face_vertex_counts) mesh.SetNormalsInterpolation("faceVarying") prim = mesh.GetPrim() # https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b # UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08 sts_primvar = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray) sts_primvar.SetInterpolation("faceVarying") sts_primvar.Set(Vt.Vec2fArray(sts)) mesh.CreateSubdivisionSchemeAttr("none") attr = prim.GetAttribute(UsdGeom.Tokens.extent) if attr: bounds = UsdGeom.Boundable.ComputeExtentFromPlugins(UsdGeom.Boundable(prim), Usd.TimeCode.Default()) if bounds: attr.Set(bounds) # set the new prim as the active selection if self._select_new_prim: self._selection.set_selected_prim_paths([prim.GetPath().pathString], False) # For back compatibility. class CreateMeshPrimCommand(CreateMeshPrimWithDefaultXformCommand): def __init__(self, prim_type: str, **kwargs): super().__init__(prim_type, **kwargs) omni.kit.commands.register(CreateMeshPrimCommand) omni.kit.commands.register(CreateMeshPrimWithDefaultXformCommand)
9,980
Python
44.995391
123
0.62505
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/cone.py
import math from .utils import ( get_int_setting, build_int_slider, modify_winding_order, transform_point, inverse_u, inverse_v, generate_disk ) from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf from typing import List, Tuple class ConeEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/cone/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/cone/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/cone/v_scale" SETTING_W_SCALE = "/persistent/app/mesh_generator/shapes/cone/w_scale" def __init__(self, attributes: dict): super().__init__(attributes) self.radius = 1.0 self.height = 2.0 # The sequence must be kept in the same as generate_circle_points # in the u direction to share points with the cap. def _eval(self, up_axis, u, v) -> Tuple[Gf.Vec3f, Gf.Vec3f]: theta = u * 2.0 * math.pi x = (1 - v) * math.cos(theta) h = v * self.height - 1 if up_axis == "Y": z = (1 - v) * math.sin(theta) point = Gf.Vec3f(x, h, z) dpdu = Gf.Vec3f(-2.0 * math.pi * z, 0.0, 2.0 * math.pi * x) dpdv = Gf.Vec3f(-x / (1 - v), self.height, -z / (1 - v)) normal = dpdv ^ dpdu normal = normal.GetNormalized() else: y = (1 - v) * math.sin(theta) point = Gf.Vec3f(x, y, h) dpdu = Gf.Vec3f(-2.0 * math.pi * y, 2.0 * math.pi * x, 0) dpdv = Gf.Vec3f(-x / (1 - v), -y / (1 - v), self.height) normal = dpdu ^ dpdv normal = normal.GetNormalized() return point, normal def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(ConeEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(ConeEvaluator.SETTING_V_SCALE, 3) num_w_verts_scale = kwargs.get("w_verts_scale", None) if num_w_verts_scale is None or num_w_verts_scale <= 0: num_w_verts_scale = get_int_setting(ConeEvaluator.SETTING_W_SCALE, 1) num_u_verts_scale = max(num_u_verts_scale, 1) num_v_verts_scale = max(num_v_verts_scale, 1) num_w_verts_scale = max(num_w_verts_scale, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 64) v_patches = kwargs.get("v_patches", 1) w_patches = kwargs.get("w_patches", 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale w_patches = w_patches * num_w_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 1) w_patches = max(int(w_patches), 1) accuracy = 0.00001 u_delta = 1.0 / u_patches v_delta = (1.0 - accuracy) / v_patches num_u_verts = u_patches num_v_verts = v_patches + 1 points: List[Gf.Vec3f] = [] point_normals: List[Gf.Vec3f] = [] normals: List[Gf.Vec3f] = [] sts: List[Gf.Vec2f] = [] face_indices: List[int] = [] face_vertex_counts: List[int] = [] for j in range(num_v_verts): for i in range(num_u_verts): u = i * u_delta v = j * v_delta point, normal = self._eval(up_axis, u, v) point = transform_point(point, origin, half_scale) points.append(point) point_normals.append(normal) def calc_index(i, j): i = i if i < num_u_verts else 0 base_index = j * num_u_verts point_index = base_index + i return point_index def get_uv(i, j): u = 1 - i * u_delta if i < num_u_verts else 0.0 v = j * v_delta if j != num_v_verts - 1 else 1.0 return Gf.Vec2f(u, v) for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) uv00 = get_uv(i, j) uv10 = get_uv(i + 1, j) uv11 = get_uv(i + 1, j + 1) uv01 = get_uv(i, j + 1) # Right-hand order if up_axis == "Y": sts.extend([uv00, uv01, uv11, uv10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normals.extend( [ point_normals[vindex00], point_normals[vindex01], point_normals[vindex11], point_normals[vindex10], ] ) else: sts.extend([inverse_u(uv00), inverse_u(uv10), inverse_u(uv11), inverse_u(uv01)]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normals.extend( [ point_normals[vindex00], point_normals[vindex10], point_normals[vindex11], point_normals[vindex01], ] ) face_vertex_counts.append(4) # Add hat if up_axis == "Y": bottom_center_point = Gf.Vec3f(0, -1, 0) top_center_point = Gf.Vec3f(0, 1 - accuracy, 0) else: bottom_center_point = Gf.Vec3f(0, 0, -1) top_center_point = Gf.Vec3f(0, 0, 1 - accuracy) def add_hat(center_point, rim_points_start_index, w_patches, invert_wind_order=False): bt_points, _, bt_sts, bt_face_indices, bt_face_vertex_counts = generate_disk( center_point, u_patches, w_patches, origin, half_scale, up_axis ) # Total points before adding hat total_points = len(points) # Skips shared points points.extend(bt_points[num_u_verts:]) if invert_wind_order: modify_winding_order(bt_face_vertex_counts, bt_sts) for st in bt_sts: sts.append(inverse_v(st)) else: sts.extend(bt_sts) face_vertex_counts.extend(bt_face_vertex_counts) normals.extend([center_point] * len(bt_face_indices)) # Remapping cap points for i, index in enumerate(bt_face_indices): if index >= num_u_verts: bt_face_indices[i] += total_points - num_u_verts else: bt_face_indices[i] += rim_points_start_index if invert_wind_order: modify_winding_order(bt_face_vertex_counts, bt_face_indices) face_indices.extend(bt_face_indices) # Add top hat to close shape top_hat_start_index = len(points) - num_u_verts add_hat(top_center_point, top_hat_start_index, 1) # Add bottom hat to close shape add_hat(bottom_center_point, 0, w_patches, True) return points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui ConeEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", ConeEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) ConeEvaluator._u_scale_slider = build_int_slider( "U Verts Scale", ConeEvaluator.SETTING_U_SCALE, 1, 1, 10, "Tessellation Level in Horizontal Direction" ) ui.Spacer(height=5) ConeEvaluator._v_scale_slider = build_int_slider( "V Verts Scale", ConeEvaluator.SETTING_V_SCALE, 1, 1, 10, "Tessellation Level in Vertical Direction" ) ui.Spacer(height=5) ConeEvaluator._w_scale_slider = build_int_slider( "W Verts Scale", ConeEvaluator.SETTING_W_SCALE, 1, 1, 10, "Tessellation Level of Bottom Cap" ) @staticmethod def reset_setting(): ConeEvaluator._half_scale_slider.set_value(ConeEvaluator.get_default_half_scale()) ConeEvaluator._u_scale_slider.set_value(1) ConeEvaluator._v_scale_slider.set_value(1) ConeEvaluator._w_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(ConeEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
9,127
Python
38.008547
112
0.5315
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/__init__.py
__all__ = ["get_geometry_mesh_prim_list", "AbstractShapeEvaluator"] import re from .abstract_shape_evaluator import AbstractShapeEvaluator from .cone import ConeEvaluator from .disk import DiskEvaluator from .cube import CubeEvaluator from .cylinder import CylinderEvaluator from .sphere import SphereEvaluator from .torus import TorusEvaluator from .plane import PlaneEvaluator _all_evaluators = {} def _get_all_evaluators(): global _all_evaluators if not _all_evaluators: evaluator_classes = list(filter(lambda x: re.search(r".+Evaluator$", x), globals().keys())) evaluator_classes.remove(AbstractShapeEvaluator.__name__) for evaluator in evaluator_classes: name = re.sub(r"(.*)Evaluator$", r"\1", evaluator) _all_evaluators[name] = globals()[f"{name}Evaluator"] return _all_evaluators def get_geometry_mesh_prim_list(): names = list(_get_all_evaluators().keys()) names.sort() return names
973
Python
27.647058
99
0.706064
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/abstract_shape_evaluator.py
from typing import List, Tuple from pxr import Gf class AbstractShapeEvaluator: # pragma: no cover def __init__(self, attributes: dict): self._attributes = attributes def eval(self, **kwargs) -> Tuple[ List[Gf.Vec3f], List[Gf.Vec3f], List[Gf.Vec2f], List[int], List[int] ]: """It must be implemented to return tuple [points, normals, uvs, face_indices, face_vertex_counts], where: * points and normals are array of Gf.Vec3f. * uvs are array of Gf.Vec2f that represents uv coordinates. * face_indexes are array of int that represents face indices. * face_vertex_counts are array of int that represents vertex count per face. * Normals and uvs must be face varying. """ raise NotImplementedError("Eval must be implemented for this shape.") @staticmethod def build_setting_ui(): pass @staticmethod def reset_setting(): pass @staticmethod def get_default_half_scale(): return 50
1,039
Python
28.714285
84
0.636189
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/utils.py
import math import carb.settings from pxr import Gf from typing import List, Tuple from numbers import Number def _save_settings(model, setting): value = model.get_value_as_int() carb.settings.get_settings().set(setting, value) def build_int_slider(name, setting, default_value, min_value, max_value, tooltip=None): from omni import ui layout = ui.HStack(height=0) with layout: ui.Spacer(width=20, height=0) ui.Label(name, height=0, name="text") model = ui.IntSlider(name="text", min=min_value, max=max_value, height=0, aligment=ui.Alignment.LEFT).model value = get_int_setting(setting, default_value) model.set_value(value) ui.Spacer(width=20, height=0) model.add_value_changed_fn(lambda m: _save_settings(m, setting)) if tooltip: layout.set_tooltip(tooltip) return model def inverse_u(uv) -> Gf.Vec2f: return Gf.Vec2f(1 - uv[0], uv[1]) def inverse_v(uv) -> Gf.Vec2f: return Gf.Vec2f(uv[0], 1 - uv[1]) def inverse_uv(uv) -> Gf.Vec2f: return Gf.Vec2f(1 - uv[0], 1 - uv[1]) def transform_point(point: Gf.Vec3f, origin: Gf.Vec3f, half_scale: float) -> Gf.Vec3f: return half_scale * point + origin def generate_circle_points( up_axis, num_points, delta, center_point=Gf.Vec3f(0.0) ) -> Tuple[List[Gf.Vec3f], List[Gf.Vec2f]]: points: List[Gf.Vec3f] = [] point_sts: List[Gf.Vec2f] = [] for i in range(num_points): theta = i * delta * math.pi * 2 if up_axis == "Y": point = Gf.Vec3f(math.cos(theta), 0.0, math.sin(theta)) st = Gf.Vec2f(1.0 - point[0] / 2.0, (1.0 + point[2]) / 2.0) else: point = Gf.Vec3f(math.cos(theta), math.sin(theta), 0.0) st = Gf.Vec2f((1.0 - point[0]) / 2.0, (1.0 + point[1]) / 2.0) point_sts.append(st) points.append(point + center_point) return points, point_sts def get_int_setting(key, default_value): settings = carb.settings.get_settings() settings.set_default(key, default_value) value = settings.get_as_int(key) return value def generate_disk( center_point: Gf.Vec3f, u_patches: int, v_patches: int, origin: Gf.Vec3f, half_scale: float, up_axis="Y" ) -> Tuple[List[Gf.Vec3f], List[Gf.Vec3f], List[Gf.Vec2f], List[int], List[int]]: u_delta = 1.0 / u_patches v_delta = 1.0 / v_patches num_u_verts = u_patches num_v_verts = v_patches + 1 points: List[Gf.Vec3f] = [] normals: List[Gf.Vec3f] = [] sts: List[Gf.Vec2f] = [] face_indices: List[int] = [] face_vertex_counts: List[int] = [] center_point = transform_point(center_point, origin, half_scale) circle_points, _ = generate_circle_points(up_axis, u_patches, 1.0 / u_patches) for i in range(num_v_verts - 1): v = v_delta * i for j in range(num_u_verts): point = transform_point(circle_points[j], (0, 0, 0), half_scale * (1 - v)) points.append(point + center_point) # Center point points.append(center_point) def calc_index(i, j): ii = i if i < num_u_verts else 0 base_index = j * num_u_verts if j == num_v_verts - 1: return base_index else: return base_index + ii def get_uv(i, j): vindex = calc_index(i, j) # Ensure all axis to be [-1, 1] point = (points[vindex] - origin) / half_scale if up_axis == "Y": st = (Gf.Vec2f(-point[0], -point[2]) + Gf.Vec2f(1, 1)) / 2 else: st = (Gf.Vec2f(point[0], point[1]) + Gf.Vec2f(1)) / 2 return st # Generating quads or triangles of the center for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) uv00 = get_uv(i, j) uv10 = get_uv(i + 1, j) uv11 = get_uv(i + 1, j + 1) uv01 = get_uv(i, j + 1) # Right-hand order if up_axis == "Y": if vindex11 == vindex01: sts.extend([inverse_u(uv00), inverse_u(uv01), inverse_u(uv10)]) face_indices.extend((vindex00, vindex01, vindex10)) else: sts.extend([inverse_u(uv00), inverse_u(uv01), inverse_u(uv11), inverse_u(uv10)]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normal = Gf.Vec3f(0.0, 1.0, 0.0) else: if vindex11 == vindex01: sts.extend([uv00, uv10, uv01]) face_indices.extend((vindex00, vindex10, vindex01)) else: sts.extend([uv00, uv10, uv11, uv01]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normal = Gf.Vec3f(0.0, 0.0, 1.0) if vindex11 == vindex01: face_vertex_counts.append(3) normals.extend([normal] * 3) else: face_vertex_counts.append(4) normals.extend([normal] * 4) return points, normals, sts, face_indices, face_vertex_counts def generate_plane(origin, half_scale, u_patches, v_patches, up_axis): if isinstance(half_scale, Number): [w, h, d] = half_scale, half_scale, half_scale else: [w, h, d] = half_scale [x, y, z] = origin[0], origin[1], origin[2] num_u_verts = u_patches + 1 num_v_verts = v_patches + 1 points = [] normals = [] sts = [] face_indices = [] face_vertex_counts = [] u_delta = 1.0 / u_patches v_delta = 1.0 / v_patches if up_axis == "Y": w_delta = 2.0 * w * u_delta h_delta = 2.0 * d * v_delta bottom_left = Gf.Vec3f(x - w, y, z - d) for i in range(num_v_verts): for j in range(num_u_verts): point = bottom_left + Gf.Vec3f(j * w_delta, 0.0, i * h_delta) points.append(point) elif up_axis == "Z": w_delta = 2.0 * w / u_patches h_delta = 2.0 * h / v_patches bottom_left = Gf.Vec3f(x - w, y - h, z) for i in range(num_v_verts): for j in range(num_u_verts): point = bottom_left + Gf.Vec3f(j * w_delta, i * h_delta, 0.0) points.append(point) else: # X up w_delta = 2.0 * h / u_patches h_delta = 2.0 * d / v_patches bottom_left = Gf.Vec3f(x, y - h, z - d) for i in range(num_v_verts): for j in range(num_u_verts): point = bottom_left + Gf.Vec3f(0, j * w_delta, i * h_delta) points.append(point) def calc_index(i, j): ii = i if i < num_u_verts else 0 jj = j if j < num_v_verts else 0 return jj * num_u_verts + ii def get_uv(i, j): u = i * u_delta if i < num_u_verts else 1.0 if up_axis == "Y": v = 1 - j * v_delta if j < num_v_verts else 0.0 else: v = j * v_delta if j < num_v_verts else 1.0 return Gf.Vec2f(u, v) # Generating quads for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) uv00 = get_uv(i, j) uv10 = get_uv(i + 1, j) uv11 = get_uv(i + 1, j + 1) uv01 = get_uv(i, j + 1) # Right-hand order if up_axis == "Y": sts.extend([uv00, uv01, uv11, uv10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normal = Gf.Vec3f(0.0, 1.0, 0.0) elif up_axis == "Z": sts.extend([uv00, uv10, uv11, uv01]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normal = Gf.Vec3f(0.0, 0.0, 1.0) else: # X sts.extend([uv00, uv01, uv11, uv10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normal = Gf.Vec3f(0.0, 1.0, 0.0) face_vertex_counts.append(4) normals.extend([normal] * 4) return points, normals, sts, face_indices, face_vertex_counts def modify_winding_order(face_counts, face_indices): total = 0 for count in face_counts: if count >= 3: start = total + 1 end = total + count face_indices[start:end] = face_indices[start:end][::-1] total += count
8,670
Python
32.608527
115
0.529873
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/plane.py
from .utils import get_int_setting, build_int_slider, inverse_u, generate_plane from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class PlaneEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/plane/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/plane/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/plane/v_scale" def __init__(self, attributes: dict): super().__init__(attributes) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(PlaneEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(PlaneEvaluator.SETTING_V_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) half_scale = [half_scale, half_scale, half_scale] u_patches = kwargs.get("u_patches", 1) v_patches = kwargs.get("v_patches", 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale u_patches = max(int(u_patches), 1) v_patches = max(int(v_patches), 1) return generate_plane(origin, half_scale, u_patches, v_patches, up_axis) @staticmethod def build_setting_ui(): from omni import ui PlaneEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", PlaneEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) PlaneEvaluator._u_scale_slider = build_int_slider("U Verts Scale", PlaneEvaluator.SETTING_U_SCALE, 1, 1, 10) ui.Spacer(height=5) PlaneEvaluator._v_scale_slider = build_int_slider("V Verts Scale", PlaneEvaluator.SETTING_V_SCALE, 1, 1, 10) @staticmethod def reset_setting(): PlaneEvaluator._half_scale_slider.set_value(PlaneEvaluator.get_default_half_scale()) PlaneEvaluator._u_scale_slider.set_value(1) PlaneEvaluator._v_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(PlaneEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
2,585
Python
39.406249
116
0.649903
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/cylinder.py
from .utils import ( get_int_setting, build_int_slider, modify_winding_order, generate_circle_points, transform_point, inverse_u, inverse_v, generate_disk ) from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf from typing import List class CylinderEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/cylinder/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/cylinder/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/cylinder/v_scale" SETTING_W_SCALE = "/persistent/app/mesh_generator/shapes/cylinder/w_scale" def __init__(self, attributes: dict): super().__init__(attributes) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(CylinderEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(CylinderEvaluator.SETTING_V_SCALE, 1) num_w_verts_scale = kwargs.get("w_verts_scale", None) if num_w_verts_scale is None or num_w_verts_scale <= 0: num_w_verts_scale = get_int_setting(CylinderEvaluator.SETTING_W_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 32) v_patches = kwargs.get("v_patches", 1) w_patches = kwargs.get("w_patches", 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale w_patches = w_patches * num_w_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 1) w_patches = max(int(w_patches), 1) u_delta = 1.0 / (u_patches if u_patches != 0 else 1) v_delta = 1.0 / (v_patches if v_patches != 0 else 1) # open meshes need an extra vert on the end to create the last patch # closed meshes reuse the vert at index 0 to close their final patch num_u_verts = u_patches num_v_verts = v_patches + 1 points: List[Gf.Vec3f] = [] normals: List[Gf.Vec3f] = [] sts: List[Gf.Vec2f] = [] face_indices: List[int] = [] face_vertex_counts: List[int] = [] # generate circle points circle_points, _ = generate_circle_points(up_axis, num_u_verts, u_delta) for j in range(num_v_verts): for i in range(num_u_verts): v = j * v_delta point = circle_points[i] if up_axis == "Y": point[1] = 2.0 * (v - 0.5) else: point[2] = 2.0 * (v - 0.5) point = transform_point(point, origin, half_scale) points.append(point) def calc_index(i, j): ii = i if i < num_u_verts else 0 jj = j if j < num_v_verts else 0 return jj * num_u_verts + ii def get_uv(i, j): u = 1 - i * u_delta if i < num_u_verts else 0.0 v = j * v_delta if j < num_v_verts else 1.0 return Gf.Vec2f(u, v) for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) uv00 = get_uv(i, j) uv10 = get_uv(i + 1, j) uv11 = get_uv(i + 1, j + 1) uv01 = get_uv(i, j + 1) p00 = points[vindex00] p10 = points[vindex10] p11 = points[vindex11] p01 = points[vindex01] # Right-hand order if up_axis == "Y": sts.extend([uv00, uv01, uv11, uv10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normals.append(Gf.Vec3f(p00[0], 0, p00[2])) normals.append(Gf.Vec3f(p01[0], 0, p01[2])) normals.append(Gf.Vec3f(p11[0], 0, p11[2])) normals.append(Gf.Vec3f(p10[0], 0, p10[2])) else: sts.extend([inverse_u(uv00), inverse_u(uv10), inverse_u(uv11), inverse_u(uv01)]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normals.append(Gf.Vec3f(p00[0], p00[1], 0)) normals.append(Gf.Vec3f(p10[0], p10[1], 0)) normals.append(Gf.Vec3f(p11[0], p11[1], 0)) normals.append(Gf.Vec3f(p01[0], p01[1], 0)) face_vertex_counts.append(4) # Add hat if up_axis == "Y": bottom_center_point = Gf.Vec3f(0, -1, 0) top_center_point = Gf.Vec3f(0, 1, 0) else: bottom_center_point = Gf.Vec3f(0, 0, -1) top_center_point = Gf.Vec3f(0, 0, 1) def add_hat(center_point, rim_points_start_index, w_patches, invert_wind_order=False): bt_points, _, bt_sts, bt_face_indices, bt_face_vertex_counts = generate_disk( center_point, u_patches, w_patches, origin, half_scale, up_axis ) total_points = len(points) # Skips shared points points.extend(bt_points[num_u_verts:]) if invert_wind_order: modify_winding_order(bt_face_vertex_counts, bt_sts) for st in bt_sts: sts.append(inverse_v(st)) else: sts.extend(bt_sts) face_vertex_counts.extend(bt_face_vertex_counts) normals.extend([center_point] * len(bt_face_indices)) # Remapping cap points for i, index in enumerate(bt_face_indices): if index >= num_u_verts: bt_face_indices[i] += total_points - num_u_verts else: bt_face_indices[i] += rim_points_start_index if invert_wind_order: modify_winding_order(bt_face_vertex_counts, bt_face_indices) face_indices.extend(bt_face_indices) top_hat_start_index = len(points) - num_u_verts # Add bottom hat to close shape add_hat(bottom_center_point, 0, w_patches, True) # Add top hat to close shape add_hat(top_center_point, top_hat_start_index, w_patches) return points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui CylinderEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", CylinderEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) CylinderEvaluator._u_scale_slider = build_int_slider( "U Verts Scale", CylinderEvaluator.SETTING_U_SCALE, 1, 1, 10, "Tessellation Level in Horizontal Direction" ) ui.Spacer(height=5) CylinderEvaluator._v_scale_slider = build_int_slider( "V Verts Scale", CylinderEvaluator.SETTING_V_SCALE, 1, 1, 10, "Tessellation Level in Vertical Direction" ) ui.Spacer(height=5) CylinderEvaluator._w_scale_slider = build_int_slider( "W Verts Scale", CylinderEvaluator.SETTING_W_SCALE, 1, 1, 10, "Tessellation Level of Bottom and Top Caps" ) @staticmethod def reset_setting(): CylinderEvaluator._half_scale_slider.set_value(CylinderEvaluator.get_default_half_scale()) CylinderEvaluator._u_scale_slider.set_value(1) CylinderEvaluator._v_scale_slider.set_value(1) CylinderEvaluator._w_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(CylinderEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
8,285
Python
40.019802
100
0.555462
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/sphere.py
import math from .utils import get_int_setting, build_int_slider from .utils import transform_point from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class SphereEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/shpere/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/sphere/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/sphere/v_scale" def __init__(self, attributes: dict): super().__init__(attributes) def _eval(self, u, v, up_axis): theta = u * 2.0 * math.pi phi = (v - 0.5) * math.pi cos_phi = math.cos(phi) if up_axis == "Y": x = cos_phi * math.cos(theta) y = math.sin(phi) z = cos_phi * math.sin(theta) else: x = cos_phi * math.cos(theta) y = cos_phi * math.sin(theta) z = math.sin(phi) return Gf.Vec3f(x, y, z) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(SphereEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(SphereEvaluator.SETTING_V_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 32) v_patches = kwargs.get("v_patches", 16) num_u_verts_scale = max(num_u_verts_scale, 1) num_v_verts_scale = max(num_v_verts_scale, 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 2) u_delta = 1.0 / u_patches v_delta = 1.0 / v_patches num_u_verts = u_patches num_v_verts = v_patches + 1 points = [] normals = [] sts = [] face_indices = [] face_vertex_counts = [] if up_axis == "Y": bottom_point = Gf.Vec3f(0.0, -1.0, 0.0) else: bottom_point = Gf.Vec3f(0.0, 0.0, -1.0) point = transform_point(bottom_point, origin, half_scale) points.append(point) for j in range(1, num_v_verts - 1): v = j * v_delta for i in range(num_u_verts): u = i * u_delta point = self._eval(u, v, up_axis) point = transform_point(point, origin, half_scale) points.append(Gf.Vec3f(point)) if up_axis == "Y": top_point = Gf.Vec3f(0.0, 1.0, 0.0) else: top_point = Gf.Vec3f(0.0, 0.0, 1.0) point = transform_point(top_point, origin, half_scale) points.append(point) def calc_index(i, j): if j == 0: return 0 elif j == num_v_verts - 1: return len(points) - 1 else: i = i if i < num_u_verts else 0 return (j - 1) * num_u_verts + i + 1 def get_uv(i, j): if up_axis == "Y": u = 1 - i * u_delta v = j * v_delta else: u = i * u_delta v = j * v_delta return Gf.Vec2f(u, v) # Generate body for j in range(v_patches): for i in range(u_patches): # Index 0 is the bottom hat point vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) st00 = get_uv(i, j) st10 = get_uv(i + 1, j) st11 = get_uv(i + 1, j + 1) st01 = get_uv(i, j + 1) p0 = points[vindex00] p1 = points[vindex10] p2 = points[vindex11] p3 = points[vindex01] # Use face varying uv if up_axis == "Y": if vindex11 == vindex01: sts.extend([st00, st01, st10]) face_indices.extend((vindex00, vindex01, vindex10)) face_vertex_counts.append(3) normals.extend([p0, p3, p1]) elif vindex00 == vindex10: sts.extend([st00, st01, st11]) face_indices.extend((vindex00, vindex01, vindex11)) face_vertex_counts.append(3) normals.extend([p0, p3, p2]) else: sts.extend([st00, st01, st11, st10]) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) face_vertex_counts.append(4) normals.extend([p0, p3, p2, p1]) else: if vindex11 == vindex01: sts.extend([st00, st10, st01]) face_indices.extend((vindex00, vindex10, vindex01)) face_vertex_counts.append(3) normals.extend([p0, p1, p3]) elif vindex00 == vindex10: sts.extend([st00, st11, st01]) face_indices.extend((vindex00, vindex11, vindex01)) face_vertex_counts.append(3) normals.extend([p0, p2, p3]) else: sts.extend([st00, st10, st11, st01]) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) face_vertex_counts.append(4) normals.extend([p0, p1, p2, p3]) return points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui SphereEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", SphereEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) SphereEvaluator._u_scale_slider = build_int_slider( "U Verts Scale", SphereEvaluator.SETTING_U_SCALE, 1, 1, 10 ) ui.Spacer(height=5) SphereEvaluator._v_scale_slider = build_int_slider( "V Verts Scale", SphereEvaluator.SETTING_V_SCALE, 1, 1, 10 ) @staticmethod def reset_setting(): SphereEvaluator._half_scale_slider.set_value(SphereEvaluator.get_default_half_scale()) SphereEvaluator._u_scale_slider.set_value(1) SphereEvaluator._v_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(SphereEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
7,142
Python
36.397906
96
0.506301
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/cube.py
from .utils import get_int_setting, build_int_slider, generate_plane, modify_winding_order from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class CubeEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/cube/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/cube/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/cube/v_scale" SETTING_W_SCALE = "/persistent/app/mesh_generator/shapes/cube/w_scale" def __init__(self, attributes: dict): super().__init__(attributes) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(CubeEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(CubeEvaluator.SETTING_V_SCALE, 1) num_w_verts_scale = kwargs.get("w_verts_scale", None) if num_w_verts_scale is None or num_w_verts_scale <= 0: num_w_verts_scale = get_int_setting(CubeEvaluator.SETTING_W_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 1) v_patches = kwargs.get("v_patches", 1) w_patches = kwargs.get("w_patches", 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale w_patches = w_patches * num_w_verts_scale u_patches = max(int(u_patches), 1) v_patches = max(int(v_patches), 1) w_patches = max(int(w_patches), 1) [x, y, z] = origin ( xy_plane_points, xy_plane_normals, xy_plane_sts, xy_plane_face_indices, xy_plane_face_vertex_counts ) = generate_plane(Gf.Vec3f(x, y, z + half_scale), half_scale, u_patches, v_patches, "Z") ( xz_plane_points, xz_plane_normals, xz_plane_sts, xz_plane_face_indices, xz_plane_face_vertex_counts ) = generate_plane(Gf.Vec3f(x, y - half_scale, z), half_scale, u_patches, w_patches, "Y") ( yz_plane_points, yz_plane_normals, yz_plane_sts, yz_plane_face_indices, yz_plane_face_vertex_counts ) = generate_plane(Gf.Vec3f(x - half_scale, y, z), half_scale, v_patches, w_patches, "X") points = [] normals = [] sts = [] face_indices = [] face_vertex_counts = [] # XY planes points.extend(xy_plane_points) normals.extend([Gf.Vec3f(0, 0, 1)] * len(xy_plane_normals)) sts.extend(xy_plane_sts) face_indices.extend(xy_plane_face_indices) face_vertex_counts.extend(xy_plane_face_vertex_counts) total_indices = len(points) plane_points = [point + Gf.Vec3f(0, 0, -2.0 * half_scale) for point in xy_plane_points] points.extend(plane_points) normals.extend([Gf.Vec3f(0, 0, -1)] * len(xy_plane_normals)) modify_winding_order(xy_plane_face_vertex_counts, xy_plane_sts) plane_sts = [Gf.Vec2f(1 - st[0], st[1]) for st in xy_plane_sts] sts.extend(plane_sts) plane_face_indices = [index + total_indices for index in xy_plane_face_indices] modify_winding_order(xy_plane_face_vertex_counts, plane_face_indices) face_indices.extend(plane_face_indices) face_vertex_counts.extend(xy_plane_face_vertex_counts) # xz planes total_indices = len(points) plane_points = [point + Gf.Vec3f(0, 2.0 * half_scale, 0) for point in xz_plane_points] points.extend(plane_points) normals.extend([Gf.Vec3f(0, 1, 0)] * len(xz_plane_normals)) sts.extend(xz_plane_sts) plane_face_indices = [index + total_indices for index in xz_plane_face_indices] face_indices.extend(plane_face_indices) face_vertex_counts.extend(xz_plane_face_vertex_counts) total_indices = len(points) points.extend(xz_plane_points) normals.extend([Gf.Vec3f(0, -1, 0)] * len(xz_plane_normals)) modify_winding_order(xz_plane_face_vertex_counts, xz_plane_sts) plane_sts = [Gf.Vec2f(st[0], 1 - st[1]) for st in xz_plane_sts] sts.extend(plane_sts) plane_face_indices = [index + total_indices for index in xz_plane_face_indices] modify_winding_order(xz_plane_face_vertex_counts, plane_face_indices) face_indices.extend(plane_face_indices) face_vertex_counts.extend(xz_plane_face_vertex_counts) # yz planes total_indices = len(points) points.extend(yz_plane_points) normals.extend([Gf.Vec3f(-1, 0, 0)] * len(yz_plane_normals)) plane_sts = [Gf.Vec2f(st[1], st[0]) for st in yz_plane_sts] sts.extend(plane_sts) plane_face_indices = [index + total_indices for index in yz_plane_face_indices] face_indices.extend(plane_face_indices) face_vertex_counts.extend(yz_plane_face_vertex_counts) total_indices = len(points) plane_points = [point + Gf.Vec3f(2.0 * half_scale, 0, 0) for point in yz_plane_points] points.extend(plane_points) normals.extend([Gf.Vec3f(1, 0, 0)] * len(yz_plane_normals)) modify_winding_order(yz_plane_face_vertex_counts, yz_plane_sts) plane_sts = [Gf.Vec2f(1 - st[1], st[0]) for st in yz_plane_sts] sts.extend(plane_sts) plane_face_indices = [index + total_indices for index in yz_plane_face_indices] modify_winding_order(yz_plane_face_vertex_counts, plane_face_indices) face_indices.extend(plane_face_indices) face_vertex_counts.extend(yz_plane_face_vertex_counts) # Welds the edges of cube keep = [True] * len(points) index_remap = [-1] * len(points) keep_points = [] for i in range(0, len(points)): if not keep[i]: continue keep_points.append(points[i]) index_remap[i] = len(keep_points) - 1 for j in range(i + 1, len(points)): if Gf.IsClose(points[j], points[i], 1e-6): keep[j] = False index_remap[j] = len(keep_points) - 1 for i in range(len(face_indices)): face_indices[i] = index_remap[face_indices[i]] return keep_points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui CubeEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", CubeEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) CubeEvaluator._u_scale_slider = build_int_slider( "U Verts Scale", CubeEvaluator.SETTING_U_SCALE, 1, 1, 10, "Tessellation Level along X Axis" ) ui.Spacer(height=5) CubeEvaluator._v_scale_slider = build_int_slider( "V Verts Scale", CubeEvaluator.SETTING_V_SCALE, 1, 1, 10, "Tessellation Level along Y Axis" ) ui.Spacer(height=5) CubeEvaluator._w_scale_slider = build_int_slider( "W Verts Scale", CubeEvaluator.SETTING_W_SCALE, 1, 1, 10, "Tessellation Level along Z Axis" ) @staticmethod def reset_setting(): CubeEvaluator._half_scale_slider.set_value(CubeEvaluator.get_default_half_scale()) CubeEvaluator._u_scale_slider.set_value(1) CubeEvaluator._v_scale_slider.set_value(1) CubeEvaluator._w_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(CubeEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
7,997
Python
41.770053
97
0.614731
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/disk.py
from .utils import get_int_setting, build_int_slider from .utils import generate_disk from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class DiskEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/disk/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/disk/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/disk/v_scale" def __init__(self, attributes: dict): super().__init__(attributes) def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(DiskEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(DiskEvaluator.SETTING_V_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) # Disk will be approximated by quads composed from inner circle # to outer circle. The parameter `u_patches` means the segments # of circle. And v_patches means the number of segments (circles) # in radius direction. u_patches = kwargs.get("u_patches", 32) v_patches = kwargs.get("v_patches", 1) num_u_verts_scale = max(num_u_verts_scale, 1) num_v_verts_scale = max(num_v_verts_scale, 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 1) center_point = Gf.Vec3f(0.0) return generate_disk(center_point, u_patches, v_patches, origin, half_scale, up_axis) @staticmethod def build_setting_ui(): from omni import ui DiskEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", DiskEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) DiskEvaluator._u_scale_slider = build_int_slider("U Verts Scale", DiskEvaluator.SETTING_U_SCALE, 1, 1, 10) ui.Spacer(height=5) DiskEvaluator._v_scale_slider = build_int_slider("V Verts Scale", DiskEvaluator.SETTING_V_SCALE, 1, 1, 10) @staticmethod def reset_setting(): DiskEvaluator._half_scale_slider.set_value(DiskEvaluator.get_default_half_scale()) DiskEvaluator._u_scale_slider.set_value(1) DiskEvaluator._v_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(DiskEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
2,917
Python
39.527777
114
0.649983
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/evaluators/torus.py
import math from .utils import get_int_setting, build_int_slider from .utils import transform_point from .abstract_shape_evaluator import AbstractShapeEvaluator from pxr import Gf class TorusEvaluator(AbstractShapeEvaluator): SETTING_OBJECT_HALF_SCALE = "/persistent/app/mesh_generator/shapes/torus/object_half_scale" SETTING_U_SCALE = "/persistent/app/mesh_generator/shapes/torus/u_scale" SETTING_V_SCALE = "/persistent/app/mesh_generator/shapes/torus/v_scale" def __init__(self, attributes: dict): super().__init__(attributes) self.hole_radius = 1.0 self.tube_radius = 0.5 def _eval(self, up_axis, u, v): theta = u * 2.0 * math.pi phi = v * 2.0 * math.pi - 0.5 * math.pi rad_cos_phi = self.tube_radius * math.cos(phi) cos_theta = math.cos(theta) sin_phi = math.sin(phi) sin_theta = math.sin(theta) x = (self.hole_radius + rad_cos_phi) * cos_theta nx = self.hole_radius * cos_theta if up_axis == "Y": y = self.tube_radius * sin_phi z = (self.hole_radius + rad_cos_phi) * sin_theta ny = 0 nz = self.hole_radius * sin_theta else: y = (self.hole_radius + rad_cos_phi) * sin_theta z = self.tube_radius * sin_phi ny = self.hole_radius * sin_theta nz = 0 point = Gf.Vec3f(x, y, z) # construct the normal by creating a vector from the center point of the tube to the surface normal = Gf.Vec3f(x - nx, y - ny, z - nz) normal = normal.GetNormalized() return point, normal def eval(self, **kwargs): half_scale = kwargs.get("half_scale", None) if half_scale is None or half_scale <= 0: half_scale = self.get_default_half_scale() num_u_verts_scale = kwargs.get("u_verts_scale", None) if num_u_verts_scale is None or num_u_verts_scale <= 0: num_u_verts_scale = get_int_setting(TorusEvaluator.SETTING_U_SCALE, 1) num_v_verts_scale = kwargs.get("v_verts_scale", None) if num_v_verts_scale is None or num_v_verts_scale <= 0: num_v_verts_scale = get_int_setting(TorusEvaluator.SETTING_V_SCALE, 1) up_axis = kwargs.get("up_axis", "Y") origin = Gf.Vec3f(0.0) u_patches = kwargs.get("u_patches", 32) v_patches = kwargs.get("v_patches", 32) num_u_verts_scale = max(num_u_verts_scale, 1) num_v_verts_scale = max(num_v_verts_scale, 1) u_patches = u_patches * num_u_verts_scale v_patches = v_patches * num_v_verts_scale u_patches = max(int(u_patches), 3) v_patches = max(int(v_patches), 3) u_delta = 1.0 / u_patches v_delta = 1.0 / v_patches num_u_verts = u_patches num_v_verts = v_patches points = [] point_normals = [] sts = [] face_indices = [] face_vertex_counts = [] for j in range(num_v_verts): v = j * v_delta for i in range(num_u_verts): u = i * u_delta point, point_normal = self._eval(up_axis, u, v) point = transform_point(point, origin, half_scale) points.append(point) point_normals.append(point_normal) def calc_index(i, j): ii = i if i < num_u_verts else 0 jj = j if j < num_v_verts else 0 return jj * num_u_verts + ii def get_uv(i, j): if up_axis == "Y": u = 1 - i * u_delta if i < num_u_verts else 0.0 else: u = i * u_delta if i < num_u_verts else 1.0 v = j * v_delta if j < num_v_verts else 1.0 return Gf.Vec2f(u, v) # Last patch from last vert to first vert to close shape normals = [] for j in range(v_patches): for i in range(u_patches): vindex00 = calc_index(i, j) vindex10 = calc_index(i + 1, j) vindex11 = calc_index(i + 1, j + 1) vindex01 = calc_index(i, j + 1) # Use face varying uv face_vertex_counts.append(4) if up_axis == "Y": sts.append(get_uv(i, j)) sts.append(get_uv(i, j + 1)) sts.append(get_uv(i + 1, j + 1)) sts.append(get_uv(i + 1, j)) face_indices.extend((vindex00, vindex01, vindex11, vindex10)) normals.extend( [ point_normals[vindex00], point_normals[vindex01], point_normals[vindex11], point_normals[vindex10], ] ) else: sts.append(get_uv(i, j)) sts.append(get_uv(i + 1, j)) sts.append(get_uv(i + 1, j + 1)) sts.append(get_uv(i, j + 1)) face_indices.extend((vindex00, vindex10, vindex11, vindex01)) normals.extend( [ point_normals[vindex00], point_normals[vindex10], point_normals[vindex11], point_normals[vindex01], ] ) return points, normals, sts, face_indices, face_vertex_counts @staticmethod def build_setting_ui(): from omni import ui TorusEvaluator._half_scale_slider = build_int_slider( "Object Half Scale", TorusEvaluator.SETTING_OBJECT_HALF_SCALE, 50, 10, 1000 ) ui.Spacer(height=5) TorusEvaluator._u_scale_slider = build_int_slider("U Verts Scale", TorusEvaluator.SETTING_U_SCALE, 1, 1, 10) ui.Spacer(height=5) TorusEvaluator._v_scale_slider = build_int_slider("V Verts Scale", TorusEvaluator.SETTING_V_SCALE, 1, 1, 10) @staticmethod def reset_setting(): TorusEvaluator._half_scale_slider.set_value(TorusEvaluator.get_default_half_scale()) TorusEvaluator._u_scale_slider.set_value(1) TorusEvaluator._v_scale_slider.set_value(1) @staticmethod def get_default_half_scale(): half_scale = get_int_setting(TorusEvaluator.SETTING_OBJECT_HALF_SCALE, 50) return half_scale
6,485
Python
36.275862
116
0.523516
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/tests/__init__.py
from .test_mesh_prims import *
31
Python
14.999993
30
0.741935
omniverse-code/kit/exts/omni.kit.primitive.mesh/omni/kit/primitive/mesh/tests/test_mesh_prims.py
import omni.kit.test import omni.usd import omni.kit.app import omni.kit.primitive.mesh import omni.kit.commands import omni.kit.actions.core from pathlib import Path from pxr import Gf, Kind, Sdf, Usd, UsdGeom, UsdShade EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests") # NOTE: those tests belong to omni.kit.primitive.mesh extension. class TestMeshPrims(omni.kit.test.AsyncTestCase): async def test_tessellation_params(self): test_data = { "Cube": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1, "w_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 1}, }, { "params": {"half_scale": 400, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "w_verts_scale": 1, "u_patches": 2, "v_patches": 2, "w_patches": 2 }, }, ], "Cone": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1, "w_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 1}, }, { "params": {"half_scale": 400, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "w_verts_scale": 1, "u_patches": 2, "v_patches": 2, "w_patches": 2 }, }, ], "Cylinder": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1, "w_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 1}, }, { "params": {"half_scale": 400, "u_verts_scale": 2, "v_verts_scale": 2, "w_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "w_verts_scale": 1, "u_patches": 2, "v_patches": 2, "w_patches": 2 }, }, ], "Disk": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "u_patches": 2, "v_patches": 2 }, }, ], "Plane": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "u_patches": 2, "v_patches": 2 }, }, ], "Sphere": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "u_patches": 2, "v_patches": 2 }, }, ], "Torus": [ { "params": {"half_scale": 100, "u_verts_scale": 2, "v_verts_scale": 1}, }, { "params": {"half_scale": 200, "u_verts_scale": 2, "v_verts_scale": 2}, }, { "params": { "half_scale": 100, "u_verts_scale": 1, "v_verts_scale": 1, "u_patches": 2, "v_patches": 2 }, }, ], } golden_file = TEST_DATA_PATH.joinpath("golden.usd") golden_stage = Usd.Stage.Open(str(golden_file)) self.assertTrue(golden_stage) await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() for prim_type, test_cases in test_data.items(): for test_case in test_cases: params = test_case["params"] result, path = omni.kit.commands.execute( "CreateMeshPrim", prim_type=prim_type, above_ground=True, **params ) self.assertTrue(result) mesh_prim = stage.GetPrimAtPath(path) self.assertTrue(mesh_prim) golden_prim = golden_stage.GetPrimAtPath(path) self.assertTrue(golden_prim) property_names = mesh_prim.GetPropertyNames() golden_property_names = golden_prim.GetPropertyNames() self.assertEqual(property_names, golden_property_names) path = Sdf.Path(path) for property_name in property_names: property_path = path.AppendProperty(property_name) prop = mesh_prim.GetPropertyAtPath(property_path) golden_prop = golden_prim.GetPropertyAtPath(property_path) # Skips relationship if hasattr(prop, "GetTypeName"): self.assertTrue(prop.GetTypeName(), golden_prop.GetTypeName()) self.assertEqual(prop.Get(), golden_prop.Get()) async def test_mesh_prims(self): """Test all mesh generator prims.""" for y_axis in [True, False]: await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() axis = UsdGeom.Tokens.y if y_axis else UsdGeom.Tokens.z UsdGeom.SetStageUpAxis(stage, axis) for prim_type in omni.kit.primitive.mesh.get_geometry_mesh_prim_list(): result, path = omni.kit.commands.execute("CreateMeshPrim", prim_type=prim_type, above_ground=True) self.assertTrue(result) def check_exist(): prim = stage.GetPrimAtPath(path) attr = prim.GetAttribute(UsdGeom.Tokens.extent) self.assertTrue(attr and attr.Get()) self.assertTrue(prim) self.assertTrue(prim.IsA(UsdGeom.Mesh)) self.assertTrue(prim.IsA(UsdGeom.Xformable)) mesh_prim = UsdGeom.Mesh(prim) points = mesh_prim.GetPointsAttr().Get() face_indices = mesh_prim.GetFaceVertexIndicesAttr().Get() normals = mesh_prim.GetNormalsAttr().Get() face_counts = mesh_prim.GetFaceVertexCountsAttr().Get() total = 0 for face_count in face_counts: total += face_count unique_indices = set(face_indices) self.assertTrue(len(points) == len(unique_indices)) self.assertTrue(total == len(normals)) self.assertTrue(total == len(face_indices)) def check_does_not_exist(): self.assertFalse(stage.GetPrimAtPath(path)) check_exist() omni.kit.undo.undo() check_does_not_exist() omni.kit.undo.redo() check_exist() omni.kit.undo.undo() check_does_not_exist() async def test_meshes_creation_from_menu(self): import omni.kit.ui_test as ui_test await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() for prim_type in omni.kit.primitive.mesh.get_geometry_mesh_prim_list(): await ui_test.menu_click(f"Create/Mesh/{prim_type.capitalize()}") path = f"/{prim_type}" def check_exist(): prim = stage.GetPrimAtPath(path) self.assertTrue(prim) def check_does_not_exist(): self.assertFalse(stage.GetPrimAtPath(path)) check_exist() omni.kit.undo.undo() check_does_not_exist() omni.kit.undo.redo() check_exist() omni.kit.undo.undo() check_does_not_exist() async def test_mesh_settings(self): import omni.kit.ui_test as ui_test await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() await ui_test.menu_click("Create/Mesh/Settings") window = ui_test.find("Mesh Generation Settings") self.assertTrue(window) await window.focus() primitive_type_combobox = window.find("**/ComboBox[*].name=='primitive_type'") self.assertTrue(primitive_type_combobox) create_button = window.find("**/Button[*].name=='create'") self.assertTrue(create_button) model = primitive_type_combobox.model value_model = model.get_item_value_model() for i, prim_type in enumerate(omni.kit.primitive.mesh.get_geometry_mesh_prim_list()): value_model.set_value(i) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await create_button.click() path = f"/{prim_type}" self.assertTrue(stage.GetPrimAtPath(path)) async def test_actions(self): await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() for prim_type in omni.kit.primitive.mesh.get_geometry_mesh_prim_list(): omni.kit.actions.core.execute_action( "omni.kit.primitive.mesh", f"create_mesh_prim_{prim_type.lower()}" ) path = f"/{prim_type}" def check_exist(): prim = stage.GetPrimAtPath(path) self.assertTrue(prim) def check_does_not_exist(): self.assertFalse(stage.GetPrimAtPath(path)) check_exist() omni.kit.undo.undo() check_does_not_exist() omni.kit.undo.redo() check_exist() omni.kit.undo.undo() check_does_not_exist()
11,354
Python
38.702797
115
0.468822
omniverse-code/kit/exts/omni.kit.primitive.mesh/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.8] - 2022-11-25 ### Changes - Improve mesh primitives for physx needs. - Make sure cone and cylinder are watertight. - Fix normal issues at the tip of Cone. - Add more tessellation settings for caps of cone and cylinder. - Add more tessellation settings for cube to tesselate cube with axis. ## [1.0.7] - 2022-11-22 ### Changes - Fix to avoid crash at shutdown when loading optional slice ## [1.0.6] - 2022-11-22 ### Changes - Make UI dpendency optional ## [1.0.5] - 2022-11-12 ### Changes - Export extent attr for mesh. ## [1.0.4] - 2022-11-11 ### Changes - Clean up dependencies. ## [1.0.3] - 2022-10-25 ### Changes - Added prepend_default_prim parameters to CreateMeshPrimWithDefaultXformCommand ## [1.0.2] - 2022-08-12 ### Changes - Added select_new_prim & prim_path parameters to CreateMeshPrimWithDefaultXformCommand ## [1.0.1] - 2022-06-08 ### Changes - Updated menus to use actions. ## [1.0.0] - 2020-09-09 ### Changes - Supports cube, cone, cylinder, disk, plane, sphere, torus generation. - Supports subdivision of meshes.
1,143
Markdown
24.999999
87
0.702537
omniverse-code/kit/exts/omni.kit.primitive.mesh/docs/index.rst
omni.kit.primitive.mesh: omni.kit.mesh_generator ################################################# Python Extension Mesh Generator
132
reStructuredText
25.599995
49
0.515152
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/animation.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__ = ['AnimationEventStream'] import carb import omni.kit.app import traceback from typing import Any, Callable class AnimationEventStream: __g_instance = None @staticmethod def get_instance(): if AnimationEventStream.__g_instance is None: AnimationEventStream.__g_instance = [AnimationEventStream(), 1] else: AnimationEventStream.__g_instance[1] = AnimationEventStream.__g_instance[1] + 1 return AnimationEventStream.__g_instance[0] def __init__(self): self.__event_sub = None self.__callbacks = {} def __del__(self): self.destroy() def destroy(self): if AnimationEventStream.__g_instance and AnimationEventStream.__g_instance[0] == self: AnimationEventStream.__g_instance[1] = AnimationEventStream.__g_instance[1] - 1 if AnimationEventStream.__g_instance[1] > 0: return AnimationEventStream.__g_instance = None self.__event_sub = None self.__callbacks = {} def __on_event(self, e: carb.events.IEvent): dt = e.payload['dt'] for _, callbacks in self.__callbacks.items(): for cb_fn in callbacks: try: cb_fn(dt) except Exception: carb.log_error(traceback.format_exc()) def __init(self): if self.__event_sub: return self.__event_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop( self.__on_event, name="omni.kit.manipulator.camera.AnimationEventStream", order=omni.kit.app.UPDATE_ORDER_PYTHON_ASYNC_FUTURE_END_UPDATE ) def add_animation(self, animation_fn: Callable, key: Any, remove_others: bool = True): if remove_others: self.__callbacks[key] = [animation_fn] else: prev_fns = self.__callbacks.get(key) or [] if prev_fns: prev_fns.append(animation_fn) else: self.__callbacks[key] = [animation_fn] self.__init() def remove_animation(self, key: Any, animation_fn: Callable = None): if animation_fn: prev_fns = self.__callbacks.get(key) if prev_fns: try: prev_fns.remove(animation_fn) except ValueError: pass else: prev_fns = None if not prev_fns: try: del self.__callbacks[key] except KeyError: pass if not self.__callbacks: self.__event_sub = None
3,114
Python
31.447916
103
0.582531
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/viewport_camera_manipulator.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. # from .model import CameraManipulatorModel, _flatten_matrix, _optional_bool, _optional_int from .usd_camera_manipulator import ( UsdCameraManipulator, KIT_COI_ATTRIBUTE, KIT_LOOKTHROUGH_ATTRIBUTE, KIT_CAMERA_LOCK_ATTRIBUTE, _compute_local_transform ) from omni.ui import scene as sc from pxr import Usd, UsdGeom, Sdf, Gf import carb import math __all__ = ['ViewportCameraManipulator'] # More advanced implementation for a Viewport that can use picked objects and -look through- arbitrary scene items # def _check_for_camera_forwarding(imageable: UsdGeom.Imageable): # Look for the relationship setup via LookAtCommand prim = imageable.GetPrim() look_through = prim.GetRelationship(KIT_LOOKTHROUGH_ATTRIBUTE).GetForwardedTargets() if look_through: stage = prim.GetStage() # Loop over all targets (should really be only one) and see if we can get a valid UsdGeom.Imageable for target in look_through: target_prim = stage.GetPrimAtPath(target) if not target_prim: continue target_imageable = UsdGeom.Imageable(target_prim) if target_imageable: return target_imageable carb.log_warn(f'{prim.GetPath()} was set up for look-thorugh, but no valid prim was found for targets: {look_through}') return imageable def _setup_center_of_interest(model: sc.AbstractManipulatorModel, prim: Usd.Prim, time: Usd.TimeCode, object_centric: int = 0, viewport_api=None, mouse=None): def get_center_of_interest(): coi_attr = prim.GetAttribute(KIT_COI_ATTRIBUTE) if not coi_attr or not coi_attr.IsAuthored(): # Use UsdGeomCamera.focusDistance is present distance = 0 fcs_dist = prim.GetAttribute('focusDistance') if fcs_dist and fcs_dist.IsAuthored(): distance = fcs_dist.Get(time) # distance 0 is invalid, so create the atribute based on length from origin if not fcs_dist or distance == 0: origin = Gf.Matrix4d(*model.get_as_floats('initial_transform')).Transform((0, 0, 0)) distance = origin.GetLength() coi_attr = prim.CreateAttribute(KIT_COI_ATTRIBUTE, Sdf.ValueTypeNames.Vector3d, True, Sdf.VariabilityUniform) coi_attr.Set(Gf.Vec3d(0, 0, -distance)) # Make sure COI isn't ridiculously low coi_val = coi_attr.Get() length = coi_val.GetLength() if length < 0.000001 or not math.isfinite(length): coi_val = Gf.Vec3d(0, 0, -100) return coi_val def query_completed(path, pos, *args): # Reset center-of-interest if there's an obect and world-space position if path and pos: # Convert carb value to Gf.Vec3d pos = Gf.Vec3d(pos.x, pos.y, pos.z) # Object centric 1 will use the object-center, so replace pos with the UsdGeom.Imageable's (0, 0, 0) coord if object_centric == 1: picked_prim = prim.GetStage().GetPrimAtPath(path) imageable = UsdGeom.Imageable(picked_prim) if picked_prim else None if imageable: pos = imageable.ComputeLocalToWorldTransform(time).Transform(Gf.Vec3d(0, 0, 0)) if math.isfinite(pos[0]) and math.isfinite(pos[1]) and math.isfinite(pos[2]): inv_xform = Gf.Matrix4d(*model.get_as_floats('transform')).GetInverse() coi = inv_xform.Transform(pos) model.set_floats('center_of_interest_picked', [pos[0], pos[1], pos[2]]) # Also need to trigger a recomputation of ndc_speed based on our new center of interest coi_item = model.get_item('center_of_interest') model.set_floats(coi_item, [coi[0], coi[1], coi[2]]) model._item_changed(coi_item) # Re-enable all movement that we previouly disabled model.set_ints('disable_pan', [disable_pan]) model.set_ints('disable_tumble', [disable_tumble]) model.set_ints('disable_look', [disable_look]) model.set_ints('disable_zoom', [disable_zoom]) coi = get_center_of_interest() model.set_floats('center_of_interest', [coi[0], coi[1], coi[2]]) if object_centric != 0: # Map the NDC co-ordinates to a viewport's texture-space mouse, viewport_api = viewport_api.map_ndc_to_texture_pixel(mouse) if (mouse is None) or (viewport_api is None): object_centric = 0 if object_centric == 0: model.set_floats('center_of_interest_picked', []) return # Block all movement until the query completes disable_pan = _optional_bool(model, 'disable_pan') disable_tumble = _optional_bool(model, 'disable_tumble') disable_look = _optional_bool(model, 'disable_look') disable_zoom = _optional_bool(model, 'disable_zoom') model.set_ints('disable_pan', [1]) model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) model.set_ints('disable_zoom', [1]) # Start the query viewport_api.request_query(mouse, query_completed) class ViewportCameraManipulator(UsdCameraManipulator): def __init__(self, viewport_api, bindings: dict = None, *args, **kwargs): super().__init__(bindings, viewport_api.usd_context_name) self.__viewport_api = viewport_api # def view_changed(*args): # return # from .gesturebase import set_frame_delivered # set_frame_delivered(True) # self.__vc_change = viewport_api.subscribe_to_frame_change(view_changed) def _on_began(self, model: CameraManipulatorModel, mouse): # We need a viewport and a stage to start. If either are missing disable any further processing. viewport_api = self.__viewport_api stage = viewport_api.stage if viewport_api else None settings = carb.settings.get_settings() # Store the viewport_id in the model for use later if necessary model.set_ints('viewport_id', [viewport_api.id if viewport_api else 0]) if not stage: # TODO: Could we forward this to adjust the viewport_api->omni.scene.ui ? model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) model.set_ints('disable_pan', [1]) model.set_ints('disable_zoom', [1]) model.set_ints('disable_fly', [1]) return cam_path = viewport_api.camera_path if hasattr(model, '_set_animation_key'): model._set_animation_key(cam_path) time = viewport_api.time cam_prim = stage.GetPrimAtPath(cam_path) cam_imageable = UsdGeom.Imageable(cam_prim) camera = UsdGeom.Camera(cam_prim) if cam_imageable else None if not cam_imageable or not cam_imageable.GetPrim().IsValid(): raise RuntimeError('ViewportCameraManipulator with an invalid UsdGeom.Imageable or Usd.Prim') # Push the viewport's projection into the model projection = _flatten_matrix(viewport_api.projection) model.set_floats('projection', projection) # Check if we should actaully keep camera at identity and forward our movements to another object target_imageable = _check_for_camera_forwarding(cam_imageable) local_xform, parent_xform = _compute_local_transform(target_imageable, time) model.set_floats('initial_transform', _flatten_matrix(local_xform)) model.set_floats('transform', _flatten_matrix(local_xform)) # Setup the model if the camera is orthographic (where for Usd we must edit apertures) # We do this before center-of-interest query to get disabled-state pushed into the model if camera: orthographic = int(camera.GetProjectionAttr().Get(time) == 'orthographic') if orthographic: model.set_floats('initial_aperture', [camera.GetHorizontalApertureAttr().Get(time), camera.GetVerticalApertureAttr().Get(time)]) else: orthographic = int(projection[15] == 1 if projection else False) model.set_floats('initial_aperture', []) up_axis = UsdGeom.GetStageUpAxis(stage) if up_axis == UsdGeom.Tokens.x: up_axis = Gf.Vec3d(1, 0, 0) elif up_axis == UsdGeom.Tokens.y: up_axis = Gf.Vec3d(0, 1, 0) elif up_axis == UsdGeom.Tokens.z: up_axis = Gf.Vec3d(0, 0, 1) if not bool(settings.get("exts/omni.kit.manipulator.camera/forceStageUp")): up_axis = parent_xform.TransformDir(up_axis).GetNormalized() model.set_floats('up_axis', [up_axis[0], up_axis[1], up_axis[2]]) # Disable undo for implict cameras. This might be better handled with custom meta-data / attribute long term disable_undo = cam_path.pathString in ['/OmniverseKit_Persp', '/OmniverseKit_Front', '/OmniverseKit_Right', '/OmniverseKit_Top'] model.set_ints('disable_undo', [int(disable_undo)]) # Test whether this camera is locked cam_lock = cam_prim.GetAttribute(KIT_CAMERA_LOCK_ATTRIBUTE) if cam_lock and cam_lock.Get(): model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) model.set_ints('disable_pan', [1]) model.set_ints('disable_zoom', [1]) model.set_ints('disable_fly', [1]) else: model.set_ints('orthographic', [orthographic]) model.set_ints('disable_tumble', [orthographic]) model.set_ints('disable_look', [orthographic]) model.set_ints('disable_pan', [0]) model.set_ints('disable_zoom', [0]) model.set_ints('disable_fly', [0]) # Extract the camera's center of interest, from a property or world-space query # model.set_ints('object_centric_movement', [1]) object_centric = settings.get('/exts/omni.kit.manipulator.camera/objectCentric/type') or 0 object_centric = _optional_int(self.model, 'object_centric_movement', object_centric) _setup_center_of_interest(model, target_imageable.GetPrim(), time, object_centric, viewport_api, mouse) # Setup the model for command execution on key-framed data had_transform_at_key = False if not time.IsDefault(): xformable = UsdGeom.Xformable(target_imageable) if xformable: for xformOp in xformable.GetOrderedXformOps(): had_transform_at_key = time in xformOp.GetTimeSamples() if had_transform_at_key: break model.set_ints('had_transform_at_key', [had_transform_at_key]) # Set the pan/zoom speed equivalent to the world space travel of the mouse model.set_floats('world_speed', [1, 1, 1]) # Make a full drag across the viewport equal to a 180 tumble uv_space = viewport_api.map_ndc_to_texture((1, 1))[0] model.set_floats('rotation_speed', [((v * 2.0) - 1.0) for v in uv_space] + [1]) # Tell the USD manipulator the context and prim to operate on self._set_context(viewport_api.usd_context_name, target_imageable.GetPath()) def destroy(self): self.__vc_change = None self.__viewport_api = None super().destroy() import omni.kit.app import time class ZoomEvents: __instances = set() @staticmethod def get_instance(viewport_api): instance = None for inst in ZoomEvents.__instances: if inst.__viewport_api == viewport_api: instance = inst break if instance is None: instance = ZoomEvents(viewport_api) ZoomEvents.__instances.add(instance) else: instance.__mark_time() return instance def __init__(self, viewport_api): self.__viewport_api = viewport_api self.__mouse = [0, 0] self.__manipulator = ViewportCameraManipulator(viewport_api, bindings={'ZoomGesture': 'LeftButton'}) self.__manipulator.on_build() self.__zoom_gesture = self.__manipulator._screen.gestures[0] self.__zoom_gesture._disable_flight() self.__zoom_gesture.on_began(self.__mouse) # 1030 if hasattr(omni.kit.app, 'UPDATE_ORDER_PYTHON_ASYNC_FUTURE_END_UPDATE'): update_order = omni.kit.app.UPDATE_ORDER_PYTHON_ASYNC_FUTURE_END_UPDATE else: update_order = 50 self.__event_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop( self.__on_event, name="omni.kit.manipulator.camera.ZoomEvents", order=update_order ) def update(self, x, y): self.__mark_time() coi = Gf.Vec3d(*self.__manipulator.model.get_as_floats('center_of_interest')) scale = math.log10(max(10, coi.GetLength())) / 40 self.__mouse = (self.__mouse[0] + x * scale, self.__mouse[1] + y * scale) self.__zoom_gesture.on_changed(self.__mouse) self.__mark_time() def __mark_time(self): self.__last_time = time.time() def __time_since_last(self): return time.time() - self.__last_time def __on_event(self, e: carb.events.IEvent): delta = self.__time_since_last() if delta > 0.1: self.destroy() def destroy(self): self.__event_sub = None self.__zoom_gesture.on_ended() self.__manipulator.destroy() try: ZoomEvents.__instances.remove(self) except KeyError: pass # Helper function to do single a zoom-operation, from a scroll-wheel for example def _zoom_operation(x, y, viewport_api): if not viewport_api: return None instance = ZoomEvents.get_instance(viewport_api) instance.update(x, y) return True
14,470
Python
43.118902
136
0.622391
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/__init__.py
# Expose these for easier import via from omni.kit.manipulator.camera import XXX from .manipulator import SceneViewCameraManipulator, CameraManipulatorBase, adjust_center_of_interest from .usd_camera_manipulator import UsdCameraManipulator from .viewport_camera_manipulator import ViewportCameraManipulator
308
Python
50.499992
101
0.863636
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/flight_mode.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__ = ['FlightModeKeyboard', 'get_keyboard_input'] from .model import CameraManipulatorModel, _accumulate_values, _optional_floats from omni.ui import scene as sc import omni.appwindow from pxr import Gf import carb import carb.input class FlightModeValues: def __init__(self): self.__xyz_values = ( [0, 0, 0], [0, 0, 0], [0, 0, 0], ) def update(self, i0, i1, value) -> bool: self.__xyz_values[i0][i1] = value total = 0 for values in self.__xyz_values: values[2] = values[1] - values[0] total += values[2] != 0 return total != 0 @property def value(self): return ( self.__xyz_values[0][2], self.__xyz_values[1][2], self.__xyz_values[2][2] ) class FlightModeKeyboard: __g_char_map = None @staticmethod def get_char_map(): if not FlightModeKeyboard.__g_char_map: key_char_map = { 'w': (2, 0), 's': (2, 1), 'a': (0, 0), 'd': (0, 1), 'q': (1, 0), 'e': (1, 1), } carb_key_map = {eval(f'carb.input.KeyboardInput.{ascii_val.upper()}'): index for ascii_val, index in key_char_map.items()} FlightModeKeyboard.__g_char_map = carb_key_map for k, v in FlightModeKeyboard.__g_char_map.items(): yield k, v def __init__(self): self.__input = None self.__model = None self.__stop_events = False self.__keyboard_sub = None self.__initial_speed = None self.__current_adjusted_speed = 1 def init(self, model, iinput, mouse, mouse_button, app_window) -> None: self.__model = model if self.__input is None: self.__input = iinput self.__keyboard = app_window.get_keyboard() self.__keyboard_sub = iinput.subscribe_to_keyboard_events(self.__keyboard, self.__on_key) self.__mouse = mouse # XXX: This isn't working # self.__mouse_sub = iinput.subscribe_to_mouse_events(mouse, self.__on_mouse) # So just query the state on key-down self.__mouse_button = mouse_button self.__key_index = {k: v for k, v in FlightModeKeyboard.get_char_map()} self.__values = FlightModeValues() # Setup for modifier keys adjusting speed self.__settings = carb.settings.get_settings() # Shift or Control can modify flight speed, get the current state self.__setup_speed_modifiers() # Need to update all input key states on start for key, index in self.__key_index.items(): # Read the key and update the value. Update has to occur whether key is down or not as numeric field # might have text focus; causing carbonite not to deliver __on_key messages key_val = self.__input.get_keyboard_value(self.__keyboard, key) self.__values.update(*index, 1 if key_val else 0) # Record whether a previous invocation had started external events prev_stop = self.__stop_events # Test if any interesting key-pair result in a value key_down = any(self.__values.value) # If a key is no longer down, it may have not gotten to __on_key subscription if a numeric entry id focused # In that case there is no more key down so kill any external trigger if prev_stop and not key_down: prev_stop = False self.__model._stop_external_events() self.__stop_events = key_down or prev_stop self.__model.set_floats('fly', self.__values.value) if self.__stop_events: self.__model._start_external_events(True) def _cancel(self) -> bool: return self.__input.get_mouse_value(self.__mouse, self.__mouse_button) == 0 if self.__input else True @property def active(self) -> bool: """Returns if Flight mode is active or not""" return bool(self.__stop_events) def __adjust_speed_modifiers(self, cur_speed_mod: float, prev_speed_mod: float): # Get the current state from initial_speed = self.__settings.get('/persistent/app/viewport/camMoveVelocity') or 1 # Undo any previos speed modification based on key state if prev_speed_mod and prev_speed_mod != 1: initial_speed /= prev_speed_mod # Store the unadjusted values for restoration later (camMoveVelocity may change underneath modifiers) self.__initial_speed = initial_speed # Set the new speed if it is different cur_speed = initial_speed * cur_speed_mod self.__settings.set('/persistent/app/viewport/camMoveVelocity', cur_speed) def __setup_speed_modifiers(self): # Default to legacy value of modifying speed by doubling / halving self.__speed_modifier_amount = self.__settings.get('/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount') if not self.__speed_modifier_amount: return # Store the current_adjusted_speed as inital_speed prev_speed_mod = self.__current_adjusted_speed cur_speed_mod = prev_speed_mod # Scan the input keys that modify speed and adjust current_adjusted_speed if self.__input.get_keyboard_value(self.__keyboard, carb.input.KeyboardInput.LEFT_SHIFT): cur_speed_mod *= self.__speed_modifier_amount if self.__input.get_keyboard_value(self.__keyboard, carb.input.KeyboardInput.LEFT_CONTROL): if self.__speed_modifier_amount != 0: cur_speed_mod /= self.__speed_modifier_amount # Store new speed into proper place if prev_speed_mod != cur_speed_mod: self.__current_adjusted_speed = cur_speed_mod self.__adjust_speed_modifiers(cur_speed_mod, prev_speed_mod) def __process_speed_modifier(self, key: carb.input.KeyboardEventType, is_down: bool): if not self.__speed_modifier_amount: return def speed_adjustment(increase: bool): return self.__speed_modifier_amount if increase else (1 / self.__speed_modifier_amount) prev_speed_mod = self.__current_adjusted_speed cur_speed_mod = prev_speed_mod if key == carb.input.KeyboardInput.LEFT_SHIFT: cur_speed_mod *= speed_adjustment(is_down) if key == carb.input.KeyboardInput.LEFT_CONTROL: cur_speed_mod *= speed_adjustment(not is_down) if prev_speed_mod != cur_speed_mod: self.__current_adjusted_speed = cur_speed_mod self.__adjust_speed_modifiers(cur_speed_mod, prev_speed_mod) return True return False def __on_key(self, e) -> bool: index, value, speed_changed = None, None, False event_type = e.type KeyboardEventType = carb.input.KeyboardEventType if event_type == KeyboardEventType.KEY_PRESS or event_type == KeyboardEventType.KEY_REPEAT: index, value = self.__key_index.get(e.input), 1 if event_type == KeyboardEventType.KEY_PRESS: speed_changed = self.__process_speed_modifier(e.input, True) elif event_type == KeyboardEventType.KEY_RELEASE: index, value = self.__key_index.get(e.input), 0 speed_changed = self.__process_speed_modifier(e.input, False) # If not a navigation key, pass it on to another handler (unless it was a speed-moficiation key). if not index: return not speed_changed canceled = self._cancel() if canceled: value = 0 has_data = self.__values.update(*index, value) if hasattr(self.__model, '_start_external_events'): if has_data: self.__stop_events = True self.__model._start_external_events(True) elif self.__stop_events: self.__stop_events = False self.__model._stop_external_events(True) self.__model.set_floats('fly', self.__values.value) # self.__model._item_changed(None) if canceled: self.destroy() return False def end(self): self.destroy() return None def __del__(self): self.destroy() def destroy(self) -> None: if self.__initial_speed is not None: self.__settings.set('/persistent/app/viewport/camMoveVelocity', self.__initial_speed) self.__initial_speed = None self.__current_adjusted_speed = 1 if self.__model: self.__model.set_floats('fly', None) if self.__stop_events: self.__model._stop_external_events() if self.__keyboard_sub: self.__input.unsubscribe_to_keyboard_events(self.__keyboard, self.__keyboard_sub) self.__keyboard_sub = None self.__keyboard = None # if self.__mouse_sub: # self.__input.unsubscribe_to_mouse_events(self.__mouse, self.__mouse_sub) # self.__mouse_sub = None self.__mouse = None self.__input = None self.__values = None self.__key_index = None def get_keyboard_input(model, walk_through: FlightModeKeyboard = None, end_with_mouse_ended: bool = False, mouse_button=carb.input.MouseInput.RIGHT_BUTTON): iinput = carb.input.acquire_input_interface() app_window = omni.appwindow.get_default_app_window() mouse = app_window.get_mouse() mouse_value = iinput.get_mouse_value(mouse, mouse_button) if mouse_value: if walk_through is None: walk_through = FlightModeKeyboard() walk_through.init(model, iinput, mouse, mouse_button, app_window) elif walk_through and end_with_mouse_ended: walk_through.destroy() walk_through = None return walk_through
10,350
Python
39.913043
156
0.604444
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/math.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__ = ['TransformAccumulator'] from pxr import Gf class TransformAccumulator: def __init__(self, initial_xform: Gf.Matrix4d): self.__inverse_xform = initial_xform.GetInverse() if initial_xform else None def get_rotation_axis(self, up_axis: Gf.Vec3d): if up_axis: return self.__inverse_xform.TransformDir(up_axis) else: return self.__inverse_xform.TransformDir(Gf.Vec3d(0, 1, 0)) def get_translation(self, amount: Gf.Vec3d): return Gf.Matrix4d().SetTranslate(amount) def get_tumble(self, degrees: Gf.Vec3d, center_of_interest: Gf.Vec3d, up_axis: Gf.Vec3d): # Rotate around proper scene axis rotate_axis = self.get_rotation_axis(up_axis) # Move to center_of_interest, rotate and move back # No need for identity, all SetXXX methods will do that for us translate = Gf.Matrix4d().SetTranslate(-center_of_interest) # X-Y in ui/mouse are swapped so x-move is rotate around Y, and Y-move is rotate around X rotate_x = Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), degrees[1])) rotate_y = Gf.Matrix4d().SetRotate(Gf.Rotation(rotate_axis, degrees[0])) return translate * rotate_x * rotate_y * translate.GetInverse() def get_look(self, degrees: Gf.Vec3d, up_axis: Gf.Vec3d): # Rotate around proper scene axis rotate_axis = self.get_rotation_axis(up_axis) # X-Y in ui/mouse are swapped so x-move is rotate around Y, and Y-move is rotate around X rotate_x = Gf.Matrix4d().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), degrees[1])) rotate_y = Gf.Matrix4d().SetRotate(Gf.Rotation(rotate_axis, degrees[0])) return rotate_x * rotate_y
2,166
Python
44.145832
97
0.686057
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/usd_camera_manipulator.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. # from .manipulator import CameraManipulatorBase, adjust_center_of_interest from .model import _optional_bool, _flatten_matrix from omni.kit import commands, undo import omni.usd from pxr import Usd, UsdGeom, Sdf, Tf, Gf import carb.profiler import carb.settings import math from typing import List __all__ = ['UsdCameraManipulator'] KIT_COI_ATTRIBUTE = 'omni:kit:centerOfInterest' KIT_LOOKTHROUGH_ATTRIBUTE = 'omni:kit:viewport:lookThrough:target' KIT_CAMERA_LOCK_ATTRIBUTE = 'omni:kit:cameraLock' def _get_context_stage(usd_context_name: str): return omni.usd.get_context(usd_context_name).get_stage() def _compute_local_transform(imageable: UsdGeom.Imageable, time: Usd.TimeCode): # xformable = UsdGeom.Xformable(imageable) # if xformable: # return xformable.GetLocalTransformation(time) world_xform = imageable.ComputeLocalToWorldTransform(time) parent_xform = imageable.ComputeParentToWorldTransform(time) parent_ixform = parent_xform.GetInverse() return (world_xform * parent_ixform), parent_ixform class SRTDecomposer: def __init__(self, prim: Usd.Prim, time: Usd.TimeCode = None): if time is None: time = Usd.TimeCode.Default() xform_srt = omni.usd.get_local_transform_SRT(prim, time) xform_srt = (Gf.Vec3d(xform_srt[0]), Gf.Vec3d(xform_srt[1]), Gf.Vec3i(xform_srt[2]), Gf.Vec3d(xform_srt[3])) self.__start_scale, self.__start_rotation_euler, self.__start_rotation_order, self.__start_translation = xform_srt self.__current_scale, self.__current_rotation_euler, self.__current_rotation_order, self.__current_translation = xform_srt @staticmethod def __repeat(t: float, length: float) -> float: return t - (math.floor(t / length) * length) @staticmethod def __generate_compatible_euler_angles(euler: Gf.Vec3d, rotation_order: Gf.Vec3i) -> List[Gf.Vec3d]: equal_eulers = [euler] mid_order = rotation_order[1] equal = Gf.Vec3d() for i in range(3): if i == mid_order: equal[i] = 180 - euler[i] else: equal[i] = euler[i] + 180 equal_eulers.append(equal) for i in range(3): equal[i] -= 360 equal_eulers.append(equal) return equal_eulers @staticmethod def __find_best_euler_angles(old_rot_vec: Gf.Vec3d, new_rot_vec: Gf.Vec3d, rotation_order: Gf.Vec3i) -> Gf.Vec3d: equal_eulers = SRTDecomposer.__generate_compatible_euler_angles(new_rot_vec, rotation_order) nearest_euler = None for euler in equal_eulers: for i in range(3): euler[i] = SRTDecomposer.__repeat(euler[i] - old_rot_vec[i] + 180.0, 360.0) + old_rot_vec[i] - 180.0 if nearest_euler is None: nearest_euler = euler else: distance_1 = (nearest_euler - old_rot_vec).GetLength() distance_2 = (euler - old_rot_vec).GetLength() if distance_2 < distance_1: nearest_euler = euler return nearest_euler def update(self, xform: Gf.Matrix4d): # Extract new translation self.__current_translation = xform.ExtractTranslation() # Extract new euler rotation ro = self.__start_rotation_order old_s_mtx = Gf.Matrix4d().SetScale(self.__start_scale) old_t_mtx = Gf.Matrix4d().SetTranslate(self.__start_translation) rot_new = (old_s_mtx.GetInverse() * xform * old_t_mtx.GetInverse()).ExtractRotation() axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]]) index_order = Gf.Vec3i() for i in range(3): index_order[ro[i]] = 2 - i new_rot_vec = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]]) new_rot_vec = self.__find_best_euler_angles(self.__start_rotation_euler, new_rot_vec, self.__start_rotation_order) self.__current_rotation_euler = new_rot_vec # Because this is a camera manipulation, we purposefully ignore scale and rotation order changes # They remain constant across the interaction. return self @property def translation(self): return self.__current_translation @property def rotation(self): return self.__current_rotation_euler @property def start_translation(self): return self.__start_translation @property def start_rotation(self): self.__start_rotation_euler class ExternalUsdCameraChange(): def __init__(self, time: Usd.TimeCode): self.__tf_listener = None self.__usd_context_name, self.__prim_path = None, None self.__updates_paused = False self.__kill_external_animation = None self.__time = time def __del__(self): self.destroy() def update(self, model, usd_context_name: str, prim_path: Sdf.Path): self.__kill_external_animation = getattr(model, '_kill_external_animation', None) if self.__kill_external_animation is None: return self.__prim_path = prim_path if usd_context_name != self.__usd_context_name: self.__usd_context_name = usd_context_name if self.__tf_listener: self.__tf_listener.Revoke() self.__tf_listener = None if not self.__tf_listener: try: stage = _get_context_stage(self.__usd_context_name) if stage: self.__tf_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.__object_changed, stage) except ImportError: pass def destroy(self): if self.__tf_listener: self.__tf_listener.Revoke() self.__tf_listener = None self.__usd_context_name, self.__prim_path = None, None self.__kill_external_animation = None @carb.profiler.profile def __object_changed(self, notice, sender): if self.__updates_paused: return if not sender or sender != _get_context_stage(self.__usd_context_name): return for p in notice.GetChangedInfoOnlyPaths(): if (p.IsPropertyPath() and p.GetPrimPath() == self.__prim_path and UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name)): xformable = UsdGeom.Xformable(sender.GetPrimAtPath(self.__prim_path)) xform = _flatten_matrix(xformable.GetLocalTransformation(self.__time)) if xformable else None self.__kill_external_animation(True, xform) break def pause_tracking(self): self.__updates_paused = True def start_tracking(self): self.__updates_paused = False # Base Usd implementation that will set model back to Usd data via kit-commands class UsdCameraManipulator(CameraManipulatorBase): def __init__(self, bindings: dict = None, usd_context_name: str = '', prim_path: Sdf.Path = None, *args, **kwargs): self.__usd_context_name, self.__prim_path = None, None self.__external_change_tracker = None super().__init__(bindings, *args, **kwargs) self._set_context(usd_context_name, prim_path) def _set_context(self, usd_context_name: str, prim_path: Sdf.Path): self.__usd_context_name = usd_context_name self.__prim_path = prim_path self.__srt_decompose = None if prim_path and carb.settings.get_settings().get('/persistent/app/camera/controllerUseSRT'): stage = _get_context_stage(self.__usd_context_name) if stage: prim = stage.GetPrimAtPath(prim_path) if prim: model = self.model time = model.get_as_floats('time') if model else None time = Usd.TimeCode(time[0]) if time else Usd.TimeCode.Default() self.__srt_decompose = SRTDecomposer(prim) def _on_began(self, model, *args, **kwargs): super()._on_began(model, *args, **kwargs) stage = _get_context_stage(self.__usd_context_name) if not stage: # TODO: Could we forward this to adjust the viewport_api->omni.scene.ui ? model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) model.set_ints('disable_pan', [1]) model.set_ints('disable_zoom', [1]) model.set_ints('disable_fly', [1]) return cam_prim = stage.GetPrimAtPath(self.__prim_path) cam_imageable = UsdGeom.Imageable(cam_prim) if bool(cam_prim) else None if not cam_imageable or not cam_imageable.GetPrim().IsValid(): raise RuntimeError('ViewportCameraManipulator with an invalid UsdGeom.Imageable or Usd.Prim') # Check if we should actaully keep camera at identity and forward our movements to another object local_xform, parent_xform = _compute_local_transform(cam_imageable, Usd.TimeCode.Default()) model.set_floats('initial_transform', _flatten_matrix(local_xform)) model.set_floats('transform', _flatten_matrix(local_xform)) up_axis = UsdGeom.GetStageUpAxis(stage) if up_axis == UsdGeom.Tokens.x: up_axis = Gf.Vec3d(1, 0, 0) elif up_axis == UsdGeom.Tokens.y: up_axis = Gf.Vec3d(0, 1, 0) elif up_axis == UsdGeom.Tokens.z: up_axis = Gf.Vec3d(0, 0, 1) if not bool(carb.settings.get_settings().get("exts/omni.kit.manipulator.camera/forceStageUp")): up_axis = parent_xform.TransformDir(up_axis).GetNormalized() model.set_floats('up_axis', [up_axis[0], up_axis[1], up_axis[2]]) @carb.profiler.profile def __vp1_cooperation(self, prim_path, time, usd_context_name: str, center_of_interest_end): try: from omni.kit import viewport_legacy vp1_iface = viewport_legacy.get_viewport_interface() final_transform, coi_world, pos_world, cam_path = None, None, None, None for vp1_handle in vp1_iface.get_instance_list(): vp1_window = vp1_iface.get_viewport_window(vp1_handle) if not vp1_window or (vp1_window.get_usd_context_name() != usd_context_name): continue if not final_transform: # Save the path's string represnetation cam_path = prim_path.pathString # We need to calculate world-space transform for VP-1, important for nested camera's # TODO: UsdBBoxCache.ComputeWorldBound in compute_path_world_transform doesn't seem to work for non-geometry: # final_transform = omni.usd.get_context(usd_context_name).compute_path_world_transform(cam_path) # final_transform = Gf.Matrix4d(*final_transform) final_transform = UsdGeom.Imageable(prim_path).ComputeLocalToWorldTransform(time) # center_of_interest_end is adjusted and returned for VP-2 center_of_interest_end = Gf.Vec3d(0, 0, -center_of_interest_end.GetLength()) # Pass world center-of-interest to VP-1 set_camera_target coi_world = final_transform.Transform(center_of_interest_end) # Pass world position to VP-1 set_camera_position pos_world = final_transform.Transform(Gf.Vec3d(0, 0, 0)) # False for first call to set target only, True for second to trigger radius re-calculation # This isn't particuarly efficient; but 'has to be' for now due to some Viewport-1 internals vp1_window.set_camera_target(cam_path, coi_world[0], coi_world[1], coi_world[2], False) vp1_window.set_camera_position(cam_path, pos_world[0], pos_world[1], pos_world[2], True) except Exception: pass return center_of_interest_end @carb.profiler.profile def on_model_updated(self, item): # Handle case of inertia being applied though a new stage-open usd_context_name = self.__usd_context_name if usd_context_name is None or _get_context_stage(usd_context_name) is None: return model = self.model prim_path = self.__prim_path time = model.get_as_floats('time') time = Usd.TimeCode(time[0]) if time else Usd.TimeCode.Default() undoable = False def run_command(cmd_name, **kwargs): carb.profiler.begin(1, cmd_name) if undoable: commands.execute(cmd_name, **kwargs) else: commands.create(cmd_name, **kwargs).do() carb.profiler.end(1) try: if item == model.get_item('transform'): if self.__external_change_tracker: self.__external_change_tracker.update(model, usd_context_name, prim_path) self.__external_change_tracker.pause_tracking() # We are undoable on the final event if undo hasn't been disabled on the model undoable = _optional_bool(self.model, 'interaction_ended') and not _optional_bool(self.model, 'disable_undo') if undoable: undo.begin_group() final_transform = Gf.Matrix4d(*model.get_as_floats('transform')) initial_transform = model.get_as_floats('initial_transform') initial_transform = Gf.Matrix4d(*initial_transform) if initial_transform else initial_transform had_transform_at_key = _optional_bool(self.model, 'had_transform_at_key') if self.__srt_decompose: srt_deompose = self.__srt_decompose.update(final_transform) run_command( 'TransformPrimSRTCommand', path=prim_path, new_translation=srt_deompose.translation, new_rotation_euler=srt_deompose.rotation, # new_scale=srt_deompose.scale, # new_rotation_order=srt_deompose.rotation_order, old_translation=srt_deompose.start_translation, old_rotation_euler=srt_deompose.start_rotation, # old_rotation_order=srt_deompose.start_rotation_order, # old_scale=srt_deompose.start_scale, time_code=time, had_transform_at_key=had_transform_at_key, usd_context_name=usd_context_name ) else: run_command( 'TransformPrimCommand', path=prim_path, new_transform_matrix=final_transform, old_transform_matrix=initial_transform, time_code=time, had_transform_at_key=had_transform_at_key, usd_context_name=usd_context_name ) center_of_interest_start, center_of_interest_end = adjust_center_of_interest(model, initial_transform, final_transform) if center_of_interest_start and center_of_interest_end: # See if we need to adjust center-of-interest to cooperate with Viewport-1, which can only do a 1 dimensional version center_of_interest_end = self.__vp1_cooperation(prim_path, time, usd_context_name, center_of_interest_end) run_command( 'ChangePropertyCommand', prop_path=prim_path.AppendProperty(KIT_COI_ATTRIBUTE), value=center_of_interest_end, prev=center_of_interest_start, usd_context_name=usd_context_name ) elif item == model.get_item('current_aperture'): # We are undoable on the final event if undo hasn't been disabled on the model undoable = _optional_bool(self.model, 'interaction_ended') and not _optional_bool(self.model, 'disable_undo') if undoable: undo.begin_group() initial_aperture = model.get_as_floats('initial_aperture') current_aperture = model.get_as_floats('current_aperture') prop_names = ('horizontalAperture', 'verticalAperture') for initial_value, current_value, prop_name in zip(initial_aperture, current_aperture, prop_names): run_command( 'ChangePropertyCommand', prop_path=prim_path.AppendProperty(prop_name), value=current_value, prev=initial_value, timecode=time, usd_context_name=usd_context_name ) elif item == model.get_item('interaction_animating'): interaction_animating = model.get_as_ints(item) if interaction_animating and interaction_animating[0]: if not self.__external_change_tracker: self.__external_change_tracker = ExternalUsdCameraChange(time) self.__external_change_tracker.update(model, usd_context_name, prim_path) self.__external_change_tracker.pause_tracking() elif self.__external_change_tracker: self.__external_change_tracker.destroy() self.__external_change_tracker = None finally: if undoable: undo.end_group() if self.__external_change_tracker: self.__external_change_tracker.start_tracking()
18,397
Python
44.539604
137
0.594717
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/model.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__ = ['CameraManipulatorModel'] from omni.ui import scene as sc from pxr import Gf from typing import Any, Callable, List, Sequence, Union from .math import TransformAccumulator from .animation import AnimationEventStream import time import carb.profiler import carb.settings ALMOST_ZERO = 1.e-4 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]] def _optional_floats(model: sc.AbstractManipulatorModel, item: str, default_value: Sequence[float] = None): item = model.get_item(item) if item: values = model.get_as_floats(item) if values: return values return default_value def _optional_float(model: sc.AbstractManipulatorModel, item: str, default_value: float = 0): item = model.get_item(item) if item: values = model.get_as_floats(item) if values: return values[0] return default_value def _optional_int(model: sc.AbstractManipulatorModel, item: str, default_value: int = 0): item = model.get_item(item) if item: values = model.get_as_ints(item) if values: return values[0] return default_value def _optional_bool(model: sc.AbstractManipulatorModel, item: str, default_value: bool = False): return _optional_int(model, item, default_value) def _accumulate_values(model: sc.AbstractManipulatorModel, name: str, x: float, y: float, z: float): item = model.get_item(name) if item: values = model.get_as_floats(item) model.set_floats(item, [values[0] + x, values[1] + y, values[2] + z] if values else [x, y, z]) return item def _scalar_or_vector(value: Sequence[float]): acceleration_len = len(value) if acceleration_len == 1: return Gf.Vec3d(value[0], value[0], value[0]) if acceleration_len == 2: return Gf.Vec3d(value[0], value[1], 1) return Gf.Vec3d(value[0], value[1], value[2]) class ModelState: def __reduce_value(self, vec: Gf.Vec3d): if vec and (vec[0] == 0 and vec[1] == 0 and vec[2] == 0): return None return vec def __expand_value(self, vec: Gf.Vec3d, alpha: float): if vec: vec = tuple(v * alpha for v in vec) if vec[0] != 0 or vec[1] != 0 or vec[2] != 0: return vec return None def __init__(self, tumble: Gf.Vec3d = None, look: Gf.Vec3d = None, move: Gf.Vec3d = None, fly: Gf.Vec3d = None): self.__tumble = self.__reduce_value(tumble) self.__look = self.__reduce_value(look) self.__move = self.__reduce_value(move) self.__fly = self.__reduce_value(fly) def any_values(self): return self.__tumble or self.__look or self.__move or self.__fly def apply_alpha(self, alpha: float): return (self.__expand_value(self.__tumble, alpha), self.__expand_value(self.__look, alpha), self.__expand_value(self.__move, alpha), self.__expand_value(self.__fly, alpha)) @property def tumble(self): return self.__tumble @property def look(self): return self.__look @property def move(self): return self.__move @property def fly(self): return self.__fly class Velocity: def __init__(self, acceleration: Sequence[float], dampening: Sequence[float] = (10,), clamp_dt: float = 0.15): self.__velocity = Gf.Vec3d(0, 0, 0) self.__acceleration_rate = _scalar_or_vector(acceleration) self.__dampening = _scalar_or_vector(dampening) self.__clamp_dt = clamp_dt def apply(self, value: Gf.Vec3d, dt: float, alpha: float = 1): ### XXX: We're not locked to anything and event can come in spuriously ### So clamp the max delta-time to a value (if this is to high, it can introduces lag) if (dt > 0) and (dt > self.__clamp_dt): dt = self.__clamp_dt if value: acceleration = Gf.CompMult(value, self.__acceleration_rate) * alpha self.__velocity += acceleration * dt damp_factor = tuple(max(min(v * dt, 0.75), 0) for v in self.__dampening) self.__velocity += Gf.CompMult(-self.__velocity, Gf.Vec3d(*damp_factor)) if Gf.Dot(self.__velocity, self.__velocity) < ALMOST_ZERO: self.__velocity = Gf.Vec3d(0, 0, 0) return self.__velocity * dt @staticmethod def create(model: sc.AbstractManipulatorModel, mode: str, clamp_dt: float = 0.15): acceleration = _optional_floats(model, f'{mode}_acceleration') if acceleration is None: return None dampening = _optional_floats(model, f'{mode}_dampening') return Velocity(acceleration, dampening or (10, 10, 10), clamp_dt) class Decay: def __init__(self): pass def apply(self, value: Gf.Vec3d, dt: float, alpha: float = 1): return value * alpha if value else None class CameraManipulatorModel(sc.AbstractManipulatorModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__settings = carb.settings.get_settings() self.__items = { # 'view': (sc.AbstractManipulatorItem(), 16), 'projection': (sc.AbstractManipulatorItem(), 16), 'transform': (sc.AbstractManipulatorItem(), 16), 'orthographic': (sc.AbstractManipulatorItem(), 1), 'center_of_interest': (sc.AbstractManipulatorItem(), 3), # Accumulated movement 'move': (sc.AbstractManipulatorItem(), 3), 'tumble': (sc.AbstractManipulatorItem(), 3), 'look': (sc.AbstractManipulatorItem(), 3), 'fly': (sc.AbstractManipulatorItem(), 3), # Optional speed for world (pan, truck) and rotation (tumble, look) operation # Can be set individually for x, y, z or as a scalar 'world_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'move_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'rotation_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'tumble_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'look_speed': (sc.AbstractManipulatorItem(), (3, 1)), 'fly_speed': (sc.AbstractManipulatorItem(), (3, 1)), # Inertia enabled, and amoint of second to apply it for 'inertia_enabled': (sc.AbstractManipulatorItem(), 1), 'inertia_seconds': (sc.AbstractManipulatorItem(), 1), # Power of ineratia decay (for an ease-out) 0 and 1 are linear 'inertia_decay': (sc.AbstractManipulatorItem(), 1), # Acceleration and dampening values 'tumble_acceleration': (sc.AbstractManipulatorItem(), (3, 1)), 'look_acceleration': (sc.AbstractManipulatorItem(), (3, 1)), 'move_acceleration': (sc.AbstractManipulatorItem(), (3, 1)), 'fly_acceleration': (sc.AbstractManipulatorItem(), (3, 1)), 'tumble_dampening': (sc.AbstractManipulatorItem(), (3, 1)), 'look_dampening': (sc.AbstractManipulatorItem(), (3, 1)), 'move_dampening': (sc.AbstractManipulatorItem(), (3, 1)), 'fly_dampening': (sc.AbstractManipulatorItem(), (3, 1)), 'fly_mode_lock_view': (sc.AbstractManipulatorItem(), 1), # Decimal precision of rotation operations 'rotation_precision': (sc.AbstractManipulatorItem(), 1), # Mapping of units from input to world 'ndc_scale': (sc.AbstractManipulatorItem(), 3), # Optional int-as-bool items 'disable_pan': (sc.AbstractManipulatorItem(), 1), 'disable_tumble': (sc.AbstractManipulatorItem(), 1), 'disable_look': (sc.AbstractManipulatorItem(), 1), 'disable_zoom': (sc.AbstractManipulatorItem(), 1), 'disable_fly': (sc.AbstractManipulatorItem(), 1), 'disable_undo': (sc.AbstractManipulatorItem(), 1), 'object_centric_movement': (sc.AbstractManipulatorItem(), 1), 'viewport_id': (sc.AbstractManipulatorItem(), 1), # USD specific concepts 'up_axis': (sc.AbstractManipulatorItem(), 3), 'current_aperture': (sc.AbstractManipulatorItem(), 2), 'initial_aperture': (sc.AbstractManipulatorItem(), 2), 'had_transform_at_key': (sc.AbstractManipulatorItem(), 1), 'time': (sc.AbstractManipulatorItem(), 1), # Internal signal for final application of the changes, use disable_undo for user-control 'interaction_ended': (sc.AbstractManipulatorItem(), 1), # Signal that undo should be applied 'interaction_active': (sc.AbstractManipulatorItem(), 1), # Signal that a gesture is manipualting camera 'interaction_animating': (sc.AbstractManipulatorItem(), 1), # Signal that an animation is manipulating camera 'center_of_interest_start': (sc.AbstractManipulatorItem(), 3), 'center_of_interest_picked': (sc.AbstractManipulatorItem(), 3), 'adjust_center_of_interest': (sc.AbstractManipulatorItem(), 1), 'initial_transform': (sc.AbstractManipulatorItem(), 16), } self.__values = {item: [] for item, _ in self.__items.values()} self.__values[self.__items.get('look_speed')[0]] = [1, 0.5] self.__values[self.__items.get('fly_speed')[0]] = [1] self.__values[self.__items.get('inertia_seconds')[0]] = [0.5] self.__values[self.__items.get('inertia_enabled')[0]] = [0] # self.__values[self.__items.get('interaction_active')[0]] = [0] # self.__values[self.__items.get('interaction_animating')[0]] = [0] self.__settings_changed_subs = [] def read_inertia_setting(mode: str, setting_scale: float): global_speed_key = f'/persistent/exts/omni.kit.manipulator.camera/{mode}Speed' subscribe = self.__settings.subscribe_to_tree_change_events self.__settings_changed_subs.append( subscribe(global_speed_key, lambda *args, **kwargs: self.__speed_setting_changed(*args, **kwargs, mode=mode, setting_scale=setting_scale)), ) self.__speed_setting_changed(None, None, carb.settings.ChangeEventType.CHANGED, mode, setting_scale) accel = self.__settings.get(f'/exts/omni.kit.manipulator.camera/{mode}Acceleration') damp = self.__settings.get(f'/exts/omni.kit.manipulator.camera/{mode}Dampening') if accel is None or damp is None: if accel is None and damp is not None: pass elif damp is None and accel is not None: pass return self.__values[self.__items.get(f'{mode}_acceleration')[0]] = [accel] self.__values[self.__items.get(f'{mode}_dampening')[0]] = [damp] read_inertia_setting('fly', 1) read_inertia_setting('look', 180) read_inertia_setting('move', 1) read_inertia_setting('tumble', 360) self.__settings_changed_subs.append( self.__settings.subscribe_to_node_change_events('/persistent/exts/omni.kit.manipulator.camera/flyViewLock', self.__fly_mode_lock_view_changed) ) self.__fly_mode_lock_view_changed(None, carb.settings.ChangeEventType.CHANGED) self.__animation_key = id(self) self.__flight_inertia_active = False self.__last_applied = None # Faster access for key-values looked up during animation self.__move = self.__items.get('move')[0] self.__tumble = self.__items.get('tumble')[0] self.__look = self.__items.get('look')[0] self.__fly = self.__items.get('fly')[0] self.__transform = self.__items.get('transform')[0] self.__projection = self.__items.get('projection')[0] self.__center_of_interest = self.__items.get('center_of_interest')[0] self.__adjust_center_of_interest = self.__items.get('adjust_center_of_interest')[0] self.__inertia_enabled = self.__items.get('inertia_enabled')[0] self.__inertia_seconds = self.__items.get('inertia_seconds')[0] self.__tumble_velocity = None self.__look_velocity = None self.__move_velocity = None self.__fly_velocity = None self.__intertia_state = None self.__anim_stream = None self.__anim_stopped = 0 self.__mode = None def __speed_setting_changed(self, tree_item: carb.dictionary.Item, changed_item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType, mode: str, setting_scale: float = 1): if tree_item is None: speed = self.__settings.get(f'/persistent/exts/omni.kit.manipulator.camera/{mode}Speed') else: speed = tree_item.get_dict() if speed: if (not isinstance(speed, tuple)) and (not isinstance(speed, list)): speed = [speed] self.__values[self.__items.get(f'{mode}_speed')[0]] = [float(x) / setting_scale for x in speed] def __fly_mode_lock_view_changed(self, changed_item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): model_key = self.__items.get('fly_mode_lock_view')[0] setting_key = '/persistent/exts/omni.kit.manipulator.camera/flyViewLock' self.__values[model_key] = [self.__settings.get(setting_key)] def __del__(self): self.destroy() def destroy(self): self.__destroy_animation() if self.__settings and self.__settings_changed_subs: for subscription in self.__settings_changed_subs: self.__settings.unsubscribe_to_change_events(subscription) self.__settings_changed_subs = None self.__settings = None def __destroy_animation(self): if self.__anim_stream: self.__anim_stream.destroy() self.__anim_stream = None self.__mark_animating(0) def __validate_arguments(self, name: Union[str, sc.AbstractManipulatorItem], values: Sequence[Union[int, float]] = None) -> sc.AbstractManipulatorItem: if isinstance(name, sc.AbstractManipulatorItem): return name item, expected_len = self.__items.get(name, (None, None)) if item is None: raise KeyError(f"CameraManipulatorModel doesn't understand values of {name}") if values and (len(values) != expected_len): if (not isinstance(expected_len, tuple)) or (not len(values) in expected_len): raise ValueError(f"CameraManipulatorModel {name} takes {expected_len} values, got {len(values)}") return item def get_item(self, name: str) -> sc.AbstractManipulatorItem(): return self.__items.get(name, (None, None))[0] def set_ints(self, item: Union[str, sc.AbstractManipulatorItem], values: Sequence[int]): item = self.__validate_arguments(item, values) self.__values[item] = values def set_floats(self, item: Union[str, sc.AbstractManipulatorItem], values: Sequence[int]): item = self.__validate_arguments(item, values) self.__values[item] = values def get_as_ints(self, item: Union[str, sc.AbstractManipulatorItem]) -> List[int]: item = self.__validate_arguments(item) return self.__values[item] def get_as_floats(self, item: Union[str, sc.AbstractManipulatorItem]) -> List[float]: item = self.__validate_arguments(item) return self.__values[item] @carb.profiler.profile def _item_changed(self, item: Union[str, sc.AbstractManipulatorItem], delta_time: float = None, alpha: float = None): # item == None is the signal to push all model values into a final matrix at 'transform' if item is not None: if not isinstance(item, sc.AbstractManipulatorItem): item = self.__items.get(item) item = item[0] if item else None # Either of these adjust the pixel-to-world mapping if item == self.__center_of_interest or item == self.__projection: self.calculate_pixel_to_world(Gf.Vec3d(self.get_as_floats(self.__center_of_interest))) super()._item_changed(item) return if self.__anim_stream and delta_time is None: # If this is the end of an interaction (mouse up), return and let animation/inertia continue as is. if _optional_int(self, 'interaction_ended', 0) or (self.__intertia_state is None): return # If inertia is active, look values should be passed through; so as camera is drifting the look-rotation # is still applied. If there is no look applied, then inertia is killed for any other movement. look = self.get_as_floats(self.__look) if self.__flight_inertia_active else None if look: # Destroy the look-velocity correction; otherwise look wil lag as camera drifts through inertia self.__look_velocity = None else: self._kill_external_animation(False) return tumble, look, move, fly = None, None, None, None if item is None or item == self.__tumble: tumble = self.get_as_floats(self.__tumble) if tumble: tumble = Gf.Vec3d(*tumble) self.set_floats(self.__tumble, None) if item is None or item == self.__look: look = self.get_as_floats(self.__look) if look: look = Gf.Vec3d(*look) self.set_floats(self.__look, None) if item is None or item == self.__move: move = self.get_as_floats(self.__move) if move: move = Gf.Vec3d(*move) self.set_floats(self.__move, None) if item is None or item == self.__fly: fly = self.get_as_floats(self.__fly) if fly: fly = Gf.Vec3d(*fly) fly_speed = _optional_floats(self, 'fly_speed') if fly_speed: if len(fly_speed) == 1: fly_speed = Gf.Vec3d(fly_speed[0], fly_speed[0], fly_speed[0]) else: fly_speed = Gf.Vec3d(*fly_speed) # Flight speed is multiplied by 5 for VP-1 compatability fly = Gf.CompMult(fly, fly_speed * 5) self.__last_applied = ModelState(tumble, look, move, fly) if (delta_time is not None) or self.__last_applied.any_values(): self._apply_state(self.__last_applied, delta_time, alpha) else: super()._item_changed(item) def calculate_pixel_to_world(self, pos): projection = Gf.Matrix4d(*self.get_as_floats(self.__projection)) top_left, bot_right = self._calculate_pixel_to_world(pos, projection, projection.GetInverse()) x = top_left[0] - bot_right[0] y = top_left[1] - bot_right[1] # For NDC-z we don't want to use the clip range which could be huge # So avergae the X-Y scales instead self.set_floats('ndc_scale', [x, y, (x + y) * 0.5]) def _calculate_pixel_to_world(self, pos, projection, inv_projection): ndc = projection.Transform(pos) top_left = inv_projection.Transform(Gf.Vec3d(-1, -1, ndc[2])) bot_right = inv_projection.Transform(Gf.Vec3d(1, 1, ndc[2])) return (top_left, bot_right) def _set_animation_key(self, key: str): self.__animation_key = key def _start_external_events(self, flight_mode: bool = False): # If flight mode is already doing inertia, do nothing. # This is for the case where right-click for WASD navigation end with a mouse up and global inertia is enabled. if self.__flight_inertia_active and not flight_mode: return False # Quick check that inertia is enabled for any mode other than flight if not flight_mode: inertia_modes = self.__settings.get('/exts/omni.kit.manipulator.camera/inertiaModesEnabled') len_inertia_enabled = len(inertia_modes) if inertia_modes else 0 if len_inertia_enabled == 0: return if len_inertia_enabled == 1: self.__inertia_modes = [inertia_modes[0], 0, 0, 0] elif len_inertia_enabled == 2: self.__inertia_modes = [inertia_modes[0], inertia_modes[1], 0, 0] elif len_inertia_enabled == 3: self.__inertia_modes = [inertia_modes[0], inertia_modes[1], inertia_modes[2], 0] else: self.__inertia_modes = inertia_modes else: self.__inertia_modes = [1, 0, 1, 0] # Setup the animation state self.__anim_stopped = 0 self.__intertia_state = None self.__flight_inertia_active = flight_mode # Pull more infor from inertai settings fro what is to be created create_tumble = self.__inertia_modes[1] create_look = flight_mode or self.__inertia_modes[2] create_move = self.__inertia_modes[3] create_fly = flight_mode if self.__anim_stream: # Handle case where key was down, then lifted, then pushed again by recreating look_velocity / flight correction. create_tumble = create_tumble and not self.__tumble_velocity create_look = create_look and not self.__look_velocity create_move = create_move and not self.__move_velocity create_fly = False clamp_dt = self.__settings.get('/ext/omni.kit.manipulator.camera/clampUpdates') or 0.15 if create_look: self.__look_velocity = Velocity.create(self, 'look', clamp_dt) if create_tumble: self.__tumble_velocity = Velocity.create(self, 'tumble', clamp_dt) if create_move: self.__move_velocity = Velocity.create(self, 'move', clamp_dt) if create_fly: self.__fly_velocity = Velocity.create(self, 'fly', clamp_dt) # If any velocities are valid, then setup an animation to apply it. if self.__tumble_velocity or self.__look_velocity or self.__move_velocity or self.__fly_velocity: # Only set up the animation in flight-mode, let _stop_external_events set it up otherwise if flight_mode and not self.__anim_stream: self.__anim_stream = AnimationEventStream.get_instance() self.__anim_stream.add_animation(self._apply_state_tick, self.__animation_key) return True if self.__anim_stream: anim_stream, self.__anim_stream = self.__anim_stream, None anim_stream.destroy() return False def _stop_external_events(self, flight_mode: bool = False): # Setup animation for inertia in non-flight mode if not flight_mode and not self.__anim_stream: tumble, look, move = None, None, None if self.__last_applied and (self.__tumble_velocity or self.__look_velocity or self.__move_velocity or self.__fly_velocity): if self.__tumble_velocity and self.__inertia_modes[1]: tumble = self.__last_applied.tumble if self.__look_velocity and self.__inertia_modes[2]: look = self.__last_applied.look if self.__move_velocity and self.__inertia_modes[3]: move = self.__last_applied.move if tumble or look or move: self.__last_applied = ModelState(tumble, look, move, self.__last_applied.fly) self.__anim_stream = AnimationEventStream.get_instance() self.__anim_stream.add_animation(self._apply_state_tick, self.__animation_key) else: self.__tumble_velocity = None self.__look_velocity = None self.__move_velocity = None self.__fly_velocity = None self.__intertia_state = None return self.__anim_stopped = time.time() self.__intertia_state = self.__last_applied self.__mark_animating(1) def __mark_animating(self, interaction_animating: int): item, _ = self.__items.get('interaction_animating', (None, None)) self.set_ints(item, [interaction_animating]) super()._item_changed(item) def _apply_state_time(self, dt: float, apply_fn: Callable): alpha = 1 if self.__anim_stopped: now = time.time() inertia_enabled = _optional_int(self, 'inertia_enabled', 0) inertia_seconds = _optional_float(self, 'inertia_seconds', 0) if inertia_enabled and inertia_seconds > 0: alpha = 1.0 - ((now - self.__anim_stopped) / inertia_seconds) if alpha > ALMOST_ZERO: decay = self.__settings.get('/exts/omni.kit.manipulator.camera/inertiaDecay') decay = _optional_int(self, 'inertia_decay', decay) alpha = pow(alpha, decay) if decay else 1 else: alpha = 0 else: alpha = 0 if alpha == 0: if self.__anim_stream: anim_stream, self.__anim_stream = self.__anim_stream, None anim_stream.destroy() self.set_ints('interaction_ended', [1]) apply_fn(dt * alpha, 1) if alpha == 0: self.set_ints('interaction_ended', [0]) self.__mark_animating(0) self.__tumble_velocity = None self.__look_velocity = None self.__move_velocity = None self.__fly_velocity = None self.__intertia_state = None self.__flight_inertia_active = False return False return True def _apply_state_tick(self, dt: float = None): keep_anim = True istate = self.__intertia_state if istate: if self.__flight_inertia_active: # See _item_changed, but during an inertia move, look should still be applied (but without any velocity) look = self.get_as_floats(self.__look) if look: self.set_floats(self.__look, None) state = ModelState(None, look, None, istate.fly) else: tumble = (self.get_as_floats(self.__tumble) or istate.tumble) if self.__inertia_modes[1] else None look = (self.get_as_floats(self.__look) or istate.look) if self.__inertia_modes[2] else None move = (self.get_as_floats(self.__move) or istate.move) if self.__inertia_modes[3] else None state = ModelState(tumble, look, move) keep_anim = self._apply_state_time(dt, lambda dt, alpha: self._apply_state(state, dt, alpha)) else: keep_anim = self._apply_state_time(dt, lambda dt, alpha: self._item_changed(None, dt, alpha)) if not keep_anim and self.__anim_stream: self.__destroy_animation() def _kill_external_animation(self, kill_stream: bool = True, initial_transform = None): if kill_stream: self.__destroy_animation() # self._stop_external_events() self.__tumble_velocity = None self.__look_velocity = None self.__move_velocity = None self.__fly_velocity = None self.__intertia_state = None self.__flight_inertia_active = False # Reset internal transform if provided if initial_transform: self.set_floats('transform', initial_transform) self.set_floats('initial_transform', initial_transform) @carb.profiler.profile def _apply_state(self, state: ModelState, dt: float = None, alpha: float = None): up_axis = _optional_floats(self, 'up_axis') rotation_precision = _optional_int(self, 'rotation_precision', 5) last_transform = Gf.Matrix4d(*self.get_as_floats(self.__transform)) xforms = TransformAccumulator(last_transform) center_of_interest = None tumble = state.tumble if self.__tumble_velocity: tumble = self.__tumble_velocity.apply(tumble, dt, alpha) if tumble: center_of_interest = Gf.Vec3d(*self.get_as_floats(self.__center_of_interest)) tumble = Gf.Vec3d(round(tumble[0], rotation_precision), round(tumble[1], rotation_precision), round(tumble[2], rotation_precision)) final_xf = xforms.get_tumble(tumble, center_of_interest, up_axis) else: final_xf = Gf.Matrix4d(1) look = state.look if self.__look_velocity: look = self.__look_velocity.apply(look, dt, alpha) if look: look = Gf.Vec3d(round(look[0], rotation_precision), round(look[1], rotation_precision), round(look[2], rotation_precision)) final_xf = final_xf * xforms.get_look(look, up_axis) move = state.move if self.__move_velocity: move = self.__move_velocity.apply(move, dt, alpha) if move: final_xf = xforms.get_translation(move) * final_xf adjust_coi = move[2] != 0 else: adjust_coi = False fly = None if _optional_int(self, 'disable_fly', 0) else state.fly if self.__fly_velocity: fly = self.__fly_velocity.apply(fly, dt, alpha) if fly: if _optional_bool(self, 'fly_mode_lock_view', False): decomp_rot = last_transform.ExtractRotation().Decompose(Gf.Vec3d.ZAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis()) rot_z = Gf.Rotation(Gf.Vec3d.ZAxis(), decomp_rot[0]) rot_y = Gf.Rotation(Gf.Vec3d.YAxis(), decomp_rot[1]) rot_x = Gf.Rotation(Gf.Vec3d.XAxis(), decomp_rot[2]) last_transform_tr = Gf.Matrix4d().SetTranslate(last_transform.ExtractTranslation()) last_transform_rt_0 = Gf.Matrix4d().SetRotate(rot_x) last_transform_rt_1 = Gf.Matrix4d().SetRotate(rot_y * rot_z) if up_axis[2]: fly[1], fly[2] = -fly[2], fly[1] elif Gf.Dot(Gf.Vec3d.ZAxis(), last_transform.TransformDir((0, 0, 1))) < 0: fly[1], fly[2] = -fly[1], -fly[2] flight_xf = xforms.get_translation(fly) last_transform = last_transform_rt_0 * flight_xf * last_transform_rt_1 * last_transform_tr else: final_xf = xforms.get_translation(fly) * final_xf transform = final_xf * last_transform # If zooming out in Z, adjust the center-of-interest and pixel-to-world in 'ndc_scale' self.set_ints(self.__adjust_center_of_interest, [adjust_coi]) if adjust_coi: center_of_interest = center_of_interest or Gf.Vec3d(*self.get_as_floats(self.__center_of_interest)) coi = Gf.Matrix4d(*self.get_as_floats('initial_transform')).Transform(center_of_interest) coi = transform.GetInverse().Transform(coi) self.calculate_pixel_to_world(coi) self.set_floats(self.__transform, _flatten_matrix(transform)) super()._item_changed(self.__transform) def _broadcast_mode(self, mode: str): if mode == self.__mode: return viewport_id = _optional_int(self, 'viewport_id', None) if viewport_id is None: return # Send a signal that contains the viewport_id and mode (carb requires a homogenous array, so as strings) self.__settings.set("/exts/omni.kit.manipulator.camera/viewportMode", [str(viewport_id), mode]) self.__mode = mode
32,559
Python
45.781609
143
0.589729
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/manipulator.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__ = ['CameraManipulatorBase', 'adjust_center_of_interest'] from omni.ui import scene as sc from .gestures import build_gestures from .model import CameraManipulatorModel, _optional_bool, _flatten_matrix from pxr import Gf # Common math to adjust the center-of-interest def adjust_center_of_interest(model: CameraManipulatorModel, initial_transform: Gf.Matrix4d, final_transform: Gf.Matrix4d): # Adjust the center-of-interest if requested. # For object-centric movement we always adjust it if an object was hit object_centric = _optional_bool(model, 'object_centric_movement') coi_picked = model.get_as_floats('center_of_interest_picked') if object_centric else False adjust_center_of_interest = (object_centric and coi_picked) or _optional_bool(model, 'adjust_center_of_interest') if not adjust_center_of_interest: return None, None # When adjusting the center of interest we'll operate on a direction and length (in camera-space) # Which helps to not introduce -drift- as we jump through the different spaces to update it. # Final camera position world_cam_pos = final_transform.Transform(Gf.Vec3d(0, 0, 0)) # center_of_interest_start is in camera-space center_of_interest_start = Gf.Vec3d(*model.get_as_floats('center_of_interest_start')) # Save the direction center_of_interest_dir = center_of_interest_start.GetNormalized() if coi_picked: # Keep original center-of-interest direction, but adjust its length to the picked position world_coi = Gf.Vec3d(coi_picked[0], coi_picked[1], coi_picked[2]) # TODO: Setting to keep subsequent movement focused on screen-center or move it to the object. if False: # Save the center-of-interest to the hit-point by adjusting direction center_of_interest_dir = final_transform.GetInverse().Transform(world_coi).GetNormalized() else: # Move center-of-interest to world space at initial transform world_coi = initial_transform.Transform(center_of_interest_start) # Now get the length between final camera-position and the world-space-coi, # and apply that to the direction. center_of_interest_end = center_of_interest_dir * (world_cam_pos - world_coi).GetLength() return center_of_interest_start, center_of_interest_end # Base class, resposible for building up the gestures class CameraManipulatorBase(sc.Manipulator): def __init__(self, bindings: dict = None, model: sc.AbstractManipulatorModel = None, *args, **kwargs): super().__init__(*args, **kwargs) self._screen = None # Provide some defaults self.model = model or CameraManipulatorModel() self.bindings = bindings # Provide a slot for a user to fill in with a GestureManager but don't use anything by default self.manager = None self.gestures = [] self.__transform = None self.__gamepad = None def _on_began(self, model: CameraManipulatorModel, *args, **kwargs): pass def on_build(self): # Need to hold a reference to this or the sc.Screen would be destroyed when out of scope self.__transform = sc.Transform() with self.__transform: self._screen = sc.Screen(gestures=self.gestures or build_gestures(self.model, self.bindings, self.manager, self._on_began)) def destroy(self): if self.__gamepad: self.__gamepad.destroy() self.__gamepad = None if self.__transform: self.__transform.clear() self.__transform = None self._screen = None if hasattr(self.model, 'destroy'): self.model.destroy() @property def gamepad_enabled(self) -> bool: return self.__gamepad is not None @gamepad_enabled.setter def gamepad_enabled(self, value: bool): if value: if not self.__gamepad: from .gamepad import GamePadController self.__gamepad = GamePadController(self) elif self.__gamepad: self.__gamepad.destroy() self.__gamepad = None # We have all the imoorts already, so provide a simple omni.ui.scene camera manipulator that one can use. # Takes an omni.ui.scene view and center-of-interest and applies model changes to that view class SceneViewCameraManipulator(CameraManipulatorBase): def __init__(self, center_of_interest, *args, **kwargs): super().__init__(*args, **kwargs) self.__center_of_interest = center_of_interest def _on_began(self, model: CameraManipulatorModel, mouse): model.set_floats('center_of_interest', [self.__center_of_interest[0], self.__center_of_interest[1], self.__center_of_interest[2]]) if _optional_bool(model, 'orthographic'): model.set_ints('disable_tumble', [1]) model.set_ints('disable_look', [1]) def on_model_updated(self, item): model = self.model if item == model.get_item('transform'): final_transform = Gf.Matrix4d(*model.get_as_floats(item)) initial_transform = Gf.Matrix4d(*model.get_as_floats('initial_transform')) # Adjust our center-of-interest coi_start, coi_end = adjust_center_of_interest(model, initial_transform, final_transform) if coi_end: self.__center_of_interest = coi_end # omni.ui.scene.SceneView.CameraModel expects 'view', but we operate on 'transform' # The following will push our transform changes into the SceneView.model.view sv_model = self.scene_view.model view = sv_model.get_item('view') sv_model.set_floats(view, _flatten_matrix(final_transform.GetInverse())) sv_model._item_changed(view)
6,222
Python
46.503816
138
0.674381
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/gesturebase.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__ = ['CameraGestureBase'] from omni.ui import scene as sc from .model import _accumulate_values, _optional_bool, _optional_floats, _flatten_matrix from .flight_mode import get_keyboard_input import carb.settings from pxr import Gf import time from typing import Callable, Sequence # Base class for camera transform manipulation/gesture # class CameraGestureBase(sc.DragGesture): def __init__(self, model: sc.AbstractManipulatorModel, configure_model: Callable = None, name: str = None, *args, **kwargs): super().__init__(*args, **kwargs) self.name = name if name else self.__class__.__name__ self.model = model # XXX: Need a manipulator on_began method self.__configure_model = configure_model self.__prev_mouse = None self.__prev_mouse_time = None self.__keyboard = None self.__fly_active = None def destroy(self): self.model = None self._disable_flight() super().destroy() @property def center_of_interest(self): return Gf.Vec3d(self.model.get_as_floats('center_of_interest')) @property def initial_transform(self): return Gf.Matrix4d(*self.model.get_as_floats('initial_transform')) @property def last_transform(self): return Gf.Matrix4d(*self.model.get_as_floats('transform')) @property def projection(self): return Gf.Matrix4d(*self.model.get_as_floats('projection')) @property def orthographic(self): return _optional_bool(self.model, 'orthographic') @property def disable_pan(self): return _optional_bool(self.model, 'disable_pan') @property def disable_tumble(self): return _optional_bool(self.model, 'disable_tumble') @property def disable_look(self): return _optional_bool(self.model, 'disable_look') @property def disable_zoom(self): return _optional_bool(self.model, 'disable_zoom') @property def intertia(self): inertia = _optional_bool(self.model, 'inertia_enabled') if not inertia: return 0 inertia = _optional_floats(self.model, 'inertia_seconds') return inertia[0] if inertia else 0 @property def up_axis(self): # Assume Y-up if not specified return _optional_bool(self.model, 'up_axis', 1) @staticmethod def __conform_speed(values): if values: vlen = len(values) if vlen == 1: return (values[0], values[0], values[0]) if vlen == 2: return (values[0], values[1], 0) return values return (1, 1, 1) def get_rotation_speed(self, secondary): model = self.model rotation_speed = self.__conform_speed(_optional_floats(model, 'rotation_speed')) secondary_speed = self.__conform_speed(_optional_floats(model, secondary)) return (rotation_speed[0] * secondary_speed[0], rotation_speed[1] * secondary_speed[1], rotation_speed[2] * secondary_speed[2]) @property def tumble_speed(self): return self.get_rotation_speed('tumble_speed') @property def look_speed(self): return self.get_rotation_speed('look_speed') @property def move_speed(self): return self.__conform_speed(_optional_floats(self.model, 'move_speed')) @property def world_speed(self): model = self.model ndc_scale = self.__conform_speed(_optional_floats(model, 'ndc_scale')) world_speed = self.__conform_speed(_optional_floats(model, 'world_speed')) return Gf.CompMult(world_speed, ndc_scale) def _disable_flight(self): if self.__keyboard: self.__keyboard.destroy() def _setup_keyboard(self, model, exit_mode: bool) -> bool: """Setup keyboard and return whether the manipualtor mode (fly) was broadcast to consumers""" self.__keyboard = get_keyboard_input(model, self.__keyboard) if self.__keyboard: # If the keyboard is active, broadcast that fly mode has been entered if self.__keyboard.active: self.__fly_active = True model._broadcast_mode("fly") return True # Check if fly mode was exited if self.__fly_active: exit_mode = self.name.replace('Gesture', '').lower() if exit_mode else "" model._broadcast_mode(exit_mode) return True return False # omni.ui.scene Gesture interface # We absract on top of this due to asynchronous picking, in that we # don't want a gesture to begin until the object/world-space query has completed # This 'delay' could be a setting, but will wind up 'snapping' from the transition # from a Camera's centerOfInterest to the new world-space position def on_began(self, mouse: Sequence[float] = None): model = self.model # Setup flight mode and possibly broadcast that mode to any consumers was_brodcast = self._setup_keyboard(model, False) # If fly mode was not broadcast, then brodcast this gesture's mode if not was_brodcast: # LookGesture => look manip_mode = self.name.replace('Gesture', '').lower() model._broadcast_mode(manip_mode) mouse = mouse if mouse else self.sender.gesture_payload.mouse if self.__configure_model: self.__configure_model(model, mouse) self.__prev_mouse = mouse xf = model.get_as_floats('transform') if xf: # Save an imutable copy of transform for undoable end-event model.set_floats('initial_transform', xf.copy()) coi = model.get_as_floats('center_of_interest') if coi: # Save an imutable copy of center_of_interest for end adjustment if desired (avoiding space conversions) model.set_floats('center_of_interest_start', coi.copy()) model._item_changed('center_of_interest') model.set_ints('interaction_active', [1]) def on_changed(self, mouse: Sequence[float] = None): self._setup_keyboard(self.model, True) self.__last_change = time.time() cur_mouse = mouse if mouse else self.sender.gesture_payload.mouse mouse_moved = (cur_mouse[0] - self.__prev_mouse[0], cur_mouse[1] - self.__prev_mouse[1]) # if (mouse_moved[0] != 0) or (mouse_moved[1] != 0): self.__prev_mouse = cur_mouse self.on_mouse_move(mouse_moved) def on_ended(self): model = self.model final_position = True # Brodcast that the camera manipulationmode is now none model._broadcast_mode("") if self.__keyboard: self.__keyboard = self.__keyboard.end() final_position = self.__keyboard is None self.__prev_mouse = None self.__prev_mouse_time = None if final_position: if model._start_external_events(False): model._stop_external_events(False) self.__apply_as_undoable() model.set_ints('adjust_center_of_interest', []) model.set_floats('current_aperture', []) model.set_ints('interaction_active', [0]) # model.set_floats('center_of_interest_start', []) # model.set_floats('center_of_interest_picked', []) def dirty_items(self, model: sc.AbstractManipulatorModel): model = self.model cur_item = model.get_item('transform') if model.get_as_floats('initial_transform') != model.get_as_floats(cur_item): return [cur_item] def __apply_as_undoable(self): model = self.model dirty_items = self.dirty_items(model) if dirty_items: model.set_ints('interaction_ended', [1]) try: for item in dirty_items: model._item_changed(item) except: raise finally: model.set_ints('interaction_ended', [0]) def _accumulate_values(self, key: str, x: float, y: float, z: float): item = _accumulate_values(self.model, key, x, y, z) if item: self.model._item_changed(None if self.__keyboard else item)
8,715
Python
35.316667
128
0.616753
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/gamepad.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. # from .model import _accumulate_values import omni.kit.app from omni.ui import scene as sc import carb import asyncio from typing import Dict, List, Sequence, Set # Setting per action mode (i.e): # /exts/omni.kit.manipulator.camera/gamePad/fly/deadZone # /exts/omni.kit.manipulator.camera/gamePad/look/deadZone ACTION_MODE_SETTING_KEYS = {"scale", "deadZone"} ACTION_MODE_SETTING_ROOT = "/exts/omni.kit.manipulator.camera/gamePad" # Setting per action trigger (i.e): # /exts/omni.kit.manipulator.camera/gamePad/button/a/scale ACTION_TRIGGER_SETTING_KEYS = {"scale"} __all__ = ['GamePadController'] class ValueMapper: def __init__(self, mode: str, trigger: str, index: int, sub_index: int): self.__mode: str = mode self.__trigger: str = trigger self.__index: int = index self.__sub_index = sub_index @property def mode(self) -> str: return self.__mode @property def trigger(self) -> str: return self.__trigger @property def index(self) -> int: return self.__index @property def sub_index(self) -> int: return self.__sub_index class ModeSettings: def __init__(self, action_mode: str, settings: carb.settings.ISettings): self.__scale: float = 1.0 self.__dead_zone: float = 1e-04 self.__action_mode = action_mode self.__setting_subs: Sequence[carb.settings.SubscriptionId] = [] for setting_key in ACTION_MODE_SETTING_KEYS: sp = self.__get_setting_path(setting_key) self.__setting_subs.append( settings.subscribe_to_node_change_events(sp, lambda *args, k=setting_key: self.__setting_changed(*args, setting_key=k)) ) self.__setting_changed(None, carb.settings.ChangeEventType.CHANGED, setting_key=setting_key) def __del__(self): self.destroy() def __get_setting_path(self, setting_key: str): return f"{ACTION_MODE_SETTING_ROOT}/{self.__action_mode}/{setting_key}" def __setting_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType, setting_key: str): if event_type == carb.settings.ChangeEventType.CHANGED: setting_path = self.__get_setting_path(setting_key) if setting_key == "scale": self.__scale = carb.settings.get_settings().get(setting_path) if self.__scale is None: self.__scale = 1.0 elif setting_key == "deadZone": # Use absolute value, no negative dead-zones and clamp to 1.0 dead_zone = carb.settings.get_settings().get(setting_path) self.__dead_zone = min(abs(dead_zone) or 1e-04, 1.0) if (dead_zone is not None) else 0.0 def destroy(self, settings: carb.settings.ISettings = None): settings = settings or carb.settings.get_settings() for setting_sub in self.__setting_subs: settings.unsubscribe_to_change_events(setting_sub) self.__setting_subs = tuple() def get_value(self, value: float, axis_idx: int) -> float: # Legacy implementation, which scales input value into new range fitted by dead_zone value = (value - self.__dead_zone) / (1.0 - self.__dead_zone) value = max(0, min(1, value)) scale = self.__scale return value * scale # Somewhat simpler version that doesn't scale input by dead-zone if abs(value) > self.__dead_zone: return value * scale return 0 def _limit_camera_velocity(value: float, settings: carb.settings.ISettings, context_name: str): cam_limit = settings.get('/exts/omni.kit.viewport.window/cameraSpeedLimit') if context_name in cam_limit: vel_min = settings.get('/persistent/app/viewport/camVelocityMin') if vel_min is not None: value = max(vel_min, value) vel_max = settings.get('/persistent/app/viewport/camVelocityMax') if vel_max is not None: value = min(vel_max, value) return value def _adjust_flight_speed(xyz_value: Sequence[float]): y = xyz_value[1] if y == 0.0: return import math settings = carb.settings.get_settings() value = settings.get('/persistent/app/viewport/camMoveVelocity') or 1 scaler = settings.get('/persistent/app/viewport/camVelocityScalerMultAmount') or 1.1 scaler = 1.0 + (max(scaler, 1.0 + 1e-8) - 1.0) * abs(y) if y < 0: value = value / scaler elif y > 0: value = value * scaler if math.isfinite(value) and (value > 1e-8): value = _limit_camera_velocity(value, settings, 'gamepad') settings.set('/persistent/app/viewport/camMoveVelocity', value) class GamePadController: def __init__(self, manipulator: sc.Manipulator): self.__manipulator: sc.Manipulator = manipulator self.__gp_event_sub: Dict[carb.input.Gamepad, int] = {} self.__compressed_events: Dict[int, float] = {} self.__action_modes: Dict[str, List[float]] = {} self.__app_event_sub: carb.events.ISubscription = None self.__mode_settings: Dict[str, ModeSettings] = {} self.__value_actions: Dict[carb.input.GamepadInput, ValueMapper] = {} self.__setting_subs: Sequence[carb.settings.SubscriptionId] = [] # Some button presses need synthetic events because unlike keyboard input, carb gamepad doesn't repeat. # event 1 left presssed: value = 0.5 # event 2 right pressed: value = 0.5 # these should cancel, but there is no notification of left event until it changes from 0.5 # This is all handled in __gamepad_event trigger_synth = {carb.input.GamepadInput.RIGHT_TRIGGER, carb.input.GamepadInput.LEFT_TRIGGER} shoulder_synth = {carb.input.GamepadInput.RIGHT_SHOULDER, carb.input.GamepadInput.LEFT_SHOULDER} self.__synthetic_state_init = { carb.input.GamepadInput.RIGHT_TRIGGER: trigger_synth, carb.input.GamepadInput.LEFT_TRIGGER: trigger_synth, carb.input.GamepadInput.RIGHT_SHOULDER: shoulder_synth, carb.input.GamepadInput.LEFT_SHOULDER: shoulder_synth, } self.__synthetic_state = self.__synthetic_state_init.copy() self.__init_gamepad_action(None, carb.settings.ChangeEventType.CHANGED) self.__gp_connect_sub = self._iinput.subscribe_to_gamepad_connection_events(self.__gamepad_connection) def __init_gamepad_action(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType): if event_type != carb.settings.ChangeEventType.CHANGED: return self.__value_actions: Dict[carb.input.GamepadInput, ValueMapper] = {} settings = carb.settings.get_settings() create_subs = not bool(self.__setting_subs) gamepad_action_paths = [] gamepad_input_names = ["rightStick", "leftStick", "dPad", "trigger", "shoulder", "button/a", "button/b", "button/x", "button/y"] for gamepad_input in gamepad_input_names: action_setting_path = f"{ACTION_MODE_SETTING_ROOT}/{gamepad_input}/action" gamepad_action_paths.append(action_setting_path) if create_subs: self.__setting_subs.append( settings.subscribe_to_node_change_events(action_setting_path, self.__init_gamepad_action) ) # TODO: Maybe need more configuable/robust action mapping def action_mapping_4(action_mode: str): action_modes = action_mode.split(".") if len(action_modes) != 1: carb.log_error(f"Action mapping '{action_mode}' for quad input is invalid, using '{action_modes[0]}'") action_mode = action_modes[0] if action_mode == "look": return action_mode, (0, 1), (0, 1, 0, 1) return action_mode, (0, 2), (1, 0, 1, 0) def action_mapping_2(action_mode: str): action_modes = action_mode.split(".") if len(action_modes) != 2: action_modes = (action_modes[0], "x") carb.log_error(f"Action mapping '{action_mode}' for dual input is invalid, using '{action_modes[0]}.x'") axis = {'x': 0, 'y': 1, 'z': 2}.get(action_modes[1], 0) return action_modes[0], axis, (0, 1) def action_mapping_1(action_mode: str): action_modes = action_mode.split(".") if len(action_modes) != 2: action_modes = (action_modes[0], "x") carb.log_error(f"Action mapping '{action_mode}' for dual input is invalid, using '{action_modes[0]}.x'") axis = {'x': 0, 'y': 1, 'z': 2}.get(action_modes[1], 0) return action_modes[0], axis, 0 # Go through the list of named events and setup the action based on it's value right_stick_action = settings.get(gamepad_action_paths[0]) if right_stick_action: right_stick_action, axis, sub_idx = action_mapping_4(right_stick_action) self.__value_actions[carb.input.GamepadInput.RIGHT_STICK_LEFT] = ValueMapper(right_stick_action, gamepad_input_names[0], axis[0], sub_idx[0]) self.__value_actions[carb.input.GamepadInput.RIGHT_STICK_RIGHT] = ValueMapper(right_stick_action, gamepad_input_names[0], axis[0], sub_idx[1]) self.__value_actions[carb.input.GamepadInput.RIGHT_STICK_UP] = ValueMapper(right_stick_action, gamepad_input_names[0], axis[1], sub_idx[2]) self.__value_actions[carb.input.GamepadInput.RIGHT_STICK_DOWN] = ValueMapper(right_stick_action, gamepad_input_names[0], axis[1], sub_idx[3]) left_stick_action = settings.get(gamepad_action_paths[1]) if left_stick_action: left_stick_action, axis, sub_idx = action_mapping_4(left_stick_action) self.__value_actions[carb.input.GamepadInput.LEFT_STICK_LEFT] = ValueMapper(left_stick_action, gamepad_input_names[1], axis[0], sub_idx[0]) self.__value_actions[carb.input.GamepadInput.LEFT_STICK_RIGHT] = ValueMapper(left_stick_action, gamepad_input_names[1], axis[0], sub_idx[1]) self.__value_actions[carb.input.GamepadInput.LEFT_STICK_UP] = ValueMapper(left_stick_action, gamepad_input_names[1], axis[1], sub_idx[2]) self.__value_actions[carb.input.GamepadInput.LEFT_STICK_DOWN] = ValueMapper(left_stick_action, gamepad_input_names[1], axis[1], sub_idx[3]) dpad_action = settings.get(gamepad_action_paths[2]) if dpad_action: dpad_action, axis, sub_idx = action_mapping_4(dpad_action) self.__value_actions[carb.input.GamepadInput.DPAD_LEFT] = ValueMapper(dpad_action, gamepad_input_names[2], axis[0], sub_idx[0]) self.__value_actions[carb.input.GamepadInput.DPAD_RIGHT] = ValueMapper(dpad_action, gamepad_input_names[2], axis[0], sub_idx[1]) self.__value_actions[carb.input.GamepadInput.DPAD_UP] = ValueMapper(dpad_action, gamepad_input_names[2], axis[1], sub_idx[2]) self.__value_actions[carb.input.GamepadInput.DPAD_DOWN] = ValueMapper(dpad_action, gamepad_input_names[2], axis[1], sub_idx[3]) trigger_action = settings.get(gamepad_action_paths[3]) if trigger_action: trigger_action, axis, sub_idx = action_mapping_2(trigger_action) self.__value_actions[carb.input.GamepadInput.RIGHT_TRIGGER] = ValueMapper(trigger_action, gamepad_input_names[3], axis, sub_idx[0]) self.__value_actions[carb.input.GamepadInput.LEFT_TRIGGER] = ValueMapper(trigger_action, gamepad_input_names[3], axis, sub_idx[1]) shoulder_action = settings.get(gamepad_action_paths[4]) if shoulder_action: shoulder_action, axis, sub_idx = action_mapping_2(shoulder_action) self.__value_actions[carb.input.GamepadInput.RIGHT_SHOULDER] = ValueMapper(shoulder_action, gamepad_input_names[4], axis, sub_idx[0]) self.__value_actions[carb.input.GamepadInput.LEFT_SHOULDER] = ValueMapper(shoulder_action, gamepad_input_names[4], axis, sub_idx[1]) button_action = settings.get(gamepad_action_paths[5]) if button_action: button_action, axis, sub_idx = action_mapping_1(button_action) self.__value_actions[carb.input.GamepadInput.A] = ValueMapper(button_action, gamepad_input_names[5], axis, sub_idx) button_action = settings.get(gamepad_action_paths[6]) if button_action: button_action, axis, sub_idx = action_mapping_1(button_action) self.__value_actions[carb.input.GamepadInput.B] = ValueMapper(button_action, gamepad_input_names[6], axis, sub_idx) button_action = settings.get(gamepad_action_paths[7]) if button_action: button_action, axis, sub_idx = action_mapping_1(button_action) self.__value_actions[carb.input.GamepadInput.X] = ValueMapper(button_action, gamepad_input_names[7], axis, sub_idx) button_action = settings.get(gamepad_action_paths[8]) if button_action: button_action, axis, sub_idx = action_mapping_1(button_action) self.__value_actions[carb.input.GamepadInput.Y] = ValueMapper(button_action, gamepad_input_names[8], axis, sub_idx) for value_mapper in self.__value_actions.values(): action_mode = value_mapper.mode if self.__mode_settings.get(action_mode) is None: self.__mode_settings[action_mode] = ModeSettings(action_mode, settings) action_trigger = value_mapper.trigger if self.__mode_settings.get(action_trigger) is None: self.__mode_settings[action_trigger] = ModeSettings(action_trigger, settings) def __del__(self): self.destroy() @property def _iinput(self): return carb.input.acquire_input_interface() async def __apply_events(self): # Grab the events to apply and reset the state to empty events, self.__compressed_events = self.__compressed_events, {} # Reset the synthetic state self.__synthetic_state = self.__synthetic_state_init.copy() if not events: return manipulator = self.__manipulator if not manipulator: return model = manipulator.model manipulator._on_began(model, None) # Map the action to +/- values per x, y, z components action_modes: Dict[str, Dict[int, List[float]]] = {} for input, value in events.items(): action = self.__value_actions.get(input) if not action: continue # Must exists, KeyError otherwise mode_seting = self.__mode_settings[action.mode] trigger_setting = self.__mode_settings[action.trigger] # Get the dict for this action storing +/- values per x, y, z pos_neg_value_dict = action_modes.get(action.mode) or {} # Get the +/- values for the x, y, z component pos_neg_values = pos_neg_value_dict.get(action.index) or [0, 0] # Scale the value by the action's scaling factor value = mode_seting.get_value(value, action.index) # Scale the value by the trigger's scaling factor value = trigger_setting.get_value(value, action.index) # Store the +/- value into the proper slot '+' into 0, '-' into 1 pos_neg_values[action.sub_index] += value # Store back into the dict mapping x, y, z to +/- values pos_neg_value_dict[action.index] = pos_neg_values # Store back into the dict storing the +/- values per x, y, z into the action action_modes[action.mode] = pos_neg_value_dict # Collapse the +/- values per individual action and x, y, z into a single total for action_mode, pos_neg_value_dict in action_modes.items(): # Some components may not have been touched but need to preserve last value xyz_value = self.__action_modes.get(action_mode) or [0, 0, 0] for xyz_index, pos_neg_value in pos_neg_value_dict.items(): xyz_value[xyz_index] = pos_neg_value[0] - pos_neg_value[1] # Apply model speed to anything but fly (that is handled by model itself) if action_mode != "fly": model_speed = model.get_item(f"{action_mode}_speed") if model_speed is not None: model_speed = model.get_as_floats(model_speed) if model_speed is not None: for i in range(len(model_speed)): xyz_value[i] *= model_speed[i] # Store the final values self.__action_modes[action_mode] = xyz_value # Prune any actions that now do nothing (has 0 for x, y, and z) self.__action_modes = { action_mode: xyz_value for action_mode, xyz_value in self.__action_modes.items() if (xyz_value[0] or xyz_value[1] or xyz_value[2]) } has_data: bool = bool(self.__action_modes) if has_data: self.__apply_gamepad_state() if hasattr(model, '_start_external_events'): if has_data: self.___start_external_events(model) else: self.__stop_external_events(model) def ___start_external_events(self, model): if self.__app_event_sub: return _broadcast_mode = getattr(model, '_broadcast_mode', None) if _broadcast_mode: _broadcast_mode("gamepad") self.__app_event_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop( self.__apply_gamepad_state, name=f"omni.kit.manipulator.camera.GamePadController.{id(self)}", # order=omni.kit.app.UPDATE_ORDER_PYTHON_ASYNC_FUTURE_END_UPDATE ) model._start_external_events(True) def __stop_external_events(self, model): if self.__app_event_sub: _broadcast_mode = getattr(model, '_broadcast_mode', None) if _broadcast_mode: _broadcast_mode("") self.__app_event_sub = None self.__action_modes = {} model._stop_external_events(True) def __apply_gamepad_state(self, *args, **kwargs): manipulator = self.__manipulator model = manipulator.model # manipulator._on_began(model, None) for action_mode, xyz_value in self.__action_modes.items(): if action_mode == "fly": model.set_floats("fly", xyz_value) continue elif action_mode == "speed": _adjust_flight_speed(xyz_value) continue item = _accumulate_values(model, action_mode, xyz_value[0], xyz_value[1], xyz_value[2]) if item: model._item_changed(item) def __gamepad_event(self, event: carb.input.GamepadEvent): event_input = event.input self.__compressed_events[event_input] = event.value # Gamepad does not get repeat events, so on certain button presses there needs to be a 'synthetic' event # that represents the inverse-key (left/right) based on its last/current state. synth_state = self.__synthetic_state.get(event.input) if synth_state: for synth_input in synth_state: del self.__synthetic_state[synth_input] if synth_input != event_input: self.__compressed_events[synth_input] = self._iinput.get_gamepad_value(event.gamepad, synth_input) asyncio.ensure_future(self.__apply_events()) def __gamepad_connection(self, event: carb.input.GamepadConnectionEvent): e_type = event.type e_gamepad = event.gamepad if e_type == carb.input.GamepadConnectionEventType.DISCONNECTED: e_gamepad_sub = self.__gp_event_sub.get(e_gamepad) if e_gamepad_sub: self._iinput.unsubscribe_to_gamepad_events(e_gamepad, e_gamepad_sub) del self.__gp_event_sub[e_gamepad] pass elif e_type == carb.input.GamepadConnectionEventType.CONNECTED: if self.__gp_event_sub.get(e_gamepad): carb.log_error("Gamepad connected event, but already subscribed") return gp_event_sub = self._iinput.subscribe_to_gamepad_events(e_gamepad, self.__gamepad_event) if gp_event_sub: self.__gp_event_sub[e_gamepad] = gp_event_sub def destroy(self): iinput = self._iinput settings = carb.settings.get_settings() # Remove gamepad connected subscriptions if self.__gp_connect_sub: iinput.unsubscribe_to_gamepad_connection_events(self.__gp_connect_sub) self.__gp_connect_sub = None # Remove gamepad event subscriptions for gamepad, gamepad_sub in self.__gp_event_sub.items(): iinput.unsubscribe_to_gamepad_events(gamepad, gamepad_sub) self.__gp_event_sub = {} # Remove any pending state on the model model = self.__manipulator.model if self.__manipulator else None if model: self.__stop_external_events(model) self.__manipulator = None # Remove any settings subscriptions for setting_sub in self.__setting_subs: settings.unsubscribe_to_change_events(setting_sub) self.__setting_subs = [] # Destroy any mode/action specific settings for action_mode, mode_settings in self.__mode_settings.items(): mode_settings.destroy(settings) self.__mode_settings = {}
22,082
Python
47.427631
154
0.623675
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/gestures.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__ = ['build_gestures', 'PanGesture', 'TumbleGesture', 'LookGesture', 'ZoomGesture'] from omni.ui import scene as sc from .gesturebase import CameraGestureBase from pxr import Gf import carb from typing import Callable kDefaultKeyBindings = { 'PanGesture': 'Any MiddleButton', 'TumbleGesture': 'Alt LeftButton', 'ZoomGesture': 'Alt RightButton', 'LookGesture': 'RightButton' } def build_gestures(model: sc.AbstractManipulatorModel, bindings: dict = None, manager: sc.GestureManager = None, configure_model: Callable = None): def _parse_binding(binding_str: str): keys = binding_str.split(' ') button = { 'LeftButton': 0, 'RightButton': 1, 'MiddleButton': 2 }.get(keys.pop()) modifiers = 0 for mod_str in keys: mod_bit = { 'Shift': carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT, 'Ctrl': carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, 'Alt': carb.input.KEYBOARD_MODIFIER_FLAG_ALT, 'Super': carb.input.KEYBOARD_MODIFIER_FLAG_SUPER, 'Any': 0xffffffff, }.get(mod_str) if not mod_bit: raise RuntimeError(f'Unparseable binding: {binding_str}') modifiers = modifiers | mod_bit return (button, modifiers) if not bindings: bindings = kDefaultKeyBindings gestures = [] for gesture, binding in bindings.items(): instantiator = globals().get(gesture) if not instantiator: carb.log_warn(f'Gesture "{gesture}" was not found for key-binding: "{binding}"') continue button, modifers = _parse_binding(binding) gestures.append(instantiator(model, configure_model, mouse_button=button, modifiers=modifers, manager=manager)) return gestures class PanGesture(CameraGestureBase): def on_mouse_move(self, mouse_moved): if self.disable_pan: return world_speed = self.world_speed move_speed = self.move_speed self._accumulate_values('move', mouse_moved[0] * 0.5 * world_speed[0] * move_speed[0], mouse_moved[1] * 0.5 * world_speed[1] * move_speed[1], 0) class TumbleGesture(CameraGestureBase): def on_mouse_move(self, mouse_moved): if self.disable_tumble: return # Mouse moved is [-1,1], so make a full drag scross the viewport a 180 tumble speed = self.tumble_speed self._accumulate_values('tumble', mouse_moved[0] * speed[0] * -90, mouse_moved[1] * speed[1] * 90, 0) class LookGesture(CameraGestureBase): def on_mouse_move(self, mouse_moved): if self.disable_look: return # Mouse moved is [-1,1], so make a full drag scross the viewport a 180 look speed = self.look_speed self._accumulate_values('look', mouse_moved[0] * speed[0] * -90, mouse_moved[1] * speed[1] * 90, 0) class OrthoZoomAperture(): def __init__(self, model: sc.AbstractManipulatorModel, apertures): self.__values = apertures.copy() def apply(self, model: sc.AbstractManipulatorModel, distance: float): # TODO ortho-speed for i in range(2): self.__values[i] -= distance * 2 model.set_floats('current_aperture', self.__values) model._item_changed(model.get_item('current_aperture')) def dirty_items(self, model: sc.AbstractManipulatorModel): cur_ap = model.get_item('current_aperture') if model.get_as_floats('initial_aperture') != model.get_as_floats(cur_ap): return [cur_ap] class OrthoZoomProjection(): def __init__(self, model: sc.AbstractManipulatorModel, projection): self.__projection = projection.copy() def apply(self, model: sc.AbstractManipulatorModel, distance: float): # TODO ortho-speed distance /= 3.0 rml = (2.0 / self.__projection[0]) tmb = (2.0 / self.__projection[5]) aspect = tmb / rml rpl = rml * -self.__projection[12] tpb = tmb * self.__projection[13] rml -= distance tmb -= distance * aspect rpl += distance tpb += distance self.__projection[0] = 2.0 / rml self.__projection[5] = 2.0 / tmb #self.__projection[12] = -rpl / rml #self.__projection[13] = tpb / tmb model.set_floats('projection', self.__projection) # Trigger recomputation of ndc_speed model._item_changed(model.get_item('projection')) def dirty_items(self, model: sc.AbstractManipulatorModel): proj = model.get_item('projection') return [proj] if model.get_as_floats('projection') != model.get_as_floats(proj): return [proj] class ZoomGesture(CameraGestureBase): def dirty_items(self, model: sc.AbstractManipulatorModel): return super().dirty_items(model) if not self.__orth_zoom else self.__orth_zoom.dirty_items(model) def __setup_ortho_zoom(self): apertures = self.model.get_as_floats('initial_aperture') if apertures: self.__orth_zoom = OrthoZoomAperture(self.model, apertures) return True projection = self.model.get_as_floats('projection') if projection: self.__orth_zoom = OrthoZoomProjection(self.model, projection) return True carb.log_warn("Orthographic zoom needs a projection or aperture") return False def on_began(self, *args, **kwargs): super().on_began(*args, **kwargs) # Setup an orthographic movement (aperture adjustment) if needed self.__orth_zoom = False if self.orthographic: self.__setup_ortho_zoom() # self.model.set_ints('adjust_center_of_interest', [1]) # Zoom into center of view or mouse interest self.__direction = Gf.Vec3d(self.center_of_interest.GetNormalized()) if False else None def on_mouse_move(self, mouse_moved): if self.disable_zoom: return # Compute length/radius from gesture start distance = (mouse_moved[0] + mouse_moved[1]) * self.world_speed.GetLength() * 1.41421356 distance *= self.move_speed[2] if self.__orth_zoom: self.__orth_zoom.apply(self.model, distance) return # Zoom into view-enter or current mouse/world interest direction = self.__direction if self.__direction else Gf.Vec3d(self.center_of_interest.GetNormalized()) amount = direction * distance self._accumulate_values('move', amount[0], amount[1], amount[2])
7,324
Python
36.372449
119
0.604178
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/tests/test_manipulator_camera.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__ = ['TestManipulatorCamera', 'TestFlightMode'] from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from omni.ui import scene as sc from omni.ui import color as cl import carb import omni.kit import omni.kit.app import omni.ui as ui from pxr import Gf from omni.kit.manipulator.camera.manipulator import CameraManipulatorBase, SceneViewCameraManipulator, adjust_center_of_interest import omni.kit.ui_test as ui_test from carb.input import MouseEventType, KeyboardEventType, KeyboardInput CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.camera}/data")) TEST_WIDTH, TEST_HEIGHT = 500, 500 TEST_UI_CENTER = ui_test.Vec2(TEST_WIDTH / 2, TEST_HEIGHT / 2) 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 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.__scene_view.model.set_floats('view', _flatten_matrix(transform.GetInverse())) elif item == model.get_item('projection'): self.__scene_view.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 async def wait_human_delay(delay=1): await ui_test.human_delay(delay) class TestManipulatorCamera(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def create_test_view(self, name: str, ortho: bool = False, custom: bool = False): window = await self.create_test_window(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) with window.frame: scene_view = SimpleScene(ortho, custom) return (window, scene_view) async def _test_perspective_camera(self): objects = await self.create_test_view('Perspective') await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_perspective_camera.png') async def _test_orthographic_camera(self): objects = await self.create_test_view('Orthographic', True) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_orthographic_camera.png') async def _test_custom_camera(self): objects = await self.create_test_view('Custom Orthographic', True, True) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_custom_camera.png') async def _test_mouse_across_screen(self, mouse_down, mouse_up): objects = await self.create_test_view('WASD Movement') mouse_begin = ui_test.Vec2(0, TEST_UI_CENTER.y) mouse_end = ui_test.Vec2(TEST_WIDTH , TEST_UI_CENTER.y) await ui_test.input.emulate_mouse(MouseEventType.MOVE, mouse_begin) await wait_human_delay() try: await ui_test.input.emulate_mouse(mouse_down, mouse_begin) await ui_test.input.emulate_mouse_slow_move(mouse_begin, mouse_end) await wait_human_delay() finally: await ui_test.input.emulate_mouse(mouse_up, mouse_end) await wait_human_delay() return objects async def test_pan_across_screen(self): """Test pan across X is a full move across NDC by default""" objects = await self._test_mouse_across_screen(MouseEventType.MIDDLE_BUTTON_DOWN, MouseEventType.MIDDLE_BUTTON_UP) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_pan_across_screen.png') async def test_look_across_screen(self): """Test look rotation across X is 180 degrees by default""" objects = await self._test_mouse_across_screen(MouseEventType.RIGHT_BUTTON_DOWN, MouseEventType.RIGHT_BUTTON_UP) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_look_across_screen.png') class TestFlightMode(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) def get_translation(self, model): matrix = model.view return (matrix[12], matrix[13], matrix[14]) async def do_key_press(self, key: KeyboardInput, operation = None): try: await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_PRESS, key) await wait_human_delay() if operation: operation() finally: await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_RELEASE, key) await wait_human_delay() async def test_movement(self): """Test flight movement via WASD keyboard.""" window, simple_scene = await self.create_test_view('WASD Movement') model = simple_scene.model await ui_test.input.emulate_mouse(MouseEventType.MOVE, TEST_UI_CENTER) await wait_human_delay() start_pos = self.get_translation(model) try: await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER) await wait_human_delay() await self.do_key_press(KeyboardInput.W) after_w = self.get_translation(model) # W should have moved Z forward self.assertAlmostEqual(after_w[0], start_pos[0], places=5) self.assertAlmostEqual(after_w[1], start_pos[1], places=5) self.assertTrue(after_w[2] > start_pos[2]) await self.do_key_press(KeyboardInput.A) after_wa = self.get_translation(model) # A should have moved X left self.assertTrue(after_wa[0] > after_w[0]) self.assertAlmostEqual(after_wa[1], after_w[1], places=5) self.assertAlmostEqual(after_wa[2], after_w[2], places=5) await self.do_key_press(KeyboardInput.S) after_was = self.get_translation(model) # S should have moved Z back self.assertAlmostEqual(after_was[0], after_wa[0], places=5) self.assertAlmostEqual(after_was[1], after_wa[1], places=5) self.assertTrue(after_was[2] < after_wa[2]) await self.do_key_press(KeyboardInput.D) after_wasd = self.get_translation(model) # D should have moved X right self.assertTrue(after_wasd[0] < after_was[0]) self.assertAlmostEqual(after_wasd[1], after_was[1], places=5) self.assertAlmostEqual(after_wasd[2], after_was[2], places=5) # Test disabling flight-mode in the model would stop keyboard from doing anything before_wasd = self.get_translation(model) simple_scene.items[-1].model.set_ints('disable_fly', [1]) await self.do_key_press(KeyboardInput.W) await self.do_key_press(KeyboardInput.A) await self.do_key_press(KeyboardInput.S) await self.do_key_press(KeyboardInput.D) await wait_human_delay() after_wasd = self.get_translation(model) simple_scene.items[-1].model.set_ints('disable_fly', [0]) self.assertTrue(Gf.IsClose(before_wasd, after_wasd, 1e-5)) finally: await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_UP) await wait_human_delay() async def _test_speed_modifier(self, value_a, value_b): vel_key = '/persistent/app/viewport/camMoveVelocity' mod_amount_key = '/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount' settings = carb.settings.get_settings() window, simple_scene = await self.create_test_view('WASD Movement') model = simple_scene.model settings.set(vel_key, 5) await ui_test.input.emulate_mouse(MouseEventType.MOVE, TEST_UI_CENTER) await wait_human_delay() def compare_velocity(velocity): vel_value = settings.get(vel_key) self.assertEqual(vel_value, velocity) try: compare_velocity(5) await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER) # By default Shift should double speed await self.do_key_press(KeyboardInput.LEFT_SHIFT, lambda: compare_velocity(value_a)) # By default Shift should halve speed await self.do_key_press(KeyboardInput.LEFT_CONTROL, lambda: compare_velocity(value_b)) await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_UP) await wait_human_delay() compare_velocity(5) finally: settings.set(vel_key, 5) settings.set(mod_amount_key, 2) await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_UP) await wait_human_delay() async def test_speed_modifier_a(self): """Test default flight speed adjustement: 2x""" await self._test_speed_modifier(10, 2.5) async def test_speed_modifier_b(self): """Test custom flight speed adjustement: 4x""" carb.settings.get_settings().set('/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount', 4) await self._test_speed_modifier(20, 1.25) async def test_speed_modifier_c(self): """Test custom flight speed adjustement: 0x""" # Test when set to 0 carb.settings.get_settings().set('/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount', 0) await self._test_speed_modifier(5, 5)
15,278
Python
45.440729
299
0.63994
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/tests/test_manipulator_usd.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__ = ['TestManipulatorUSDCamera'] from omni.kit.manipulator.camera.usd_camera_manipulator import UsdCameraManipulator from omni.kit.manipulator.camera.model import CameraManipulatorModel, _flatten_matrix import omni.usd import omni.kit.test import carb.settings from pxr import Gf, Sdf, UsdGeom from pathlib import Path from typing import List, Sequence import sys import unittest TESTS_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.camera}/data")).absolute().resolve() USD_FILES = TESTS_PATH.joinpath("tests", "usd") class TestManipulatorUSDCamera(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await omni.usd.get_context().new_stage_async() self.stage = omni.usd.get_context().get_stage() super().setUp() # After running each test async def tearDown(self): super().tearDown() def __reset_initial_xf(self, usd_manip, initial_transform_item, prim): # Reset the initial transform to the current transform matrix = omni.usd.get_world_transform_matrix(prim) usd_manip.model.set_floats(initial_transform_item, _flatten_matrix(matrix)) # This synthesizes the start of a new event usd_manip._set_context('', prim.GetPath()) def __setup_usdmanip_tumble_test(self, prim_path: Sdf.Path): usd_manip = UsdCameraManipulator(prim_path=prim_path) usd_manip.model = CameraManipulatorModel() usd_manip._on_began(usd_manip.model) cam_prim = self.stage.GetPrimAtPath(prim_path) self.assertTrue(bool(cam_prim)) initial_transform_item = usd_manip.model.get_item('initial_transform') tumble_item = usd_manip.model.get_item('tumble') transform_item = usd_manip.model.get_item('transform') self.__reset_initial_xf(usd_manip, initial_transform_item, cam_prim) usd_manip.model.set_floats(transform_item, _flatten_matrix(Gf.Matrix4d(1))) usd_manip.on_model_updated(transform_item) return (usd_manip, cam_prim, initial_transform_item, tumble_item) async def __test_tumble_camera(self, prim_path: Sdf.Path, rotations: List[Sequence[float]], epsilon: float = 1.0e-5): (usd_manip, cam_prim, initial_transform_item, tumble_item) = self.__setup_usdmanip_tumble_test(prim_path) rotateYXZ = cam_prim.GetAttribute('xformOp:rotateYXZ') self.assertIsNotNone(rotateYXZ) cur_rot = Gf.Vec3d(rotateYXZ.Get()) self.assertTrue(Gf.IsClose(cur_rot, Gf.Vec3d(0, 0, 0), epsilon)) is_linux = sys.platform.startswith('linux') for index, rotation in enumerate(rotations): usd_manip.model.set_floats(tumble_item, [-90, 0, 0]) usd_manip.model._item_changed(tumble_item) self.__reset_initial_xf(usd_manip, initial_transform_item, cam_prim) cur_rot = Gf.Vec3d(rotateYXZ.Get()) is_equal = Gf.IsClose(cur_rot, Gf.Vec3d(rotation), epsilon) if is_equal: continue # Linux and Windows are returning different results for some rotations that are essentially equivalent is_equal = True for current, expected in zip(cur_rot, rotation): if not Gf.IsClose(current, expected, epsilon): expected = abs(expected) is_equal = (expected == 180) or (expected == 360) if not is_equal: break self.assertTrue(is_equal, msg=f"Rotation values differ: current: {cur_rot}, expected: {rotation}") async def __test_camera_YXZ_edit(self, rotations: List[Sequence[float]]): camera = UsdGeom.Camera.Define(self.stage, '/Camera') cam_prim = camera.GetPrim() cam_prim.CreateAttribute('omni:kit:centerOfInterest', Sdf.ValueTypeNames.Vector3d, True, Sdf.VariabilityUniform).Set(Gf.Vec3d(0, 0, -10)) await self.__test_tumble_camera(cam_prim.GetPath(), rotations) async def test_camera_rotate(self): '''Test rotation values in USD (with controllerUseSRT set to False)''' await self.__test_camera_YXZ_edit([ (0, -90, 0), (0, 180, 0), (0, 90, 0), (0, 0, 0) ]) async def test_camera_rotate_SRT(self): '''Test rotation accumulation in USD with controllerUseSRT set to True''' settings = carb.settings.get_settings() try: settings.set('/persistent/app/camera/controllerUseSRT', True) await self.__test_camera_YXZ_edit([ (0, -90, 0), (0, -180, 0), (0, -270, 0), (0, -360, 0) ]) finally: settings.destroy_item('/persistent/app/camera/controllerUseSRT') async def test_camera_yup_in_zup(self): '''Test Viewport rotation of a camera from a y-up layer, referenced in a z-up stage''' await omni.usd.get_context().open_stage_async(str(USD_FILES.joinpath('yup_in_zup.usda'))) self.stage = omni.usd.get_context().get_stage() await self.__test_tumble_camera(Sdf.Path('/World/yup_ref/Camera'), [ (0, -90, 0), (0, 180, 0), (0, 90, 0), (0, 0, 0) ] ) async def test_camera_zup_in_yup(self): '''Test Viewport rotation of a camera from a z-up layer, referenced in a y-up stage''' await omni.usd.get_context().open_stage_async(str(USD_FILES.joinpath('zup_in_yup.usda'))) self.stage = omni.usd.get_context().get_stage() await self.__test_tumble_camera(Sdf.Path('/World/zup_ref/Camera'), [ (0, 0, -90), (0, 0, 180), (0, 0, 90), (0, 0, 0) ] )
6,352
Python
38.216049
121
0.615712
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.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.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.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/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/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/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.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/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/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/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/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