file_path
stringlengths 21
202
| content
stringlengths 13
1.02M
| size
int64 13
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 5.43
98.5
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.91
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.tasking/docs/Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create a C++ object that uses the carb tasking system for async processing.
See also: [https://docs.omniverse.nvidia.com/kit/docs/carbonite/latest/docs/tasking/index.html](https://docs.omniverse.nvidia.com/kit/docs/carbonite/latest/docs/tasking/index.html)
# C++ Usage Examples
## Spawning Tasks
```
class ExampleTaskingExtension : public omni::ext::IExt
{
public:
void onStartup(const char* extId) override
{
// Get the tasking interface from the Carbonite Framework.
carb::tasking::ITasking* tasking = carb::getCachedInterface<carb::tasking::ITasking>();
// Add a task defined by a standalone function.
tasking->addTask(carb::tasking::Priority::eDefault, {}, &exampleStandaloneFunctionTask, this);
// Add a task defined by a member function.
tasking->addTask(carb::tasking::Priority::eDefault, {}, &ExampleTaskingExtension::exampleMemberFunctionTask, this);
// Add a task defined by a lambda function.
tasking->addTask(carb::tasking::Priority::eDefault, {}, [this] {
// Artifical wait to ensure this task finishes first.
carb::getCachedInterface<carb::tasking::ITasking>()->sleep_for(std::chrono::milliseconds(1000));
printHelloFromTask("exampleLambdaFunctionTask");
});
}
void onShutdown() override
{
std::lock_guard<carb::tasking::MutexWrapper> lock(m_helloFromTaskCountMutex);
m_helloFromTaskCount = 0;
}
void exampleMemberFunctionTask()
{
// Artifical wait to ensure this task finishes second.
carb::getCachedInterface<carb::tasking::ITasking>()->sleep_for(std::chrono::milliseconds(2000));
printHelloFromTask("exampleMemberFunctionTask");
}
void printHelloFromTask(const char* taskName)
{
std::lock_guard<carb::tasking::MutexWrapper> lock(m_helloFromTaskCountMutex);
++m_helloFromTaskCount;
printf("Hello from task: %s\n"
"%d tasks have said hello since extension startup.\n\n",
taskName, m_helloFromTaskCount);
}
private:
// We must use a fiber aware mutex: https://docs.omniverse.nvidia.com/kit/docs/carbonite/latest/docs/tasking/TaskingBestPractices.html#mutexes
carb::tasking::MutexWrapper m_helloFromTaskCountMutex;
int m_helloFromTaskCount = 0;
};
void exampleStandaloneFunctionTask(ExampleTaskingExtension* exampleTaskingExtension)
{
// Artifical wait to ensure this task finishes last.
carb::getCachedInterface<carb::tasking::ITasking>()->sleep_for(std::chrono::milliseconds(3000));
exampleTaskingExtension->printHelloFromTask("exampleStandaloneFunctionTask");
}
```
| 2,800 | Markdown | 36.346666 | 180 | 0.702143 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt_mesh/README.md | # omni.example.python.usdrt_mesh
Example Kit extension that demonstrates how to use USDRT to create, update, and delete a UsdGeom.Mesh prim.
## Usage
### Windows
```bash
.\build.bat
.\_build\windows-x86_64\release\kit\kit.exe .\source\apps\omni.app.kit.dev.kit --enable omni.example.python.usdrt_mesh --ext-folder source\extensions --/app/useFabricSceneDelegate=true
```
### Linux
```bash
./build.sh
./_build/linux-x86_64/release/kit/kit ./source/apps/omni.app.kit.dev.kit --enable omni.example.python.usdrt_mesh --ext-folder source/extensions --/app/useFabricSceneDelegate=true
```
| 589 | Markdown | 28.499999 | 184 | 0.743633 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt_mesh/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "0.0.1"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["Justin Shrake <[email protected]>"]
# The title and description fields are primarily for displaying extension info in UI
title = "Example Python Extension: USDRT Mesh"
description="Example Kit extension that demonstrates how to create, update, and delete a USDRT Mesh"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp"
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example", "usdrt", "scenegraph", "fabric"]
# 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 and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Extension dependencies
[dependencies]
"omni.kit.uiapp" = {}
"usdrt.scenegraph" = {}
"omni.usd" = {}
"omni.kit.primitive.mesh" = {}
"omni.warp" = { optional = true }
# Main python module this extension provides
[[python.module]]
name = "omni.example.python.usdrt_mesh"
[[test]]
waiver = "Just example code, not for production"
#TODO
# Define the documentation that will be generated for this extension.
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
] | 1,856 | TOML | 32.160714 | 118 | 0.738685 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt_mesh/omni/example/python/usdrt_mesh/__init__.py | from .example_python_usdrt_mesh_extension import *
| 51 | Python | 24.999988 | 50 | 0.803922 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt_mesh/omni/example/python/usdrt_mesh/example_python_usdrt_mesh_extension.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import carb
import carb.events
import numpy as np
import omni.ext
import omni.kit.app
import omni.ui
import omni.usd
import usdrt
PLANE_SUBDIV = 32
PLANE_EXTENT = 50
PLANE_HEIGHT = 10
PRIM_PATH = f"/World/Plane{PLANE_SUBDIV}x{PLANE_SUBDIV}"
class ExamplePythonUsdrtMeshExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self.sub = None
self.step = 0
self.playing = False
self.init_ui()
def on_shutdown(self):
if self.sub:
self.sub.unsubscribe()
self.sub = None
self.step = 0
self.playing = False
def init_ui(self):
def create_mesh():
stage = get_usdrt_stage()
create_mesh_usdrt(stage, PRIM_PATH, PLANE_SUBDIV, PLANE_SUBDIV)
def delete_mesh():
stage = get_usdrt_stage()
delete_prim_usdrt(stage, PRIM_PATH)
def toggle_update_mesh():
self.playing = not self.playing
if not self.sub:
self.init_on_update()
def toggle_mesh_visibility():
stage = get_usdrt_stage()
prim = stage.GetPrimAtPath(PRIM_PATH)
attr = prim.GetAttribute("_worldVisibility")
val = attr.Get()
attr.Set(not val)
return
def save_stage_to_file():
stage = get_usdrt_stage()
stage.WriteToLayer("example_python_usdrt_mesh_example.usda")
return
self.window = omni.ui.Window("omni.example.python.usdrt_mesh", width=300, height=300)
style = {
# "color": omni.ui.color.WHITE,
# "background_color": omni.ui.color.BLACK,
}
self.window.frame.style = style
with self.window.frame:
with omni.ui.VStack():
with omni.ui.HStack():
omni.ui.Button("Create Plane").set_clicked_fn(create_mesh)
omni.ui.Button("Delete Plane").set_clicked_fn(delete_mesh)
with omni.ui.HStack():
omni.ui.Button("Toggle Update").set_clicked_fn(toggle_update_mesh)
omni.ui.Button("Toggle Visibility").set_clicked_fn(toggle_mesh_visibility)
omni.ui.Button("Save").set_clicked_fn(save_stage_to_file)
def init_on_update(self):
@carb.profiler.profile(zone_name="omni.example.python.usdrt_mesh.on_update")
def on_update(e: carb.events.IEvent):
if not self.playing:
return
try:
stage = get_usdrt_stage()
self.step += 1
update_mesh_usdrt(stage, PRIM_PATH, PLANE_SUBDIV, PLANE_SUBDIV, self.step)
except Exception as e:
carb.log_error(e)
return
update_stream = omni.kit.app.get_app().get_update_event_stream()
self.sub = update_stream.create_subscription_to_pop(on_update, name="omni.example.python.usdrt_mesh.on_update")
return
def get_usdrt_stage() -> usdrt.Usd.Stage:
ctx = omni.usd.get_context()
stage = usdrt.Usd.Stage.Attach(ctx.get_stage_id())
return stage
def create_mesh_usdrt(stage: usdrt.Usd.Stage, prim_path: str, num_x_divisions: int, num_z_divisions: int):
mesh = usdrt.UsdGeom.Mesh.Define(stage, prim_path)
# Create the vertices and face counts
vertices = calculate_mesh_vertices(num_x_divisions, num_z_divisions, 0)
face_vertex_counts = []
face_vertex_indices = []
for z in range(num_z_divisions):
for x in range(num_x_divisions):
vertex0 = z * (num_x_divisions + 1) + x
vertex1 = vertex0 + 1
vertex2 = (z + 1) * (num_x_divisions + 1) + x
vertex3 = vertex2 + 1
face_vertex_counts.append(4)
face_vertex_indices.extend([vertex0, vertex1, vertex3, vertex2])
# Set the mesh data
mesh.CreatePointsAttr().Set(usdrt.Vt.Vec3fArray(vertices))
mesh.CreateFaceVertexCountsAttr().Set(usdrt.Vt.IntArray(face_vertex_counts))
mesh.CreateFaceVertexIndicesAttr().Set(usdrt.Vt.IntArray(face_vertex_indices))
prim = mesh.GetPrim()
# Visibility Attribute
attr = prim.CreateAttribute("_worldVisibility", usdrt.Sdf.ValueTypeNames.Bool, True)
attr.Set(True)
# Set the xform
xformable = usdrt.Rt.Xformable(prim)
xformable.CreateWorldPositionAttr(usdrt.Gf.Vec3d(0.0, 0.0, 0.0))
xformable.CreateWorldScaleAttr(usdrt.Gf.Vec3f(1.0, 1.0, 1.0))
xformable.CreateWorldOrientationAttr(usdrt.Gf.Quatf(0.0, 0.0, 0.0, 1.0))
# Set the extents
bound = usdrt.Rt.Boundable(prim)
world_ext = bound.CreateWorldExtentAttr()
world_ext.Set(
usdrt.Gf.Range3d(
usdrt.Gf.Vec3d(-PLANE_EXTENT, -PLANE_EXTENT, -PLANE_EXTENT),
usdrt.Gf.Vec3d(PLANE_EXTENT, PLANE_EXTENT, PLANE_EXTENT),
)
)
return mesh
def delete_prim_usdrt(stage: usdrt.Usd.Stage, prim_path: str):
stage.RemovePrim(prim_path)
return
def update_mesh_usdrt(stage: usdrt.Usd.Stage, prim_path: str, num_x_divisions: int, num_z_divisions: int, step: int):
# Find the prim
prim = stage.GetPrimAtPath(prim_path)
if not prim.IsValid():
carb.log_verbose(f"Prim at '{prim_path}' is invalid")
return
vertices = calculate_mesh_vertices(num_x_divisions, num_z_divisions, step)
# Set the mesh data
mesh = usdrt.UsdGeom.Mesh(prim)
mesh.CreateVisibilityAttr().Set(True)
mesh.GetPointsAttr().Set(usdrt.Vt.Vec3fArray(vertices))
return mesh
def calculate_mesh_vertices(num_x_divisions: int, num_z_divisions: int, step: int) -> [float]:
x_positions = np.linspace(-PLANE_EXTENT, PLANE_EXTENT, num_x_divisions + 1)
z_positions = np.linspace(-PLANE_EXTENT, PLANE_EXTENT, num_z_divisions + 1)
x_grid, z_grid = np.meshgrid(x_positions, z_positions)
tau = 6.28318
s = 100.0
t = step / s
sx = tau / s
sz = tau / s
y_grid = PLANE_HEIGHT * (np.cos(sx * x_grid + t) + np.sin(sz * z_grid + t))
vertices = np.column_stack((x_grid.flatten(), y_grid.flatten(), z_grid.flatten()))
return vertices.tolist()
| 6,531 | Python | 34.118279 | 119 | 0.62456 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt_mesh/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.1.0] - 2023-12-01
- Initial version
| 137 | Markdown | 18.714283 | 80 | 0.678832 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt_mesh/docs/Overview.md | # USDRT UsdGeom.Mesh Example [omni.example.python.usdrt_mesh]
Example Kit extension that demonstrates how to use USDRT to create, update, and delete a UsdGeom.Mesh prim. Specifically:
- How to create a Usdrt.UsdGeom.Mesh
- How to delete a Usdrt prim
- How to update the vertex buffer data
- How to toggle the mesh visbility
- How to save the Usdrt stage to disk
| 364 | Markdown | 35.499996 | 121 | 0.774725 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.hello_world/config/extension.toml | [package]
version = "1.0.0" # Semantic Versioning is used: https://semver.org/
# These fields are used primarily for display in the extension browser UI.
title = "Example Python Extension: Hello World"
description = "Demonstrates how to create a Python module that will startup / shutdown along with the extension."
category = "Example"
keywords = ["example"]
icon = "data/icon.png"
preview_image = "data/preview.png"
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
authors = ["Anton Novoselov <[email protected]>", "David Bosnich <[email protected]>"]
repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp"
# Define the Python modules that this extension provides.
[[python.module]]
name = "omni.example.python.hello_world"
# Define the documentation that will be generated for this extension.
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 915 | TOML | 34.230768 | 113 | 0.744262 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.hello_world/omni/example/python/hello_world/hello_world_extension.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.ext
# Functions and variables are available to other extensions which import this module.
def hello_from(caller: str):
print(f"[omni.example.python.hello_world] hello_from was called from {caller}.")
return "Hello back from omni.example.python.hello_world!"
def hello_squared(x: int):
print(f"[omni.example.python.hello_world] hello_squared was called with {x}.")
return x**x
# When this extension is enabled, any class that derives from 'omni.ext.IExt'
# declared in the top level module (see 'python.modules' of 'extension.toml')
# will be instantiated and 'on_startup(ext_id)' called. When the extension is
# later disabled, a matching 'on_shutdown()' call will be made on the object.
class ExamplePythonHelloWorldExtension(omni.ext.IExt):
# ext_id can be used to query the extension manager for additional information about
# this extension, for example the location of this extension in the local filesystem.
def on_startup(self, ext_id):
print(f"ExamplePythonHelloWorldExtension starting up (ext_id: {ext_id}).")
def on_shutdown(self):
print(f"ExamplePythonHelloWorldExtension shutting down.")
| 1,604 | Python | 43.583332 | 89 | 0.754364 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.hello_world/omni/example/python/hello_world/tests/test_hello_world.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.
##
# omni.kit.test is primarily Python's standard unittest module
# with additional wrapping to add suport for async/await tests.
# Please see: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# The Python module we are testing, imported with an absolute
# path to simulate using it from a different Python extension.
import omni.example.python.hello_world
# Any class that dervives from 'omni.kit.test.AsyncTestCase'
# declared at the root of the module will be auto-discovered,
class ExamplePythonHelloWorldTest(omni.kit.test.AsyncTestCase):
# Called before running each test.
async def setUp(self):
pass
# Called after running each test.
async def tearDown(self):
pass
# Example test case (notice it is an 'async' function, so 'await' can be used if needed).
async def test_hello_from(self):
result = omni.example.python.hello_world.hello_from("test_hello_world")
self.assertEqual(result, "Hello back from omni.example.python.hello_world!")
# Example test case (notice it is an 'async' function, so 'await' can be used if needed).
async def test_hello_squared(self):
result = omni.example.python.hello_world.hello_squared(4)
self.assertEqual(result, 256)
| 1,698 | Python | 41.474999 | 93 | 0.743227 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.hello_world/docs/CHANGELOG.md | # Changelog
## [1.0.0] - 2022-06-30
### Added
- Initial implementation.
| 73 | Markdown | 11.333331 | 25 | 0.630137 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.hello_world/docs/Overview.md | # Overview
An example Python extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create a Python module that will startup / shutdown along with the extension.
Also demonstrates how to expose Python functions so that they can be called from other extensions.
# Python Usage Examples
## Defining Extensions
```
# When this extension is enabled, any class that derives from 'omni.ext.IExt'
# declared in the top level module (see 'python.modules' of 'extension.toml')
# will be instantiated and 'on_startup(ext_id)' called. When the extension is
# later disabled, a matching 'on_shutdown()' call will be made on the object.
class ExamplePythonHelloWorldExtension(omni.ext.IExt):
# ext_id can be used to query the extension manager for additional information about
# this extension, for example the location of this extension in the local filesystem.
def on_startup(self, ext_id):
print(f"ExamplePythonHelloWorldExtension starting up (ext_id: {ext_id}).")
def on_shutdown(self):
print(f"ExamplePythonHelloWorldExtension shutting down.")
```
| 1,129 | Markdown | 34.312499 | 98 | 0.756422 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd/python/tests/test_usd_example.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import omni.usd
import omni.example.cpp.usd
class TestUsdExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
# Cache the example usd interface.
self.example_usd_interface = omni.example.cpp.usd.get_example_usd_interface()
# Open a new USD stage.
omni.usd.get_context().new_stage()
self.usd_stage = omni.usd.get_context().get_stage()
async def tearDown(self):
# Close the USD stage.
await omni.usd.get_context().close_stage_async()
self.usd_stage = None
# Clear the example usd interface.
self.example_usd_interface = None
async def test_create_prims(self):
self.example_usd_interface.create_prims()
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_0"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_1"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_2"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_3"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_4"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_5"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_6"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_7"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_8"))
self.assertFalse(self.usd_stage.GetPrimAtPath("/World/a_random_prim"))
| 1,982 | Python | 43.066666 | 85 | 0.709384 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd/python/impl/example_usd_extension.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.ext
import omni.usd
from .._example_usd_bindings import *
# Global public interface object.
_example_usd_interface = None
# Public API.
def get_example_usd_interface() -> IExampleUsdInterface:
return _example_usd_interface
# Use the extension entry points to acquire and release the interface,
# and to subscribe to usd stage events.
class ExampleUsdExtension(omni.ext.IExt):
def on_startup(self):
# Acquire the example USD interface.
global _example_usd_interface
_example_usd_interface = acquire_example_usd_interface()
# Inform the C++ plugin if a USD stage is already open.
usd_context = omni.usd.get_context()
if usd_context.get_stage_state() == omni.usd.StageState.OPENED:
_example_usd_interface.on_default_usd_stage_changed(usd_context.get_stage_id())
# Subscribe to omni.usd stage events so we can inform the C++ plugin when a new stage opens.
self._stage_event_sub = usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="omni.example.cpp.usd"
)
# Print some info about the stage from C++.
_example_usd_interface.print_stage_info()
# Create some example prims from C++.
_example_usd_interface.create_prims()
# Print some info about the stage from C++.
_example_usd_interface.print_stage_info()
# Animate the example prims from C++.
_example_usd_interface.start_timeline_animation()
def on_shutdown(self):
global _example_usd_interface
# Stop animating the example prims from C++.
_example_usd_interface.stop_timeline_animation()
# Remove the example prims from C++.
_example_usd_interface.remove_prims()
# Unsubscribe from omni.usd stage events.
self._stage_event_sub = None
# Release the example USD interface.
release_example_usd_interface(_example_usd_interface)
_example_usd_interface = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.OPENED):
_example_usd_interface.on_default_usd_stage_changed(omni.usd.get_context().get_stage_id())
elif event.type == int(omni.usd.StageEventType.CLOSED):
_example_usd_interface.on_default_usd_stage_changed(0)
| 2,793 | Python | 37.805555 | 102 | 0.686359 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd/bindings/python/omni.example.cpp.usd/ExampleUsdBindings.cpp | // 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.
//
#include <carb/BindingsPythonUtils.h>
#include <omni/example/cpp/usd/IExampleUsdInterface.h>
CARB_BINDINGS("omni.example.cpp.usd.python")
DISABLE_PYBIND11_DYNAMIC_CAST(omni::example::cpp::usd::IExampleUsdInterface)
namespace
{
// Define the pybind11 module using the same name specified in premake5.lua
PYBIND11_MODULE(_example_usd_bindings, m)
{
using namespace omni::example::cpp::usd;
m.doc() = "pybind11 omni.example.cpp.usd bindings";
carb::defineInterfaceClass<IExampleUsdInterface>(
m, "IExampleUsdInterface", "acquire_example_usd_interface", "release_example_usd_interface")
.def("create_prims", &IExampleUsdInterface::createPrims)
.def("remove_prims", &IExampleUsdInterface::removePrims)
.def("print_stage_info", &IExampleUsdInterface::printStageInfo)
.def("start_timeline_animation", &IExampleUsdInterface::startTimelineAnimation)
.def("stop_timeline_animation", &IExampleUsdInterface::stopTimelineAnimation)
.def("on_default_usd_stage_changed", &IExampleUsdInterface::onDefaultUsdStageChanged)
/**/;
}
}
| 1,530 | C++ | 38.256409 | 100 | 0.752941 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd/include/omni/example/cpp/usd/IExampleUsdInterface.h | // 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.
//
#pragma once
#include <carb/Interface.h>
namespace omni
{
namespace example
{
namespace cpp
{
namespace usd
{
/**
* Interface used to interact with the example C++ USD plugin from Python.
*/
class IExampleUsdInterface
{
public:
/// @private
CARB_PLUGIN_INTERFACE("omni::example::cpp::usd::IExampleUsdInterface", 1, 0);
/**
* Creates some example prims using C++.
*/
virtual void createPrims() = 0;
/**
* Remove the example prims using C++.
*/
virtual void removePrims() = 0;
/**
* Print some info about the currently open USD stage from C++.
*/
virtual void printStageInfo() const = 0;
/**
* Start animating the example prims using the timeline.
*/
virtual void startTimelineAnimation() = 0;
/**
* Stop animating the example prims using the timeline.
*/
virtual void stopTimelineAnimation() = 0;
/**
* Called when the default USD stage (ie. the one open in the main viewport) changes.
* Necessary for now until the omni.usd C++ API becomes ready for public consumption.
*
* @param stageId The id of the new default USD stage.
*/
virtual void onDefaultUsdStageChanged(long stageId) = 0;
};
}
}
}
}
| 1,675 | C | 23.289855 | 89 | 0.678209 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd/plugins/omni.example.cpp.usd/ExampleUsdExtension.cpp | // 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.
//
#define CARB_EXPORTS
#include <carb/PluginUtils.h>
#include <omni/example/cpp/usd/IExampleUsdInterface.h>
#include <omni/ext/ExtensionsUtils.h>
#include <omni/ext/IExt.h>
#include <omni/kit/IApp.h>
#include <omni/timeline/ITimeline.h>
#include <omni/timeline/TimelineTypes.h>
#include <pxr/usd/usd/notice.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/stageCache.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usdGeom/metrics.h>
#include <pxr/usd/usdGeom/xform.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <vector>
const struct carb::PluginImplDesc pluginImplDesc = { "omni.example.cpp.usd.plugin",
"An example C++ extension.", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
namespace omni
{
namespace example
{
namespace cpp
{
namespace usd
{
class ExampleCppUsdExtension : public IExampleUsdInterface
, public PXR_NS::TfWeakBase
{
protected:
void createPrims() override
{
// It is important that all USD stage reads/writes happen from the main thread:
// https ://graphics.pixar.com/usd/release/api/_usd__page__multi_threading.html
if (!m_stage)
{
return;
}
constexpr int numPrimsToCreate = 9;
const float rotationIncrement = 360.0f / (numPrimsToCreate - 1);
for (int i = 0; i < numPrimsToCreate; ++i)
{
// Create a cube prim.
const PXR_NS::SdfPath primPath("/World/example_prim_" + std::to_string(i));
if (m_stage->GetPrimAtPath(primPath))
{
// A prim already exists at this path.
continue;
}
PXR_NS::UsdPrim prim = m_stage->DefinePrim(primPath, PXR_NS::TfToken("Cube"));
// Set the size of the cube prim.
const double cubeSize = 0.5 / PXR_NS::UsdGeomGetStageMetersPerUnit(m_stage);
prim.CreateAttribute(PXR_NS::TfToken("size"), PXR_NS::SdfValueTypeNames->Double).Set(cubeSize);
// Leave the first prim at the origin and position the rest in a circle surrounding it.
if (i == 0)
{
m_primsWithRotationOps.push_back({ prim });
}
else
{
PXR_NS::UsdGeomXformable xformable = PXR_NS::UsdGeomXformable(prim);
// Setup the global rotation operation.
const float initialRotation = rotationIncrement * static_cast<float>(i);
PXR_NS::UsdGeomXformOp globalRotationOp = xformable.AddRotateYOp(PXR_NS::UsdGeomXformOp::PrecisionFloat);
globalRotationOp.Set(initialRotation);
// Setup the translation operation.
const PXR_NS::GfVec3f translation(0.0f, 0.0f, cubeSize * 4.0f);
xformable.AddTranslateOp(PXR_NS::UsdGeomXformOp::PrecisionFloat).Set(translation);
// Setup the local rotation operation.
PXR_NS::UsdGeomXformOp localRotationOp = xformable.AddRotateXOp(PXR_NS::UsdGeomXformOp::PrecisionFloat);
localRotationOp.Set(initialRotation);
// Store the prim and rotation ops so we can update them later in animatePrims().
m_primsWithRotationOps.push_back({ prim, localRotationOp, globalRotationOp });
}
}
// Subscribe to timeline events so we know when to start or stop animating the prims.
if (auto timeline = omni::timeline::getTimeline())
{
m_timelineEventsSubscription = carb::events::createSubscriptionToPop(
timeline->getTimelineEventStream(),
[this](carb::events::IEvent* timelineEvent) {
onTimelineEvent(static_cast<omni::timeline::TimelineEventType>(timelineEvent->type));
});
}
}
void removePrims() override
{
if (!m_stage)
{
return;
}
// Release all event subscriptions.
PXR_NS::TfNotice::Revoke(m_usdNoticeListenerKey);
m_timelineEventsSubscription = nullptr;
m_updateEventsSubscription = nullptr;
// Remove all prims.
for (auto& primWithRotationOps : m_primsWithRotationOps)
{
m_stage->RemovePrim(primWithRotationOps.m_prim.GetPath());
}
m_primsWithRotationOps.clear();
}
void printStageInfo() const override
{
if (!m_stage)
{
return;
}
printf("---Stage Info Begin---\n");
// Print the USD stage's up-axis.
const PXR_NS::TfToken stageUpAxis = PXR_NS::UsdGeomGetStageUpAxis(m_stage);
printf("Stage up-axis is: %s.\n", stageUpAxis.GetText());
// Print the USD stage's meters per unit.
const double metersPerUnit = PXR_NS::UsdGeomGetStageMetersPerUnit(m_stage);
printf("Stage meters per unit: %f.\n", metersPerUnit);
// Print the USD stage's prims.
const PXR_NS::UsdPrimRange primRange = m_stage->Traverse();
for (const PXR_NS::UsdPrim& prim : primRange)
{
printf("Stage contains prim: %s.\n", prim.GetPath().GetString().c_str());
}
printf("---Stage Info End---\n\n");
}
void startTimelineAnimation() override
{
if (auto timeline = omni::timeline::getTimeline())
{
timeline->play();
}
}
void stopTimelineAnimation() override
{
if (auto timeline = omni::timeline::getTimeline())
{
timeline->stop();
}
}
void onDefaultUsdStageChanged(long stageId) override
{
PXR_NS::TfNotice::Revoke(m_usdNoticeListenerKey);
m_timelineEventsSubscription = nullptr;
m_updateEventsSubscription = nullptr;
m_primsWithRotationOps.clear();
m_stage.Reset();
if (stageId)
{
m_stage = PXR_NS::UsdUtilsStageCache::Get().Find(PXR_NS::UsdStageCache::Id::FromLongInt(stageId));
m_usdNoticeListenerKey = PXR_NS::TfNotice::Register(PXR_NS::TfCreateWeakPtr(this), &ExampleCppUsdExtension::onObjectsChanged);
}
}
void onObjectsChanged(const PXR_NS::UsdNotice::ObjectsChanged& objectsChanged)
{
// Check whether any of the prims we created have been (potentially) invalidated.
// This may be too broad a check, but handles prims being removed from the stage.
for (auto& primWithRotationOps : m_primsWithRotationOps)
{
if (!primWithRotationOps.m_invalid &&
objectsChanged.ResyncedObject(primWithRotationOps.m_prim))
{
primWithRotationOps.m_invalid = true;
}
}
}
void onTimelineEvent(omni::timeline::TimelineEventType timelineEventType)
{
switch (timelineEventType)
{
case omni::timeline::TimelineEventType::ePlay:
{
startAnimatingPrims();
}
break;
case omni::timeline::TimelineEventType::eStop:
{
stopAnimatingPrims();
}
break;
default:
{
}
break;
}
}
void startAnimatingPrims()
{
if (m_updateEventsSubscription)
{
// We're already animating the prims.
return;
}
// Subscribe to update events so we can animate the prims.
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
m_updateEventsSubscription = carb::events::createSubscriptionToPop(app->getUpdateEventStream(), [this](carb::events::IEvent*)
{
onUpdateEvent();
});
}
}
void stopAnimatingPrims()
{
m_updateEventsSubscription = nullptr;
onUpdateEvent(); // Reset positions.
}
void onUpdateEvent()
{
// It is important that all USD stage reads/writes happen from the main thread:
// https ://graphics.pixar.com/usd/release/api/_usd__page__multi_threading.html
if (!m_stage)
{
return;
}
// Update the value of each local and global rotation operation to (crudely) animate the prims around the origin.
const size_t numPrims = m_primsWithRotationOps.size();
const float initialLocalRotationIncrement = 360.0f / (numPrims - 1); // Ignore the first prim at the origin.
const float initialGlobalRotationIncrement = 360.0f / (numPrims - 1); // Ignore the first prim at the origin.
const float currentAnimTime = omni::timeline::getTimeline()->getCurrentTime() * m_stage->GetTimeCodesPerSecond();
for (size_t i = 1; i < numPrims; ++i) // Ignore the first prim at the origin.
{
if (m_primsWithRotationOps[i].m_invalid)
{
continue;
}
PXR_NS::UsdGeomXformOp& localRotationOp = m_primsWithRotationOps[i].m_localRotationOp;
const float initialLocalRotation = initialLocalRotationIncrement * static_cast<float>(i);
const float currentLocalRotation = initialLocalRotation + (360.0f * (currentAnimTime / 100.0f));
localRotationOp.Set(currentLocalRotation);
PXR_NS::UsdGeomXformOp& globalRotationOp = m_primsWithRotationOps[i].m_globalRotationOp;
const float initialGlobalRotation = initialGlobalRotationIncrement * static_cast<float>(i);
const float currentGlobalRotation = initialGlobalRotation - (360.0f * (currentAnimTime / 100.0f));
globalRotationOp.Set(currentGlobalRotation);
}
}
private:
struct PrimWithRotationOps
{
PXR_NS::UsdPrim m_prim;
PXR_NS::UsdGeomXformOp m_localRotationOp;
PXR_NS::UsdGeomXformOp m_globalRotationOp;
bool m_invalid = false;
};
PXR_NS::UsdStageRefPtr m_stage;
PXR_NS::TfNotice::Key m_usdNoticeListenerKey;
std::vector<PrimWithRotationOps> m_primsWithRotationOps;
carb::events::ISubscriptionPtr m_updateEventsSubscription;
carb::events::ISubscriptionPtr m_timelineEventsSubscription;
};
}
}
}
}
CARB_PLUGIN_IMPL(pluginImplDesc, omni::example::cpp::usd::ExampleCppUsdExtension)
void fillInterface(omni::example::cpp::usd::ExampleCppUsdExtension& iface)
{
}
| 10,791 | C++ | 33.925566 | 138 | 0.61505 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd/docs/CHANGELOG.md | # Changelog
## [1.0.1] - 2023-04-27
### Updated
- Build against Kit 105.0
## [1.0.0] - 2022-07-07
### Added
- Initial implementation.
| 136 | Markdown | 12.699999 | 25 | 0.610294 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd/docs/Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create a C++ plugin that can interact with the current USD stage by:
- Subscribing to USD stage events from Python.
- Sending the current USD stage id to C++.
- Storing a reference to the USD stage in C++.
- Adding some prims to the USD stage from C++.
- Animating the USD prims each update from C++.
- Printing information about the USD stage from C++.
Note: It is important that all USD stage reads/writes happen from the main thread:
[https://graphics.pixar.com/usd/release/api/_usd__page__multi_threading.html](https://graphics.pixar.com/usd/release/api/_usd__page__multi_threading.html)
# Example

| 775 | Markdown | 32.739129 | 154 | 0.750968 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.hello_world/config/extension.toml | [package]
version = "1.0.0" # Semantic Versioning is used: https://semver.org/
# These fields are used primarily for display in the extension browser UI.
title = "Example C++ Extension: Hello World"
description = "Demonstrates how to create a C++ object that will startup / shutdown along with the extension."
category = "Example"
keywords = ["example", "C++", "cpp"]
icon = "data/icon.png"
preview_image = "data/preview.png"
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
authors = ["Anton Novoselov <[email protected]>", "David Bosnich <[email protected]>"]
repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp"
# Define the Python modules that this extension provides.
# C++ only extensions need this just so tests don't fail.
[[python.module]]
name = "omni.example.cpp.hello_world"
# Define the C++ plugins that this extension provides.
[[native.plugin]]
path = "bin/*.plugin"
# Define the documentation that will be generated for this extension.
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 1,074 | TOML | 33.677418 | 110 | 0.727188 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.hello_world/plugins/omni.example.cpp.hello_world/HelloWorldExtension.cpp | // 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.
//
#define CARB_EXPORTS
#include <carb/PluginUtils.h>
#include <omni/ext/IExt.h>
#include <omni/kit/IApp.h>
const struct carb::PluginImplDesc pluginImplDesc = { "omni.example.cpp.hello_world.plugin",
"An example C++ extension.", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
CARB_PLUGIN_IMPL_DEPS(omni::kit::IApp)
namespace omni
{
namespace example
{
namespace cpp
{
namespace hello_world
{
// When this extension is enabled, any class that derives from omni.ext.IExt
// will be instantiated and 'onStartup(extId)' called. When the extension is
// later disabled, a matching 'onShutdown()' call will be made on the object.
class ExampleCppHelloWorldExtension : public omni::ext::IExt
{
public:
void onStartup(const char* extId) override
{
printf("ExampleCppHelloWorldExtension starting up (ext_id: %s).\n", extId);
// Get the app interface from the Carbonite Framework.
if (omni::kit::IApp* app = carb::getFramework()->acquireInterface<omni::kit::IApp>())
{
// Subscribe to update events.
m_updateEventsSubscription =
carb::events::createSubscriptionToPop(app->getUpdateEventStream(), [this](carb::events::IEvent*) {
onUpdate();
});
}
}
void onShutdown() override
{
printf("ExampleCppHelloWorldExtension shutting down.\n");
// Unsubscribe from update events.
m_updateEventsSubscription = nullptr;
}
void onUpdate()
{
if (m_updateCounter % 1000 == 0)
{
printf("Hello from the omni.example.cpp.hello_world extension! %d updates counted.\n", m_updateCounter);
}
m_updateCounter++;
}
private:
carb::events::ISubscriptionPtr m_updateEventsSubscription;
int m_updateCounter = 0;
};
}
}
}
}
CARB_PLUGIN_IMPL(pluginImplDesc, omni::example::cpp::hello_world::ExampleCppHelloWorldExtension)
void fillInterface(omni::example::cpp::hello_world::ExampleCppHelloWorldExtension& iface)
{
}
| 2,554 | C++ | 29.058823 | 116 | 0.661316 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.hello_world/docs/Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create a C++ object that will startup / shutdown along with the extension.
# C++ Usage Examples
## Defining Extensions
```
// When this extension is enabled, any class that derives from omni.ext.IExt
// will be instantiated and 'onStartup(extId)' called. When the extension is
// later disabled, a matching 'onShutdown()' call will be made on the object.
class ExampleCppHelloWorldExtension : public omni::ext::IExt
{
public:
void onStartup(const char* extId) override
{
printf("ExampleCppHelloWorldExtension starting up (ext_id: %s).\n", extId);
if (omni::kit::IApp* app = carb::getFramework()->acquireInterface<omni::kit::IApp>())
{
// Subscribe to update events.
m_updateEventsSubscription =
carb::events::createSubscriptionToPop(app->getUpdateEventStream(), [this](carb::events::IEvent*) {
onUpdate();
});
}
}
void onShutdown() override
{
printf("ExampleCppHelloWorldExtension shutting down.\n");
// Unsubscribe from update events.
m_updateEventsSubscription = nullptr;
}
void onUpdate()
{
if (m_updateCounter % 1000 == 0)
{
printf("Hello from the omni.example.cpp.hello_world extension! %d updates counted.\n", m_updateCounter);
}
m_updateCounter++;
}
private:
carb::events::ISubscriptionPtr m_updateEventsSubscription;
int m_updateCounter = 0;
};
```
| 1,609 | Markdown | 26.75862 | 116 | 0.646364 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt/omni/example/python/usdrt/example_python_usdrt_extension.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import math
import random
from ctypes import alignment
import omni.ext
import omni.ui as ui
import omni.usd
from usdrt import Gf, Rt, Sdf, Usd, Vt
try:
wp = None
import warp as wp
wp.init()
@wp.kernel
def deform(positions: wp.array(dtype=wp.vec3), t: float):
tid = wp.tid()
x = positions[tid]
offset = -wp.sin(x[0])
scale = wp.sin(t) * 10.0
x = x + wp.vec3(0.0, offset * scale, 0.0)
positions[tid] = x
except ImportError:
pass
def get_selected_prim_path():
"""Return the path of the first selected prim"""
context = omni.usd.get_context()
selection = context.get_selection()
paths = selection.get_selected_prim_paths()
return None if not paths else paths[0]
def get_stage_id():
"""Return the stage Id of the current stage"""
context = omni.usd.get_context()
return context.get_stage_id()
def is_vtarray(obj):
"""Check if this is a VtArray type
In Python, each data type gets its own
VtArray class i.e. Vt.Float3Array etc.
so this helper identifies any of them.
"""
return hasattr(obj, "IsFabricData")
def condensed_vtarray_str(data):
"""Return a string representing VtArray data
Include at most 6 values, and the total items
in the array
"""
size = len(data)
if size > 6:
datastr = "[{}, {}, {}, .. {}, {}, {}] (size: {})".format(
data[0], data[1], data[2], data[-3], data[-2], data[-1], size
)
else:
datastr = "["
for i in range(size - 1):
datastr += str(data[i]) + ", "
datastr += str(data[-1]) + "]"
return datastr
def get_fabric_data_for_prim(stage_id, path):
"""Get the Fabric data for a path as a string"""
if path is None:
return "Nothing selected"
stage = Usd.Stage.Attach(stage_id)
# If a prim does not already exist in Fabric,
# it will be fetched from USD by simply creating the
# Usd.Prim object. At this time, only the attributes that have
# authored opinions will be fetch into Fabric.
prim = stage.GetPrimAtPath(Sdf.Path(path))
if not prim:
return f"Prim at path {path} is not in Fabric"
# This diverges a bit from USD - only attributes
# that exist in Fabric are returned by this API
attrs = prim.GetAttributes()
result = f"Fabric data for prim at path {path}\n\n\n"
for attr in attrs:
try:
data = attr.Get()
datastr = str(data)
if data is None:
datastr = "<no value>"
elif is_vtarray(data):
datastr = condensed_vtarray_str(data)
except TypeError:
# Some data types not yet supported in Python
datastr = "<no Python conversion>"
result += "{} ({}): {}\n".format(attr.GetName(), str(attr.GetTypeName().GetAsToken()), datastr)
return result
def apply_random_rotation(stage_id, path):
"""Apply a random world space rotation to a prim in Fabric"""
if path is None:
return "Nothing selected"
stage = Usd.Stage.Attach(stage_id)
prim = stage.GetPrimAtPath(Sdf.Path(path))
if not prim:
return f"Prim at path {path} is not in Fabric"
rtxformable = Rt.Xformable(prim)
if not rtxformable.HasWorldXform():
rtxformable.SetWorldXformFromUsd()
angle = random.random() * math.pi * 2
axis = Gf.Vec3f(random.random(), random.random(), random.random()).GetNormalized()
halfangle = angle / 2.0
shalfangle = math.sin(halfangle)
rotation = Gf.Quatf(math.cos(halfangle), axis[0] * shalfangle, axis[1] * shalfangle, axis[2] * shalfangle)
rtxformable.GetWorldOrientationAttr().Set(rotation)
return f"Set new world orientation on {path} to {rotation}"
def deform_mesh_with_warp(stage_id, path, time):
"""Use Warp to deform a Mesh prim"""
if path is None:
return "Nothing selected"
stage = Usd.Stage.Attach(stage_id)
prim = stage.GetPrimAtPath(Sdf.Path(path))
if not prim:
return f"Prim at path {path} is not in Fabric"
if not prim.HasAttribute("points"):
return f"Prim at path {path} does not have points attribute"
if not wp:
return "Warp failed to initialize. Install/Load the warp extension."
# Tell OmniHydra to render points from Fabric
if not prim.HasAttribute("Deformable"):
prim.CreateAttribute("Deformable", Sdf.ValueTypeNames.PrimTypeTag, True)
points = prim.GetAttribute("points")
pointsarray = points.Get()
warparray = wp.array(pointsarray, dtype=wp.vec3, device="cuda")
wp.launch(kernel=deform, dim=len(pointsarray), inputs=[warparray, time], device="cuda")
points.Set(Vt.Vec3fArray(warparray.numpy()))
return f"Deformed points on prim {path}"
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class UsdrtExamplePythonExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[omni.example.python.usdrt] startup")
self._window = ui.Window(
"What's in Fabric?", width=300, height=300, dockPreference=ui.DockPreference.RIGHT_BOTTOM
)
self._t = 0
with self._window.frame:
with ui.VStack():
frame = ui.ScrollingFrame()
with frame:
label = ui.Label("Select a prim and push a button", alignment=ui.Alignment.LEFT_TOP)
def get_fabric_data():
label.text = get_fabric_data_for_prim(get_stage_id(), get_selected_prim_path())
def rotate_prim():
label.text = apply_random_rotation(get_stage_id(), get_selected_prim_path())
def deform_prim():
label.text = deform_mesh_with_warp(get_stage_id(), get_selected_prim_path(), self._t)
self._t += 1
ui.Button("What's in Fabric?", clicked_fn=get_fabric_data, height=0)
ui.Button("Rotate it in Fabric!", clicked_fn=rotate_prim, height=0)
ui.Button("Deform it with Warp!", clicked_fn=deform_prim, height=0)
def on_shutdown(self):
print("[omni.example.python.usdrt] shutdown")
| 6,999 | Python | 31.71028 | 119 | 0.632519 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt/omni/example/python/usdrt/__init__.py | from .example_python_usdrt_extension import *
| 46 | Python | 22.499989 | 45 | 0.804348 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt/omni/example/python/usdrt/tests/test_whats_in_fabric.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.example.python.usdrt
# omni.kit.test is primarily Python's standard unittest module
# with additional wrapping to add suport for async/await tests.
# Please see: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# The Python module we are testing, imported with an absolute
# path to simulate using it from a different Python extension.
import omni.usd
import usdrt
# Any class that dervives from 'omni.kit.test.AsyncTestCase'
# declared at the root of the module will be auto-discovered,
class ExamplePythonUsdrtTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
# Open a new USD stage.
omni.usd.get_context().new_stage()
self.usd_stage = omni.usd.get_context().get_stage()
self.stage_id = omni.usd.get_context().get_stage_id()
# create a torus
(success, pathString) = omni.kit.commands.execute("CreateMeshPrimWithDefaultXformCommand", prim_type="Torus")
self.assertTrue(success)
self.prim_path = pathString
async def tearDown(self):
# Close the USD stage.
await omni.usd.get_context().close_stage_async()
self.usd_stage = None
async def test_get_fabric_data_for_prim(self):
result = omni.example.python.usdrt.get_fabric_data_for_prim(self.stage_id, self.prim_path)
self.assertTrue("Fabric data for prim at path %s\n\n\n" % self.prim_path in result)
for attr in ["points", "normals", "primvars:st", "extent"]:
self.assertTrue(attr in result)
# test invalid prim
result = omni.example.python.usdrt.get_fabric_data_for_prim(self.stage_id, "/invalidPrim")
self.assertTrue(result == "Prim at path /invalidPrim is not in Fabric")
# test empty path
result = omni.example.python.usdrt.get_fabric_data_for_prim(self.stage_id, None)
self.assertTrue(result == "Nothing selected")
async def test_apply_random_rotation(self):
result = omni.example.python.usdrt.apply_random_rotation(self.stage_id, self.prim_path)
self.assertTrue("Set new world orientation on %s to (" % self.prim_path in result)
# test invalid prim
result = omni.example.python.usdrt.apply_random_rotation(self.stage_id, "/invalidPrim")
self.assertTrue(result == "Prim at path /invalidPrim is not in Fabric")
# test empty path
result = omni.example.python.usdrt.apply_random_rotation(self.stage_id, None)
self.assertTrue(result == "Nothing selected")
async def test_deform_mesh_with_warp(self):
try:
import warp
t = 0
result = omni.example.python.usdrt.deform_mesh_with_warp(self.stage_id, self.prim_path, t)
self.assertTrue(result == f"Deformed points on prim {self.prim_path}")
# test invalid prim
result = omni.example.python.usdrt.deform_mesh_with_warp(self.stage_id, "/invalidPrim", t)
self.assertTrue(result == "Prim at path /invalidPrim is not in Fabric")
# test empty path
result = omni.example.python.usdrt.deform_mesh_with_warp(self.stage_id, None, t)
self.assertTrue(result == "Nothing selected")
except ImportError:
pass
| 3,687 | Python | 41.390804 | 117 | 0.681584 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.1] - 2022-10-07
- More cleanup for publish retry
## [1.0.0] - 2022-10-06
- Cleanup and publish for documentation example
## [0.1.0] - 2022-05-31
- Initial version
| 271 | Markdown | 15.999999 | 80 | 0.667897 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt/docs/Overview.md | # What's in Fabric? USDRT Scenegraph API example [omni.example.python.usdrt]
This is an example Kit extension using the USDRT Scenegraph API. This Python
extension demonstrates the following:
- Inspecting Fabric data using the USDRT Scenegraph API
- Manipulating prim transforms in Fabric using the RtXformable schema
- Deforming Mesh geometry on the GPU with USDRT and Warp
| 377 | Markdown | 40.999995 | 76 | 0.811671 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.omnigraph_node/config/extension.toml | [package]
version = "1.0.1" # Semantic Versioning is used: https://semver.org/
# These fields are used primarily for display in the extension browser UI.
title = "Example C++ Extension: OmniGraph Node"
description = "Demonstrates how to create a C++ node for OmniGraph"
category = "Example"
keywords = ["example", "C++", "cpp", "Graph", "Node", "OmniGraph"]
icon = "data/icon.png"
preview_image = "data/preview.png"
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
authors = ["Kevin Picott <[email protected]>", "David Bosnich <[email protected]>"]
repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp"
[dependencies]
"omni.graph.core" = {}
"omni.graph.tools" = {}
[[python.module]]
name = "omni.example.cpp.omnigraph_node"
[[native.plugin]]
path = "bin/*.plugin"
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 883 | TOML | 27.516128 | 86 | 0.697622 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.omnigraph_node/plugins/omni.example.cpp.omnigraph_node/ExampleOmniGraphNodeExtension.cpp | // 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.
//
#define CARB_EXPORTS
#include <carb/PluginUtils.h>
#include <omni/ext/IExt.h>
#include <omni/graph/core/IGraphRegistry.h>
#include <omni/graph/core/ogn/Database.h>
#include <omni/graph/core/ogn/Registration.h>
// Standard plugin definitions required by Carbonite.
const struct carb::PluginImplDesc pluginImplDesc = { "omni.example.cpp.omnigraph_node.plugin",
"An example C++ extension.", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
// These interface dependencies are required by all OmniGraph node types
CARB_PLUGIN_IMPL_DEPS(omni::graph::core::IGraphRegistry,
omni::fabric::IPath,
omni::fabric::IToken)
// This macro sets up the information required to register your node type definitions with OmniGraph
DECLARE_OGN_NODES()
namespace omni
{
namespace example
{
namespace cpp
{
namespace omnigraph_node
{
class ExampleOmniGraphNodeExtension : public omni::ext::IExt
{
public:
void onStartup(const char* extId) override
{
printf("ExampleOmniGraphNodeExtension starting up (ext_id: %s).\n", extId);
// This macro walks the list of pending node type definitions and registers them with OmniGraph
INITIALIZE_OGN_NODES()
}
void onShutdown() override
{
printf("ExampleOmniGraphNodeExtension shutting down.\n");
// This macro walks the list of registered node type definitions and deregisters all of them. This is required
// for hot reload to work.
RELEASE_OGN_NODES()
}
private:
};
}
}
}
}
CARB_PLUGIN_IMPL(pluginImplDesc, omni::example::cpp::omnigraph_node::ExampleOmniGraphNodeExtension)
void fillInterface(omni::example::cpp::omnigraph_node::ExampleOmniGraphNodeExtension& iface)
{
}
| 2,269 | C++ | 30.527777 | 118 | 0.698986 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.omnigraph_node/plugins/nodes/OgnExampleNode.cpp | // 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.
//
#include <OgnExampleNodeDatabase.h>
// Helpers to explicit shorten names you know you will use
using omni::graph::core::Type;
using omni::graph::core::BaseDataType;
namespace omni {
namespace example {
namespace cpp {
namespace omnigraph_node {
class OgnExampleNode
{
public:
static bool compute(OgnExampleNodeDatabase& db)
{
// The database has a few useful utilities that simplify common operations such as converting strings to tokens
static auto pointsToken = db.stringToToken("points");
// This is how to extract a single-valued attribute. The return values for db.inputs.XXX() are
// const-ref accessors that provide an interface to the actual data. For simple values it can be
// considered to be the POD type so this line would be equivalent to:
// const bool& disableOffset = db.inputs.disable();
const auto& disableOffset = db.inputs.disable();
// This is how to extract an output array attribute. It returns an accessor that behaves basically the same as
// the std::array type, except that the data is managed by Fabric. It further adds the ability to set the array
// size explicitly, required to ensure that Fabric has enough space allocated for the attribute data.
// Since this is an output the reference is no longer a const, enabling modification of the data to which it
// provides access.
auto& points = db.outputs.points();
// Attributes with well-defined types, like float/float[3], cast by default to the USD data types, however you
// can use any binary compatible types you have. See the .ogn documentation on type configurations to see how
// to change types. For bundle members and extended types whose type is determined at runtime the types are all
// POD types (though they can also be cast to other types at runtime if they are easier to use)
pxr::GfVec3f pointOffset{ 0.0f, 0.0f, 0.0f };
// This is how to extract a variable-typed input attribute. By default if the type has not been resolved to
// one of the legal types, in this case float[3] or float, the compute() will not be called. You can
// add "unvalidated":true to the attribute definition and handle the case of unresolved types here.
// The return value is an accessor that provides type information and the cast operators to get the
// resolved data types.
const auto& offsetValue = db.inputs.offset();
if (auto floatOffset = offsetValue.get<float>())
{
// The data received back from the "get<>()" method is an accessor that provides a boolean operator,
// which did the type compatibility test that got us into this section of the "if", and an indirection
// operator that returns a reference to data of the type that was matched (float in this case).
pointOffset = pxr::GfVec3f{*floatOffset, *floatOffset, *floatOffset};
std::cout << "Got a float value of " << *floatOffset << std::endl;
}
// Repeat the same process of checking and applying for the other accepted value type of float[3]
else if (auto float3Offset = offsetValue.get<float[3]>())
{
pointOffset = pxr::GfVec3f{*float3Offset};
std::cout << "Got a float[3] value of " << pointOffset[0] << ", " << pointOffset[1] << ", " << pointOffset[2] << std::endl;
}
else
{
// If the resolved type was not one of the recognized one then something went wrong and the node is
// incapable of computing so log an error and return false.
db.logError("Unrecognized offset type %s", offsetValue.typeName().c_str());
return false;
}
// -------------------------------------------------------------------------------------------------------------
// With only a few accepted data types you can use the cascading "if" cast method above. If you have a lot of
// types being accepted then you should use a switch statement on the attribute type like this, as it has much
// better performance.
// const auto& type = offsetValue.type();
// switch (type.baseDataType)
// {
// case BaseDataType::eFloat:
// if ((type.componentCount == 1) and (type.arrayDepth == 0))
// {
// return handleFloatValue();
// }
// if ((type.componentCount == 3) and (type.arrayDepth == 0))
// {
// return handleFloat3Value();
// }
// }
// db.logError("Unrecognized offset type %s", offsetValue.typeName().c_str());
// return false;
// -------------------------------------------------------------------------------------------------------------
// This is how to extract an input bundle attribute. It returns an accessor that lets you inspect the bundle
// contents and the values of the attributes in the bundle.
const auto& bundleWithGeometry = db.inputs.geometry();
// The accessor supports a range-based for-loop for iterating over members. Since the output has to have a
// fixed size there is a first pass here just to count the matching members.
size_t numPointsToOffset{ 0 };
for (auto const& bundleMember : bundleWithGeometry)
{
auto inputPoint = bundleMember.get<float[3]>();
// The member accessor supports a boolean operator indicating if it is valid, meaning the type is
// compatible with the templated type with which it was extracted (float[3]).
if (inputPoint)
{
numPointsToOffset++;
}
}
// Now that all values are accessible the actual computation can happen.
//
// Output arrays must always be first resized to be the total number of entries they will eventually
// contain. Repeated resizing can be expensive so it's best to do it once up front.
points.resize(numPointsToOffset);
// The array accessor provides the common definitions that allow range-based for loops
size_t pointIndex{ 0 };
for (auto const& bundleMember : bundleWithGeometry)
{
auto inputPoint = bundleMember.get<float[3]>();
if (! inputPoint)
{
continue;
}
auto& point = points[pointIndex++];
point = pxr::GfVec3f(inputPoint);
if (! disableOffset)
{
point += pointOffset;
}
pointIndex++;
}
// Returning true tells Omnigraph that the compute was successful and the output value is now valid.
return true;
}
};
// This macro provides the information necessary to OmniGraph that lets it automatically register and deregister
// your node type definition.
REGISTER_OGN_NODE()
} // omnigraph_node
} // cpp
} // example
} // omni
| 7,538 | C++ | 49.26 | 135 | 0.620854 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.omnigraph_node/docs/Overview.md | ```{csv-table}
**Extension**: {{ extension_version }},**Documentation Generated**: {sub-ref}`today`,{ref}`changelog_omni_example_cpp_omnigraph_node`
```
(ext_omni_example_cpp_omnigraph_node)=
# Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create a C++ node for omni.graph
| 356 | Markdown | 26.461536 | 133 | 0.730337 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/python/tests/test_pybind_example.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.example.cpp.pybind
class TestPybindExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
# Cache the pybind interface.
self.bound_interface = omni.example.cpp.pybind.get_bound_interface()
# Create and register a bound object.
self.bound_object = omni.example.cpp.pybind.BoundObject("test_bound_object")
self.bound_object.property_int = 9
self.bound_object.property_bool = True
self.bound_object.property_string = "Ninety-Nine"
self.bound_interface.register_bound_object(self.bound_object)
async def tearDown(self):
# Deregister and clear the bound object.
self.bound_interface.deregister_bound_object(self.bound_object)
self.bound_object = None
# Clear the pybind interface.
self.bound_interface = None
async def test_find_bound_object(self):
found_object = self.bound_interface.find_bound_object("test_bound_object")
self.assertIsNotNone(found_object)
async def test_find_unregistered_bound_object(self):
found_object = self.bound_interface.find_bound_object("unregistered_object")
self.assertIsNone(found_object)
async def test_access_bound_object_properties(self):
self.assertEqual(self.bound_object.id, "test_bound_object")
self.assertEqual(self.bound_object.property_int, 9)
self.assertEqual(self.bound_object.property_bool, True)
self.assertEqual(self.bound_object.property_string, "Ninety-Nine")
async def test_call_bound_object_functions(self):
# Test calling a bound function that accepts an argument.
self.bound_object.multiply_int_property(9)
self.assertEqual(self.bound_object.property_int, 81)
# Test calling a bound function that returns a value.
result = self.bound_object.toggle_bool_property()
self.assertEqual(result, False)
self.assertEqual(self.bound_object.property_bool, False)
# Test calling a bound function that accepts an argument and returns a value.
result = self.bound_object.append_string_property(" Red Balloons")
self.assertEqual(result, "Ninety-Nine Red Balloons")
self.assertEqual(self.bound_object.property_string, "Ninety-Nine Red Balloons")
| 2,746 | Python | 43.306451 | 87 | 0.714494 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/python/impl/example_pybind_extension.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.ext
from .._example_pybind_bindings import *
# Global public interface object.
_bound_interface = None
# Public API.
def get_bound_interface() -> IExampleBoundInterface:
return _bound_interface
# Use the extension entry points to acquire and release the interface.
class ExamplePybindExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
global _bound_interface
_bound_interface = acquire_bound_interface()
def on_shutdown(self):
global _bound_interface
release_bound_interface(_bound_interface)
_bound_interface = None
| 1,045 | Python | 31.687499 | 77 | 0.733014 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/bindings/python/omni.example.cpp.pybind/ExamplePybindBindings.cpp | // 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.
//
#include <carb/BindingsPythonUtils.h>
#include <omni/example/cpp/pybind/ExampleBoundObject.h>
#include <omni/example/cpp/pybind/IExampleBoundInterface.h>
#include <string>
CARB_BINDINGS("omni.example.cpp.pybind.python")
DISABLE_PYBIND11_DYNAMIC_CAST(omni::example::cpp::pybind::IExampleBoundInterface)
DISABLE_PYBIND11_DYNAMIC_CAST(omni::example::cpp::pybind::IExampleBoundObject)
namespace
{
/**
* Concrete bound object class that will be reflected to Python.
*/
class PythonBoundObject : public omni::example::cpp::pybind::ExampleBoundObject
{
public:
/**
* Factory.
*
* @param id Id of the bound action.
*
* @return The bound object that was created.
*/
static carb::ObjectPtr<PythonBoundObject> create(const char* id)
{
// Note: It is important to construct the handler using ObjectPtr<T>::InitPolicy::eSteal,
// otherwise we end up incresing the reference count by one too many during construction,
// resulting in carb::ObjectPtr<T> instance whose wrapped object will never be destroyed.
return carb::stealObject<PythonBoundObject>(new PythonBoundObject(id));
}
/**
* Constructor.
*
* @param id Id of the bound object.
*/
PythonBoundObject(const char* id)
: ExampleBoundObject(id)
, m_memberInt(0)
, m_memberBool(false)
, m_memberString()
{
}
// To deomnstrate binding a fuction that accepts an argument.
void multiplyIntProperty(int value)
{
m_memberInt *= value;
}
// To deomnstrate binding a fuction that returns a value.
bool toggleBoolProperty()
{
m_memberBool = !m_memberBool;
return m_memberBool;
}
// To deomnstrate binding a fuction that accepts an argument and returns a value.
const char* appendStringProperty(const char* value)
{
m_memberString += value;
return m_memberString.c_str();
}
// To deomnstrate binding properties using accessors.
const char* getMemberString() const
{
return m_memberString.c_str();
}
// To deomnstrate binding properties using accessors.
void setMemberString(const char* value)
{
m_memberString = value;
}
// To deomnstrate binding properties directly.
int m_memberInt;
bool m_memberBool;
private:
// To deomnstrate binding properties using accessors.
std::string m_memberString;
};
// Define the pybind11 module using the same name specified in premake5.lua
PYBIND11_MODULE(_example_pybind_bindings, m)
{
using namespace omni::example::cpp::pybind;
m.doc() = "pybind11 omni.example.cpp.pybind bindings";
carb::defineInterfaceClass<IExampleBoundInterface>(
m, "IExampleBoundInterface", "acquire_bound_interface", "release_bound_interface")
.def("register_bound_object", &IExampleBoundInterface::registerBoundObject,
R"(
Register a bound object.
Args:
object: The bound object to register.
)",
py::arg("object"))
.def("deregister_bound_object", &IExampleBoundInterface::deregisterBoundObject,
R"(
Deregister a bound object.
Args:
object: The bound object to deregister.
)",
py::arg("object"))
.def("find_bound_object", &IExampleBoundInterface::findBoundObject, py::return_value_policy::reference,
R"(
Find a bound object.
Args:
id: Id of the bound object.
Return:
The bound object if it exists, an empty object otherwise.
)",
py::arg("id"))
/**/;
py::class_<IExampleBoundObject, carb::ObjectPtr<IExampleBoundObject>>(m, "IExampleBoundObject")
.def_property_readonly("id", &IExampleBoundObject::getId, py::return_value_policy::reference,
R"(
Get the id of this bound object.
Return:
The id of this bound object.
)")
/**/;
py::class_<PythonBoundObject, IExampleBoundObject, carb::ObjectPtr<PythonBoundObject>>(m, "BoundObject")
.def(py::init([](const char* id) { return PythonBoundObject::create(id); }),
R"(
Create a bound object.
Args:
id: Id of the bound object.
Return:
The bound object that was created.
)",
py::arg("id"))
.def_readwrite("property_int", &PythonBoundObject::m_memberInt,
R"(
Int property bound directly.
)")
.def_readwrite("property_bool", &PythonBoundObject::m_memberBool,
R"(
Bool property bound directly.
)")
.def_property("property_string", &PythonBoundObject::getMemberString, &PythonBoundObject::setMemberString, py::return_value_policy::reference,
R"(
String property bound using accessors.
)")
.def("multiply_int_property", &PythonBoundObject::multiplyIntProperty,
R"(
Bound fuction that accepts an argument.
Args:
value_to_multiply: The value to multiply by.
)",
py::arg("value_to_multiply"))
.def("toggle_bool_property", &PythonBoundObject::toggleBoolProperty,
R"(
Bound fuction that returns a value.
Return:
The toggled bool value.
)")
.def("append_string_property", &PythonBoundObject::appendStringProperty, py::return_value_policy::reference,
R"(
Bound fuction that accepts an argument and returns a value.
Args:
value_to_append: The value to append.
Return:
The new string value.
)",
py::arg("value_to_append"))
/**/;
}
}
| 6,447 | C++ | 31.079602 | 150 | 0.607725 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/include/omni/example/cpp/pybind/IExampleBoundInterface.h | // 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.
//
#pragma once
#include <omni/example/cpp/pybind/IExampleBoundObject.h>
#include <carb/Interface.h>
namespace omni
{
namespace example
{
namespace cpp
{
namespace pybind
{
/**
* An example interface to demonstrate reflection using pybind.
*/
class IExampleBoundInterface
{
public:
/// @private
CARB_PLUGIN_INTERFACE("omni::example::cpp::pybind::IExampleBoundInterface", 1, 0);
/**
* Register a bound object.
*
* @param object The bound object to register.
*/
virtual void registerBoundObject(carb::ObjectPtr<IExampleBoundObject>& object) = 0;
/**
* Deregister a bound object.
*
* @param object The bound object to deregister.
*/
virtual void deregisterBoundObject(carb::ObjectPtr<IExampleBoundObject>& object) = 0;
/**
* Find a bound object.
*
* @param id Id of the bound object.
*
* @return The bound object if it exists, an empty ObjectPtr otherwise.
*/
virtual carb::ObjectPtr<IExampleBoundObject> findBoundObject(const char* id) const = 0;
};
}
}
}
}
| 1,500 | C | 23.606557 | 91 | 0.704 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/include/omni/example/cpp/pybind/ExampleBoundObject.h | // 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.
//
#pragma once
#include <omni/example/cpp/pybind/IExampleBoundObject.h>
#include <carb/ObjectUtils.h>
#include <omni/String.h>
namespace omni
{
namespace example
{
namespace cpp
{
namespace pybind
{
/**
* Helper base class for bound object implementations.
*/
class ExampleBoundObject : public IExampleBoundObject
{
CARB_IOBJECT_IMPL
public:
/**
* Constructor.
*
* @param id Id of the bound object.
*/
ExampleBoundObject(const char* id)
: m_id(id ? id : "")
{
}
/**
* @ref IExampleBoundObject::getId
*/
const char* getId() const override
{
return m_id.c_str();
}
protected:
const omni::string m_id; //!< Id of the bound object.
};
}
}
}
}
| 1,169 | C | 18.5 | 77 | 0.681779 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/include/omni/example/cpp/pybind/IExampleBoundObject.h | // 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.
//
#pragma once
#include <carb/IObject.h>
namespace omni
{
namespace example
{
namespace cpp
{
namespace pybind
{
/**
* Pure virtual bound object interface.
*/
class IExampleBoundObject : public carb::IObject
{
public:
/**
* Get the id of this object.
*
* @return Id of this object.
*/
virtual const char* getId() const = 0;
};
/**
* Implement the equality operator so these can be used in std containers.
*/
inline bool operator==(const carb::ObjectPtr<IExampleBoundObject>& left,
const carb::ObjectPtr<IExampleBoundObject>& right) noexcept
{
return (left.get() == right.get());
}
}
}
}
}
| 1,086 | C | 21.183673 | 82 | 0.70442 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/config/extension.toml | [package]
version = "1.0.1" # Semantic Versioning is used: https://semver.org/
# These fields are used primarily for display in the extension browser UI.
title = "Example C++ Extension: pybind"
description = "Demonstrates how to reflect C++ code using pybind11 so that it can be called from Python code."
category = "Example"
keywords = ["example", "C++", "cpp", "pybind"]
icon = "data/icon.png"
preview_image = "data/preview.png"
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
authors = ["David Bosnich <[email protected]>"]
repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp"
# Define the Python modules that this extension provides.
[[python.module]]
name = "omni.example.cpp.pybind"
# Define the C++ plugins that this extension provides.
[[native.plugin]]
path = "bin/*.plugin"
# Define any test specific properties of this extension.
[[test]]
cppTests.libraries = [
"bin/${lib_prefix}omni.example.cpp.pybind.tests${lib_ext}"
]
# Define the documentation that will be generated for this extension.
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
cpp_api = [
"include/omni/example/cpp/pybind/IExampleBoundInterface.h",
"include/omni/example/cpp/pybind/IExampleBoundObject.h",
"include/omni/example/cpp/pybind/ExampleBoundObject.h",
]
| 1,330 | TOML | 31.463414 | 110 | 0.72406 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/plugins/omni.example.cpp.pybind.tests/ExamplePybindTests.cpp | // Copyright (c) 2020-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.
//
#include <omni/example/cpp/pybind/IExampleBoundInterface.h>
#include <omni/example/cpp/pybind/ExampleBoundObject.h>
#include <doctest/doctest.h>
#include <carb/BindingsUtils.h>
CARB_BINDINGS("omni.example.cpp.pybind.tests")
namespace omni
{
namespace example
{
namespace cpp
{
namespace pybind
{
class ExampleCppObject : public ExampleBoundObject
{
public:
static carb::ObjectPtr<IExampleBoundObject> create(const char* id)
{
return carb::stealObject<IExampleBoundObject>(new ExampleCppObject(id));
}
ExampleCppObject(const char* id)
: ExampleBoundObject(id)
{
}
};
class ExamplePybindTestFixture
{
public:
static constexpr const char* k_registeredObjectId = "example_bound_object";
ExamplePybindTestFixture()
: m_exampleBoundInterface(carb::getCachedInterface<omni::example::cpp::pybind::IExampleBoundInterface>())
, m_exampleBoundObject(ExampleCppObject::create(k_registeredObjectId))
{
m_exampleBoundInterface->registerBoundObject(m_exampleBoundObject);
}
~ExamplePybindTestFixture()
{
m_exampleBoundInterface->deregisterBoundObject(m_exampleBoundObject);
}
protected:
IExampleBoundInterface* getExampleBoundInterface()
{
return m_exampleBoundInterface;
}
carb::ObjectPtr<IExampleBoundObject> getExampleBoundObject()
{
return m_exampleBoundObject;
}
private:
IExampleBoundInterface* m_exampleBoundInterface = nullptr;
carb::ObjectPtr<IExampleBoundObject> m_exampleBoundObject;
};
}
}
}
}
TEST_SUITE("omni.example.cpp.pybind.tests")
{
using namespace omni::example::cpp::pybind;
TEST_CASE_FIXTURE(ExamplePybindTestFixture, "Get Example Bound Interface")
{
CHECK(getExampleBoundInterface() != nullptr);
}
TEST_CASE_FIXTURE(ExamplePybindTestFixture, "Get Example Bound Object")
{
CHECK(getExampleBoundObject().get() != nullptr);
}
TEST_CASE_FIXTURE(ExamplePybindTestFixture, "Find Example Bound Object")
{
SUBCASE("Registered")
{
carb::ObjectPtr<IExampleBoundObject> foundObject = getExampleBoundInterface()->findBoundObject(k_registeredObjectId);
CHECK(foundObject.get() == getExampleBoundObject().get());
CHECK(foundObject.get() != nullptr);
}
SUBCASE("Unregistered")
{
carb::ObjectPtr<IExampleBoundObject> foundObject = getExampleBoundInterface()->findBoundObject("unregistered_object_id");
CHECK(foundObject.get() != getExampleBoundObject().get());
CHECK(foundObject.get() == nullptr);
}
}
}
| 3,079 | C++ | 26.747748 | 133 | 0.708996 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/plugins/omni.example.cpp.pybind/ExamplePybindExtension.cpp | // 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.
//
#define CARB_EXPORTS
#include <carb/PluginUtils.h>
#include <omni/ext/IExt.h>
#include <omni/example/cpp/pybind/IExampleBoundInterface.h>
#include <unordered_map>
const struct carb::PluginImplDesc pluginImplDesc = { "omni.example.cpp.pybind.plugin",
"An example C++ extension.", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
namespace omni
{
namespace example
{
namespace cpp
{
namespace pybind
{
class ExampleBoundImplementation : public IExampleBoundInterface
{
public:
void registerBoundObject(carb::ObjectPtr<IExampleBoundObject>& object) override
{
if (object)
{
m_registeredObjectsById[object->getId()] = object;
}
}
void deregisterBoundObject(carb::ObjectPtr<IExampleBoundObject>& object) override
{
if (object)
{
const auto& it = m_registeredObjectsById.find(object->getId());
if (it != m_registeredObjectsById.end())
{
m_registeredObjectsById.erase(it);
}
}
}
carb::ObjectPtr<IExampleBoundObject> findBoundObject(const char* id) const override
{
const auto& it = m_registeredObjectsById.find(id);
if (it != m_registeredObjectsById.end())
{
return it->second;
}
return carb::ObjectPtr<IExampleBoundObject>();
}
private:
std::unordered_map<std::string, carb::ObjectPtr<IExampleBoundObject>> m_registeredObjectsById;
};
}
}
}
}
CARB_PLUGIN_IMPL(pluginImplDesc, omni::example::cpp::pybind::ExampleBoundImplementation)
void fillInterface(omni::example::cpp::pybind::ExampleBoundImplementation& iface)
{
}
| 2,187 | C++ | 26.012345 | 98 | 0.657522 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/docs/Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to reflect C++ code using pybind11 so that it can be called from Python code.
The IExampleBoundInterface located in `include/omni/example/cpp/pybind/IExampleBoundInterface.h` is:
- Implemented in `plugins/omni.example.cpp.pybind/ExamplePybindExtension.cpp`.
- Reflected in `bindings/python/omni.example.cpp.pybind/ExamplePybindBindings.cpp`.
- Accessed from Python in `python/tests/test_pybind_example.py` via `python/impl/example_pybind_extension.py`.
# C++ Usage Examples
## Defining Pybind Module
```
PYBIND11_MODULE(_example_pybind_bindings, m)
{
using namespace omni::example::cpp::pybind;
m.doc() = "pybind11 omni.example.cpp.pybind bindings";
carb::defineInterfaceClass<IExampleBoundInterface>(
m, "IExampleBoundInterface", "acquire_bound_interface", "release_bound_interface")
.def("register_bound_object", &IExampleBoundInterface::registerBoundObject,
R"(
Register a bound object.
Args:
object: The bound object to register.
)",
py::arg("object"))
.def("deregister_bound_object", &IExampleBoundInterface::deregisterBoundObject,
R"(
Deregister a bound object.
Args:
object: The bound object to deregister.
)",
py::arg("object"))
.def("find_bound_object", &IExampleBoundInterface::findBoundObject, py::return_value_policy::reference,
R"(
Find a bound object.
Args:
id: Id of the bound object.
Return:
The bound object if it exists, an empty object otherwise.
)",
py::arg("id"))
/**/;
py::class_<IExampleBoundObject, carb::ObjectPtr<IExampleBoundObject>>(m, "IExampleBoundObject")
.def_property_readonly("id", &IExampleBoundObject::getId, py::return_value_policy::reference,
R"(
Get the id of this bound object.
Return:
The id of this bound object.
)")
/**/;
py::class_<PythonBoundObject, IExampleBoundObject, carb::ObjectPtr<PythonBoundObject>>(m, "BoundObject")
.def(py::init([](const char* id) { return PythonBoundObject::create(id); }),
R"(
Create a bound object.
Args:
id: Id of the bound object.
Return:
The bound object that was created.
)",
py::arg("id"))
.def_readwrite("property_int", &PythonBoundObject::m_memberInt,
R"(
Int property bound directly.
)")
.def_readwrite("property_bool", &PythonBoundObject::m_memberBool,
R"(
Bool property bound directly.
)")
.def_property("property_string", &PythonBoundObject::getMemberString, &PythonBoundObject::setMemberString, py::return_value_policy::reference,
R"(
String property bound using accessors.
)")
.def("multiply_int_property", &PythonBoundObject::multiplyIntProperty,
R"(
Bound fuction that accepts an argument.
Args:
value_to_multiply: The value to multiply by.
)",
py::arg("value_to_multiply"))
.def("toggle_bool_property", &PythonBoundObject::toggleBoolProperty,
R"(
Bound fuction that returns a value.
Return:
The toggled bool value.
)")
.def("append_string_property", &PythonBoundObject::appendStringProperty, py::return_value_policy::reference,
R"(
Bound fuction that accepts an argument and returns a value.
Args:
value_to_append: The value to append.
Return:
The new string value.
)",
py::arg("value_to_append"))
/**/;
}
```
| 4,125 | Markdown | 33.099173 | 150 | 0.575273 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd_physics/plugins/omni.example.cpp.usd_physics/ExampleUsdPhysicsExtension.cpp | // 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.
//
#define CARB_EXPORTS
#include <carb/PluginUtils.h>
#include <omni/ext/IExt.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdGeom/cube.h>
#include <pxr/usd/usdGeom/metrics.h>
#include <pxr/usd/usdPhysics/collisionAPI.h>
#include <pxr/usd/usdPhysics/massAPI.h>
#include <pxr/usd/usdPhysics/rigidBodyAPI.h>
#include <pxr/usd/usdPhysics/scene.h>
#include <pxr/usd/usdUtils/stageCache.h>
const struct carb::PluginImplDesc pluginImplDesc = { "omni.example.cpp.usd_physics.plugin",
"An example C++ extension.", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
namespace omni
{
namespace example
{
namespace cpp
{
namespace usd_physics
{
class ExampleUsdPhysicsExtension : public omni::ext::IExt
{
protected:
void onStartup(const char* extId) override
{
// Get the 'active' USD stage from the USD stage cache.
const std::vector<PXR_NS::UsdStageRefPtr> allStages = PXR_NS::UsdUtilsStageCache::Get().GetAllStages();
if (allStages.size() != 1)
{
CARB_LOG_WARN("Cannot determine the 'active' USD stage (%zu stages present in the USD stage cache).", allStages.size());
return;
}
// Get the meters per unit and up axis of the 'active' USD stage.
PXR_NS::UsdStageRefPtr activeStage = allStages[0];
const double activeStageMetersPerUnit = PXR_NS::UsdGeomGetStageMetersPerUnit(activeStage);
if (PXR_NS::UsdGeomGetStageUpAxis(activeStage) != PXR_NS::UsdGeomTokens->y)
{
// Handling this is possible, but it would complicate the example,
// that is only designed to work in an empty stage with Y-axis up.
CARB_LOG_WARN("The up axis of the 'active' USD stage is not Y.");
return;
}
// Create and setup the USD physics scene.
static const PXR_NS::SdfPath kPhysicsScenePath("/World/PhysicsScene");
if (!activeStage->GetPrimAtPath(kPhysicsScenePath))
{
static constexpr PXR_NS::GfVec3f kGravityDirection = { 0.0f, -1.0f, 0.0f };
static constexpr float kGravityMagnitude = 981.0f;
PXR_NS::UsdPhysicsScene physicsScene = PXR_NS::UsdPhysicsScene::Define(activeStage, kPhysicsScenePath);
physicsScene.CreateGravityDirectionAttr().Set(kGravityDirection);
physicsScene.CreateGravityMagnitudeAttr().Set(kGravityMagnitude);
}
// Create and setup a static ground plane (box for now, should use UsdGeomPlane instead).
static const PXR_NS::SdfPath kGroundPlanePath("/World/StaticGroundPlane");
if (!activeStage->GetPrimAtPath(kGroundPlanePath))
{
const double kSize = 5.0 / activeStageMetersPerUnit;
const PXR_NS::GfVec3f kColour = { 1.0f, 1.0f, 1.0f };
const PXR_NS::GfVec3f kPosition = { 0.0f, -(float)kSize * 0.5f, 0.0f };
PXR_NS::UsdGeomCube geomPrim = PXR_NS::UsdGeomCube::Define(activeStage, kGroundPlanePath);
geomPrim.CreateSizeAttr().Set(kSize);
geomPrim.AddTranslateOp(PXR_NS::UsdGeomXformOp::PrecisionFloat).Set(kPosition);
geomPrim.CreateDisplayColorAttr().Set(PXR_NS::VtArray<PXR_NS::GfVec3f>({ kColour }));
PXR_NS::UsdPhysicsCollisionAPI::Apply(geomPrim.GetPrim());
}
// Create and setup a rigid body box.
const PXR_NS::SdfPath kRigidBodyPath("/World/RigidBodyBox");
if (!activeStage->GetPrimAtPath(kRigidBodyPath))
{
const double kSize = 0.5 / activeStageMetersPerUnit;
const PXR_NS::GfVec3f kColour = { 0.0f, 0.0f, 1.0f };
const PXR_NS::GfVec3f kPosition = { 0.0f, (float)kSize * 5.0f, 0.0f };
PXR_NS::UsdGeomCube geomPrim = PXR_NS::UsdGeomCube::Define(activeStage, kRigidBodyPath);
geomPrim.CreateSizeAttr().Set(kSize);
geomPrim.AddTranslateOp(PXR_NS::UsdGeomXformOp::PrecisionFloat).Set(kPosition);
geomPrim.CreateDisplayColorAttr().Set(PXR_NS::VtArray<PXR_NS::GfVec3f>({ kColour }));
static constexpr PXR_NS::GfVec3f kVelocity = { 2.0f, 1.0f, 2.0f };
static constexpr PXR_NS::GfVec3f kAngularVelocity = { 180.0f, 0.0f, 0.0f };
PXR_NS::UsdPhysicsCollisionAPI::Apply(geomPrim.GetPrim());
PXR_NS::UsdPhysicsMassAPI::Apply(geomPrim.GetPrim());
auto rigidBodyAPI = PXR_NS::UsdPhysicsRigidBodyAPI::Apply(geomPrim.GetPrim());
rigidBodyAPI.CreateVelocityAttr().Set(kVelocity);
rigidBodyAPI.CreateAngularVelocityAttr().Set(kAngularVelocity);
}
}
void onShutdown() override
{
}
};
}
}
}
}
CARB_PLUGIN_IMPL(pluginImplDesc, omni::example::cpp::usd_physics::ExampleUsdPhysicsExtension)
void fillInterface(omni::example::cpp::usd_physics::ExampleUsdPhysicsExtension& iface)
{
}
| 5,348 | C++ | 40.465116 | 132 | 0.658377 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd_physics/docs/Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create a C++ plugin that can add physics to the current USD stage by:
- Using the UsdStageCache to get a USD stage from C++.
- Adding a UsdPhysicsScene to the USD stage from C++.
- Adding a static body box to the USD stage from C++.
- Adding a rigid body box to the USD stage from C++.
Note: It is important that all USD stage reads/writes happen from the main thread:
[https://graphics.pixar.com/usd/release/api/_usd__page__multi_threading.html](https://graphics.pixar.com/usd/release/api/_usd__page__multi_threading.html)
# Example

| 715 | Markdown | 33.095237 | 154 | 0.748252 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.commands/plugins/omni.example.cpp.commands/ExampleCommandsExtension.cpp | // 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.
//
#define CARB_EXPORTS
#include <carb/PluginUtils.h>
#include <omni/ext/IExt.h>
#include <omni/kit/commands/Command.h>
#include <omni/kit/commands/ICommandBridge.h>
const struct carb::PluginImplDesc pluginImplDesc = { "omni.example.cpp.commands.plugin",
"An example C++ extension.", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
namespace omni
{
namespace example
{
namespace cpp
{
namespace commands
{
using namespace omni::kit::commands;
class ExampleCppCommand : public Command
{
public:
static carb::ObjectPtr<ICommand> create(const char* extensionId,
const char* commandName,
const carb::dictionary::Item* kwargs)
{
// Note: It is important to construct the handler using ObjectPtr<T>::InitPolicy::eSteal,
// otherwise we end up incresing the reference count by one too many during construction,
// resulting in a carb::ObjectPtr<IAction> whose object instance will never be destroyed.
return carb::stealObject<ICommand>(new ExampleCppCommand(extensionId, commandName, kwargs));
}
static void populateKeywordArgs(carb::dictionary::Item* defaultKwargs,
carb::dictionary::Item* optionalKwargs,
carb::dictionary::Item* requiredKwargs)
{
if (carb::dictionary::IDictionary* iDictionary = carb::getCachedInterface<carb::dictionary::IDictionary>())
{
iDictionary->makeAtPath(defaultKwargs, "x", 9);
iDictionary->makeAtPath(defaultKwargs, "y", -1);
}
}
ExampleCppCommand(const char* extensionId, const char* commandName, const carb::dictionary::Item* kwargs)
: Command(extensionId, commandName)
{
if (carb::dictionary::IDictionary* iDictionary = carb::getCachedInterface<carb::dictionary::IDictionary>())
{
m_x = iDictionary->get<int32_t>(kwargs, "x");
m_y = iDictionary->get<int32_t>(kwargs, "y");
}
}
void doCommand() override
{
printf("Executing command '%s' with params 'x=%d' and 'y=%d'.\n", getName(), m_x, m_y);
}
void undoCommand() override
{
printf("Undoing command '%s' with params 'x=%d' and 'y=%d'.\n", getName(), m_x, m_y);
}
private:
int32_t m_x = 0;
int32_t m_y = 0;
};
class ExampleCommandsExtension : public omni::ext::IExt
{
public:
void onStartup(const char* extId) override
{
auto commandBridge = carb::getCachedInterface<ICommandBridge>();
if (!commandBridge)
{
CARB_LOG_WARN("Could not get cached ICommandBridge interface.");
return;
}
// Example of registering a command from C++.
commandBridge->registerCommand(
"omni.example.cpp.commands", "ExampleCppCommand", ExampleCppCommand::create, ExampleCppCommand::populateKeywordArgs);
}
void onShutdown() override
{
if (auto commandBridge = carb::getCachedInterface<ICommandBridge>())
{
commandBridge->deregisterCommand("omni.example.cpp.commands", "ExampleCppCommand");
}
else
{
CARB_LOG_WARN("Could not get cached ICommandBridge interface.");
}
}
};
}
}
}
}
CARB_PLUGIN_IMPL(pluginImplDesc, omni::example::cpp::commands::ExampleCommandsExtension)
void fillInterface(omni::example::cpp::commands::ExampleCommandsExtension& iface)
{
}
| 4,025 | C++ | 31.731707 | 129 | 0.631304 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.commands/plugins/omni.example.cpp.commands.tests/ExampleCommandsTests.cpp | // Copyright (c) 2020-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.
//
#include <doctest/doctest.h>
#include <carb/BindingsUtils.h>
#include <omni/kit/commands/ICommandBridge.h>
CARB_BINDINGS("omni.example.cpp.commands.tests")
TEST_SUITE("omni.example.cpp.commands.tests")
{
using namespace omni::kit::commands;
TEST_CASE("Execute Example C++ Command")
{
auto commandBridge = carb::getCachedInterface<ICommandBridge>();
REQUIRE(commandBridge != nullptr);
// Execute
bool result = commandBridge->executeCommand("ExampleCpp");
CHECK(result);
// Undo
result = commandBridge->undoCommand();
CHECK(result);
// Redo
result = commandBridge->redoCommand();
CHECK(result);
// Undo
result = commandBridge->undoCommand();
CHECK(result);
// Execute with args
carb::dictionary::IDictionary* iDictionary = carb::getCachedInterface<carb::dictionary::IDictionary>();
REQUIRE(iDictionary != nullptr);
carb::dictionary::Item* kwargs = iDictionary->createItem(nullptr, "", carb::dictionary::ItemType::eDictionary);
REQUIRE(kwargs != nullptr);
iDictionary->makeAtPath(kwargs, "x", -9);
iDictionary->makeAtPath(kwargs, "y", 99);
result = commandBridge->executeCommand("ExampleCpp", kwargs);
iDictionary->destroyItem(kwargs);
CHECK(result);
// Repeat
result = commandBridge->repeatCommand();
CHECK(result);
// Undo
result = commandBridge->undoCommand();
CHECK(result);
// Undo
result = commandBridge->undoCommand();
CHECK(result);
// Undo (empty command stack)
result = commandBridge->undoCommand();
CHECK(!result);
}
}
| 2,186 | C++ | 29.802816 | 119 | 0.651418 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.commands/omni/example/cpp/commands/tests/test_commands_example.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.commands
import omni.kit.undo
class TestCommandsExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
omni.kit.undo.clear_stack()
async def tearDown(self):
omni.kit.undo.clear_stack()
async def test_cpp_commands(self):
# Execute
res = omni.kit.commands.execute("ExampleCpp")
self.assertEqual(res, (True, None))
# Undo
res = omni.kit.undo.undo()
self.assertTrue(res)
# Redo
res = omni.kit.undo.redo()
self.assertTrue(res)
# Repeat
res = omni.kit.undo.repeat()
self.assertTrue(res)
# Undo
res = omni.kit.undo.undo()
self.assertTrue(res)
# Undo
res = omni.kit.undo.undo()
self.assertTrue(res)
# Undo (empty command stack)
res = omni.kit.undo.undo()
self.assertFalse(res)
| 1,355 | Python | 26.119999 | 77 | 0.648708 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.commands/docs/Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create commands in C++ that can then be executed from either C++ or Python.
See the omni.kit.commands extension for extensive documentation about commands themselves.
# C++ Usage Examples
## Defining Commands
```
using namespace omni::kit::commands;
class ExampleCppCommand : public Command
{
public:
static carb::ObjectPtr<ICommand> create(const char* extensionId,
const char* commandName,
const carb::dictionary::Item* kwargs)
{
return carb::stealObject<ICommand>(new ExampleCppCommand(extensionId, commandName, kwargs));
}
static void populateKeywordArgs(carb::dictionary::Item* defaultKwargs,
carb::dictionary::Item* optionalKwargs,
carb::dictionary::Item* requiredKwargs)
{
if (carb::dictionary::IDictionary* iDictionary = carb::getCachedInterface<carb::dictionary::IDictionary>())
{
iDictionary->makeAtPath(defaultKwargs, "x", 9);
iDictionary->makeAtPath(defaultKwargs, "y", -1);
}
}
ExampleCppCommand(const char* extensionId, const char* commandName, const carb::dictionary::Item* kwargs)
: Command(extensionId, commandName)
{
if (carb::dictionary::IDictionary* iDictionary = carb::getCachedInterface<carb::dictionary::IDictionary>())
{
m_x = iDictionary->get<int32_t>(kwargs, "x");
m_y = iDictionary->get<int32_t>(kwargs, "y");
}
}
void doCommand() override
{
printf("Executing command '%s' with params 'x=%d' and 'y=%d'.\n", getName(), m_x, m_y);
}
void undoCommand() override
{
printf("Undoing command '%s' with params 'x=%d' and 'y=%d'.\n", getName(), m_x, m_y);
}
private:
int32_t m_x = 0;
int32_t m_y = 0;
};
```
## Registering Commands
```
auto commandBridge = carb::getCachedInterface<omni::kit::commands::ICommandBridge>());
commandBridge->registerCommand(
"omni.example.cpp.commands", "ExampleCppCommand", ExampleCppCommand::create, ExampleCppCommand::populateKeywordArgs);
// Note that the command name (in this case "ExampleCppCommand") is arbitrary and does not need to match the C++ class
```
## Executing Commands
```
auto commandBridge = carb::getCachedInterface<omni::kit::commands::ICommandBridge>());
// Create the kwargs dictionary.
auto iDictionary = carb::getCachedInterface<carb::dictionary::IDictionary>();
carb::dictionary::Item* kwargs = iDictionary->createItem(nullptr, "", carb::dictionary::ItemType::eDictionary);
iDictionary->makeIntAtPath(kwargs, "x", 7);
iDictionary->makeIntAtPath(kwargs, "y", 9);
// Execute the command using its name...
commandBridge->executeCommand("ExampleCppCommand", kwargs);
// or without the 'Command' postfix just like Python commands...
commandBridge->executeCommand("ExampleCpp", kwargs);
// or fully qualified if needed to disambiguate (works with or without the 'Command)' postfix.
commandBridge->executeCommand("omni.example.cpp.commands", "ExampleCppCommand", kwargs);
// Destroy the kwargs dictionary.
iDictionary->destroyItem(kwargs);
// The C++ command can be executed from Python exactly like any Python command,
// and we can also execute Python commands from C++ in the same ways as above:
commandBridge->executeCommand("SomePythonCommand", kwargs);
// etc.
```
## Undo/Redo/Repeat Commands
```
auto commandBridge = carb::getCachedInterface<omni::kit::commands::ICommandBridge>());
// It doesn't matter whether the command stack contains Python commands, C++ commands,
// or a mix of both, and the same stands for when undoing/redoing commands from Python.
commandBridge->undoCommand();
commandBridge->redoCommand();
commandBridge->repeatCommand();
```
## Deregistering Commands
```
auto commandBridge = carb::getCachedInterface<omni::kit::commands::ICommandBridge>());
commandBridge->deregisterCommand("omni.example.cpp.commands", "ExampleCppCommand");
```
| 4,154 | Markdown | 32.508064 | 121 | 0.685123 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/python/tests/test_cpp_widget.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__ = ["TestCppWidget"]
from omni.example.cpp.ui_widget import CppWidget
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.kit.app
import omni.ui as ui
EXTENSION_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
GOLDEN_PATH = EXTENSION_PATH.joinpath("data/golden")
STYLE = {"CppWidget": {"color": ui.color.red}}
class TestCppWidget(OmniUiTest):
async def test_general(self):
"""Testing general look of CppWidget"""
window = await self.create_test_window()
with window.frame:
CppWidget(thickness=2, style=STYLE)
await self.finalize_test(golden_img_dir=GOLDEN_PATH, golden_img_name=f"test_general.png")
| 1,180 | Python | 34.787878 | 108 | 0.738136 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/bindings/python/omni.example.cpp.ui_widget/BindCppWidget.cpp | // 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.
//
#include <omni/ui/bind/BindUtils.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <CppWidget.h>
#include <BindCppWidget.h>
using namespace pybind11;
OMNIUI_NAMESPACE_USING_DIRECTIVE
OMNIUI_CPPWIDGET_NAMESPACE_USING_DIRECTIVE
void wrapCppWidget(module& m)
{
const char* cppWidgetDoc = OMNIUI_PYBIND_CLASS_DOC(CppWidget);
const char* cppWidgetConstructorDoc = OMNIUI_PYBIND_CONSTRUCTOR_DOC(CppWidget, CppWidget);
class_<CppWidget, omni::ui::Widget, std::shared_ptr<CppWidget>>(m, "CppWidget", cppWidgetDoc)
.def(init([](kwargs kwargs) { OMNIUI_PYBIND_INIT(CppWidget) }), cppWidgetConstructorDoc)
.def_property(
"thickness", &CppWidget::getThickness, &CppWidget::setThickness, OMNIUI_PYBIND_DOC_CppWidget_thickness)
/* */;
}
| 1,263 | C++ | 36.17647 | 115 | 0.752177 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/bindings/python/omni.example.cpp.ui_widget/Module.cpp | // 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.
//
#include <carb/BindingsUtils.h>
#include <omni/ui/bind/BindUtils.h>
#include <pybind11/pybind11.h>
// We need to be registered as Carbonite plugin because we need to use CARB_LOG_ERROR
CARB_BINDINGS("omni.example.cpp.ui_widget.python")
PYBIND11_MODULE(_example_cpp_widget, m)
{
pybind11::module::import("omni.ui");
OMNIUI_BIND(CppWidget);
}
| 787 | C++ | 33.260868 | 85 | 0.768742 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/bindings/python/omni.example.cpp.ui_widget/DocCppWidget.h | // 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.
//
#pragma once
#define OMNIUI_PYBIND_DOC_CppWidget \
"A simple C++ omni.ui widget that draws a rectangle.\n" \
"\n"
#define OMNIUI_PYBIND_DOC_CppWidget_thickness "This property holds the thickness of the rectangle line.\n"
#define OMNIUI_PYBIND_DOC_CppWidget_CppWidget "Constructor.\n"
| 873 | C | 47.555553 | 120 | 0.647194 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/bindings/python/omni.example.cpp.ui_widget/BindCppWidget.h | // 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.
//
#pragma once
#include <DocCppWidget.h>
#include <omni/ui/bind/BindWidget.h>
// clang-format off
#define OMNIUI_PYBIND_INIT_CppWidget \
OMNIUI_PYBIND_INIT_CAST(thickness, setThickness, float) \
OMNIUI_PYBIND_INIT_Widget
#define OMNIUI_PYBIND_KWARGS_DOC_CppWidget \
"\n `thickness : float`\n " \
OMNIUI_PYBIND_DOC_CppWidget_thickness \
OMNIUI_PYBIND_KWARGS_DOC_Widget
// clang-format on
| 1,224 | C | 47.999998 | 120 | 0.52451 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/include/CppWidget.h | // 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.
//
#pragma once
#include "Api.h"
#include <string>
#include <omni/ui/Widget.h>
OMNIUI_CPPWIDGET_NAMESPACE_OPEN_SCOPE
/**
* @brief A simple C++ omni.ui widget that draws a rectangle.
*/
class OMNIUI_CPPWIDGET_CLASS_API CppWidget : public OMNIUI_NS::Widget
{
OMNIUI_OBJECT(CppWidget)
public:
OMNIUI_CPPWIDGET_API
~CppWidget() override;
/**
* @brief This property holds the thickness of the rectangle line.
*/
/// @private (suppress doc generation error)
OMNIUI_PROPERTY(float, thickness, DEFAULT, 1.0f, READ, getThickness, WRITE, setThickness);
protected:
/**
* Constructor.
*/
OMNIUI_CPPWIDGET_API
CppWidget();
/**
* @brief Reimplemented the rendering code of the widget.
*
* @see Widget::_drawContent
*/
OMNIUI_CPPWIDGET_API
void _drawContent(float elapsedTime) override;
private:
};
OMNIUI_CPPWIDGET_NAMESPACE_CLOSE_SCOPE
| 1,354 | C | 24.092592 | 94 | 0.710487 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/include/Api.h | // 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.
//
#pragma once
#ifdef _WIN32
// When we build DLL, we need the __declspec(dllexport) keyword to export class
// member functions from a DLL. __declspec(dllexport) adds the export directive
// to the object file, so you do not need to use a .def file.
# define OMNIUI_CPPWIDGET_EXPORT __declspec(dllexport)
// When we build a third-party library that uses public symbols defined by this
// DLL, the symbols must be imported. We need to use __declspec(dllimport) on
// the declarations of the public symbols.
# define OMNIUI_CPPWIDGET_IMPORT __declspec(dllimport)
# define OMNIUI_CPPWIDGET_CLASS_EXPORT
#else
// It works similarly in Linux. The symbols must be visible in DSO because we
// build with the compiler option -fvisibility=hidden.
# define OMNIUI_CPPWIDGET_EXPORT __attribute__((visibility("default")))
// But to use them we don't need to use any dirrective.
# define OMNIUI_CPPWIDGET_IMPORT
// typeinfo of the class should be visible in DSO as well.
# define OMNIUI_CPPWIDGET_CLASS_EXPORT __attribute__((visibility("default")))
#endif
#if defined(OMNIUI_CPPWIDGET_STATIC)
# define OMNIUI_CPPWIDGET_API
# define OMNIUI_CPPWIDGET_CLASS_API
#else
# if defined(OMNIUI_CPPWIDGET_EXPORTS)
# define OMNIUI_CPPWIDGET_API OMNIUI_CPPWIDGET_EXPORT
# define OMNIUI_CPPWIDGET_CLASS_API OMNIUI_CPPWIDGET_CLASS_EXPORT
# else
# define OMNIUI_CPPWIDGET_API OMNIUI_CPPWIDGET_IMPORT
# define OMNIUI_CPPWIDGET_CLASS_API
# endif
#endif
#define OMNIUI_CPPWIDGET_NS omni::ui::example_cpp_widget
#define OMNIUI_CPPWIDGET_NAMESPACE_USING_DIRECTIVE using namespace OMNIUI_CPPWIDGET_NS;
#define OMNIUI_CPPWIDGET_NAMESPACE_OPEN_SCOPE \
namespace omni \
{ \
namespace ui \
{ \
namespace example_cpp_widget \
{
#define OMNIUI_CPPWIDGET_NAMESPACE_CLOSE_SCOPE \
} \
} \
}
| 3,167 | C | 54.578946 | 120 | 0.533944 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/config/extension.toml | [package]
version = "1.0.1" # Semantic Versioning is used: https://semver.org/
# These fields are used primarily for display in the extension browser UI.
title = "Example C++ Extension: UI Widget"
description = "Demonstrates how to create a C++ widget for omni.ui"
category = "Example"
keywords = ["example", "C++", "cpp", "UI"]
icon = "data/icon.png"
preview_image = "data/preview.png"
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
authors = ["Victor Yudin <[email protected]>", "David Bosnich <[email protected]>"]
repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp"
[dependencies]
"omni.ui" = {}
[[python.module]]
name = "omni.example.cpp.ui_widget"
[[native.library]]
path = "bin/${lib_prefix}omni.example.cpp.ui_widget${lib_ext}"
[[test]]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.ui_test",
]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
stdoutFailPatterns.exclude = [
"*omniclient: Initialization failed*",
]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
cpp_api = [
"include/CppWidget.h",
]
| 1,177 | TOML | 23.040816 | 85 | 0.675446 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/plugins/omni.example.cpp.ui_widget/ExampleUIExtension.cpp | // 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.
//
#include <carb/BindingsUtils.h>
#include <omni/ui/Api.h>
#ifdef _WIN32
# include <Windows.h>
#endif
// We need to be registered as Carbonite client because we need to use Carbonite interfaces.
CARB_BINDINGS("omni.example.cpp.ui_widget")
| 677 | C++ | 34.684209 | 92 | 0.776957 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/plugins/omni.example.cpp.ui_widget/CppWidget.cpp | // 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.
//
#include <imgui/imgui.h>
#include <imgui/imgui_internal.h>
#include <CppWidget.h>
OMNIUI_CPPWIDGET_NAMESPACE_OPEN_SCOPE
CppWidget::CppWidget() : Widget{}
{
}
CppWidget::~CppWidget()
{
}
void CppWidget::_drawContent(float elapsedTime)
{
ImVec2 start = ImGui::GetCursorScreenPos();
float computedWidth = this->getComputedContentWidth();
float computedHeight = this->getComputedContentHeight();
// Draw a rect
ImVec2 rectMax{ start.x + computedWidth, start.y + computedHeight };
// We need to scale the thickness to look similar on all the monitors.
float scaledThickness = this->getThickness() * this->getDpiScale();
// Determine which color we need from the style. The style should look like
// this to set red color:
// {"CppWidget": {"color": ui.color.red}}
uint32_t color = 0xff000000;
this->_resolveStyleProperty(StyleColorProperty::eColor, &color);
ImGui::GetWindowDrawList()->AddRect(start, rectMax, 0xff0000ff, 0.0f, 0, scaledThickness);
}
OMNIUI_CPPWIDGET_NAMESPACE_CLOSE_SCOPE
| 1,481 | C++ | 31.217391 | 94 | 0.738015 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/docs/Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create a C++ widget for omni.ui that has a property and draws a simple rectangle.
| 211 | Markdown | 29.28571 | 101 | 0.777251 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usdrt/python/tests/test_usdrt_example.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.example.cpp.usdrt
import omni.kit.app
import omni.kit.test
import omni.usd
from usdrt import Sdf
class TestUsdrtExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
# Cache the example usdrt interface.
self.example_usdrt_interface = omni.example.cpp.usdrt.get_example_usdrt_interface()
# Open a new USD stage.
omni.usd.get_context().new_stage()
self.usd_stage = omni.usd.get_context().get_stage()
self.stage_id = omni.usd.get_context().get_stage_id()
# Create a torus
(success, pathString) = omni.kit.commands.execute("CreateMeshPrimWithDefaultXformCommand", prim_type="Torus")
self.assertTrue(success)
self.prim_path = Sdf.Path(pathString)
async def tearDown(self):
# Close the USD stage.
await omni.usd.get_context().close_stage_async()
self.usd_stage = None
# Clear the example usdrt interface.
self.example_usdrt_interface = None
async def test_get_attributes_for_prim(self):
(err, attrs) = self.example_usdrt_interface.get_attributes_for_prim(self.stage_id, self.prim_path)
self.assertTrue(err == "")
self.assertTrue(attrs)
# test invalid prim
(err, attrs) = self.example_usdrt_interface.get_attributes_for_prim(self.stage_id, Sdf.Path("/invalidPrim"))
self.assertTrue(err == "Prim at path /invalidPrim is not in Fabric")
self.assertFalse(attrs)
# test empty path
(err, attrs) = self.example_usdrt_interface.get_attributes_for_prim(self.stage_id, Sdf.Path(""))
self.assertTrue(err == "Nothing selected")
self.assertFalse(attrs)
async def test_apply_random_rotation(self):
(err, rotation) = self.example_usdrt_interface.apply_random_rotation(self.stage_id, self.prim_path)
self.assertTrue(err == "")
self.assertTrue(rotation)
# test invalid prim
(err, rotation) = self.example_usdrt_interface.apply_random_rotation(self.stage_id, Sdf.Path("/invalidPrim"))
self.assertTrue(err == "Prim at path /invalidPrim is not in Fabric")
# test empty path
(err, rotation) = self.example_usdrt_interface.apply_random_rotation(self.stage_id, Sdf.Path(""))
self.assertTrue(err == "Nothing selected")
async def test_deform_mesh(self):
t = 0
result = self.example_usdrt_interface.deform_mesh(self.stage_id, self.prim_path, t)
self.assertTrue(result == f"Deformed points on prim {self.prim_path}")
# test invalid prim
result = self.example_usdrt_interface.deform_mesh(self.stage_id, Sdf.Path("/invalidPrim"), t)
self.assertTrue(result == "Prim at path /invalidPrim is not in Fabric")
# test empty path
result =self.example_usdrt_interface.deform_mesh(self.stage_id, Sdf.Path(""), t)
self.assertTrue(result == "Nothing selected")
| 3,357 | Python | 39.951219 | 117 | 0.677391 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usdrt/python/impl/example_usdrt_extension.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import math
import random
from ctypes import alignment
import omni.ext
import omni.ui as ui
import omni.usd
from usdrt import Gf, Rt, Sdf, Usd, Vt
from .._example_usdrt_bindings import *
# Global public interface object.
_example_usdrt_interface = None
# Public API.
def get_example_usdrt_interface() -> IExampleUsdrtInterface:
return _example_usdrt_interface
def get_selected_prim_path():
"""Return the path of the first selected prim"""
context = omni.usd.get_context()
selection = context.get_selection()
paths = selection.get_selected_prim_paths()
return None if not paths else paths[0]
def get_stage_id():
"""Return the stage Id of the current stage"""
context = omni.usd.get_context()
return context.get_stage_id()
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class ExampleUsdrtExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
# Acquire the example USDRT interface.
global _example_usdrt_interface
_example_usdrt_interface = acquire_example_usdrt_interface()
print("[omni.example.cpp.usdrt] startup")
self._window = ui.Window(
"What's in Fabric?", width=300, height=300, dockPreference=ui.DockPreference.RIGHT_BOTTOM
)
self._t = 0
with self._window.frame:
with ui.VStack():
frame = ui.ScrollingFrame()
with frame:
label = ui.Label("Select a prim and push a button", alignment=ui.Alignment.LEFT_TOP)
def get_fabric_data():
selected_prim_path = get_selected_prim_path()
(err, data) = _example_usdrt_interface.get_attributes_for_prim(
get_stage_id(), selected_prim_path
)
if err:
label.text = err
else:
result = f"Fabric data for prim at path {selected_prim_path}\n\n\n"
for attr in data:
try:
data = attr.Get()
datastr = str(data)
if data is None:
datastr = "<no value>"
except TypeError:
# Some data types not yet supported in Python
datastr = "<no Python conversion>"
result += "{} ({}): {}\n".format(
attr.GetName(), str(attr.GetTypeName().GetAsToken()), datastr
)
label.text = result
def rotate_prim():
selected_prim_path = get_selected_prim_path()
(err, rotation) = _example_usdrt_interface.apply_random_rotation(
get_stage_id(), selected_prim_path
)
label.text = err if err else f"Set new world orientation on {selected_prim_path} to {rotation}"
def deform_prim():
label.text = _example_usdrt_interface.deform_mesh(
get_stage_id(), get_selected_prim_path(), self._t
)
self._t += 1
ui.Button("What's in Fabric?", clicked_fn=get_fabric_data, height=0)
ui.Button("Rotate it in Fabric!", clicked_fn=rotate_prim, height=0)
ui.Button("Deform it!", clicked_fn=deform_prim, height=0)
def on_shutdown(self):
global _example_usdrt_interface
# Release the example USDRT interface.
release_example_usdrt_interface(_example_usdrt_interface)
_example_usdrt_interface = None
print("[omni.example.cpp.usdrt] shutdown")
| 4,631 | Python | 39.631579 | 119 | 0.57547 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usdrt/bindings/python/omni.example.cpp.usdrt/ExampleUsdrtBindings.cpp | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <carb/BindingsPythonUtils.h>
#include <omni/example/cpp/usdrt/IExampleUsdrtInterface.h>
#include <usdrt/scenegraph/base/gf/quatf.h>
#include <usdrt/scenegraph/usd/sdf/path.h>
#include <usdrt/scenegraph/usd/usd/attribute.h>
CARB_BINDINGS("omni.example.cpp.usdrt.python")
DISABLE_PYBIND11_DYNAMIC_CAST(
omni::example::cpp::usdruntime::IExampleUsdrtInterface)
namespace {
// Define the pybind11 module using the same name specified in premake5.lua
PYBIND11_MODULE(_example_usdrt_bindings, m) {
using namespace omni::example::cpp::usdruntime;
m.doc() = "pybind11 omni.example.cpp.usdrt bindings";
carb::defineInterfaceClass<IExampleUsdrtInterface>(
m, "IExampleUsdrtInterface", "acquire_example_usdrt_interface",
"release_example_usdrt_interface")
.def("get_attributes_for_prim",
[](IExampleUsdrtInterface &self, long int id,
usdrt::SdfPath* path) {
std::vector<usdrt::UsdAttribute> data;
std::string err = self.get_attributes_for_prim(id, path, &data);
return std::make_tuple(err, data);
},
py::arg("stageId"), py::arg("primPath"))
.def("apply_random_rotation",
[](IExampleUsdrtInterface &self,long int id,
usdrt::SdfPath* path) {
usdrt::GfQuatf rot;
std::string err = self.apply_random_rotation(id, path, &rot);
return std::make_tuple(err, rot);
},
py::arg("stageId"), py::arg("primPath"))
.def("deform_mesh",
&IExampleUsdrtInterface::deform_mesh, py::arg("stageId"),
py::arg("primPath"), py::arg("time"));
}
} // namespace
| 2,108 | C++ | 37.345454 | 77 | 0.671727 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usdrt/include/omni/example/cpp/usdrt/IExampleUsdrtInterface.h | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Interface.h>
#include <usdrt/scenegraph/usd/usd/attribute.h>
#include <usdrt/scenegraph/usd/sdf/path.h>
#include <usdrt/scenegraph/base/gf/quatf.h>
namespace omni
{
namespace example
{
namespace cpp
{
namespace usdruntime
{
/**
* Interface used to interact with the example C++ USDRT plugin from Python.
*/
class IExampleUsdrtInterface
{
public:
/// @private
CARB_PLUGIN_INTERFACE("omni::example::cpp::usdruntime::IExampleUsdrtInterface", 1, 0);
/*
Get the Fabric data for a path.
*/
virtual std::string get_attributes_for_prim(long int stageId, usdrt::SdfPath* path, std::vector<usdrt::UsdAttribute>* data) = 0;
/*
Apply a random world space rotation to a prim in Fabric.
*/
virtual std::string apply_random_rotation(long int stageId, usdrt::SdfPath* path, usdrt::GfQuatf* rot) = 0;
/*
Deform a Mesh prim
*/
virtual std::string deform_mesh(long int stageId, usdrt::SdfPath* path, int time) = 0;
};
}
}
}
}
| 1,445 | C | 25.290909 | 132 | 0.715571 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usdrt/plugins/omni.example.cpp.usdrt/ExampleUsdrtExtension.cpp | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#define CARB_EXPORTS
#include <carb/PluginUtils.h>
#include <omni/example/cpp/usdrt/IExampleUsdrtInterface.h>
#include <omni/ext/ExtensionsUtils.h>
#include <omni/ext/IExt.h>
#include <omni/kit/IApp.h>
#include <usdrt/scenegraph/usd/usd/stage.h>
#include <usdrt/scenegraph/usd/usd/prim.h>
#include <usdrt/scenegraph/usd/rt/xformable.h>
#include <usdrt/scenegraph/usd/sdf/path.h>
#include <usdrt/scenegraph/base/gf/vec3f.h>
#include <usdrt/scenegraph/base/gf/quatf.h>
#include <usdrt/scenegraph/base/vt/array.h>
#include <usdrt/scenegraph/usd/usd/attribute.h>
#include <omni/fabric/IFabric.h>
#include <vector>
#include <random>
const struct carb::PluginImplDesc pluginImplDesc = { "omni.example.cpp.usdrt.plugin",
"An example C++ USDRT extension.", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
namespace omni
{
namespace example
{
namespace cpp
{
namespace usdruntime
{
class ExampleCppUsdrtExtension : public IExampleUsdrtInterface
{
protected:
/*
Get the Fabric data for a path.
*/
std::string get_attributes_for_prim(long int stageId, usdrt::SdfPath* path, std::vector<usdrt::UsdAttribute>* data) override;
/*
Apply a random world space rotation to a prim in Fabric.
*/
std::string apply_random_rotation(long int stageId, usdrt::SdfPath* path, usdrt::GfQuatf* rot) override;
/*
Deform a Mesh prim
*/
std::string deform_mesh(long int stageId, usdrt::SdfPath* path, int time) override;
private:
};
inline std::string ExampleCppUsdrtExtension::get_attributes_for_prim(long int stageId, usdrt::SdfPath* path, std::vector<usdrt::UsdAttribute>* data)
{
if (!path || path->IsEmpty()) {
return "Nothing selected";
}
if (data == nullptr) {
return "Invalid data";
}
usdrt::UsdStageRefPtr stage = usdrt::UsdStage::Attach(omni::fabric::UsdStageId(stageId));
// If a prim does not already exist in Fabric,
// it will be fetched from USD by simply creating the
// Usd.Prim object. At this time, only the attributes that have
// authored opinions will be fetch into Fabric.
usdrt::UsdPrim prim = stage->GetPrimAtPath(*path);
if (!prim) {
return "Prim at path " + path->GetString() + " is not in Fabric";
}
// This diverges a bit from USD - only attributes
// that exist in Fabric are returned by this API
std::vector<usdrt::UsdAttribute> attrs = prim.GetAttributes();
*data = attrs;
return "";
}
inline std::string ExampleCppUsdrtExtension::apply_random_rotation(long int stageId, usdrt::SdfPath* path, usdrt::GfQuatf* rot) {
//Apply a random world space rotation to a prim in Fabric
if (!path || path->IsEmpty()) {
return "Nothing selected";
}
if (rot == nullptr) {
return "Invalid data";
}
usdrt::UsdStageRefPtr stage = usdrt::UsdStage::Attach(omni::fabric::UsdStageId(stageId));
usdrt::UsdPrim prim = stage->GetPrimAtPath(*path);
if (!prim) {
return "Prim at path " + path->GetString() + " is not in Fabric";
}
usdrt::RtXformable rtxformable = usdrt::RtXformable(prim);
if (!rtxformable.HasWorldXform()) {
rtxformable.SetWorldXformFromUsd();
}
std::random_device rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<float> dist(0.0f, 1.0f);
float angle = dist(gen) * M_PI * 2;
usdrt::GfVec3f axis = usdrt::GfVec3f(dist(gen), dist(gen), dist(gen)).GetNormalized();
float halfangle = angle / 2.0;
float shalfangle = sin(halfangle);
usdrt::GfQuatf rotation = usdrt::GfQuatf(cos(halfangle), axis[0] * shalfangle, axis[1] * shalfangle, axis[2] * shalfangle);
rtxformable.GetWorldOrientationAttr().Set(rotation);
*rot = rotation;
return "";
}
inline std::string ExampleCppUsdrtExtension::deform_mesh(long int stageId, usdrt::SdfPath* path, int time) {
// Deform a Mesh prim
if (!path || path->IsEmpty()) {
return "Nothing selected";
}
usdrt::UsdStageRefPtr stage = usdrt::UsdStage::Attach(omni::fabric::UsdStageId(stageId));
usdrt::UsdPrim prim = stage->GetPrimAtPath(*path);
if (!prim) {
return "Prim at path " + path->GetString() + " is not in Fabric";
}
if (!prim.HasAttribute("points")) {
return "Prim at path " + path->GetString() + " does not have points attribute";
}
// Tell OmniHydra to render points from Fabric
if (!prim.HasAttribute("Deformable")) {
prim.CreateAttribute("Deformable", usdrt::SdfValueTypeNames->PrimTypeTag, true);
}
usdrt::UsdAttribute points = prim.GetAttribute("points");
usdrt::VtArray<usdrt::GfVec3f> pointsarray;
points.Get(&pointsarray);
// Deform points
// In the python example, this uses warp to run the deformation on GPU
// The more correct C++ equivalent would be to write a CUDA kernel for this
// but for simplicity of this example, do the deformation here on CPU.
for (usdrt::GfVec3f& point : pointsarray) {
float offset = -sin(point[0]);
float scale = sin(time) * 10.0;
point = point + usdrt::GfVec3f(0.0, offset * scale, 0.0);
}
points.Set(pointsarray);
return "Deformed points on prim " + path->GetString();
}
}
}
}
}
CARB_PLUGIN_IMPL(pluginImplDesc, omni::example::cpp::usdruntime::ExampleCppUsdrtExtension)
void fillInterface(omni::example::cpp::usdruntime::ExampleCppUsdrtExtension& iface)
{
}
| 6,075 | C++ | 31.666666 | 148 | 0.670123 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usdrt/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.1] - 2023-11-13
- Updated USDRT example
## [1.0.0] - 2023-10-17
- Initial version
| 186 | Markdown | 17.699998 | 80 | 0.66129 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usdrt/docs/Overview.md | # Overview
# What's in Fabric? USDRT Scenegraph API example [omni.example.cpp.usdrt]
This is an example Kit extension using the USDRT Scenegraph API. This C++
extension demonstrates the following:
- Inspecting Fabric data using the USDRT Scenegraph API
- Manipulating prim transforms in Fabric using the RtXformable schema
- Deforming Mesh geometry | 351 | Markdown | 34.199997 | 73 | 0.803419 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.ui/config/extension.toml | [package]
version = "1.0.0" # Semantic Versioning is used: https://semver.org/
# These fields are used primarily for display in the extension browser UI.
title = "Example Python Extension: UI"
description = "Demonstrates how to create simple UI elements (eg. buttons and labels) from Python."
category = "Example"
keywords = ["example"]
icon = "data/icon.png"
preview_image = "data/preview.png"
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
authors = ["Anton Novoselov <[email protected]>", "David Bosnich <[email protected]>"]
repository = "https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp"
# List all dependencies of this extension.
[dependencies]
"omni.kit.uiapp" = {}
"omni.example.cpp.ui_widget" = {} # To demonstrate using widgets defined in C++
# Define the Python modules that this extension provides.
[[python.module]]
name = "omni.example.python.ui"
# Define any test specific properties of this extension.
[[test]]
dependencies = [
"omni.kit.ui_test"
]
# Define the documentation that will be generated for this extension.
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 1,153 | TOML | 30.189188 | 99 | 0.730269 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.ui/omni/example/python/ui/example_python_ui_extension.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.ext
import omni.ui as ui
from omni.example.cpp.ui_widget import CppWidget
class ExamplePythonUIExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print(f"ExamplePythonUIExtension starting up (ext_id: {ext_id}).")
self._count = 0
self._window = ui.Window("Example Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
label = ui.Label("")
def on_click():
self._count += 1
label.text = f"count: {self._count}"
def on_reset():
self._count = 0
label.text = "empty"
on_reset()
with ui.HStack():
ui.Button("Add", clicked_fn=on_click)
ui.Button("Reset", clicked_fn=on_reset)
# Use a widget that was defined in C++
STYLE = {"CppWidget": {"color": ui.color.red}}
CppWidget(thickness=2, style=STYLE)
def on_shutdown(self):
print(f"ExamplePythonUIExtension shutting down.")
self._count = 0
| 1,579 | Python | 33.347825 | 77 | 0.592147 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.ui/omni/example/python/ui/tests/test_example_python_ui.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.
##
# omni.kit.test is primarily Python's standard unittest module
# with additional wrapping to add suport for async/await tests.
# Please see: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# omni.kit.ui_test is for simulating UI interactions in tests.
import omni.kit.ui_test as ui_test
# The Python module we are testing, imported with an absolute
# path to simulate using it from a different Python extension.
import omni.example.python.ui
# Any class that dervives from 'omni.kit.test.AsyncTestCase'
# declared at the root of the module will be auto-discovered,
class Test(omni.kit.test.AsyncTestCase):
# Called before running each test.
async def setUp(self):
pass
# Called after running each test.
async def tearDown(self):
pass
# Example test case that simulates UI interactions.
async def test_window_button(self):
# Find a label in the window.
label = ui_test.find("Example Window//Frame/**/Label[*]")
# Find buttons in the window.
add_button = ui_test.find("Example Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("Example Window//Frame/**/Button[*].text=='Reset'")
# Click the add button.
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
# Click the add button.
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
# Click the reset button.
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
| 2,009 | Python | 35.545454 | 87 | 0.703335 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.ui/docs/CHANGELOG.md | # Changelog
## [1.0.0] - 2022-07-01
### Added
- Initial implementation.
| 73 | Markdown | 11.333331 | 25 | 0.630137 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.ui/docs/Overview.md | # Overview
An example Python extension that can be used as a template for creating new extensions.
Demonstrates how to create simple UI elements (eg. buttons and labels) from Python, and also how to use UI widgets that were created in C++.
| 243 | Markdown | 33.857138 | 140 | 0.777778 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.actions/plugins/omni.example.cpp.actions.tests/ExampleActionsTests.cpp | // Copyright (c) 2020-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.
//
#include <omni/kit/actions/core/IActionRegistry.h>
#include <doctest/doctest.h>
#include <carb/BindingsUtils.h>
CARB_BINDINGS("omni.example.cpp.actions.tests")
TEST_SUITE("omni.example.cpp.actions.tests")
{
using namespace omni::kit::actions::core;
TEST_CASE("Execute Example C++ Action")
{
auto actionRegistry = carb::getCachedInterface<IActionRegistry>();
REQUIRE(actionRegistry != nullptr);
carb::ObjectPtr<IAction> action;
SUBCASE("Custom")
{
action = actionRegistry->getAction("omni.example.cpp.actions", "example_custom_action_id");
REQUIRE(action.get() != nullptr);
auto result = action->execute();
CHECK(result.hasValue());
CHECK(result.getValue<uint32_t>() == 1);
result = action->execute();
CHECK(result.hasValue());
CHECK(result.getValue<uint32_t>() == 2);
}
SUBCASE("Lambda")
{
action = actionRegistry->getAction("omni.example.cpp.actions", "example_lambda_action_id");
REQUIRE(action.get() != nullptr);
auto result = action->execute();
CHECK(!result.hasValue());
}
}
}
| 1,665 | C++ | 31.038461 | 103 | 0.643243 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.actions/plugins/omni.example.cpp.actions/ExampleActionsExtension.cpp | // 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.
//
#define CARB_EXPORTS
#include <carb/PluginUtils.h>
#include <omni/ext/IExt.h>
#include <omni/kit/actions/core/IActionRegistry.h>
#include <omni/kit/actions/core/LambdaAction.h>
const struct carb::PluginImplDesc pluginImplDesc = { "omni.example.cpp.actions.plugin",
"An example C++ extension.", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
namespace omni
{
namespace example
{
namespace cpp
{
namespace actions
{
using namespace omni::kit::actions::core;
class ExampleCustomAction : public Action
{
public:
static carb::ObjectPtr<IAction> create(const char* extensionId,
const char* actionId,
const MetaData* metaData)
{
// Note: It is important to construct the handler using ObjectPtr<T>::InitPolicy::eSteal,
// otherwise we end up incresing the reference count by one too many during construction,
// resulting in a carb::ObjectPtr<IAction> whose object instance will never be destroyed.
return carb::stealObject<IAction>(new ExampleCustomAction(extensionId, actionId, metaData));
}
ExampleCustomAction(const char* extensionId, const char* actionId, const MetaData* metaData)
: Action(extensionId, actionId, metaData), m_executionCount(0)
{
}
carb::variant::Variant execute(const carb::variant::Variant& args = {},
const carb::dictionary::Item* kwargs = nullptr) override
{
++m_executionCount;
printf("Executing %s (execution count = %d).\n", getActionId(), m_executionCount);
return carb::variant::Variant(m_executionCount);
}
void invalidate() override
{
resetExecutionCount();
}
uint32_t getExecutionCount() const
{
return m_executionCount;
}
protected:
void resetExecutionCount()
{
m_executionCount = 0;
}
private:
uint32_t m_executionCount = 0;
};
class ExampleActionsExtension : public omni::ext::IExt
{
public:
void onStartup(const char* extId) override
{
auto actionRegistry = carb::getCachedInterface<IActionRegistry>();
if (!actionRegistry)
{
CARB_LOG_WARN("Could not get cached IActionRegistry interface.");
return;
}
// Example of registering a custom action from C++.
Action::MetaData metaData;
metaData.displayName = "Example Custom Action Display Name";
metaData.description = "Example Custom Action Description.";
m_exampleCustomAction = ExampleCustomAction::create("omni.example.cpp.actions", "example_custom_action_id", &metaData);
actionRegistry->registerAction(m_exampleCustomAction);
// Example of registering a lambda action from C++.
m_exampleLambdaAction = actionRegistry->registerAction(
"omni.example.cpp.actions", "example_lambda_action_id",
[](const carb::variant::Variant& args = {}, const carb::dictionary::Item* kwargs = nullptr) {
printf("Executing example_lambda_action_id.\n");
return carb::variant::Variant();
},
"Example Lambda Action Display Name",
"Example Lambda Action Description.");
}
void onShutdown() override
{
if (auto actionRegistry = carb::getCachedInterface<IActionRegistry>())
{
actionRegistry->deregisterAction(m_exampleLambdaAction);
m_exampleLambdaAction = nullptr;
actionRegistry->deregisterAction(m_exampleCustomAction);
m_exampleCustomAction = nullptr;
}
else
{
CARB_LOG_WARN("Could not get cached IActionRegistry interface.");
}
}
private:
carb::ObjectPtr<IAction> m_exampleCustomAction;
carb::ObjectPtr<IAction> m_exampleLambdaAction;
};
}
}
}
}
CARB_PLUGIN_IMPL(pluginImplDesc, omni::example::cpp::actions::ExampleActionsExtension)
void fillInterface(omni::example::cpp::actions::ExampleActionsExtension& iface)
{
}
| 4,585 | C++ | 31.524822 | 127 | 0.646456 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.actions/omni/example/cpp/actions/tests/test_actions_example.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.actions.core
class TestActionsExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
self.action_registry = omni.kit.actions.core.get_action_registry()
self.extension_id = "omni.example.cpp.actions"
async def tearDown(self):
self.extension_id = None
self.action_registry = None
async def test_find_and_execute_custom_action(self):
action = self.action_registry.get_action(self.extension_id, "example_custom_action_id")
self.assertIsNotNone(action)
result = action.execute()
self.assertEqual(result, 3) # 3 because this was already executed twice in the C++ tests
result = action.execute()
self.assertEqual(result, 4)
async def test_find_and_execute_lambda_action(self):
action = self.action_registry.get_action(self.extension_id, "example_lambda_action_id")
self.assertIsNotNone(action)
result = action.execute()
self.assertIsNone(result)
| 1,455 | Python | 36.333332 | 96 | 0.716151 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.actions/docs/Overview.md | # Overview
An example C++ extension that can be used as a reference/template for creating new extensions.
Demonstrates how to create actions in C++ that can then be executed from either C++ or Python.
See the omni.kit.actions.core extension for extensive documentation about actions themselves.
# C++ Usage Examples
## Defining Custom Actions
```
using namespace omni::kit::actions::core;
class ExampleCustomAction : public Action
{
public:
static carb::ObjectPtr<IAction> create(const char* extensionId,
const char* actionId,
const MetaData* metaData)
{
return carb::stealObject<IAction>(new ExampleCustomAction(extensionId, actionId, metaData));
}
ExampleCustomAction(const char* extensionId, const char* actionId, const MetaData* metaData)
: Action(extensionId, actionId, metaData), m_executionCount(0)
{
}
carb::variant::Variant execute(const carb::variant::Variant& args = {},
const carb::dictionary::Item* kwargs = nullptr) override
{
++m_executionCount;
printf("Executing %s (execution count = %d).\n", getActionId(), m_executionCount);
return carb::variant::Variant(m_executionCount);
}
void invalidate() override
{
resetExecutionCount();
}
uint32_t getExecutionCount() const
{
return m_executionCount;
}
protected:
void resetExecutionCount()
{
m_executionCount = 0;
}
private:
uint32_t m_executionCount = 0;
};
```
## Creating and Registering Custom Actions
```
// Example of creating and registering a custom action from C++.
Action::MetaData metaData;
metaData.displayName = "Example Custom Action Display Name";
metaData.description = "Example Custom Action Description.";
carb::ObjectPtr<IAction> exampleCustomAction =
ExampleCustomAction::create("omni.example.cpp.actions", "example_custom_action_id", &metaData);
carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>()->registerAction(exampleCustomAction);
```
## Creating and Registering Lambda Actions
```
auto actionRegistry = carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>();
// Example of creating and registering a lambda action from C++.
omni::kit::actions::core::IAction::MetaData metaData;
metaData.displayName = "Example Lambda Action Display Name";
metaData.description = "Example Lambda Action Description.";
carb::ObjectPtr<IAction> exampleLambdaAction =
omni::kit::actions::core::LambdaAction::create(
"omni.example.cpp.actions", "example_lambda_action_id", &metaData,
[this](const carb::variant::Variant& args = {}, const carb::dictionary::Item* kwargs = nullptr) {
printf("Executing example_lambda_action_id.\n");
return carb::variant::Variant();
}));
carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>()->registerAction(exampleLambdaAction);
```
```
// Example of creating and registering (at the same time) a lambda action from C++.
carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>()->registerAction(
"omni.example.cpp.actions", "example_lambda_action_id",
[](const carb::variant::Variant& args = {}, const carb::dictionary::Item* kwargs = nullptr) {
printf("Executing example_lambda_action_id.\n");
return carb::variant::Variant();
},
"Example Lambda Action Display Name",
"Example Lambda Action Description.");
```
## Discovering Actions
```
auto registry = carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>();
// Retrieve an action that has been registered using the registering extension id and the action id.
carb::ObjectPtr<IAction> action = registry->getAction("omni.example.cpp.actions", "example_custom_action_id");
// Retrieve all actions that have been registered by a specific extension id.
std::vector<carb::ObjectPtr<IAction>> actions = registry->getAllActionsForExtension("example");
// Retrieve all actions that have been registered by any extension.
std::vector<carb::ObjectPtr<IAction>> actions = registry->getAllActions();
```
## Deregistering Actions
```
auto actionRegistry = carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>();
// Deregister an action directly...
actionRegistry->deregisterAction(exampleCustomAction);
// or using the registering extension id and the action id...
actionRegistry->deregisterAction("omni.example.cpp.actions", "example_custom_action_id");
// or deregister all actions that were registered by an extension.
actionRegistry->deregisterAllActionsForExtension("omni.example.cpp.actions");
```
## Executing Actions
```
auto actionRegistry = carb::getCachedInterface<omni::kit::actions::core::IActionRegistry>();
// Execute an action after retrieving it from the action registry.
auto action = actionRegistry->getAction("omni.example.cpp.actions", "example_custom_action_id");
action->execute();
// Execute an action indirectly (retrieves it internally).
actionRegistry->executeAction("omni.example.cpp.actions", "example_custom_action_id");
// Execute an action that was stored previously.
exampleCustomAction->execute();
```
Note: All of the above will find any actions that have been registered from either Python or C++,
and you can interact with them without needing to know anything about where they were registered.
| 5,460 | Markdown | 32.503067 | 110 | 0.712088 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/README.md | # omni.ui.scene Kit Extension Samples
## [Object Info (omni.example.ui_scene.object_info)](exts/omni.example.ui_scene.object_info)
[](exts/omni.example.ui_scene.object_info)
### About
This extension uses the omni.ui.scene API to add simple graphics and labels in the viewport above your selected prim. The labels provide the prim path of the selected prim and the prim path of its assigned material.
### [README](exts/omni.example.ui_scene.object_info)
See the [README for this extension](exts/omni.example.ui_scene.object_info) to learn more about it including how to use it.
### [Tutorial](exts/omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md)
Follow a [step-by-step tutorial](exts/omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
## [Widget Info (omni.example.ui_scene.widget_info)](exts/omni.example.ui_scene.object_info)
[](exts/omni.example.ui_scene.widget_info)
### About
This extension uses the omni.ui.scene API to add a widget in the viewport, just above your selected prim. The widget provides the prim path of your selection and a scale slider.
### [README](exts/omni.example.ui_scene.widget_info)
See the [README for this extension](exts/omni.example.ui_scene.widget_info) to learn more about it including how to use it.
### [Tutorial](exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md)
Follow a [step-by-step tutorial](exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
## [Light Manipulator (omni.example.ui_scene.light_manipulator)](exts/omni.example.ui_scene.light_manipulator)
[](exts/omni.example.ui_scene.light_manipulator)
### About
This extension add a custom manipulator for RectLights that allows you to control the width, height, and intensity of RectLights by clicking and dragging in the viewport.
### [README](exts/omni.example.ui_scene.light_manipulator)
See the [README for this extension](exts/omni.example.ui_scene.light_manipulator) to learn more about it including how to use it.
### [Tutorial](exts/omni.example.ui_scene.light_manipulator/tutorial/tutorial.md)
Follow a [step-by-step tutorial](exts/omni.example.ui_scene.light_manipulator/tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
## [Slider Manipulator (omni.example.ui_scene.slider_manipulator)](exts/omni.example.ui_scene.slider_manipulator)
[](exts/omni.example.ui_scene.slider_manipulator)
### About
This extension add a custom slider manipulator above you selected prim that controls the scale of the prim when you click and drag the slider.
### [README](exts/omni.example.ui_scene.slider_manipulator)
See the [README for this extension](exts/omni.example.ui_scene.slider_manipulator) to learn more about it including how to use it.
### [Tutorial](exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md)
Follow a [step-by-step tutorial](exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
# Adding These Extensions
To add these extensions to your Omniverse app:
1. Go into: Extension Manager -> Gear Icon -> Extension Search Path
2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene?branch=main&dir=exts`
## Linking with an Omniverse app
For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included.
Run:
```bash
> link_app.bat
```
There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```bash
> link_app.bat --app code
```
You can also just pass a path to create link to:
```bash
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3"
```
Running this command adds a symlink to Omniverse Code. This makes intellisense work and lets you easily run the app from the terminal.
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 4,736 | Markdown | 52.224719 | 215 | 0.776394 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md | 
# How to make a Slider Manipulator
In this guide you will learn how to draw a 3D slider in the viewport that overlays on the top of the bounding box of the selected prim. This slider will control the scale of the prim with a custom manipulator, model, and gesture. When the slider is changed, the manipulator processes the custom gesture that changes the data in the model, which changes the data directly in the USD stage.

# Learning Objectives
- Create an extension
- Import omni.ui and USD
- Set up Model and Manipulator
- Create Gestures
- Create a working scale slider
# Prerequisites
To help understand the concepts used in this guide, it is recommended that you complete the following:
- [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial)
- [Spawning Prims Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims)
- [Display Object Info Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/tree/main/exts/omni.example.ui_scene.object_info)
:exclamation: <span style="color:red"><b>WARNING:</b> Check that Viewport Utility Extension is turned ON in the Extensions Manager: </span>

# Step 1: Create the extension
In this section, you will create a new extension in Omniverse Code.
## Step 1.1: Create new extension template
In Omniverse Code navigate to the `Extensions` tab and create a new extension by clicking the ➕ icon in the upper left corner and select `New Extension Template Project`.


<br>
A new extension template window and Visual Studio Code will open after you have selected the folder location, folder name, and extension ID.
## Step 1.2: Naming your extension
In the extension manager, you may have noticed that each extension has a title and description:

You can change this in the `extension.toml` file by navigating to `VS Code` and editing the file there. It is important that you give your extension a detailed title and summary for the end user to understand what your extension will accomplish or display. Here is how to change it for this guide:
```python
# The title and description fields are primarily for displaying extension info in UI
title = "UI Scene Slider Manipulator"
description="Interactive example of the slider manipulator with omni.ui.scene"
```
## Step 2: Model module
In this step you will be creating the `slider_model.py` module where you will be tracking the current selected prim, listening to stage events, and getting the position directly from USD.
This module will be made up of many lines so be sure to review the <b>":memo:Code Checkpoint"</b> for updated code of the module at various steps.
### Step 2.1: Import omni.ui and USD
After creating `slider_model.py` in the same folder as `extension.py`, import `scene` from `omni.ui` and the necessary USD modules, as follows:
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
```
### Step 2.2: `SliderModel` and `PositionItem` Classes
Next, let's set up your `SliderModel` and `PositionItem` classes. `SliderModel` tracks the position and scale of the selected prim and `PositionItem` stores the position value.
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
# NEW
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# END NEW
```
## Step 2.3: Current Selection and Tracking Selection
In this section, you will be setting the variables for the current selection and tracking the selected prim, where you will also set parameters for the stage event later on.
```python
...
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# NEW
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
# END NEW
```
>:memo: Code Checkpoint
<details>
<summary> Click here for the updated <b>SliderModel</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
```
</details>
## Step 2.4: Define `on_stage_event()`
With your selection variables set, you now define the `on_stage_event()` call back to get the selected prim and its position on selection changes. You will start the new function for these below module previous code:
```python
...
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
```
>:memo: Code Checkpoint
<details>
<summary> Click here for the updated <b>SliderModel</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
```
</details>
<br>
## Step 2.5: `Tf.Notice` callback
In the previous step, you registered a callback to be called when objects in the stage change. [Click here for more information on Tf.Notice.](https://graphics.pixar.com/usd/dev/api/page_tf__notification.html) Now, you will define the callback function. You want to update the stored position of the selected prim. You can add that as follows:
```python
...
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
```
## Step 2.6: Set the Position Identifier and return Position
Let's define the identifier for position like so:
```python
...
def get_item(self, identifier):
if identifier == "position":
return self.position
```
And now, you will set item to return the position and get the value from the item:
```python
...
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
```
>:memo: Code Checkpoint
<details>
<summary> Click here for the updated <b>SliderModel</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
```
</details>
### Step 2.7: Position from USD
In this last section of `slider_model.py`, you will be defining `get_position` to compute position directly from USD, like so:
```python
...
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
>:memo: Code Checkpoint
<details>
<summary> Click here for the full <b>slider_model.py</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
</details>
## Step 3: Manipulator Module
In this step, you will be creating `slider_manipulator.py` in the same folder as `slider_model.py`. The Manipulator class will define `on_build()` as well as create the `Label` and regenerate the model.
### Step 3.1: Import omni.ui
After creating `slider_manipulator.py`, import `omni.ui` as follows:
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
```
### Step 3.2: Create `SliderManipulator` class
Now, you will begin the `SliderManipulator` class and define the `__init__()`:
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
```
### Step 3.3: Define `on_build()` and create the `Label`
`on_build()` is called when the model is changed and it will rebuild the slider. You will also create the `Label` for the slider and position it more towards the top of the screen.
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
```
### Step 3.4: Regenerate the Manipulator
Finally, let's define `on_model_updated()` to regenerate the manipulator:
```python
...
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the full <b>slider_manipulator.py</b> </summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
<br>
<br>
## Step 4: Registry Module
In this step, you will create `slider_registry.py` in the same location as the `slider_manipulator.py`. You will use `slider_registry.py` to have the number display on the screen when the prim is selected.
### Step 4.1: Import from Model and Manipulator
After creating `slider_registry.py`, import from the `SliderModel` and `SliderManipulator`, as well as `import typing` for type hinting, like so:
```python
from .slider_model import SliderModel
from .slider_manipulator import SliderManipulator
from typing import Any
from typing import Dict
from typing import Optional
```
### Step 4.2: Disable Selection in Viewport Legacy
Your first class will address disabling the selection in viewport legacy but you may encounter a bug that will not set your focused window to `True`. As a result, you will operate all `Viewport` instances for a given usd_context instead:
```python
...
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact the focused window!
# And there's no good solution to this when multiple Viewport-1 instances are open; so you just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
```
### Step 4.3: `SliderChangedGesture` Class
Under your previously defined `ViewportLegacyDisableSelection` class, you will define `SliderChangedGesture` class. In this class you will start with `__init__()` and then define `on_began()`, which will disable the selection rect when the user drags the slider:
```python
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, you don't want to see the selection rect
self.__disable_selection = ViewportLegacyDisableSelection()
```
Next in this class, you will define `on_changed()`, which will be called when the user moves the slider. This will update the mesh as the scale of the model is changed. You will also define `on_ended()` to re-enable the selection rect when the slider is not being dragged.
```python
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
```
>:memo: Code Checkpoint
<details>
<summary>Click here for <b>slider_registry.py</b> up to this point</summary>
```python
from .slider_model import SliderModel
from .slider_manipulator import SliderManipulator
from typing import Any
from typing import Dict
from typing import Optional
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact the focused window!
# And there's no good solution to this when multiple Viewport-1 instances are open; so you just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, you don't want to see the selection rect
self.__disable_selection = ViewportLegacyDisableSelection()
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
```
</details>
### Step 4.4: `SliderRegistry` Class
Now create `SliderRegistry` class after your previous functions.
This class is created by `omni.kit.viewport.registry` or `omni.kit.manipulator.viewport` per viewport and will keep the manipulator and some other properties that are needed in the viewport. You will set the `SliderRegistry` class after the class you made in the previous step. Included in this class are the `__init__()` methods for your manipulator and some getters and setters:
```python
...
class SliderRegistry:
"""
Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per
viewport. Keeps the manipulator and some properties that are needed to the
viewport.
"""
def __init__(self, description: Optional[Dict[str, Any]] = None):
self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture())
def destroy(self):
if self.__slider_manipulator:
self.__slider_manipulator.destroy()
self.__slider_manipulator = None
# PrimTransformManipulator & TransformManipulator don't have their own visibility
@property
def visible(self):
return True
@visible.setter
def visible(self, value):
pass
@property
def categories(self):
return ("manipulator",)
@property
def name(self):
return "Example Slider Manipulator"
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the full <b>slider_registry.py</b> </summary>
```python
from .slider_model import SliderModel
from .slider_manipulator import SliderManipulator
from typing import Any
from typing import Dict
from typing import Optional
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so you just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, you don't want to see the selection rect
self.__disable_selection = ViewportLegacyDisableSelection()
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
class SliderRegistry:
"""
Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per
viewport. Keeps the manipulator and some properties that are needed to the
viewport.
"""
def __init__(self, description: Optional[Dict[str, Any]] = None):
self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture())
def destroy(self):
if self.__slider_manipulator:
self.__slider_manipulator.destroy()
self.__slider_manipulator = None
# PrimTransformManipulator & TransformManipulator don't have their own visibility
@property
def visible(self):
return True
@visible.setter
def visible(self, value):
pass
@property
def categories(self):
return ("manipulator",)
@property
def name(self):
return "Example Slider Manipulator"
```
</details>
<br>
<br>
## Step 5: Update `extension.py`
You still have the default code in `extension.py` so now you will update the code to reflect the the modules you made. You can locate the `extension.py` in the `exts` folder hierarchy where you created `slider_model.py` and `slider_manipulator.py`.
### Step 5.1: New `extension.py` Imports
Let's begin by updating the imports at the top of `extension.py` to include `ManipulatorFactory`, `RegisterScene`, and `SliderRegistry` so that you can use them later on:
```python
import omni.ext
# NEW
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.viewport.registry import RegisterScene
from .slider_registry import SliderRegistry
# END NEW
```
### Step 5.2: References in on_startup
In this step, you will remove the default code in `on_startup` and replace it with a reference to the `slider_registry` and `slider_factory`, like so:
```python
...
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
# NEW
self.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider")
self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry)
# END NEW
```
### Step 5.3: Update on_shutdown
Now, you need to properly shutdown the extension. Let's remove the print statement and replace it with:
```python
...
def on_shutdown(self):
# NEW
ManipulatorFactory.destroy_manipulator(self.slider_factory)
self.slider_factory = None
self.slider_registry.destroy()
self.slider_registry = None
# END NEW
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the full <b>extension.py</b></summary>
```python
import omni.ext
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.viewport.registry import RegisterScene
from .slider_registry import SliderRegistry
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider")
self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry)
def on_shutdown(self):
ManipulatorFactory.destroy_manipulator(self.slider_factory)
self.slider_factory = None
self.slider_registry.destroy()
self.slider_registry = None
```
</details>
This is what you should see at this point in the viewport:

## Step 6: Creating the Slider Widget
Now that you have all of the variables and necessary properties referenced, let's start to create the slider widget. You will begin by creating the geometry needed for the widget, like the line, and then you will add a circle to the line.
### Step 6.1: Geometry Properties
You are going to begin by adding new geometry to `slider_manipulator.py`. You will set the geometry properties in the `__init__()` like so:
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# NEW
# Geometry properties
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
# END NEW
```
### Step 6.2: Create the line
Next, you will create a line above the selected prim. Let's add this to `on_build()`:
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# NEW
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# END NEW
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
```
This should be the result in your viewport:

### Step 6.3: Create the circle
You are still working in `slider_manipulator.py` and now you will be adding the circle on the line for the slider. This will also be added to `on_build()` like so:
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self.radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# NEW
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# END NEW
...
```
Now, your line in your viewport should look like this:

<details>
<summary>Click here for the full <b>slider_manipulatory.py</b></summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Geometry properties
self.width = 100
self.thickness = 5
self.radius = 5
self.radius_hovered = 7
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
<br>
## Step 7: Set up the Model
For this step, you will need to set up `SliderModel` to hold the information you need for the size of the selected prim. You will later use this information to connect it to the Manipulator.
### Step 7.1: Import Omniverse Command Library
First, let's start by importing the Omniverse Command Library in `slider_model.py`
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
# NEW IMPORT
import omni.kit.commands
# END NEW
```
### Step 7.2: ValueItem Class
Next, you will add a new Manipulator Item class, which you will name `ValueItem`, like so:
```python
...
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
# NEW MANIPULATOR ITEM
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
# END NEW
...
```
You will use this new class to create the variables for the min and max of the scale:
```python
...
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self) -> None:
super().__init__()
# NEW
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
# END NEW
self.position = SliderModel.PositionItem()
...
```
### Step 7.3: Set Scale to Stage
With the new variables for the scale, populate them in `on_stage_event()` like so:
```python
...
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
# NEW
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# END NEW
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
...
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the updated <b>slider_model.py</b> at this point </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
import omni.kit.commands
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self) -> None:
super().__init__()
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
</details>
### Step 7.4: Define Identifiers
Just as you defined the identifier for position, you must do the same for value, min, and max. You will add these to `get_item`:
```python
...
def get_item(self, identifier):
if identifier == "position":
return self.position
# NEW
if identifier == "value":
return self.scale
if identifier == "min":
return self.min
if identifier == "max":
return self.max
# END NEW
...
```
### Step 7.5: Set Floats
Previously, you called `set_floats()`, now define it after `get_item()`. In this function, you will set the scale when setting the value, set directly to the item, and update the manipulator:
```python
def set_floats(self, item, value):
if not self.current_path:
return
if not value or not item or item.value == value:
return
if item == self.scale:
# Set the scale when setting the value.
value[0] = min(max(value[0], self.min.value[0]), self.max.value[0])
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(
self.stage.GetPrimAtPath(self.current_path)
)
omni.kit.commands.execute(
"TransformPrimSRTCommand",
path=self.current_path,
new_translation=old_translation,
new_rotation_euler=old_rotation_euler,
new_scale=Gf.Vec3d(value[0], value[0], value[0]),
)
# Set directly to the item
item.value = value
# This makes the manipulator updated
self._item_changed(item)
```
<details>
<summary>Click here for the full <b>slider_model.py</b> </summary>
```python
from omni.ui import scene as sc
from pxr import Tf
from pxr import Gf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
import omni.kit.commands
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because you take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self) -> None:
super().__init__()
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, you don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
if identifier == "value":
return self.scale
if identifier == "min":
return self.min
if identifier == "max":
return self.max
def set_floats(self, item, value):
if not self.current_path:
return
if not value or not item or item.value == value:
return
if item == self.scale:
# Set the scale when setting the value.
value[0] = min(max(value[0], self.min.value[0]), self.max.value[0])
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(
self.stage.GetPrimAtPath(self.current_path)
)
omni.kit.commands.execute(
"TransformPrimSRTCommand",
path=self.current_path,
new_translation=old_translation,
new_rotation_euler=old_rotation_euler,
new_scale=Gf.Vec3d(value[0], value[0], value[0]),
)
# Set directly to the item
item.value = value
# This makes the manipulator updated
self._item_changed(item)
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
</details>
## Step 8: Add Gestures
For your final step, you will be updating `slider_manipulator.py` to add the gestures needed to connect what you programmed in the Model. This will include checking that the gesture is not prevented during drag, calling the gesture, restructure the geometry properties, and update the Line and Circle.
### Step 8.1: `SliderDragGesturePayload` Class
Begin by creating a new class that the user will access to get the current value of the slider, like so:
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
# NEW
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
## END NEW
...
```
### Step 8.2 `SliderChangedGesture` Class
Next, you will create another new class that the user will reimplement to process the manipulator's callbacks, in addition to a new `__init__()`:
```python
...
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
# NEW
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
# END NEW
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
...
```
Nested inside of the `SliderChangedGesture` class, define `process()` directly after the `__init__()` definition of this class:
```python
...
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
# NEW
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# END NEW
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
```
>:memo:Code Checkpoint
<details>
<summary>Click here for the updated <b>slider_manipulator.py</b> at this point </summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
Now, you need to define a few of the Public API functions after the `process` function:
```python
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# NEW
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
# END NEW
```
### Step 8.3 `_ArcGesturePrioritize` Class
You will be adding an `_ArcGesture` class in the next step that needs the manager `_ArcGesturePrioritize` to make it the priority gesture. You will add the manager first to make sure the drag of the slider is not prevented during drag. You will slot this new class after your Public API functions:
```python
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
# NEW
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
# END NEW
```
### Step 8.4: `_ArcGesture` Class
Now, create the class `_ArcGesture` where you will set the new slider value and redirect to `SliderChangedGesture` class you made previously. This new class will be after the `ArcGesturePrioritize` manager class.
```python
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
# NEW
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
# END NEW
```
>:memo:Code Checkpoint
<details>
<summary>Click here for the updated <b>slider_manipulator.py</b> at this point </summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
### Step 8.5: Restructure Geometry Parameters
For this step, you will be adding to `__init__()` that nests your Geometry properties, such as `width`,`thickness`,`radius`, and `radius_hovered`.
>:bulb: Tip: If you are having trouble locating the geometry properties, be reminded that this `__init__()` is after the new classes you added in the previous steps. You should find it under "_ArcGesture"
Start by defining `set_radius()` for the circle so that you can change it on hover later, and also set the parameters for arc_gesture to make sure it's active when the object is recreated:
```python
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Geometry properties
self._width = 100
self._thickness = 5
self._radius = 5
self._radius_hovered = 7
# NEW
def set_radius(circle, radius):
circle.radius = radius
# You don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
# END NEW
```
### Step 8.6: Add Hover Gestures
Now that you have set the geometry properties for when you hover over them, create the `HoverGesture` instance. You will set this within an `if` statement under the parameters for `self._arc_gesture`:
```python
# You don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
# NEW
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
# END NEW
```
## Step 8.7: UI Getters and Setters
Before moving on, you need to add a few Python decorators for the UI, such as `@property`,`@width.setter` and `@height.setter`. These can be added after the `HoverGesture` statement from the step above:
```python
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the updated <b>slider_manipulator.py</b> at this point</summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def set_radius(circle, radius):
circle.radius = radius
# You don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
value = 0.0
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * 1 - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * 1
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
### Step 8.8: Update `on_build()`
For your final step in the Manipulator module, you will update `on_build()` to update the min and max values of the model, update the line and circle, and update the label.
Start with replacing the `value` variable you had before with a new set of variables for `_min`,`_max`, new `value`, and `value_normalized`.
```python
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
### REPLACE ####
value = 0.0
### WITH ####
_min = self.model.get_as_floats(self.model.get_item("min"))[0]
_max = self.model.get_as_floats(self.model.get_item("max"))[0]
value = float(self.model.get_as_floats(self.model.get_item("value"))[0])
value_normalized = (value - _min) / (_max - _min)
value_normalized = max(min(value_normalized, 1.0), 0.0)
# END NEW
position = self.model.get_as_floats(self.model.get_item("position"))
```
Now, you will add a new line to the slider so that you have a line for when the slider is moved to the left and to the right. Locate just below your previously set parameters the `Left Line` you created in `Step 6.2`.
Before you add the new line, replace the `1` in `line_to` with your new parameter `value_normalized`.
Then add the `Right Line` below the `Left Line`, as so:
```python
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * value_normalized - self._radius # REPLACED THE 1 WITH value_normalized
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# NEW: same as left line but flipped
# Right line
line_from = -self.width * 0.5 + self.width * value_normalized + self._radius
line_to = self.width * 0.5
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# END NEW
```
Next, update the circle to add the `hover_gesture`. This will increase the circle in size when hovered over. Also change the `1` value like you did for `Line` to `value_normalized` and also add the gesture to `sc.Arc`:
```python
# Circle
# NEW : Changed 1 value to value_normalized
circle_position = -self.width * 0.5 + self.width * value_normalized
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
# NEW: Added Gesture when hovering over the circle it will increase in size
gestures = [self._arc_gesture]
if self._hover_gesture:
gestures.append(self._hover_gesture)
if self._hover_gesture.state == sc.GestureState.CHANGED:
radius = self._radius_hovered
sc.Arc(radius, axis=2, color=cl.gray, gestures=gestures)
# END NEW
```
Last of all, update the `Label` below your circle to add more space between the slider and the label:
```python
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# NEW: Added more space between the slider and the label
# Move it to the top
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)):
# END NEW
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
```
>:memo: Code Checkpoint
<details>
<summary>Click here for the full <b>slider_manipulator.py</b></summary>
```python
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def set_radius(circle, radius):
circle.radius = radius
# You don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If you don't have a selection then just return
if self.model.get_item("name") == "":
return
_min = self.model.get_as_floats(self.model.get_item("min"))[0]
_max = self.model.get_as_floats(self.model.get_item("max"))[0]
value = float(self.model.get_as_floats(self.model.get_item("value"))[0])
value_normalized = (value - _min) / (_max - _min)
value_normalized = max(min(value_normalized, 1.0), 0.0)
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * value_normalized - self._radius # REPLACED THE 1 WITH value_normalized
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# NEW: same as left line but flipped
# Right line
line_from = -self.width * 0.5 + self.width * value_normalized + self._radius
line_to = self.width * 0.5
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * value_normalized
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
gestures = [self._arc_gesture]
if self._hover_gesture:
gestures.append(self._hover_gesture)
if self._hover_gesture.state == sc.GestureState.CHANGED:
radius = self._radius_hovered
sc.Arc(radius, axis=2, color=cl.gray)
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# NEW: Added more space between the slider and the label
# Move it to the top
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)):
# END NEW
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
<br>
<br>
>:exclamation: If you are running into any errors in the Console, disable `Autoload` in the `Extension Manager` and restart Omniverse Code.
### Step 8.9: Completion
Congratulations! You have completed the guide `How to make a Slider Manipulator` and now have a working scale slider!
| 93,815 | Markdown | 33.605681 | 389 | 0.614923 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_manipulator.py | from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def set_radius(circle, radius):
circle.radius = radius
# We don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
_min = self.model.get_as_floats(self.model.get_item("min"))[0]
_max = self.model.get_as_floats(self.model.get_item("max"))[0]
value = float(self.model.get_as_floats(self.model.get_item("value"))[0])
value_normalized = (value - _min) / (_max - _min)
value_normalized = max(min(value_normalized, 1.0), 0.0)
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * value_normalized - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# NEW: same as left line but flipped
# Right line
line_from = -self.width * 0.5 + self.width * value_normalized + self._radius
line_to = self.width * 0.5
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * value_normalized
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
# NEW: Added Gesture when hovering over the circle it will increase in size
gestures = [self._arc_gesture]
if self._hover_gesture:
gestures.append(self._hover_gesture)
if self._hover_gesture.state == sc.GestureState.CHANGED:
radius = self._radius_hovered
sc.Arc(radius, axis=2, color=cl.gray, gestures=gestures)
# END NEW
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# NEW: Added more space between the slider and the label
# Move it to the top
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)):
# END NEW
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate() | 7,610 | Python | 37.439394 | 108 | 0.574244 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_registry.py | from .slider_model import SliderModel
from .slider_manipulator import SliderManipulator
from typing import Any
from typing import Dict
from typing import Optional
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, we don't want to see the selection rect
self.__disable_selection = ViewportLegacyDisableSelection()
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
class SliderRegistry:
"""
Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per
viewport. Keeps the manipulator and some properties that are needed to the
viewport.
"""
def __init__(self, description: Optional[Dict[str, Any]] = None):
self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture())
def destroy(self):
if self.__slider_manipulator:
self.__slider_manipulator.destroy()
self.__slider_manipulator = None
# PrimTransformManipulator & TransformManipulator don't have their own visibility
@property
def visible(self):
return True
@visible.setter
def visible(self, value):
pass
@property
def categories(self):
return ("manipulator",)
@property
def name(self):
return "Example Slider Manipulator" | 3,144 | Python | 34.738636 | 114 | 0.640585 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/extension.py | import omni.ext
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.viewport.registry import RegisterScene
from .slider_registry import SliderRegistry
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider")
self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry)
def on_shutdown(self):
ManipulatorFactory.destroy_manipulator(self.slider_factory)
self.slider_factory = None
self.slider_registry.destroy()
self.slider_registry = None
| 785 | Python | 40.368419 | 119 | 0.75414 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_model.py | from omni.ui import scene as sc
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
import omni.kit.commands
from pxr import Gf
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because we take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self) -> None:
super().__init__()
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, we don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
if identifier == "value":
return self.scale
if identifier == "min":
return self.min
if identifier == "max":
return self.max
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def set_floats(self, item, value):
if not self.current_path:
return
if not value or not item or item.value == value:
return
if item == self.scale:
# Set the scale when setting the value.
value[0] = min(max(value[0], self.min.value[0]), self.max.value[0])
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(
self.stage.GetPrimAtPath(self.current_path)
)
omni.kit.commands.execute(
"TransformPrimSRTCommand",
path=self.current_path,
new_translation=old_translation,
new_rotation_euler=old_rotation_euler,
new_scale=Gf.Vec3d(value[0], value[0], value[0]),
)
# Set directly to the item
item.value = value
# This makes the manipulator updated
self._item_changed(item)
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
| 5,473 | Python | 34.089743 | 121 | 0.576466 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/config/extension.toml | [package]
version = "1.2.1"
authors = ["Victor Yudin <[email protected]>"]
title = "Omni.UI Scene Slider Example"
description="The interactive example of the slider manipulator with omni.ui.scene"
readme = "docs/README.md"
repository="https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene"
category = "Documentation"
keywords = ["ui", "example", "scene", "docs", "documentation", "slider"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.kit.manipulator.viewport" = {}
"omni.kit.viewport.registry" = {}
"omni.ui.scene" = {}
"omni.usd" = {}
[[python.module]]
name = "omni.example.ui_scene.slider_manipulator"
| 686 | TOML | 30.227271 | 82 | 0.718659 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/slider_extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["SliderExtension"]
from .slider_registry import SliderRegistry
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.viewport.registry import RegisterScene
import omni.ext
class SliderExtension(omni.ext.IExt):
"""The entry point to the extension"""
def on_startup(self, ext_id):
# Viewport Next: omni.kit.viewport.window
self._slider_registry = RegisterScene(SliderRegistry, "omni.example.ui_scene.slider_manipulator")
# Viewport Legacy: omni.kit.window.viewport
self._slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry)
def on_shutdown(self):
ManipulatorFactory.destroy_manipulator(self._slider_factory)
self._slider_factory = None
self._slider_registry.destroy()
self._slider_registry = None
| 1,255 | Python | 38.249999 | 105 | 0.753785 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/docs/CHANGELOG.md | # Changelog
omni.example.ui_scene.slider_manipulator
## [1.2.1] - 2022-06-17
### Added
- Documentation
## [1.2.0] - 2022-06-01
### Changed
- Full refactoring
## [1.1.1] - 2021-12-22
### Changed
- Fixes for tests on 103.0+release.679.1bc9fadb
## [1.1.0] - 2021-12-06
### Changed
- Using the model-based SceneView
### Added
- Support for HoverGesture
## [1.0.1] - 2021-11-25
### Changed
- Default aspect ratio to match Kit Viewport
- Renamed Intersection to GesturePayload (need omni.ui.scene 1.1.0)
## [1.0.0] - 2021-11-19
### Added
- The initial documentation
| 567 | Markdown | 17.32258 | 67 | 0.66843 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/docs/README.md | # Slider Manipulator (omni.example.ui_scene.slider_manipulator)

## Overview
We provide the End-to-End example that draws a 3D slider in the viewport overlay
on the top of the bounding box of the selected imageable. The slider controls
the scale of the prim. It has a custom manipulator, model, and gesture. When the
slider's value is changed, the manipulator processes the custom gesture that
changes the data in the model, which changes the data directly in the USD stage.
The viewport overlay is synchronized with the viewport using `Tf.Notice` that
watches the USD Camera.
### Manipulator
The manipulator is a very basic implementation of the slider in 3D space. The
main feature of the manipulator is that it redraws and recreates all the
children once the model is changed. It makes the code straightforward. It takes
the position and the slider value from the model, and when the user changes the
slider position, it processes a custom gesture. It doesn't write to the model
directly to let the user decide what to do with the new data and how the
manipulator should react to the modification. For example, if the user wants to
implement the snapping to the round value, it would be handy to do it in the
custom gesture.
### Model
The model contains the following named items:
- `value` - the current value of the slider
- `min` - the minimum value of the slider
- `max` - the maximum value of the slider
- `position` - the position of the slider in 3D space
The model demonstrates two main strategies working with the data.
The first strategy is that the model is the bridge between the manipulator and
the data, and it doesn't keep and doesn't duplicate the data. When the
manipulator requests the position from the model, the model computes the
position using USD API and returns it to the manipulator.
The first strategy is that the model can be a container of the data. For
example, the model pre-computes min and max values and passes them to the
manipulator once the selection is changed.
## [Tutorial](../Tutorial/slider_Manipulator_Tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions.
In the tutorial you will learn how to create an extension from the Extension Manager in Omniverse Code, set up your files, and use Omniverse's Library. Additionally, the tutorial has a `Final Scripts` folder to use as a reference as you go along.
[Get started with the tutorial here.](../Tutorial/slider_Manipulator_Tutorial.md)
## Usage
Once the extension is enabled in the `Extension Manager`, go to your `Viewport` and right-click to create a primitive - such as a cube, sphere, cylinder, etc. Then, left-click/select the primitive to view and manipulate the slider.
| 2,943 | Markdown | 48.898304 | 247 | 0.783554 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/docs/index.rst | omni.example.ui_scene.slider_manipulator
########################################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
| 171 | reStructuredText | 13.333332 | 40 | 0.549708 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/config/extension.toml | [package]
version = "1.1.1"
authors = ["NVIDIA"]
title = "Omni.UI Scene Sample For Manipulating Select Light"
description = "This example show an 3D manipulator for a selected light"
readme = "docs/README.md"
repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene"
category = "Documentation"
keywords = ["ui", "example", "scene", "docs", "documentation", "light"]
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui.scene" = { }
"omni.usd" = { }
"omni.kit.viewport.utility" = { }
"omni.kit.commands" = { }
[[python.module]]
name = "omni.example.ui_scene.light_manipulator"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/app/viewport/forceHideFps=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.test_helpers_gfx",
"omni.kit.viewport.utility",
"omni.kit.window.viewport"
]
| 1,030 | TOML | 26.131578 | 82 | 0.667961 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["LightManipulatorExtension"]
import carb
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportScene
class LightManipulatorExtension(omni.ext.IExt):
def __init__(self):
self._viewport_scene = None
def on_startup(self, ext_id):
# Get the active (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# Issue an error if there is no Viewport
if not viewport_window:
carb.log_error(f"No Viewport Window to add {ext_id} scene to")
return
# Build out the scene
self._viewport_scene = ViewportScene(viewport_window, ext_id)
def on_shutdown(self):
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
| 1,294 | Python | 33.078946 | 76 | 0.705564 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_model.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__ = ["LightModel"]
import carb
from omni.ui import scene as sc
import omni.usd
from pxr import Usd, UsdGeom, UsdLux, Tf, Gf
def _flatten_matrix(matrix: Gf.Matrix4d):
m0, m1, m2, m3 = matrix[0], matrix[1], matrix[2], matrix[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],
]
class LightModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the attributes of the selected light.
"""
class MatrixItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the tranformation. It doesn't contain anything
because we take the tranformation directly from USD when requesting.
"""
identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
def __init__(self):
super().__init__()
self.value = self.identity.copy()
class FloatItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value about some attibute"""
def __init__(self, value=0.0):
super().__init__()
self.value = value
class StringItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single string value about some attibute"""
def __init__(self, value=""):
super().__init__()
self.value = value
def __init__(self):
super().__init__()
self.prim_path = LightModel.StringItem()
self.transform = LightModel.MatrixItem()
self.intensity = LightModel.FloatItem()
self.width = LightModel.FloatItem()
self.height = LightModel.FloatItem()
# Save the UsdContext name (we currently only work with single Context)
self._usd_context_name = ""
# Current selection
self._light = None
self._stage_listener = None
# Track selection change
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="Light Manipulator Selection Change"
)
def __del__(self):
self._invalidate_object()
@property
def _usd_context(self) -> Usd.Stage:
# Get the UsdContext we are attached to
return omni.usd.get_context(self._usd_context_name)
@property
def _current_path(self):
return self.prim_path.value
@property
def _time(self):
return Usd.TimeCode.Default()
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice. When USD data changes, we update the ui"""
light_path = self.prim_path.value
if not light_path:
return
changed_items = set()
for p in notice.GetChangedInfoOnlyPaths():
prim_path = p.GetPrimPath().pathString
if prim_path != light_path:
# Update on any parent transformation changes too
if light_path.startswith(prim_path):
if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name):
changed_items.add(self.transform)
continue
if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name):
changed_items.add(self.transform)
elif self.width and p.name == "width":
changed_items.add(self.width)
elif self.height and p.name == "height":
changed_items.add(self.height)
elif self.intensity and p.name == "intensity":
changed_items.add(self.intensity)
for item in changed_items:
self._item_changed(item)
def get_as_floats(self, item):
"""get the item value directly from USD"""
if item == self.transform:
return self._get_transform(self._time)
if item == self.intensity:
return self._get_intensity(self._time)
if item == self.width:
return self._get_width(self._time)
if item == self.height:
return self._get_height(self._time)
if item:
# Get the value directly from the item
return item.value
return None
def set_floats_commands(self, item, value):
"""set the item value to USD using commands, this is useful because it supports undo/redo"""
if not self._current_path:
return
if not value or not item:
return
# we get the previous value from the model instead of USD
if item == self.height:
prev_value = self.height.value
if prev_value == value:
return
height_attr = self._light.GetHeightAttr()
omni.kit.commands.execute('ChangeProperty', prop_path=height_attr.GetPath(), value=value, prev=prev_value)
elif item == self.width:
prev_value = self.width.value
if prev_value == value:
return
width_attr = self._light.GetWidthAttr()
omni.kit.commands.execute('ChangeProperty', prop_path=width_attr.GetPath(), value=value, prev=prev_value)
elif item == self.intensity:
prev_value = self.intensity.value
if prev_value == value:
return
intensity_attr = self._light.GetIntensityAttr()
omni.kit.commands.execute('ChangeProperty', prop_path=intensity_attr.GetPath(), value=value, prev=prev_value)
# This makes the manipulator updated
self._item_changed(item)
def set_item_value(self, item, value):
""" This is used to set the model value instead of the usd. This is used to record previous value for
omni.kit.commands """
item.value = value
def set_floats(self, item, value):
"""set the item value directly to USD. This is useful when we want to update the usd but not record it in commands"""
if not self._current_path:
return
if not value or not item:
return
pre_value = self.get_as_floats(item)
# no need to update if the updated value is the same
if pre_value == value:
return
if item == self.height:
self._set_height(self._time, value)
elif item == self.width:
self._set_width(self._time, value)
elif item == self.intensity:
self._set_intensity(self._time, value)
def _on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_kit_selection_changed()
def _invalidate_object(self, settings):
# Revoke the Tf.Notice listener, we don't need to update anything
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
# Reset original Viewport gizmo line width
settings.set("/persistent/app/viewport/gizmo/lineWidth", 0)
# Clear any cached UsdLux.Light object
self._light = None
# Set the prim_path to empty
self.prim_path.value = ""
self._item_changed(self.prim_path)
def _on_kit_selection_changed(self):
# selection change, reset it for now
self._light = None
# Turn off any native selected light drawing
settings = carb.settings.get_settings()
settings.set("/persistent/app/viewport/gizmo/lineWidth", 0)
usd_context = self._usd_context
if not usd_context:
return self._invalidate_object(settings)
stage = usd_context.get_stage()
if not stage:
return self._invalidate_object(settings)
prim_paths = usd_context.get_selection().get_selected_prim_paths() if usd_context else None
if not prim_paths:
return self._invalidate_object(settings)
prim = stage.GetPrimAtPath(prim_paths[0])
if prim and prim.IsA(UsdLux.RectLight):
self._light = UsdLux.RectLight(prim)
if not self._light:
return self._invalidate_object(settings)
selected_path = self._light.GetPrim().GetPath().pathString
if selected_path != self.prim_path.value:
self.prim_path.value = selected_path
self._item_changed(self.prim_path)
# Add a Tf.Notice listener to update the light attributes
if not self._stage_listener:
self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage)
def _get_transform(self, time: Usd.TimeCode):
"""Returns world transform of currently selected object"""
if not self._light:
return LightModel.MatrixItem.identity.copy()
# Compute matrix from world-transform in USD
world_xform = self._light.ComputeLocalToWorldTransform(time)
# Flatten Gf.Matrix4d to list
return _flatten_matrix(world_xform)
def _get_intensity(self, time: Usd.TimeCode):
"""Returns intensity of currently selected light"""
if not self._light:
return 0.0
# Get intensity directly from USD
return self._light.GetIntensityAttr().Get(time)
def _set_intensity(self, time: Usd.TimeCode, value):
"""set intensity of currently selected light"""
if not self._light:
return
# set height dirctly to USD
self._light.GetIntensityAttr().Set(value, time=time)
def _get_width(self, time: Usd.TimeCode):
"""Returns width of currently selected light"""
if not self._light:
return 0.0
# Get radius directly from USD
return self._light.GetWidthAttr().Get(time)
def _set_width(self, time: Usd.TimeCode, value):
"""set width of currently selected light"""
if not self._light:
return
# set height dirctly to USD
self._light.GetWidthAttr().Set(value, time=time)
def _get_height(self, time: Usd.TimeCode):
"""Returns height of currently selected light"""
if not self._light:
return 0.0
# Get height directly from USD
return self._light.GetHeightAttr().Get(time)
def _set_height(self, time: Usd.TimeCode, value):
"""set height of currently selected light"""
if not self._light:
return
# set height dirctly to USD
self._light.GetHeightAttr().Set(value, time=time)
| 11,040 | Python | 33.07716 | 125 | 0.600272 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_manipulator.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__ = ["LightManipulator"]
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.kit
import omni.kit.commands
INTENSITY_SCALE = 500.0
ARROW_WIDTH = 0.015
ARROW_HEIGHT = 0.1
ARROW_P = [
[ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, -ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, ARROW_WIDTH, 0],
[ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[ARROW_WIDTH, -ARROW_WIDTH, 0],
]
ARROW_VC = [3, 3, 3, 3, 4]
ARROW_VI = [i for i in range(sum(ARROW_VC))]
class _ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact is the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class _DragGesture(sc.DragGesture):
""""Gesture to disable rectangle selection in the viewport legacy"""
def __init__(self, manipulator, orientation, flag):
super().__init__()
self._manipulator = manipulator
# record this _previous_ray_point to get the mouse moved vector
self._previous_ray_point = None
# this defines the orientation of the move, 0 means x, 1 means y, 2 means z. It's a list so that we can move a selection
self.orientations = orientation
# global flag to indicate if the manipulator changes all the width, height and intensity, rectangle manipulator
# in the example
self.is_global = len(self.orientations) > 1
# this defines the negative or positive of the move. E.g. when we move the positive x line to the right, it
# enlarges the width, and when we move the negative line to the left, it also enlarges the width
# 1 means positive and -1 means negative. It's a list so that we can reflect list orientation
self.flag = flag
def on_began(self):
# When the user drags the slider, we don't want to see the selection
# rect. In Viewport Next, it works well automatically because the
# selection rect is a manipulator with its gesture, and we add the
# slider manipulator to the same SceneView.
# In Viewport Legacy, the selection rect is not a manipulator. Thus it's
# not disabled automatically, and we need to disable it with the code.
self.__disable_selection = _ViewportLegacyDisableSelection()
# initialize the self._previous_ray_point
self._previous_ray_point = self.gesture_payload.ray_closest_point
# record the previous value for the model
self.model = self._manipulator.model
if 0 in self.orientations:
self.width_item = self.model.width
self._manipulator.model.set_item_value(self.width_item, self.model.get_as_floats(self.width_item))
if 1 in self.orientations:
self.height_item = self.model.height
self._manipulator.model.set_item_value(self.height_item, self.model.get_as_floats(self.height_item))
if 2 in self.orientations or self.is_global:
self.intensity_item = self.model.intensity
self._manipulator.model.set_item_value(self.intensity_item, self.model.get_as_floats(self.intensity_item))
def on_changed(self):
object_ray_point = self.gesture_payload.ray_closest_point
# calculate the ray moved vector
moved = [a - b for a, b in zip(object_ray_point, self._previous_ray_point)]
# transfer moved from world to object space, [0] to make it a normal, not point
moved = self._manipulator._x_xform.transform_space(sc.Space.WORLD, sc.Space.OBJECT, moved + [0])
# 2.0 because `_shape_xform.transform` is a scale matrix and it means
# the width of the rectangle is twice the scale matrix.
moved_x = moved[0] * 2.0 * self.flag[0]
moved_y = moved[1] * 2.0 * (self.flag[1] if self.is_global else self.flag[0])
moved_z = moved[2] * self.flag[0]
# update the self._previous_ray_point
self._previous_ray_point = object_ray_point
# since self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
# when we want to update the manipulator, we are actually updating self._manipulator._shape_xform.transform[0]
# for width and self._manipulator._shape_xform.transform[5] for height and
# self._manipulator._shape_xform.transform[10] for intensity
width = self._manipulator._shape_xform.transform[0]
height = self._manipulator._shape_xform.transform[5]
intensity = self._manipulator._shape_xform.transform[10]
self.width_new = width + moved_x
self.height_new = height + moved_y
# update the USD as well as update the ui
if 0 in self.orientations:
# update the data in the model
self.model.set_floats(self.width_item, self.width_new)
self._manipulator._shape_xform.transform[0] = self.width_new
if 1 in self.orientations:
# update the data in the model
self.model.set_floats(self.height_item, self.height_new)
self._manipulator._shape_xform.transform[5] = self.height_new
if 2 in self.orientations:
self._manipulator._shape_xform.transform[10] += moved_z
self.intensity_new = self._manipulator._shape_xform.transform[10] * INTENSITY_SCALE
self.model.set_floats(self.intensity_item, self.intensity_new)
if self.is_global:
# need to update the intensity in a different way
intensity_new = intensity * width * height / (self.width_new * self.height_new)
self._manipulator._shape_xform.transform[10] = intensity_new
self.intensity_new = intensity_new * INTENSITY_SCALE
self.model.set_floats(self.intensity_item, self.intensity_new)
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
if self.is_global:
# start group command
omni.kit.undo.begin_group()
if 0 in self.orientations:
self.model.set_floats_commands(self.width_item, self.width_new)
if 1 in self.orientations:
self.model.set_floats_commands(self.height_item, self.height_new)
if 2 in self.orientations or self.is_global:
self.model.set_floats_commands(self.intensity_item, self.intensity_new)
if self.is_global:
# end group command
omni.kit.undo.end_group()
class LightManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._shape_xform = None
def __del__(self):
self.model = None
def _build_shape(self):
if not self.model:
return
if self.model.width and self.model.height and self.model.intensity:
x = self.model.get_as_floats(self.model.width)
y = self.model.get_as_floats(self.model.height)
# this INTENSITY_SCALE is too make the transform a reasonable length with large intensity number
z = self.model.get_as_floats(self.model.intensity) / INTENSITY_SCALE
self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1]
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
model = self.model
if not model:
return
# if we don't have selection then just return
prim_path_item = model.prim_path
prim_path = prim_path_item.value if prim_path_item else None
if not prim_path:
return
# Style settings, as kwargs
thickness = 1
hover_thickness = 3
color = cl.yellow
shape_style = {"thickness": thickness, "color": color}
def set_thickness(sender, shapes, thickness):
for shape in shapes:
shape.thickness = thickness
self.__root_xf = sc.Transform(model.get_as_floats(model.transform))
with self.__root_xf:
self._x_xform = sc.Transform()
with self._x_xform:
self._shape_xform = sc.Transform()
# Build the shape's transform
self._build_shape()
with self._shape_xform:
# Build the shape geomtery as unit-sized
h = 0.5
z = -1.0
# the rectangle
shape1 = sc.Line((-h, h, 0), (h, h, 0), **shape_style)
shape2 = sc.Line((-h, -h, 0), (h, -h, 0), **shape_style)
shape3 = sc.Line((h, h, 0), (h, -h, 0), **shape_style)
shape4 = sc.Line((-h, h, 0), (-h, -h, 0), **shape_style)
# add gesture to the lines of the rectangle to update width or height of the light
vertical_hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_thickness(sender, [shape1, shape2], hover_thickness),
on_ended_fn=lambda sender: set_thickness(sender, [shape1, shape2], thickness),
)
shape1.gestures = [_DragGesture(self, [1], [1]), vertical_hover_gesture]
shape2.gestures = [_DragGesture(self, [1], [-1]), vertical_hover_gesture]
horizontal_hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_thickness(sender, [shape3, shape4], hover_thickness),
on_ended_fn=lambda sender: set_thickness(sender, [shape3, shape4], thickness),
)
shape3.gestures = [_DragGesture(self, [0], [1]), horizontal_hover_gesture]
shape4.gestures = [_DragGesture(self, [0], [-1]), horizontal_hover_gesture]
# create z-axis to indicate the intensity
z1 = sc.Line((h, h, 0), (h, h, z), **shape_style)
z2 = sc.Line((-h, -h, 0), (-h, -h, z), **shape_style)
z3 = sc.Line((h, -h, 0), (h, -h, z), **shape_style)
z4 = sc.Line((-h, h, 0), (-h, h, z), **shape_style)
def make_arrow(translate):
vert_count = len(ARROW_VI)
with sc.Transform(
transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])
* sc.Matrix44.get_rotation_matrix(0, -180, 0, True)
):
return sc.PolygonMesh(ARROW_P, [color] * vert_count, ARROW_VC, ARROW_VI, visible=False)
# arrows on the z-axis
arrow_1 = make_arrow((h, h, z))
arrow_2 = make_arrow((-h, -h, z))
arrow_3 = make_arrow((h, -h, z))
arrow_4 = make_arrow((-h, h, z))
# the line underneath the arrow which is where the gesture applies
z1_arrow = sc.Line((h, h, z), (h, h, z - ARROW_HEIGHT), **shape_style)
z2_arrow = sc.Line((-h, -h, z), (-h, -h, z - ARROW_HEIGHT), **shape_style)
z3_arrow = sc.Line((h, -h, z), (h, -h, z - ARROW_HEIGHT), **shape_style)
z4_arrow = sc.Line((-h, h, z), (-h, h, z - ARROW_HEIGHT), **shape_style)
def set_visible(sender, shapes, thickness, arrows, visible):
set_thickness(sender, shapes, thickness)
for arrow in arrows:
arrow.visible = visible
thickness_group = [z1, z1_arrow, z2, z2_arrow, z3, z3_arrow, z4, z4_arrow]
visible_group = [arrow_1, arrow_2, arrow_3, arrow_4]
visible_arrow_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_visible(sender, thickness_group, hover_thickness, visible_group, True),
on_ended_fn=lambda sender: set_visible(sender, thickness_group, thickness, visible_group, False),
)
gestures = [_DragGesture(self, [2], [-1]), visible_arrow_gesture]
z1_arrow.gestures = gestures
z2_arrow.gestures = gestures
z3_arrow.gestures = gestures
z4_arrow.gestures = gestures
# create 4 rectangles at the corner, and add gesture to update width, height and intensity at the same time
s = 0.03
def make_corner_rect(translate):
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])):
return sc.Rectangle(s, s, color=0x0)
r1 = make_corner_rect((h - 0.5 * s, -h + 0.5 * s, 0))
r2 = make_corner_rect((h - 0.5 * s, h - 0.5 * s, 0))
r3 = make_corner_rect((-h + 0.5 * s, h - 0.5 * s, 0))
r4 = make_corner_rect((-h + 0.5 * s, -h + 0.5 * s, 0))
def set_color_and_visible(sender, shapes, thickness, arrows, visible, rects, color):
set_visible(sender, shapes, thickness, arrows, visible)
for rect in rects:
rect.color = color
highlight_group = [shape1, shape2, shape3, shape4] + thickness_group
color_group = [r1, r2, r3, r4]
hight_all_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_color_and_visible(sender, highlight_group, hover_thickness, visible_group, True, color_group, color),
on_ended_fn=lambda sender: set_color_and_visible(sender, highlight_group, thickness, visible_group, False, color_group, 0x0),
)
r1.gestures = [_DragGesture(self, [0, 1], [1, -1]), hight_all_gesture]
r2.gestures = [_DragGesture(self, [0, 1], [1, 1]), hight_all_gesture]
r3.gestures = [_DragGesture(self, [0, 1], [-1, 1]), hight_all_gesture]
r4.gestures = [_DragGesture(self, [0, 1], [-1, -1]), hight_all_gesture]
def on_model_updated(self, item):
# Regenerate the mesh
if not self.model:
return
if item == self.model.transform:
# If transform changed, update the root transform
self.__root_xf.transform = self.model.get_as_floats(item)
elif item == self.model.prim_path:
# If prim_path or width or height or intensity changed, redraw everything
self.invalidate()
elif item == self.model.width or item == self.model.height or item == self.model.intensity:
# Interpret None as changing multiple light shape settings
self._build_shape()
| 16,572 | Python | 48.471642 | 156 | 0.57573 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/tests/test_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.
##
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
import omni.kit
import omni.kit.app
import omni.kit.test
from omni.example.ui_scene.light_manipulator import LightManipulator, LightModel
import omni.usd
from omni.ui import scene as sc
from pxr import UsdLux, UsdGeom
from omni.kit.viewport.utility import next_viewport_frame_async
from omni.kit.viewport.utility.tests import setup_vieport_test_window
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.example.ui_scene.light_manipulator}/data"))
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
class TestLightManipulator(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 setup_viewport(self, resolution_x: int = 800, resolution_y: int = 600):
await self.create_test_area(resolution_x, resolution_y)
return await setup_vieport_test_window(resolution_x, resolution_y)
async def test_manipulator_transform(self):
viewport_window = await self.setup_viewport()
viewport = viewport_window.viewport_api
await omni.usd.get_context().new_stage_async()
stage = omni.usd.get_context().get_stage()
# Wait until the Viewport has delivered some frames
await next_viewport_frame_async(viewport, 2)
with viewport_window.get_frame(0):
# Create a default SceneView (it has a default camera-model)
scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with scene_view.scene:
LightManipulator(model=LightModel())
omni.kit.commands.execute(
"CreatePrim",
prim_path="/RectLight",
prim_type="RectLight",
select_new_prim=True,
attributes={},
)
rect_light = UsdLux.RectLight(stage.GetPrimAtPath("/RectLight"))
# change light attribute
rect_light.GetHeightAttr().Set(100)
rect_light.GetWidthAttr().Set(200)
rect_light.GetIntensityAttr().Set(10000)
# rotate the light to have a better angle
rect_light_x = UsdGeom.Xformable(rect_light)
rect_light_x.ClearXformOpOrder()
rect_light_x.AddRotateXOp().Set(30)
rect_light_x.AddRotateYOp().Set(45)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 3,133 | Python | 37.219512 | 114 | 0.684966 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/tests/__init__.py | from .test_manipulator import TestLightManipulator | 50 | Python | 49.99995 | 50 | 0.9 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/docs/CHANGELOG.md | # Changelog
omni.example.ui_scene.light_manipulator
## [1.1.1] - 2022-6-21
### Added
- Documentation
## [1.1.0] - 2022-6-06
### Changed
- Removed other lights except RectLight
- Added gesture to the RectLight so that users can drag the manipulator to change the width, height and intensity
- The drag gesture can be just on the width (x-axis line) or height (y-axis line) or intensity (z-axis line) or all of
them when drag the corner rectangles
- Added test for the extension
## [1.0.0] - 2022-5-26
### Added
- The initial version
| 536 | Markdown | 25.849999 | 118 | 0.720149 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/docs/README.md | # Light Manipulator (omni.example.ui_scene.light_manipulator)
## Overview
We provide an End-to-End example of a light manipulator extension, which adds manipulators to RectLight.
There are 6 types of lights in Omniverse, shown in the image below. Here is the link of how to add a light: https://www.youtube.com/watch?v=c7qyI8pZvF4. In this example, we only create manipulators to RectLight.

It contains the LightModel which stores the light attribute values. Focused on "width", "height" and "intensity" in this example. It also plays the role of communication with the USD data, reading and writing updated attributes from and to USD.
LightManipulator defines 4 types of manipulators which separately control the light's width, height, intensity and all of the three.
## [Tutorial](../tutorial/tutorial.md)
Follow this [step-by-step guide](../tutorial/tutorial.md) to learn how this extension was created.
## Manipulator
The manipulator contains a rectangle and 4 lines perpendicular to the rectangle face. The manipulator is generated in a unit size, and the update of the look is through the parent transform of the manipulator.
- When you hover over the rectangle's width or height of the manipulator, you will see the line representation of the width or height highlighted and you can drag and move the manipulator. When you drag and move the height or width of the rectangle of the manipulator, you will see the width or height attributes of the RectLight in the property window are updated.
 
- When you hover over on the tip of any line perpendicular to the rectangle face, you will see the 4 lines will be highlighted and the arrow on the tip will reveal. When you drag and move the arrow, you will see the intensity attribute of the RectLight is updated.

- When you hover over to the corner of the rectangle (slightly inside the rectangle), you will see the entire manipulator is highlighted, and there will be 4 small rectangles revealed at the corner of the rectangle. When you drag and move the small rectangle, you will see all of the width, height and intensity attributes of the RectLight are updated.

- When you change the attributes (Width, height and intensity) of the RectLight in the property window, you will see the manipulator appearance updates.

## Gesture
The example defined a customized `_DragGesture` for the manipulator. This is how the gesture is implemented:
- `on_began`: the start attributes data is restored into the model, so that we have a record of previous values later for running `omni.kit.commands`.
- `on_changed`: update the attributes into the model, and the model will directly write the value to the USD without keeping it since we want to see the real-time updating of attribute value in the property window
- `on_ended`: update the attributes into the model, and the model will call `omni.kit.commands` to change the property since we want to support the undo/redo for the dragging. The previous value from `on_began` is used here.
## Model
The model contains the following named items:
- width - the width attribute of the RectLight
- height - the height attribute of the RectLight
- intensity - the intensity attribute of the RectLight
- prim_path - the USD prim path of the RectLight.
- transform - the transform of the RectLight.
The model is the bridge between the manipulator and the attributes data. The manipulator subscribes to the model change to update the look. All the attributes values are directly coming from USD data.
We use `Tf.Notice` to watch the rectLight and update the model. The model itself doesn't keep and doesn't duplicate the USD data, except the previous value when a gesture starts.
- When the model's `width`, `height` or `intensity` changes, the manipulator's parent transform is updated.
- The model's `prim_path` is subscribed to `omni.usd.StageEventType.SELECTION_CHANGED`, so when the selection of RectLight is changed, the entire manipulator is redrawn.
- When the model's `transform` is changed, the root transform of the manipulator is updated.
For width, height and intensity, the model demonstrates two strategies working with the data.
It keeps the attribute data during the manipulating, so that the manipulator has the only one truth of data from the model. When the manipulator requests the attributes from the model, the model computes the position using USD API and returns it to the manipulator.
## Overlaying with the viewport
We use `sc.Manipulator` to draw the manipulator in 3D view. To show it in the viewport, we overlay `sc.SceneView` with our `sc.Manipulator`
on top of the viewport window.
```python
from omni.kit.viewport.utility import get_active_viewport_window
viewport_window = get_active_viewport_window()
# Create a unique frame for our SceneView
with viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self._scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self._scene_view.scene:
LightManipulator(model=LightModel())
```
To synchronize the projection and view matrices, `omni.kit.viewport.utility` has
the method `add_scene_view`, which replaces the camera model, and the
manipulator visually looks like it's in the main viewport.
```python
# Register the SceneView with the Viewport to get projection and view updates
viewport_window.viewport_api.add_scene_view(self._scene_view)
``` | 5,614 | Markdown | 64.290697 | 366 | 0.773245 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md | # How to make an extension to display Object Info
The object info extension displays the selected prim’s Path and Type. This guide is great for first time extension builders.
> NOTE: Visual Studio Code is the preferred IDE, hence forth we will be referring to it throughout this guide.
# Learning Objectives
In this tutorial you learn how to:
- Create an extension in Omniverse Code
- Use the omni.ui.scene API
- Display object info in the viewport
- Translate from World space to Local space
# Prerequisites
We recommend that you complete these tutorials before moving forward:
- [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial)
- [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims)
> :exclamation: <span style="color:red"><b> WARNING: Check that Viewport Utility Extension is turned ON in the extension manager: </b></span> <br> 
# Step 1: Create an Extension
> **Note:** This is a review, if you know how to create an extension, feel free to skip this step.
For this guide, we will briefly go over how to create an extension. If you have not completed [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) we recommend you pause here and complete that before moving forward.
## Step 1.1: Create the extension template
In Omniverse Code navigate to the `Extensions` tab and create a new extension by clicking the ➕ icon in the upper left corner and select `New Extension Template Project`.
<br>

<br>
<icon> | <new template>
:-------------------------:|:-------------------------:
 | 
<br>
A new extension template window and Visual Studio Code will open after you have selected the folder location, folder name, and extension ID.
## Step 1.2: Naming your extension
Before beginning to code, navigate into `VS Code` and change how the extension is viewed in the **Extension Manager**. It's important to give your extension a title and description for the end user to understand the extension's purpose.
<br>
Inside of the `config` folder, locate the `extension.toml` file:

<br>
> **Note:** `extension.toml` is located inside of the `exts` folder you created for your extension. <br> 
<br>
Inside of this file, there is a title and description for how the extension will look in the **Extension Manager**. Change the title and description for the object info extension. Here is an example of how it looks in `VS code` and how it looks in the **Extension Manager**:

<br>

# Step 2: Get the active viewport
In this section, you import `omni.kit.viewport.utility` into `extension.py`. Then, you use it to store the active viewport. Finally, you will print the name of the active viewport to the console.
## Step 2.1: Navigate to `extension.py`
Navigate to `extension.py`:

This module contains boilerplate code for building a new extension:

## Step 2.2: Import the `omni.kit.viewport.utility`
Import the viewport utility:
```python
import omni.ext
import omni.ui as ui
# NEW: Import function to get the active viewport
from omni.kit.viewport.utility import get_active_viewport_window
```
Now that you've imported the viewport utility library, begin adding to the `MyExtension` class.
## Step 2.3: Get the activate viewport window
In `on_startup()` set the `viewport_window` variable to the active viewport:
```python
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[company.hello.world] MyExtension startup")
# NEW: Get the active Viewport
viewport_window = get_active_viewport_window()
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
def on_click():
print("clicked!")
ui.Button("Click Me", clicked_fn=lambda: on_click())
...
```
At startup the active window is the default Viewport.
## Step 2.4: Print the active viewport
In `on_click()`, print the active viewport:
```python
def on_click():
print(viewport_window)
```
Here, `on_click()` is acting as a convenience method that ensures you stored the active viewport
## Step 2.5: Review your changes
Navigate to Omniverse Code, click the **Click Me** button inside of *My Window*, and locate "Viewport" in the *Console*.

Here you see the result of the print statement you added in the last step.
> **Tip:** If you encounter an error in your console, please refer to the [Viewport Utility tip in Prerequisites](#prerequisites)
<br>
## Step 2.6: Create `object_info_model.py`
In this new module, you will create the necessary information for the object information to be called, such as the selected prim and tracking when the selection changes.
Create a file in the same file location as `extension.py` and name it `object_info_model.py`.
<br>
# Step 3: `object_info_model.py` Code
> **Note:** Work in the `object_info_model.py` module for this section.
<br>
The objective of this step is to get the basic information that the `Manipulator` and `Viewport` will need to display on the selected prim.
## Step 3.1: Import scene from `omni.ui`
As with `extension.py`, import `scene` from `omni.ui` to utilize scene related utilities. Also import `omni.usd`.
```python
from omni.ui import scene as sc
import omni.usd
```
## Step 3.2: Begin setting up variables
Next, create a new class and begin setting variables. Create the `ObjInfoModel` below the imports:
```python
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
```
## Step 3.3: Initialize `ObjInfoModel`
Use `__init__()` inside this class to initialize the object and events. In `__init__()`, set the variable for the current selected prim:
```python
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.position = [0, 0, 0]
```
## Step 3.4: Use UsdContext to listen for selection changes
Finally, get the `UsdContext` ([see here for more information on UsdContext](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.usd/docs/index.html#omni.usd.UsdContext)) to track when the selection changes and create a stage event callback function to be used later on:
```python
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.position = [0, 0, 0]
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
print("A stage event has occurred")
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
<br>
It's important to include `destroy()` in the model class. You want to unsubscribed from events when the model is destroyed.
<br>
## Step 4: Work on the object model
> **Note:** Work in `extension.py` for this section.
Now that you have created `object_info_model.py`, you need to do a few things in `extension.py` use the object model, such as import the model class, create an instance when the extension startsup, and then destroy the model when the extension is shutdown.
## Step 4.1: Import ObjInfoModel
Import ObjInfoModel into `extension.py` from `object_info_model.py`:
```python
import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
# NEW: import model class
from .object_info_model import ObjInfoModel
...
```
## Step 4.2: Create a variable for the object model
Create a variable for object model in `__init()__` of the `MyExtension` Class:
```python
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
# NEW: Reference to the objModel when created so we can destroy it later
def __init__(self) -> None:
super().__init__()
self.obj_model = None
...
```
## Step 4.3: Manage the object model
You should then create the object in `on_startup()` and destroy it later on in `on_shutdown()`:
```python
def on_startup(self, ext_id):
print("[omni.objInfo.tutorial] MyExtension startup")
# Get the active Viewport (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# NEW: create the object
self.obj_model = ObjInfoModel()
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
def on_click():
# Print to see that we did grab the active viewport
print(viewport_window)
ui.Button("Click Me", clicked_fn=lambda: on_click())
def on_shutdown(self):
"""Called when the extension is shutting down."""
print("[omni.objInfo.tutorial] MyExtension shutdown")
# NEW: Destroy the model when created
self.obj_model.destroy()
```
<details>
<summary>Click here for the updated <b>extension.py</b> module </summary>
```python
import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .object_info_model import ObjInfoModel
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self) -> None:
super().__init__()
self.obj_model = None
def on_startup(self, ext_id):
"""Called when the extension is starting up.
Args:
ext_id: Extension ID provided by Kit.
"""
print("[omni.objInfo.tutorial] MyExtension startup")
# Get the active Viewport (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# create the object
self.obj_model = ObjInfoModel()
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
def on_click():
# Print to see that we did grab the active viewport
print(viewport_window)
ui.Button("Click Me", clicked_fn=lambda: on_click())
def on_shutdown(self):
"""Called when the extension is shutting down."""
print("[omni.objInfo.tutorial] MyExtension shutdown")
# Destroy the model when created
self.obj_model.destroy()
```
</details>
<br>
# Step 5: Get the selected prim's data
At this point, there is nothing viewable in Omniverse Code as you the code is not doing anything yet when stage events occur. In this section, you will fill in the logic for the stage event callback to get the selected object's information. By the end of Step 5 you should be able to view the object info in the console.
> **Note:** Work in `object_info_model.py` for this section.
At this point, you have created the start of the `on_stage_event()` callback in `object_info_model.py` but there is nothing happening in the event.
Replace what's in `on_stage_event()` with the variable for the prim path and where that path information is located:
```python
def on_stage_event(self, event):
"""Called by stage_event_stream."""
# NEW
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
self.prim = prim
self.current_path = prim_path[0]
print("prim: " + str(prim))
...
```
You can check that this is working by navigating back to Omniverse Code and create a prim in the viewport. When the prim is created, it's path should display at the bottom.

# Step 6: Object Path Name in Scene
In this step you create another `__init__()` method in a new class to represent the position. This position will be taken directly from USD when requested.
## Step 6.1: Nest the `PositionItem` class
Nest the new `PositionItem` class inside of the `ObjInfoModel` class as so:
```python
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
# NEW: needed for when we call item changed
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
...
```
## Step 6.2: Set path and position
Set the current path and update the position from `[0,0,0]` to store a `PositionItem`:
```python
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
#NEW: set to current path.
self.current_path = ""
# NEW: update to hold position obj created
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
...
```
## Step 6.3: Check the stage
After updating the position, check the stage when the selection of an object is changed. Do this with an `if` statement in `on_stage_event()`, like so:
```python
def on_stage_event(self, event):
# NEW: if statement to only check when selection changed
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
self.prim = prim
self.current_path = prim_path[0]
# NEW: Update on item change
# Position is changed because new selected object has a different position
self._item_changed(self.position)
...
```
## Step 6.4: Set identifiers
Finally, create a new function underneath `on_stage_event()` to set the identifiers:
```python
# NEW: function to get identifiers from the model
def get_item(self, identifier):
if identifier == "name":
return self.current_path
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
<details>
<summary>Click here for the updated <b>object_info_model.py</b> module </summary>
```python
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.position = ObjInfoModel.PositionItem()
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
</details>
<br>
# Step 7: The Manipulator Class
In this step you will create a new module for the manipulator class for the object info, which will be displayed in the viewport in another step ([see here for more information on the Manipulator Class in Omniverse](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Manipulator.html)).<br>
## Step 7.1: Create `object_info_manipulator.py`
Similar to when you created `object_info_model.py`, create a new module in the same folder and name it `object_info_manipulator.py`.
The objective of this module is to getf the object model's details, such as name and path, and display it in the viewport through using `on_build()`. This is important as it connects the nested data in `object_info_model.py`.
## Step 7.2: Import ui
import from omni.ui:
```python
from omni.ui import scene as sc
import omni.ui as ui
```
## Step 7.3: Create `ObjectInfoManipilator`
Create the `ObjInfoManipulator` class:
```python
...
class ObjInfoManipulator(sc.Manipulator):
"""Manipulator that displays the object path and material assignment
with a leader line to the top of the object's bounding box.
"""
```
## Step 7.4 Populate `ObjInfoManipulator`
Populate the `ObjInfoManipulator` class with `on_build()`:
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
position = [0, 0, 0]
sc.Label(f"Path: {self.model.get_item('name')}")
```
This method checks if there is a selection and creates a label for the path.
## Step 7.5 Invalidate the manipulator on model update
Before moving on from `object_info_manipulator.py`, navigate to the end of the file and call `invalidate()`.
```python
...
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
This method purges old memory when the model is updated.
<details>
<summary>Click here for the full <b>object_info_manipulator.py</b> module </summary>
```python
from omni.ui import scene as sc
import omni.ui as ui
class ObjInfoManipulator(sc.Manipulator):
"""Manipulator that displays the object path and material assignment
with a leader line to the top of the object's bounding box.
"""
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
position = [0, 0, 0]
sc.Label(f"Path: {self.model.get_item('name')}")
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
```
</details>
<br>
# Step 8: Displaying information in the viewport
In this step, you will create a new module that uses the gathered information from other modules and displays them in the active viewport.
## Step 8.1: Create new file
Add this module to the same folder and name it `viewport_scene.py`.
Import the `scene` from `omni.ui`, `ObjInfoModel`, and `ObjInfoManipulator`:
```python
from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjInfoManipulator
from .object_info_model import ObjInfoModel
```
## Step 8.2 Create new class
Create the `ViewportSceneInfo` class and define the `__init__()`:
```python
...
class ViewportSceneInfo():
"""The Object Info Manipulator, placed into a Viewport"""
def __init__(self, viewport_window, ext_id) -> None:
self.scene_view = None
self.viewport_window = viewport_window
```
## Step 8.3 Display object information
To display the information, set the default SceneView. Then add the manipulator into the SceneView's scene and register it with the Viewport:
```python
...
class ViewportSceneInfo():
"""The Object Info Manipulator, placed into a Viewport"""
def __init__(self, viewport_window, ext_id) -> None:
self.scene_view = None
self.viewport_window = viewport_window
# NEW: Create a unique frame for our SceneView
with self.viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self.scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self.scene_view.scene:
ObjInfoManipulator(model=ObjInfoModel())
# Register the SceneView with the Viewport to get projection and view updates
self.viewport_window.viewport_api.add_scene_view(self.scene_view)
```
## Step 8.4: Clean up scene and viewport memory
Before closing out on `viewport_scene.py` don't forget to call `destroy()` to clear the scene and un-register our unique SceneView from the Viewport.
```python
...
def __del__(self):
self.destroy()
def destroy(self):
if self.scene_view:
# Empty the SceneView of any elements it may have
self.scene_view.scene.clear()
# un-register the SceneView from Viewport updates
if self.viewport_window:
self.viewport_window.viewport_api.remove_scene_view(self.scene_view)
# Remove our references to these objects
self.viewport_window = None
self.scene_view = None
```
<details>
<summary>Click here for the full <b>viewport_scene.py</b> module </summary>
```python
from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjInfoManipulator
from .object_info_model import ObjInfoModel
class ViewportSceneInfo():
"""The Object Info Manipulator, placed into a Viewport"""
def __init__(self, viewport_window, ext_id) -> None:
self.scene_view = None
self.viewport_window = viewport_window
# Create a unique frame for our SceneView
with self.viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self.scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self.scene_view.scene:
ObjInfoManipulator(model=ObjInfoModel())
# Register the SceneView with the Viewport to get projection and view updates
self.viewport_window.viewport_api.add_scene_view(self.scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self.scene_view:
# Empty the SceneView of any elements it may have
self.scene_view.scene.clear()
# un-register the SceneView from Viewport updates
if self.viewport_window:
self.viewport_window.viewport_api.remove_scene_view(self.scene_view)
# Remove our references to these objects
self.viewport_window = None
self.scene_view = None
```
</details>
<br>
# Step 9: Cleaning up `extension.py`
> **Note:** Work in `extension.py` for this section.
Now that you've have established a Viewport, you need to clean up `extension.py` to reflect these changes. You will remove some of code from previous steps and ensure that the viewport is flushed out on shutdown.
## Step 9.1: Import class
Import `ViewportSceneInfo`:
```python
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
# NEW:
from .viewport_scene import ViewportSceneInfo
```
## Step 9.2: Remove `ObjInfoModel`
Remove the import from the `object_info_model` module as it will no longer be used:
```python
# REMOVE
from .object_info_model import ObjInfoModel
```
## Step 9.3: Remove reference
As you removed the import from `ObjInfoModel` import, remove its reference in the `__init__()` method and replace it with the `viewport_scene`:
```python
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self) -> None:
super().__init__()
# NEW: removed reference to objmodelinfo and replaced with viewportscene
self.viewport_scene = None
```
## Step 9.4: Remove start up code
Remove the start up code that constructs the `ObjInfoModel` object and the code following it that creates the extension window and **Click Me** button:
```python
...
def on_startup(self, ext_id):
# # # !REMOVE! # # #
print("[omni.objInfo.tutorial] MyExtension startup")
viewport_window = get_active_viewport_window()
self.obj_model = ObjInfoModel()
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
def on_click():
print(viewport_window)
ui.Button("Click Me", clicked_fn=lambda: on_click())
# # # END # # #
# # # !REPLACE WITH! # # #
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
# # # END # # #
```
<details>
<summary>Click to view final <b>on_startup</b> code</summary>
```python
def on_startup(self, ext_id):
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
```
</details>
<br>
## Step 9.5: Clean up viewport memory
Finally, update `on_shutdown()` to clean up the viewport:
```python
...
def on_shutdown(self):
"""Called when the extension is shutting down."""
# NEW: updated to destroy viewportscene
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None
```
<details>
<summary>Click to view the updated <b>extension.py</b> </summary>
```python
import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportSceneInfo
class MyExtension(omni.ext.IExt):
"""Creates an extension which will display object info in 3D
over any object in a UI Scene.
"""
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self) -> None:
super().__init__()
self.viewport_scene = None
def on_startup(self, ext_id):
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
def on_shutdown(self):
"""Called when the extension is shutting down."""
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None
```
</details>
<br>
## Congratulations!
You should be able to create a prim in the viewport and view the Object Info at the world position `[0,0,0]`.

>💡 Tip: If you are logging any errors in the Console in Omniverse Code after updating `extention.py` try refreshing the application.
<br>
# Step 10: Displaying Object Info in Local Space
At this stage, the Object Info is displaying in the viewport but it is displayed at the origin. This means that regardless of where your object is located in the World, the info will always be displayed at [0,0,0]. In the next few steps you will convert this into Local Space. By the end of step 4 the Object Info should follow the object.
## Step 10.1: Import USD
> **Note:** Work in `object_info_model.py` for this section.
In this step and the following steps, we will be doing a little bit of math. Before we jump into that though, let's import what we need to make this work into `object_info_model.py`. We will be importing primarily what we need from USD and we will place these imports at the top of the file:
```python
# NEW IMPORTS
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
```
## Step 10.2: Add identifier
Add a new identifier for the position in `get_item()`:
```python
...
def get_item(self, identifier):
if identifier == "name":
return self.current_path
# NEW: new identifier
elif identifier == "position":
return self.position
```
## Step 10.3: Add `get_as_floats()`
After adding to `get_item()`, create a new function to get the position of the prim. Call this function `get_as_floats()`:
```python
...
# NEW: new function to get position of prim
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
```
This function requests the position and value from the item.
## Step 10.4: Define `get_position()`:
Although you created this new function to get the position, you've yet to define the position. The position will be defined in a new function based on the bounding box we will compute for the prim. Name the new function `get_position()` and get a reference to the stage:
```python
...
# NEW: new function that defines the position based on the bounding box of the prim
def get_position(self):
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
```
## Step 10.5: Get the position
Use `get_position()` to get the position directly form USD using the bounding box:
```python
...
def get_position(self):
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin() #bbox stands for bounding box
bboxMax = range.GetMax()
```
## Step 10.6: Find the top center
Finally, find the top center of the bounding box. Additionally, add a small offset upward so that the information is not overlapping our prim. Append this code to `get_position()`:
```python
...
def get_position(self):
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin() #bbox stands for bounding box
bboxMax = range.GetMax()
# NEW
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
```
<details>
<summary>Click here for the final <b>object_info_model.py</b> code for this step.</summary>
```python
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
elif identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
# defines the position based on the bounding box of the prim
def get_position(self):
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin() #bbox stands for bounding box
bboxMax = range.GetMax()
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
</details>
<br>
# Step 11: Updating `ObjInfoManipulator`
> **Note:** You are working in `object_info_manipulator.py` for this section.
In this step, you need to update the position value and to position the Object Info at the object's origin and then offset it in the up-direction. You'll also want to make sure that it is scaled properly in the viewport.
Fortunately, this does not require a big alteration to our existing code. You merely need to add onto the `on_build` function in the `object_info_manipulator.py` module:
```python
...
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
# NEW: update to position value and added transform functions to position the Label at the object's origin and +5 in the up direction
# we also want to make sure it is scaled properly
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
with sc.Transform(scale_to=sc.Space.SCREEN):
sc.Label(f"Path: {self.model.get_item('name')}")
sc.Label(f"Path: {self.model.get_item('name')}")
...
```
# Step 12: Moving the Label with the prim
In the viewport, the text does not follow our object despite positioning the label at the top center of the bounding box of the object. The text also remains in the viewport even when the object is no longer selected. This is because we are reacting to all stage events and not only when a prim is selected. In this final step we will be guiding you to cleaning up these issues.
> **Note:** Work in `object_info_model.py` for this section
## 12.1: Import `Tf`
Place one more import into `object_info_model.py` at the top of the file, as so:
```python
# NEW
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
```
You will use `Tf` to receive notifications of any selection changes.
### 12.2: Store the stage listener
Add a new variable to store the stage listener under the second `__init__()` method:
```python
...
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
# NEW: new variable
self.stage_listener = None
self.position = ObjInfoModel.PositionItem()
...
```
### 12.3: Handle prim selection events
Now, you need to add some code to `on_stage_event()`.
You need to do a few things in this function, such as checking if the `prim_path` exists, turn off the manipulator if it does not, then check if the selected item is a `UsdGeom.Imageable` and remove the stage listener if not. Additionally, notice a change with the stage listener when the selection has changed.
```python
...
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
# NEW: if prim path doesn't exist we want to make sure nothing shows up because that means we do not have a prim selected
if not prim_path:
# This turns off the manipulator when everything is deselected
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
# NEW: if the selected item is not a prim we need to revoke the stagelistener since we don't need to update anything
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
# Revoke the Tf.Notice listener, we don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
# NEW: Register a notice when objects in the scene have changed
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
```
<details>
<summary>Click here for the full <b>on_stage_event</b> function </summary>
```python
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
```
</details>
## 12.4: Setup `notice_changed()` callback
In the final step, create a new function that will be called when any objects change. It will loop through all changed prim paths until the selected one is found and get the latest position for the selected prim. After this, the path should follow the selected object.:
```python
...
# NEW: function that will get called when objects change in the scene. We only care about our selected object so we loop through all notices that get passed along until we find ours
def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None:
"""Called by Tf.Notice. Used when the current selected object changes in some way."""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
...
```
<details>
<summary>Click here for the final <b>object_info_model.py</b> code </summary>
```python
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.stage_listener = None
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
elif identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
# loop through all notices that get passed along until we find selected
def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None:
"""Called by Tf.Notice. Used when the current selected object changes in some way."""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe()
```
</details>
# Congratulations!
Your viewport should now display the object info above the selected object and move with the prim in the scene. You have successfully created the Object Info Extension!
 | 47,854 | Markdown | 32.748237 | 378 | 0.663623 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/extension.py | import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportSceneInfo
class MyExtension(omni.ext.IExt):
"""Creates an extension which will display object info in 3D
over any object in a UI Scene.
"""
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self) -> None:
super().__init__()
self.viewport_scene = None
def on_startup(self, ext_id):
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
def on_shutdown(self):
"""Called when the extension is shutting down."""
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None | 915 | Python | 34.230768 | 119 | 0.679781 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/viewport_scene.py | from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjInfoManipulator
from .object_info_model import ObjInfoModel
class ViewportSceneInfo():
def __init__(self, viewportWindow, ext_id) -> None:
self.sceneView = None
self.viewportWindow = viewportWindow
with self.viewportWindow.get_frame(ext_id):
self.sceneView = sc.SceneView()
with self.sceneView.scene:
ObjInfoManipulator(model=ObjInfoModel())
self.viewportWindow.viewport_api.add_scene_view(self.sceneView)
def __del__(self):
self.destroy()
def destroy(self):
if self.sceneView:
self.sceneView.scene.clear()
if self.viewportWindow:
self.viewportWindow.viewport_api.remove_scene_view(self.sceneView)
self.viewportWindow = None
self.sceneView = None | 921 | Python | 27.812499 | 82 | 0.641694 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/object_info_model.py | from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.stage_listener = None
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
elif identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
# loop through all notices that get passed along until we find selected
def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None:
"""Called by Tf.Notice. Used when the current selected object changes in some way."""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe() | 4,115 | Python | 34.482758 | 111 | 0.598056 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/object_info_manipulator.py | from omni.ui import scene as sc
import omni.ui as ui
class ObjInfoManipulator(sc.Manipulator):
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
# NEW: update to position value and added transform functions to position the Label at the object's origin and +5 in the up direction
# we also want to make sure it is scaled properly
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
with sc.Transform(scale_to=sc.Space.SCREEN):
# END NEW
sc.Label(f"Path: {self.model.get_item('name')}")
sc.Label(f"Path: {self.model.get_item('name')}")
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate() | 1,050 | Python | 35.241378 | 141 | 0.626667 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/config/extension.toml | [package]
version = "1.0.0"
authors = ["NVIDIA"]
title = "Omni UI Scene Object Info Example"
description = "This example shows a 3D info popover-type tool tip scene object"
readme = "docs/README.md"
repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene"
category = "Documentation"
keywords = ["ui", "example", "scene", "docs", "documentation", "popover"]
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui.scene" = { }
"omni.usd" = { }
"omni.kit.viewport.utility" = { }
[[python.module]]
name = "omni.example.ui_scene.object_info"
[[test]]
args = ["--/renderer/enabled=pxr", "--/renderer/active=pxr", "--no-window"]
dependencies = ["omni.hydra.pxr", "omni.kit.window.viewport"]
| 775 | TOML | 30.039999 | 82 | 0.689032 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ObjectInfoExtension"]
import carb
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportScene
class ObjectInfoExtension(omni.ext.IExt):
"""Creates an extension which will display object info in 3D
over any object in a UI Scene.
"""
def __init__(self):
self._viewport_scene = None
def on_startup(self, ext_id: str) -> None:
"""Called when the extension is starting up.
Args:
ext_id: Extension ID provided by Kit.
"""
# Get the active Viewport (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# Issue an error if there is no Viewport
if not viewport_window:
carb.log_error(f"No Viewport Window to add {ext_id} scene to")
return
# Build out the scene
self._viewport_scene = ViewportScene(viewport_window, ext_id)
def on_shutdown(self) -> None:
"""Called when the extension is shutting down."""
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
| 1,609 | Python | 32.541666 | 76 | 0.679925 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.