file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/__init__.py | from .extension import ViewportDocsExtension
| 45 | Python | 21.999989 | 44 | 0.888889 |
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/window.py | # Copyright (c) 2018-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.kit.documentation.builder import DocumentationBuilderWindow
from pathlib import Path
__all__ = ["ViewportDocsWindow"]
class ViewportDocsWindow(DocumentationBuilderWindow):
"""The window with the documentation"""
def __init__(self, title: str, **kwargs):
module_root = Path(__file__).parent
docs_root = module_root.parent.parent.parent.parent.joinpath("docs")
pages = ['overview.md', 'window.md', 'widget.md', 'viewport_api.md', 'capture.md', 'camera_manipulator.md']
filenames = [f'{docs_root.joinpath(page_source)}' for page_source in pages]
super().__init__(title, filenames=filenames, **kwargs)
| 1,095 | Python | 41.153845 | 115 | 0.73242 |
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/tests/__init__.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.ui_test
class TestViewportDocsWindow(OmniUiTest):
async def setUp(self):
await super().setUp()
async def tearDown(self):
await super().tearDown()
async def test_just_opened(self):
win = omni.kit.ui_test.find("Viewport Doc")
self.assertIsNotNone(win)
| 819 | Python | 31.799999 | 77 | 0.741148 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/camera_manipulator.md | # Camera Manipulator
Mouse interaction with the Viewport is handled with classes from `omni.kit.manipulator.camera`, which is built on top of the `omni.ui.scene` framework.
We've created an `omni.ui.scene.SceneView` to host the manipulator, and by simply assigning the camera manipulators model
into the SceneView's model, all of the edits to the Camera's transform will be pushed through to the `SceneView`.
```
# And finally add the camera-manipulator into that view
with self.__scene_view.scene:
self.__camera_manip = ViewportCameraManipulator(self.viewport_api)
# Push the camera manipulator's model into the SceneView so it'lll auto-update
self.__scene_view.model = self.__camera_manip.model
```
The `omni.ui.scene.SceneView` only understands two values: 'view' and 'projection'. Our CameraManipulator's model will push
out those values as edits are made; however, it supports a larger set of values to control the manipulator itself.
## Operations and Values
The CameraManipulator model store's the amount of movement according to three modes, applied in this order:
1. Tumble
2. Look
3. Move (Pan)
4. Fly (FlightMode / WASD navigation)
### tumble
Tumble values are specified in degrees as the amount to rotate around the current up-axis.
These values should be pre-scaled with any speed before setting into the model.
This allows for different manipulators/gestures to interpret speed differently, rather than lock to a constant speed.
```python
# Tumble by 180 degrees around Y (as a movement across ui X would cause)
model.set_floats('tumble', [0, 180, 0])
```
### look
Look values are specified in degrees as the amount to rotate around the current up-axis.
These values should be pre-scaled with any speed before setting into the model.
This allows for different manipulators/gestures to interpret speed differently, rather than lock to a constant speed.
```python
# Look by 90 degrees around X (as a movement across ui Y would cause)
# i.e Look straight up
model.set_floats('look', [90, 0, 0])
```
### move
Move values are specified in world units and the amount to move the camera by.
Move is applied after rotation, so the X, Y, Z are essentially left, right, back.
These values should be pre-scaled with any speed before setting into the model.
This allows for different manipulators/gestures to interpret speed differently, rather than lock to a constant speed.
```python
# Move left by 30 units, up by 60 and back by 90
model.set_floats('move', [30, 60, 90])
```
### fly
Fly values are the direction of flight in X, Y, Z.
Fly is applied after rotation, so the X, Y, Z are essentially left, right, back.
These values will be scaled with `fly_speed` before aplication.
Because fly is a direction with `fly_speed` automatically applied, if a gesture/manipulator wants to fly slower
without changing `fly_speed` globally, it must apply whatever factor is required before setting.
```python
# Move left
model.set_floats('fly', [1, 0, 0])
# Move up
model.set_floats('fly', [0, 1, 0])
```
## Speed
By default the Camera manipulator will map a full mouse move across the viewport as follows:
- Pan: A full translation of the center-of-interest across the Viewport.
- Tumble: A 180 degree rotation across X or Y.
- Look: A 180 degree rotation across X and a 90 degree rotation across Y.
These speed can be adjusted by setting float values into the model.
### world_speed
The Pan and Zoom speed can be adjusted with three floats set into the model as 'world_speed'.
```python
# Half the movement speed for both Pan and Zoom
pan_speed_x = 0.5, pan_speed_y = 0.5, zoom_speed_z = 0.5
model.set_floats('world_speed', [pan_speed_x, pan_speed_y, zoom_speed_z])
```
### rotation_speed
The Tumble and Look speed can be adjusted with either a scalar value for all rotation axes or per component.
```python
# Half the rotation speed for both Tumble and Look
rot_speed_both = 0.5
model.set_floats('rotation_speed', [rot_speed_both])
# Half the rotation speed for both Tumble and Look in X and quarter if for Y
rot_speed_x = 0.5, rot_speed_y = 0.25
model.set_floats('rotation_speed', [rot_speed_x, rot_speed_y])
```
### tumble_speed
Tumble can be adjusted separately with either a scalar value for all rotation axes or per component.
The final speed of Tumble operation is `rotation_speed * tumble_speed`
```python
# Half the rotation speed for Tumble
rot_speed_both = 0.5
model.set_floats('tumble_speed', [rot_speed_both])
# Half the rotation speed for Tumble in X and quarter if for Y
rot_speed_x = 0.5, rot_speed_y = 0.25
model.set_floats('tumble_speed', [rot_speed_x, rot_speed_y])
```
### look_speed
Look can be adjusted separately with either a scalar value for all rotation axes or per component.
The final speed of a Look operation is `rotation_speed * tumble_speed`
```python
# Half the rotation speed for Look
rot_speed_both = 0.5
model.set_floats('look_speed', [rot_speed_both])
# Half the rotation speed for Tumble in X and quarter if for Y
rot_speed_x = 0.5, rot_speed_y = 0.25
model.set_floats('look_speed', [rot_speed_x, rot_speed_y])
```
### fly_speed
The speed at which FlightMode (WASD navigation) will fly through the scene.
FlightMode speed can be adjusted separately with either a scalar value for all axes or per component.
```python
# Half the speed in all directions
fly_speed = 0.5
model.set_floats('fly_speed', [fly_speed])
# Half the speed when moving in X or Y, but double it moving in Z
fly_speed_x_y = 0.5, fly_speed_z = 2
model.set_floats('fly_speed', [fly_speed_x_y, fly_speed_x_y, fly_speed_z])
```
## Undo
Because we're operating on a unique `omni.usd.UsdContext` we don't want movement in the preview-window to affect the undo-stack.
To accomplish that, we'll set the 'disable_undo' value to an array of 1 int; essentially saying `disable_undo=True`.
```python
# Let's disable any undo for these movements as we're a preview-window
model.set_ints('disable_undo', [1])
```
## Disabling operations
By default the manipulator will allow Pan, Zoom, Tumble, and Look operations on a perspective camera, but only allow
Pan and Zoom on an orthographic one. If we want to explicitly disable any operations again we set int values as booleans
into the model.
### disable_tumble
```python
# Disable the Tumble manipulation
model.set_ints('disable_tumble', [1])
```
### disable_look
```python
# Disable the Look manipulation
model.set_ints('disable_look', [1])
```
### disable_pan
```python
# Disable the Pan manipulation.
model.set_ints('disable_pan', [1])
```
### disable_zoom
```python
# Disable the Zoom manipulation.
model.set_ints('disable_zoom', [1])
```
| 6,646 | Markdown | 35.927778 | 151 | 0.7418 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/widget.md | # Stage Preview Widget
The `StagePreviewWidget` is comprised of a few `omni.ui` objects which are stacked on top of one-another.
So first an `omni.ui.ZStack` container is instantiated and using the `omni.ui` with syntax, the remaining objects
are created in its scope:
```python
self.__ui_container = ui.ZStack()
with self.__ui_container:
```
## Background
First we create an `omni.ui.Rectangle` that will fill the entire frame with a constant color, using black as the default.
We add a few additional style arguments so that the background color can be controlled easily from calling code.
```python
# Add a background Rectangle that is black by default, but can change with a set_style
ui.Rectangle(style_type_name_override='ViewportBackgroundColor', style={'ViewportBackgroundColor': {'background_color': 0xff000000}})
```
## ViewportWidget
Next the `omni.kit.widget.viewport.ViewportWidget` is created, directly above the background Rectangle.
In the `stage_preview` example, the `ViewportWidget` is actually created to always fill the parent frame by
passing `resolution='fill_frame'`, which will essentially make it so the black background never seen.
If a constant resolution was requested by passing a tuple `resolution=(640, 480)`; however, the rendered image would be
locked to that resolution and causing the background rect to be seen if the Widget was wider or taller than the texture's
resolution.
```python
self.__vp_widget = ViewportWidget(usd_context_name=usd_context_name, camera_path=camera_path, resolution=resolution, *ui_args, **ui_kw_args)
```
## SceneView
The final `omni.ui` element we are going to create is an `omni.ui.scene.SceneView`. We are creating it primarily to
host our camera-manipulators which are written for the `omni.ui.scene` framework, but it could also be used to insert
additional drawing on top of the `ViewportWidget` in 3D space.
```python
# Add the omni.ui.scene.SceneView that is going to host the camera-manipulator
self.__scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH)
# And finally add the camera-manipulator into that view
with self.__scene_view.scene:
```
## Full code
```python
class StagePreviewWidget:
def __init__(self, usd_context_name: str = '', camera_path: str = None, resolution: Union[tuple, str] = None, *ui_args ,**ui_kw_args):
"""StagePreviewWidget contructor
Args:
usd_context_name (str): The name of a UsdContext the Viewport will be viewing.
camera_path (str): The path of the initial camera to render to.
resolution (x, y): The resolution of the backing texture, or 'fill_frame' to match the widget's ui-size
*ui_args, **ui_kw_args: Additional arguments to pass to the ViewportWidget's parent frame
"""
# Put the Viewport in a ZStack so that a background rectangle can be added underneath
self.__ui_container = ui.ZStack()
with self.__ui_container:
# Add a background Rectangle that is black by default, but can change with a set_style
ui.Rectangle(style_type_name_override='ViewportBackgroundColor', style={'ViewportBackgroundColor': {'background_color': 0xff000000}})
# Create the ViewportWidget, forwarding all of the arguments to this constructor
self.__vp_widget = ViewportWidget(usd_context_name=usd_context_name, camera_path=camera_path, resolution=resolution, *ui_args, **ui_kw_args)
# Add the omni.ui.scene.SceneView that is going to host the camera-manipulator
self.__scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH)
# And finally add the camera-manipulator into that view
with self.__scene_view.scene:
self.__camera_manip = ViewportCameraManipulator(self.viewport_api)
model = self.__camera_manip.model
# Let's disable any undo for these movements as we're a preview-window
model.set_ints('disable_undo', [1])
# We'll also let the Viewport automatically push view and projection changes into our scene-view
self.viewport_api.add_scene_view(self.__scene_view)
def __del__(self):
self.destroy()
def destroy(self):
self.__view_change_sub = None
if self.__camera_manip:
self.__camera_manip.destroy()
self.__camera_manip = None
if self.__scene_view:
self.__scene_view.destroy()
self.__scene_view = None
if self.__vp_widget:
self.__vp_widget.destroy()
self.__vp_widget = None
if self.__ui_container:
self.__ui_container.destroy()
self.__ui_container = None
@property
def viewport_api(self):
# Access to the underying ViewportAPI object to control renderer, resolution
return self.__vp_widget.viewport_api
@property
def scene_view(self):
# Access to the omni.ui.scene.SceneView
return self.__scene_view
def set_style(self, *args, **kwargs):
# Give some styling access
self.__ui_container.set_style(*args, **kwargs)
```
| 5,212 | Markdown | 43.555555 | 152 | 0.683615 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/CHANGELOG.md | # Changelog
Documentation for the next Viewport
## [104.0.2] - 2022-05-04
### Changed
- Imported to kit repro and bump version to match Kit SDK
## [1.0.2] - 2022-02-09
### Changed
- Updated documentation to include latest changes and Viewport capturing
## [1.0.1] - 2021-12-22
### Changed
- Add documentation for add_scene_view and remove_scene_view methods.
## [1.0.0] - 2021-12-20
### Changed
- Initial release
| 418 | Markdown | 19.949999 | 72 | 0.696172 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/overview.md | # Overview
Viewport Next is a preview of the next generation of Kit's Viewport. It was
designed to be as light as possible, providing a way to isolate features and
compose them as needed to create unique experiences.
This documentation will walk through a few simple examples using this technology,
as well as how it can be used in tandem with the `omni.ui.scene` framework.
## What is a Viewport
Exactly what a viewport is can be a bit ill-defined and dependent on what you are
trying to accomplish, so it's best to define some terms up front and explain what
this documentation is targeting.

At a very high level a Viewport is a way for a user to visualize (and often
interact with) a Renderer's output of a scene. When you create a "Viewport Next"
instance via Kit's Window menu, you are actually creating a hierarchy of objects.

The three objects of interest in this hierarchy are:
1. The `ViewportWindow`, which we will be re-implementing as `StagePreviewWindow`
2. The `ViewportWidget`, one of which we will be instantiating.
3. The `ViewportTexture`, which is created and owned by the `ViewportWidget`.
While we will be using (or re-implementing) all three of those objects, this documentation is primarily
targeted towards understanding the `ViewportWidget` and it's usage in the `omni.kit.viewport.stage_preview`.
After creating a Window and instance of a `ViewportWidget`, we will finally add a camera manipulator built
with `omni.ui.scene` to interact with the `Usd.Stage`, as well as control aspects of the
Renderer's output to the underlying `ViewportTexture`.
Even though the `ViewportWidget` is our main focus, it is good to understand the backing `ViewportTexture` is independent
of the `ViewportWidget`, and that a texture's resolution may not neccessarily match the size of the `ViewportWidget`
it is contained in. This is particularly import for world-space queries or other advanced usage.
## Enabling the extension
To enable the extension and open a "Viewport Next" window, go to the "Extensions" tab
and enable the "Viewport Window" extension (`omni.kit.viewport.window`).

## Simplest example
The `omni.kit.viewport.stage_preview` adds additional features that make may make a first read of the code a bit harder.
So before stepping through that example, lets take a moment to reduce it to an even simpler case where we create
a single Window and add only a Viewport which is tied to the default `UsdContext` and `Usd.Stage`.
We won't be able to interact with the Viewport other than through Python, but because we are associated with the
default `UsdContext`: any changes in the `Usd.Stage` (from navigation or editing in another Viewport or adding a `Usd.Prim`
from the Create menu) will be reflected in our new view.
```python
from omni.kit.widget.viewport import ViewportWidget
viewport_window = omni.ui.Window('SimpleViewport', width=1280, height=720+20) # Add 20 for the title-bar
with viewport_window.frame:
viewport_widget = ViewportWidget(resolution = (1280, 720))
# Control of the ViewportTexture happens through the object held in the viewport_api property
viewport_api = viewport_widget.viewport_api
# We can reduce the resolution of the render easily
viewport_api.resolution = (640, 480)
# We can also switch to a different camera if we know the path to one that exists
viewport_api.camera_path = '/World/Camera'
# And inspect
print(viewport_api.projection)
print(viewport_api.transform)
# Don't forget to destroy the objects when done with them
# viewport_widget.destroy()
# viewport_window.destroy()
# viewport_window, viewport_widget = None, None
```

| 3,733 | Markdown | 42.929411 | 123 | 0.776855 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/window.md | # Stage Preview Window
In order to display the Renderer's output, we'll need to have an `omni.ui.window`
that will host our widget. We're interested in this level primarily to demonstrate the
ability to create a `ViewportWidget` that isn't tied to the application's main `UsdContext`;
rather you can provide a usd_context_name string argument and the `StagePreviewWindow` will
either reuse an existing `UsdContext` with that name, or create a new one.
Keep in mind a `ViewportWidget` is currently tied to exactly one `UsdContext` for its lifetime.
If you wanted to change the `UsdContext` you are viewing, you would need to hide and show a new `ViewportWidget` based
on which context you want to be displayed.

## Context creation
The first step we take is to check whether the named `UsdContext` exists, and if not, create it.
```python
# We may be given an already valid context, or we'll be creating and managing it ourselves
usd_context = omni.usd.get_context(usd_context_name)
if not usd_context:
self.__usd_context_name = usd_context_name
self.__usd_context = omni.usd.create_context(usd_context_name)
else:
self.__usd_context_name = None
self.__usd_context = None
```
## Viewport creation
Once we know a valid context with usd_context_name exists, we create the `omni.ui.Window` passing along
the window size and window flags. The `omni.ui` documentation has more in depth description of what an `omni.ui.Window`
is and the arguments for it's creation.
After the `omni.ui.Window` has been created, we'll finally be able to create the `StagePreviewWidget`, passing along
the `usd_context_name`. We do this within the context of the `omni.ui.Window.frame` property, and forward any
additional arguments to the `StagePreviewWidget` constructor.
```python
super().__init__(title, width=window_width, height=window_height, flags=flags)
with self.frame:
self.__preview_viewport = StagePreviewWidget(usd_context_name, *vp_args, **vp_kw_args)
```
## Full code
```python
class StagePreviewWindow(ui.Window):
def __init__(self, title: str, usd_context_name: str = '', window_width: int = 1280, window_height: int = 720 + 20, flags: int = ui.WINDOW_FLAGS_NO_SCROLLBAR, *vp_args, **vp_kw_args):
"""StagePreviewWindow contructor
Args:
title (str): The name of the Window.
usd_context_name (str): The name of a UsdContext this Viewport will be viewing.
window_width(int): The width of the Window.
window_height(int): The height of the Window.
flags(int): ui.WINDOW flags to use for the Window.
*vp_args, **vp_kw_args: Additional arguments to pass to the StagePreviewWidget
"""
# We may be given an already valid context, or we'll be creating and managing it ourselves
usd_context = omni.usd.get_context(usd_context_name)
if not usd_context:
self.__usd_context_name = usd_context_name
self.__usd_context = omni.usd.create_context(usd_context_name)
else:
self.__usd_context_name = None
self.__usd_context = None
super().__init__(title, width=window_width, height=window_height, flags=flags)
with self.frame:
self.__preview_viewport = StagePreviewWidget(usd_context_name, *vp_args, **vp_kw_args)
def __del__(self):
self.destroy()
@property
def preview_viewport(self):
return self.__preview_viewport
def open_stage(self, file_path: str):
# Reach into the StagePreviewWidget and get the viewport where we can retrieve the usd_context or usd_context_name
self.__preview_viewport.viewport_api.usd_context.open_stage(file_path)
# the Viewport doesn't have any idea of omni.ui.scene so give the models a sync after open (camera may have changed)
self.__preview_viewport.sync_models()
def destroy(self):
if self.__preview_viewport:
self.__preview_viewport.destroy()
self.__preview_viewport = None
if self.__usd_context:
# We can't fully tear down everything yet, so just clear out any active stage
self.__usd_context.remove_all_hydra_engines()
# self.__usd_context = None
# omni.usd.destroy_context(self.__usd_context_name)
super().destroy()
```
| 4,376 | Markdown | 43.663265 | 187 | 0.684186 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/viewport_api.md | # Viewport API
The ViewportAPI object is used to access and control aspects of the render, who will then push images into the backing texture.
It is accessed via the `ViewportWidget.viewport_api` property which returns a Python `weakref.proxy` object.
The use of a weakref is done in order to make sure that a Renderer and Texture aren't kept alive because client code
is keeping a reference to one of these objects. That is: the lifetime of a Viewport is controlled by the creator of the Viewport and
cannot be extended beyond the usage they expect.
With our simple `omni.kit.viewport.stage_preview` example, we'll now run through some cases of directly controlling the render,
similar to what the Content context-menu does.
```python
from omni.kit.viewport.stage_preview.window import StagePreviewWindow
# Viewport widget can be setup to fill the frame with 'fill_frame', or to a constant resolution (x, y).
resolution = 'fill_frame' or (640, 480) # Will use 'fill_frame'
# Give the Window a unique name, the window-size, and forward the resolution to the Viewport itself
preview_window = StagePreviewWindow('My Stage Preview', usd_context_name='MyStagePreviewWindowContext',
window_width=640, window_height=480, resolution=resolution)
# Open a USD file in the UsdContext that the preview_window is using
preview_window.open_stage('http://omniverse-content-production.s3-us-west-2.amazonaws.com/Samples/Astronaut/Astronaut.usd')
# Save an easy-to-use reference to the ViewportAPI object
viewport_api = preview_window.preview_viewport.viewport_api
```
## Camera
The camera being used to render the image is controlled with the `camera_path` property.
It will return and is settable with a an `Sdf.Path`.
The property will also accept a string, but it is slightly more efficient to set with an `Sdf.Path` if you have one available.
```python
print(viewport_api.camera_path)
# => '/Root/LongView'
# Change the camera to view through the implicit Top camera
viewport_api.camera_path = '/OmniverseKit_Front'
# Change the camera to view through the implicit Perspective camera
viewport_api.camera_path = '/OmniverseKit_Persp'
```
## Filling the canvas
Control whether the texture-resolution should be adjusted based on the parent objects ui-size with the `fill_frame` property.
It will return and is settable with a bool.
```python
print('viewport_api.fill_frame)
# => True
# Disable the automatic resolution
viewport_api.fill_frame = False
# And give it an explicit resolution
viewport_api.resolution = (640, 480)
```
## Resolution
Resolution of the underlying `ViewportTexture` can be queried and set via the `resolution` property.
It will return and is settable with a tuple representing the (x, y) resolution of the rendered image.
```python
print(viewport_api.resolution)
# => (640, 480)
# Change the render output resolution to a 512 x 512 texture
viewport_api.resolution = (512, 512)
```
## SceneView
For simplicity, the ViewportAPI can push both view and projection matrices into an `omni.ui.scene.SceneView.model`.
The use of these methods are not required, rather provided a convenient way to
auto-manage their relationship (particularly for stage independent camera, resolution, and widget size changes),
while also providing room for future expansion where a `SceneView` may be locked
to last delivered rendered frame versus the current implementation that pushes changes
into the Renderer and the `SceneView` simultaneously.
### add_scene_view
Add an `omni.ui.scene.SceneView` to the list of models that the Viewport will notify with changes to view and projection matrices.
The Viewport will only retain a weak-reference to the provided `SceneView` to avoid extending the lifetime of the `SceneView` itself.
A `remove_scene_view` is available if the need to dynamically change the list of models to be notified is necessary.
```python
scene_view = omni.ui.scene.SceneView()
# Pass the real object, as a weak-reference will be retained
viewport_api.add_scene_view(scene_view)
```
### remove_scene_view
Remove the `omni.ui.scene.SceneView` from the list of models that the Viewport will notify from changes to view and projection matrices.
Because the Viewport only retains a weak-reference to the `SceneView`, calling this explicitly isn't mandatory, but can be
used to dynamically change the list of `SceneView` objects whose model should be updated.
```python
viewport_api.remove_scene_view(scene_view)
```
## Additional Accessors
The `ViewportAPI` provides a few additional read-only accessors for convenience:
### usd_context_name
```python
viewport_api.usd_context_name => str
# Returns the name of the UsdContext the Viewport is bound to.
```
### usd_context
```python
viewport_api.usd_context => omni.usd.UsdContext
# Returns the actual UsdContext the Viewport is bound to, essentially `omni.usd.get_context(self.usd_context_name)`.
```
### stage
```python
viewport_api.stage => Usd.Stage
# Returns the `Usd.Stage` the ViewportAPI is bound to, essentially: `omni.usd.get_context(self.usd_context_name).get_stage()`.
```
### projection
```python
viewport_api.projection=> Gf.Matrix4d
# Returns the Gf.Matrix4d of the projection. This may differ than the projection of the `Usd.Camera` based on how the Viewport is placed in the parent widget.
```
### transform
```python
viewport_api.transform => Gf.Matrix4d
# Return the Gf.Matrix4d of the transform for the `Usd.Camera` in world-space.
```
### view
```python
viewport_api.view => Gf.Matrix4d
# Return the Gf.Matrix4d of the inverse-transform for the `Usd.Camera` in world-space.
```
### time
```python
viewport_api.time => Usd.TimeCode
# Return the Usd.TimeCode that the Viewport is using.
```
## Space Mapping
The `ViewportAPI` natively uses NDC coordinates to interop with the payloads from `omni.ui.scene` gestures.
To understand where these coordinates are in 3D-space for the `ViewportTexture`, two properties will
can be used to get a `Gf.Matrix4d` to convert to and from NDC-space to World-space.
```python
origin = (0, 0, 0)
origin_screen = viewport_api.world_to_ndc.Transform(origin)
print('Origin is at {origin_screen}, in screen-space')
origin = viewport_api.ndc_to_world.Transform(origin_screen)
print('Converted back to world-space, origin is {origin}')
```
### world_to_ndc
```python
viewport_api.world_to_ndc => Gf.Matrix4d
# Returns a Gf.Matrix4d to move from World/Scene space into NDC space
```
### ndc_to_world
```python
viewport_api.ndc_to_world => Gf.Matrix4d
# Returns a Gf.Matrix4d to move from NDC space into World/Scene space
```
## World queries
While it is useful being able to move through these spaces is useful, for the most part what we'll be more interested
in using this to inspect the scene that is being rendered. What that means is that we'll need to move from an NDC coordinate
into pixel-space of our rendered image.
A quick breakdown of the three spaces in use:
The native NDC space that works with `omni.ui.scene` gestures can be thought of as a cartesian space centered on the rendered image.

We can easily move to a 0.0 - 1.0 uv space on the rendered image.

And finally expand that 0.0 - 1.0 uv space into pixel space.

Now that we know how to map between the ui and texture space, we can use it to convert between screen and 3D-space.
More importantly, we can use it to actually query the backing `ViewportTexture` about objects and locations in the scene.
### request_query
```python
viewport_api.request_query(pixel_coordinate: (x, y), query_completed: callable) => None
# Query a pixel co-ordinate with a callback to be executed when the query completes
# Get the mouse position from within an omni.ui.scene gesture
mouse_ndc = self.sender.gesture_payload.mouse
# Convert the ndc-mouse to pixel-space in our ViewportTexture
mouse, in_viewport = viewport_api.map_ndc_to_texture_pixel(mouse_ndc)
# We know immediately if the mapping is outside the ViewportTexture
if not in_viewport:
return
# Inside the ViewportTexture, create a callback and query the 3D world
def query_completed(path, pos, *args):
if not path:
print('No object')
else:
print(f"Object '{path}' hit at {pos}")
viewport_api.request_query(mouse, query_completed)
```
## Asynchronous waiting
Some properties and API calls of the Viewport won't take effect immediately after control-flow has returned to the caller.
For example, setting the camera-path or resolution won't immediately deliver frames from that Camera at the new resolution.
There are two methods available to asynchrnously wait for the changes to make their way through the pipeline.
### wait_for_render_settings_change
Asynchronously wait until a render-settings change has been ansorbed by the backend.
This can be useful after changing the camera, resolution, or render-product.
```python
my_custom_product = '/Render/CutomRenderProduct'
viewport_api.render_product_path = my_custom_product
settings_changed = await viewport_api.wait_for_render_settings_change()
print('settings_changed', settings_changed)
```
### wait_for_rendered_frames
Asynchronously wait until a number of frames have been delivered.
Default behavior is to wait for deivery of 1 frame, but the function accepts an optional argument for an additional number of frames to wait on.
```python
await viewport_api.wait_for_rendered_frames(10)
print('Waited for 10 frames')
```
## Capturing Viewport frames
To access the state of the Viewport's next frame and any AOVs it may be rendering, you can schedule a capture with the `schedule_capture` method.
There are a variety of default Capturing delegates in the `omni.kit.widget.viewport.capture` that can handle writing to disk or accesing the AOV's buffer.
Because capture is asynchronous, it will likely not have occured when control-flow has returned to the caller of `schedule_capture`.
To wait until it has completed, the returned object has a `wait_for_result` method that can be used.
### schedule_capture
```python
viewport_api.schedule_capture(capture_delegate: Capture): -> Capture
```
```python
from omni.kit.widget.viewport.capture import FileCapture
capture = viewport_api.schedule_capture(FileCapture(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
| 10,506 | Markdown | 37.346715 | 159 | 0.762136 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/capture.md | # Capture
`omni.kit.widget.viewport.capture` is the interface to a capture a Viewport's state and AOVs.
It provides a few convenient implementations that will write AOV(s) to disk or pass CPU buffers for pixel access.
## FileCapture
A simple delegate to capture a single AOV to a single file.
It can be used as is, or subclassed to access additional information/meta-data to be written.
By default it will capture a color AOV, but accepts an explicit AOV-name to capture instead.
```python
from omni.kit.widget.viewport.capture import FileCapture
capture = viewport_api.schedule_capture(FileCapture(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
A sample subclass implementation to write additional data.
```python
from omni.kit.widget.viewport.capture import FileCapture
SideCarWriter(FileCapture):
def __init__(self, image_path, aov_name=''):
super().__init__(image_path, aov_name)
def capture_aov(self, file_path, aov):
# Call the default file-saver
self.save_aov_to_file(file_path, aov)
# Possibly append data to a custom image
print(f'Wrote AOV "{aov['name']}" to "{file_path}")
print(f' with view: {self.view}")
print(f' with projection: {self.projection}")
capture = viewport_api.schedule_capture(SideCarWriter(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
## ByteCapture
A simple delegate to capture a single AOV and deliver it as CPU pixel data.
It can be used as is with a free-standing function, or subclassed to access additional information/meta-data.
By default it will capture a color AOV, but accepts an explicit AOV-name to capture instead.
```python
from omni.kit.widget.viewport.capture import ByteCapture
def on_capture_completed(buffer, buffer_size, width, height, format):
print(f'PixelData resolution: {width} x {height}')
print(f'PixelData format: {format}')
capture = viewport_api.schedule_capture(ByteCapture(on_capture_completed))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
print(f'It had a camera view of {capture.view}')
else:
print(f'No image was written to "{image_path}"')
```
A sample subclass implementation to write additional data.
```python
from omni.kit.widget.viewport.capture import ByteCapture
SideCarData(ByteCapture):
def __init__(self, image_path, aov_name=''):
super().__init__(image_path, aov_name)
def on_capture_completed(self, buffer, buffer_size, width, height, format):
print(f'PixelData resolution: {width} x {height}')
print(f'PixelData format: {format}')
print(f'PixelData has a camera view of {self.view}')
capture = viewport_api.schedule_capture(SideCarData(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
| 3,284 | Markdown | 34.32258 | 113 | 0.714677 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/__init__.py | from .scripts import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/create_actions.py | import omni.usd
import omni.kit.actions.core
from pxr import Usd, UsdGeom, UsdLux, OmniAudioSchema
def get_action_name(name):
return name.lower().replace('-', '_').replace(' ', '_')
def get_geometry_standard_prim_list(usd_context=None):
if not usd_context:
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
if stage:
meters_per_unit = UsdGeom.GetStageMetersPerUnit(stage)
else:
meters_per_unit = 0.01
geom_base = 0.5 / meters_per_unit
geom_base_double = geom_base * 2
geom_base_half = geom_base / 2
all_shapes = sorted([
(
"Cube",
{
UsdGeom.Tokens.size: geom_base_double,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
(
"Sphere",
{
UsdGeom.Tokens.radius: geom_base,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
(
"Cylinder",
{
UsdGeom.Tokens.radius: geom_base,
UsdGeom.Tokens.height: geom_base_double,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
(
"Capsule",
{
UsdGeom.Tokens.radius: geom_base_half,
UsdGeom.Tokens.height: geom_base,
# Create extent with command dynamically since it's different in different up-axis.
},
),
(
"Cone",
{
UsdGeom.Tokens.radius: geom_base,
UsdGeom.Tokens.height: geom_base_double,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
])
shape_attrs = {}
for name, attrs in all_shapes:
shape_attrs[name] = attrs
return shape_attrs
def get_audio_prim_list():
return [
("Spatial Sound", "OmniSound", {}),
(
"Non-Spatial Sound",
"OmniSound",
{OmniAudioSchema.Tokens.auralMode: OmniAudioSchema.Tokens.nonSpatial}
),
("Listener", "OmniListener", {})
]
def get_light_prim_list(usd_context=None):
if not usd_context:
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
if stage:
meters_per_unit = UsdGeom.GetStageMetersPerUnit(stage)
else:
meters_per_unit = 0.01
geom_base = 0.5 / meters_per_unit
geom_base_double = geom_base * 2
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
return sorted([
("Distant Light", "DistantLight", {UsdLux.Tokens.inputsAngle: 1.0, UsdLux.Tokens.inputsIntensity: 3000}),
("Sphere Light", "SphereLight", {UsdLux.Tokens.inputsRadius: geom_base, UsdLux.Tokens.inputsIntensity: 30000}),
(
"Rect Light",
"RectLight",
{
UsdLux.Tokens.inputsWidth: geom_base_double,
UsdLux.Tokens.inputsHeight: geom_base_double,
UsdLux.Tokens.inputsIntensity: 15000,
},
),
("Disk Light", "DiskLight", {UsdLux.Tokens.inputsRadius: geom_base, UsdLux.Tokens.inputsIntensity: 60000}),
(
"Cylinder Light",
"CylinderLight",
{UsdLux.Tokens.inputsLength: geom_base_double, UsdLux.Tokens.inputsRadius: 5, UsdLux.Tokens.inputsIntensity: 30000},
),
(
"Dome Light",
"DomeLight",
{UsdLux.Tokens.inputsIntensity: 1000, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong},
),
])
return sorted([
("Distant Light", "DistantLight", {UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.intensity: 3000}),
("Sphere Light", "SphereLight", {UsdLux.Tokens.radius: geom_base, UsdLux.Tokens.intensity: 30000}),
(
"Rect Light",
"RectLight",
{
UsdLux.Tokens.width: geom_base_double,
UsdLux.Tokens.height: geom_base_double,
UsdLux.Tokens.intensity: 15000,
},
),
("Disk Light", "DiskLight", {UsdLux.Tokens.radius: geom_base, UsdLux.Tokens.intensity: 60000}),
(
"Cylinder Light",
"CylinderLight",
{UsdLux.Tokens.length: geom_base_double, UsdLux.Tokens.radius: 5, UsdLux.Tokens.intensity: 30000},
),
(
"Dome Light",
"DomeLight",
{UsdLux.Tokens.intensity: 1000, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong},
),
])
def register_actions(extension_id, cls, get_self_fn):
actions_tag = "Create Menu Actions"
# actions
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim",
cls.on_create_prim,
display_name="Create->Create Prim",
description="Create Prim",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim_camera",
lambda: cls.on_create_prim("Camera", {}),
display_name="Create->Create Camera Prim",
description="Create Camera Prim",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim_scope",
lambda: cls.on_create_prim("Scope", {}),
display_name="Create->Create Scope",
description="Create Scope",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim_xform",
lambda: cls.on_create_prim("Xform", {}),
display_name="Create->Create Xform",
description="Create Xform",
tag=actions_tag
)
def on_create_shape(shape_name):
shape_attrs = get_geometry_standard_prim_list()
cls.on_create_prim(shape_name, shape_attrs[shape_name])
for prim in get_geometry_standard_prim_list().keys():
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
f"create_prim_{prim.lower()}",
lambda p=prim: on_create_shape(p),
display_name=f"Create->Create Prim {prim}",
description=f"Create Prim {prim}",
tag=actions_tag
)
for name, prim, attrs in get_light_prim_list():
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
f"create_prim_{get_action_name(name)}",
lambda p=prim, a=attrs: cls.on_create_light(p, a),
display_name=f"Create->Create Prim {name}",
description=f"Create Prim {name}",
tag=actions_tag
)
for name, prim, attrs in get_audio_prim_list():
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
f"create_prim_{get_action_name(name)}",
lambda p=prim, a=attrs: cls.on_create_prim(p, a),
display_name=f"Create->Create Prim {name}",
description=f"Create Prim {name}",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"high_quality_option_toggle",
get_self_fn()._high_quality_option_toggle,
display_name="Create->High Quality Option Toggle",
description="Create High Quality Option Toggle",
tag=actions_tag
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 8,014 | Python | 32.67647 | 132 | 0.564387 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/__init__.py | from .create import *
| 22 | Python | 10.499995 | 21 | 0.727273 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/create.py | import os
import functools
import carb.input
import omni.ext
import omni.kit.ui
import omni.kit.menu.utils
from functools import partial
from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder
from .create_actions import register_actions, deregister_actions, get_action_name, get_geometry_standard_prim_list, get_audio_prim_list, get_light_prim_list
_extension_instance = None
_extension_path = None
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class CreateMenuExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
omni.kit.menu.utils.set_default_menu_proirity("Create", -8)
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
global _extension_path
_extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", True)
self._create_menu_list = None
self._build_create_menu()
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name, CreateMenuExtension, lambda: _extension_instance)
def on_shutdown(self):
global _extension_instance
deregister_actions(self._ext_name)
_extension_instance = None
omni.kit.menu.utils.remove_menu_items(self._create_menu_list, "Create")
def _rebuild_menus(self):
omni.kit.menu.utils.remove_menu_items(self._create_menu_list, "Create")
self._build_create_menu()
def _high_quality_option_toggle(self):
enabled = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality")
self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", not enabled)
def _build_create_menu(self):
def is_create_type_enabled(type: str):
settings = carb.settings.get_settings()
if type == "Shape":
if settings.get("/app/primCreation/hideShapes") == True or \
settings.get("/app/primCreation/enableMenuShape") == False:
return False
return True
enabled = settings.get(f"/app/primCreation/enableMenu{type}")
if enabled == True or enabled == False:
return enabled
return True
# setup menus
self._create_menu_list = []
# Shapes
if is_create_type_enabled("Shape"):
sub_menu = []
for prim in get_geometry_standard_prim_list().keys():
sub_menu.append(
MenuItemDescription(name=prim, onclick_action=("omni.kit.menu.create", f"create_prim_{prim.lower()}"))
)
def on_high_quality_option_select():
enabled = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality")
self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", not enabled)
def on_high_quality_option_checked():
enabled = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality")
return enabled
sub_menu.append(MenuItemDescription())
sub_menu.append(
MenuItemDescription(
name="High Quality",
onclick_action=("omni.kit.menu.create", "high_quality_option_toggle"),
ticked_fn=lambda: on_high_quality_option_checked()
)
)
self._create_menu_list.append(
MenuItemDescription(name="Shape", glyph="menu_prim.svg", appear_after=["Mesh", MenuItemOrder.FIRST], sub_menu=sub_menu)
)
# Lights
if is_create_type_enabled("Light"):
sub_menu = []
for name, prim, attrs in get_light_prim_list():
sub_menu.append(
MenuItemDescription(name=name, onclick_action=("omni.kit.menu.create", f"create_prim_{get_action_name(name)}")
)
)
if is_create_type_enabled("Shape"):
appear_after="Shape"
else:
appear_after="Mesh"
self._create_menu_list.append(
MenuItemDescription(name="Light", glyph="menu_light.svg", appear_after=appear_after, sub_menu=sub_menu)
)
# Audio
if is_create_type_enabled("Audio"):
sub_menu = []
for name, prim, attrs in get_audio_prim_list():
sub_menu.append(
MenuItemDescription(
name=name, onclick_action=("omni.kit.menu.create", f"create_prim_{get_action_name(name)}")
)
)
self._create_menu_list.append(
MenuItemDescription(name="Audio", glyph="menu_audio.svg", appear_after="Light", sub_menu=sub_menu)
)
# Camera
if is_create_type_enabled("Camera"):
self._create_menu_list.append(
MenuItemDescription(
name="Camera",
glyph="menu_camera.svg",
appear_after="Audio",
onclick_action=("omni.kit.menu.create", "create_prim_camera"),
)
)
# Scope
if is_create_type_enabled("Scope"):
self._create_menu_list.append(
MenuItemDescription(
name="Scope",
glyph="menu_scope.svg",
appear_after="Camera",
onclick_action=("omni.kit.menu.create", "create_prim_scope"),
)
)
# Xform
if is_create_type_enabled("Xform"):
self._create_menu_list.append(
MenuItemDescription(
name="Xform",
glyph="menu_xform.svg",
appear_after="Scope",
onclick_action=("omni.kit.menu.create", "create_prim_xform"),
)
)
if self._create_menu_list:
omni.kit.menu.utils.add_menu_items(self._create_menu_list, "Create", -8)
def on_create_prim(prim_type, attributes, use_settings: bool = False):
usd_context = omni.usd.get_context()
with omni.kit.usd.layers.active_authoring_layer_context(usd_context):
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type=prim_type, attributes=attributes)
def on_create_light(light_type, attributes):
usd_context = omni.usd.get_context()
with omni.kit.usd.layers.active_authoring_layer_context(usd_context):
omni.kit.commands.execute("CreatePrim", prim_type=light_type, attributes=attributes)
def on_create_prims():
usd_context = omni.usd.get_context()
with omni.kit.usd.layers.active_authoring_layer_context(usd_context):
omni.kit.commands.execute("CreatePrims", prim_types=["Cone", "Cylinder", "Cone"])
def get_extension_path(sub_directory):
global _extension_path
path = _extension_path
if sub_directory:
path = os.path.normpath(os.path.join(path, sub_directory))
return path
def rebuild_menus():
if _extension_instance:
_extension_instance._rebuild_menus()
| 7,415 | Python | 37.827225 | 156 | 0.582333 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/test_func_create_prims.py | import asyncio
import os
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, get_prims, select_prims, wait_for_window
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from pxr import Sdf, UsdShade
PERSISTENT_SETTINGS_PREFIX = "/persistent"
async def create_test_func_create_camera(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Camera")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Camera'])
# Test creation with typed-defaults
settings = carb.settings.get_settings()
try:
focal_len_key = '/persistent/app/primCreation/typedDefaults/camera/focalLength'
settings.set(focal_len_key, 48)
await ui_test.menu_click("Create/Camera")
cam_prim = omni.usd.get_context().get_stage().GetPrimAtPath('/Camera_01')
tester.assertIsNotNone(cam_prim)
tester.assertEqual(cam_prim.GetAttribute('focalLength').Get(), 48)
finally:
# Delete the change now for any other tests
settings.destroy_item(focal_len_key)
async def create_test_func_create_scope(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Scope")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Scope'])
async def create_test_func_create_xform(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Xform")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Xform'])
async def create_test_func_create_shape_capsule(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Capsule")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Capsule'])
async def create_test_func_create_shape_cone(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Cone")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cone'])
async def create_test_func_create_shape_cube(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Cube")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cube'])
async def create_test_func_create_shape_cylinder(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Cylinder")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cylinder'])
async def create_test_func_create_shape_sphere(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Sphere")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Sphere'])
async def create_test_func_create_shape_high_quality(tester, menu_item: MenuItemDescription):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", False)
# use menu
await ui_test.menu_click("Create/Shape/High Quality")
# verify
tester.assertTrue(carb.settings.get_settings().get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality"))
async def create_test_func_create_light_cylinder_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Cylinder Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/CylinderLight'])
async def create_test_func_create_light_disk_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Disk Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/DiskLight'])
async def create_test_func_create_light_distant_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Distant Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/DistantLight'])
async def create_test_func_create_light_dome_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Dome Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/DomeLight'])
async def create_test_func_create_light_rect_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Rect Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/RectLight'])
async def create_test_func_create_light_sphere_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Sphere Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/SphereLight'])
async def create_test_func_create_audio_spatial_sound(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Audio/Spatial Sound")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/OmniSound'])
async def create_test_func_create_audio_non_spatial_sound(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Audio/Non-Spatial Sound")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/OmniSound'])
async def create_test_func_create_audio_listener(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Audio/Listener")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/OmniListener'])
async def create_test_func_create_mesh_cone(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Cone")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cone'])
async def create_test_func_create_mesh_cube(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Cube")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cube'])
async def create_test_func_create_mesh_cylinder(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Cylinder")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cylinder'])
async def create_test_func_create_mesh_disk(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Disk")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Disk'])
async def create_test_func_create_mesh_plane(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Plane")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Plane'])
async def create_test_func_create_mesh_sphere(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Sphere")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Sphere'])
async def create_test_func_create_mesh_torus(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Torus")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Torus'])
async def create_test_func_create_mesh_settings(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Settings")
await wait_for_window("Mesh Generation Settings")
ui_test.find("Mesh Generation Settings").widget.visible = False
async def create_test_func_create_material(tester, material_name: str):
mdl_name = material_name.split('/')[-1].replace(" ", "_")
stage = omni.usd.get_context().get_stage()
if mdl_name == "Add_MDL_File":
# click on menu item
await ui_test.menu_click(material_name)
await ui_test.human_delay()
# use add material dialog
async with MaterialLibraryTestHelper() as material_test_helper:
await material_test_helper.handle_add_material_dialog(get_test_data_path(__name__, "mdl/TESTEXPORT.mdl"), "TESTEXPORT.mdl")
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify
shader = UsdShade.Shader(stage.GetPrimAtPath("/Looks/Material/Shader"))
identifier = shader.GetSourceAssetSubIdentifier("mdl")
tester.assertTrue(identifier == "Material")
return
if mdl_name == "USD_Preview_Surface":
await ui_test.menu_click(material_name)
tester.assertTrue(tester.get_stage_prims() == ['/Looks', '/Looks/PreviewSurface', '/Looks/PreviewSurface/Shader'])
elif mdl_name == "USD_Preview_Surface_Texture":
await ui_test.menu_click(material_name)
tester.assertTrue(tester.get_stage_prims() == ['/Looks', '/Looks/PreviewSurfaceTexture', '/Looks/PreviewSurfaceTexture/PreviewSurfaceTexture', '/Looks/PreviewSurfaceTexture/st', '/Looks/PreviewSurfaceTexture/diffuseColorTex', '/Looks/PreviewSurfaceTexture/metallicTex', '/Looks/PreviewSurfaceTexture/roughnessTex', '/Looks/PreviewSurfaceTexture/normalTex'])
else:
# create sphere, select & create material
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/Sphere"])
await ui_test.menu_click(material_name)
# verify material is created
tester.assertTrue(tester.get_stage_prims() == ["/Sphere", "/Looks", f"/Looks/{mdl_name}", f"/Looks/{mdl_name}/Shader"])
prim = stage.GetPrimAtPath(f"/Looks/{mdl_name}/Shader")
asset_path = prim.GetAttribute("info:mdl:sourceAsset").Get()
tester.assertFalse(os.path.isabs(asset_path.path))
tester.assertTrue(os.path.isabs(asset_path.resolvedPath))
# verify /Sphere is bound to material
prim = stage.GetPrimAtPath("/Sphere")
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
tester.assertEqual(bound_material.GetPath().pathString, f"/Looks/{mdl_name}")
| 9,882 | Python | 34.046099 | 365 | 0.699757 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/__init__.py | from .create_tests import *
from .test_enable_menu import *
| 60 | Python | 19.333327 | 31 | 0.75 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/create_tests.py | import sys
import re
import asyncio
import unittest
import carb
import omni.kit.test
from .test_func_create_prims import *
class TestMenuCreate(omni.kit.test.AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
async def test_create_menus(self):
import omni.kit.material.library
# wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
await omni.kit.material.library.get_mdl_list_async()
await ui_test.human_delay()
material_list = []
menus = omni.kit.menu.utils.get_merged_menus()
prefix = "create_test"
to_test = []
this_module = sys.modules[__name__]
for key in menus.keys():
# create menu only
if key.startswith("Create"):
for item in menus[key]['items']:
if item.name != "" and item.has_action():
key_name = re.sub('\W|^(?=\d)','_', key.lower())
func_name = re.sub('\W|^(?=\d)','_', item.name.replace("${kit}/", "").lower())
while key_name and key_name[-1] == "_":
key_name = key_name[:-1]
while func_name and func_name[-1] == "_":
func_name = func_name[:-1]
test_fn = f"{prefix}_func_{key_name}_{func_name}"
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item))
except AttributeError:
if test_fn.startswith("create_test_func_create_material_"):
material_list.append(f"{key.replace('_', '/')}/{item.name}")
else:
carb.log_error(f"test function \"{test_fn}\" not found")
if item.original_menu_item and item.original_menu_item.hotkey:
test_fn = f"{prefix}_hotkey_func_{key_name}_{func_name}"
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item.original_menu_item))
except AttributeError:
carb.log_error(f"test function \"{test_fn}\" not found")
for to_call, test_fn, menu_item in to_test:
await omni.usd.get_context().new_stage_async()
omni.kit.menu.utils.refresh_menu_items("Create")
await ui_test.human_delay()
print(f"Running test {test_fn}")
try:
await to_call(self, menu_item)
except Exception as exc:
carb.log_error(f"error {test_fn} failed - {exc}")
import traceback
traceback.print_exc(file=sys.stdout)
for material_name in material_list:
await omni.usd.get_context().new_stage_async()
omni.kit.menu.utils.refresh_menu_items("Create")
await ui_test.human_delay()
print(f"Running test create_test_func_create_material {material_name}")
try:
await create_test_func_create_material(self, material_name)
except Exception as exc:
carb.log_error(f"error create_test_func_create_material failed - {exc}")
import traceback
traceback.print_exc(file=sys.stdout)
def get_stage_prims(self):
stage = omni.usd.get_context().get_stage()
return [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
| 3,757 | Python | 42.697674 | 111 | 0.51424 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/test_enable_menu.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 omni.kit.app
import omni.kit.test
import omni.usd
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows
class TestEnableCreateMenu(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await omni.usd.get_context().new_stage_async()
await wait_stage_loading()
# Test(s)
async def test_enable_create_menu(self):
settings = carb.settings.get_settings()
def reset_prim_creation():
settings.set("/app/primCreation/hideShapes", False)
settings.set("/app/primCreation/enableMenuShape", True)
settings.set("/app/primCreation/enableMenuLight", True)
settings.set("/app/primCreation/enableMenuAudio", True)
settings.set("/app/primCreation/enableMenuCamera", True)
settings.set("/app/primCreation/enableMenuScope", True)
settings.set("/app/primCreation/enableMenuXform", True)
def verify_menu(mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool):
menu_widget = ui_test.get_menubar()
menu_widgets = []
for w in menu_widget.find_all("**/"):
if isinstance(w.widget, (ui.Menu, ui.MenuItem)) and w.widget.text.strip() != "placeholder":
menu_widgets.append(w.widget.text)
self.assertEqual("Mesh" in menu_widgets, mesh)
self.assertEqual("Shape" in menu_widgets, shape)
self.assertEqual("Light" in menu_widgets, light)
self.assertEqual("Audio" in menu_widgets, audio)
self.assertEqual("Camera" in menu_widgets, camera)
self.assertEqual("Scope" in menu_widgets, scope)
self.assertEqual("Xform" in menu_widgets, xform)
async def test_menu(mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool):
omni.kit.menu.create.rebuild_menus()
verify_menu(mesh, shape, light, audio, camera, scope, xform)
try:
# verify default
reset_prim_creation()
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=True)
# verify hide shapes
reset_prim_creation()
settings.set("/app/primCreation/hideShapes", True)
await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True)
reset_prim_creation()
settings.set("/app/primCreation/enableMenuShape", False)
await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True)
# verify hide light
reset_prim_creation()
settings.set("/app/primCreation/enableMenuLight", False)
await test_menu(mesh=True, shape=True, light=False, audio=True, camera=True, scope=True, xform=True)
# verify hide audio
reset_prim_creation()
settings.set("/app/primCreation/enableMenuAudio", False)
await test_menu(mesh=True, shape=True, light=True, audio=False, camera=True, scope=True, xform=True)
# verify hide camera
reset_prim_creation()
settings.set("/app/primCreation/enableMenuCamera", False)
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=False, scope=True, xform=True)
# verify hide scope
reset_prim_creation()
settings.set("/app/primCreation/enableMenuScope", False)
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=False, xform=True)
# verify hide xform
reset_prim_creation()
settings.set("/app/primCreation/enableMenuXform", False)
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=False)
finally:
reset_prim_creation()
| 4,545 | Python | 45.865979 | 112 | 0.649725 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/PACKAGE-LICENSES/omni.kit.window.file_exporter-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/scripts/demo_file_exporter.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import asyncio
import omni.ui as ui
from typing import List
from omni.kit.window.file_exporter import get_file_exporter, ExportOptionsDelegate
# BEGIN-DOC-export_options
class MyExportOptionsDelegate(ExportOptionsDelegate):
def __init__(self):
super().__init__(build_fn=self._build_ui_impl, destroy_fn=self._destroy_impl)
self._widget = None
def _build_ui_impl(self):
self._widget = ui.Frame()
with self._widget:
with ui.VStack(style={"background_color": 0xFF23211F}):
ui.Label("Checkpoint Description", alignment=ui.Alignment.CENTER)
ui.Separator(height=5)
model = ui.StringField(multiline=True, height=80).model
model.set_value("This is my new checkpoint.")
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
# END-DOC-export_options
# BEGIN-DOC-tagging_options
class MyTaggingOptionsDelegate(ExportOptionsDelegate):
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
filename_changed_fn=self._filename_changed_impl,
selection_changed_fn=self._selection_changed_impl,
destroy_fn=self._destroy_impl
)
self._widget = None
def _build_ui_impl(self, file_type: str=''):
self._widget = ui.Frame()
with self._widget:
with ui.VStack():
ui.Button(f"Tags for {file_type or 'unknown'} type", height=24)
def _filename_changed_impl(self, filename: str):
if filename:
_, ext = os.path.splitext(filename)
self._build_ui_impl(file_type=ext)
def _selection_changed_impl(self, selections: List[str]):
if len(selections) == 1:
_, ext = os.path.splitext(selections[0])
self._build_ui_impl(file_type=ext)
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
# END-DOC-tagging_options
class DemoFileExporterDialog:
"""
Example that demonstrates how to invoke the file exporter dialog.
"""
def __init__(self):
self._app_window: ui.Window = None
self._export_options = ExportOptionsDelegate = None
self._tag_options = ExportOptionsDelegate = None
self.build_ui()
def build_ui(self):
""" """
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
self._app_window = ui.Window("File Exporter", width=1000, height=500, flags=window_flags)
with self._app_window.frame:
with ui.VStack(spacing=10):
with ui.HStack(height=30):
ui.Spacer()
button = ui.RadioButton(text="Export File", width=120)
button.set_clicked_fn(self._show_dialog)
ui.Spacer()
asyncio.ensure_future(self._dock_window("File Exporter", ui.DockPosition.TOP))
def _show_dialog(self):
# BEGIN-DOC-get_instance
# Get the singleton extension object, but as weakref to guard against the extension being removed.
file_exporter = get_file_exporter()
if not file_exporter:
return
# END-DOC-get_instance
# BEGIN-DOC-show_window
file_exporter.show_window(
title="Export As ...",
export_button_label="Save",
export_handler=self.export_handler,
filename_url="omniverse://ov-rc/NVIDIA/Samples/Marbles/foo",
show_only_folders=True,
enable_filename_input=False,
)
# END-DOC-show_window
# BEGIN-DOC-add_tagging_options
self._tagging_options = MyTaggingOptionsDelegate()
file_exporter.add_export_options_frame("Tagging Options", self._tagging_options)
# END-DOC-add_tagging_options
# BEGIN-DOC-add_export_options
self._export_options = MyExportOptionsDelegate()
file_exporter.add_export_options_frame("Export Options", self._export_options)
# END-DOC-add_export_options
def _hide_dialog(self):
# Get the Content extension object. Same as: omni.kit.window.file_exporter.get_extension()
# Keep as weakref to guard against the extension being removed at any time. If it is removed,
# then invoke appropriate handler; in this case the destroy method.
file_exporter = get_file_exporter()
if file_exporter:
file_exporter.hide()
# BEGIN-DOC-export_handler
def export_handler(self, filename: str, dirname: str, extension: str = "", selections: List[str] = []):
# NOTE: Get user inputs from self._export_options, if needed.
print(f"> Export As '{filename}{extension}' to '{dirname}' with additional selections '{selections}'")
# END-DOC-export_handler
async def _dock_window(self, window_title: str, position: ui.DockPosition, ratio: float = 1.0):
frames = 3
while frames > 0:
if ui.Workspace.get_window(window_title):
break
frames = frames - 1
await omni.kit.app.get_app().next_update_async()
window = ui.Workspace.get_window(window_title)
dockspace = ui.Workspace.get_window("DockSpace")
if window and dockspace:
window.dock_in(dockspace, position, ratio=ratio)
window.dock_tab_bar_visible = False
def destroy(self):
if self._app_window:
self._app_window.destroy()
self._app_window = None
if __name__ == "__main__":
view = DemoFileExporterDialog()
| 6,054 | Python | 36.376543 | 110 | 0.623059 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/config/extension.toml | [package]
title = "File Exporter"
version = "1.0.10"
category = "core"
feature = true
description = "A dialog for exporting files"
authors = ["NVIDIA"]
slackids = ["UQY4RMR3N"]
repository = ""
keywords = ["kit", "ui"]
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.usd" = {}
"omni.kit.window.filepicker" = {}
[[python.module]]
name = "omni.kit.window.file_exporter"
[settings]
exts."omni.kit.window.file_exporter".appSettings = "/persistent/app/file_exporter"
[[python.scriptFolder]]
path = "scripts"
[[test]]
dependencies = [
"omni.kit.renderer.core"
]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 747 | TOML | 17.7 | 82 | 0.672021 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import asyncio
import omni.ext
import omni.kit.app
import carb.settings
import carb.windowing
from typing import List, Tuple, Callable, Dict
from functools import partial
from carb import log_warn, events
from omni.kit.window.filepicker import FilePickerDialog, UI_READY_EVENT
from omni.kit.widget.filebrowser import FileBrowserItem
from . import ExportOptionsDelegate
g_singleton = None
WINDOW_NAME = "File Exporter"
# BEGIN-DOC-file_postfix_options
DEFAULT_FILE_POSTFIX_OPTIONS = [
None,
"anim",
"cache",
"curveanim",
"geo",
"material",
"project",
"seq",
"skel",
"skelanim",
]
# END-DOC-file_postfix_options
# BEGIN-DOC-file_extension_types
DEFAULT_FILE_EXTENSION_TYPES = [
("*.usd", "Can be Binary or Ascii"),
("*.usda", "Human-readable text format"),
("*.usdc", "Binary format"),
]
# END-DOC-file_extension_types
def on_filter_item(dialog: FilePickerDialog, show_only_folders: True, item: FileBrowserItem) -> bool:
if item and not item.is_folder:
if show_only_folders:
return False
else:
return file_filter_handler(item.path or '', dialog.get_file_postfix(), dialog.get_file_extension())
return True
def on_export(
export_fn: Callable[[str, str, str, List[str]], None],
dialog: FilePickerDialog,
filename: str,
dirname: str,
should_validate: bool = False,
):
# OM-64312: should only perform validation when specified, default to not validate
if should_validate:
# OM-58150: should not allow saving with a empty filename
if not _filename_validation_handler(filename):
return
file_postfix = dialog.get_file_postfix()
file_extension = dialog.get_file_extension()
_save_default_settings({'directory': dirname})
selections = dialog.get_current_selections() or []
dialog.hide()
def normalize_filename_parts(filename, file_postfix, file_extension) -> Tuple[str, str]:
splits = filename.split('.')
keep = len(splits) - 1
# leaving the dynamic writable usd file exts strip logic here, in case writable exts are loaded at runtime
try:
import omni.usd
if keep > 0 and splits[keep] in omni.usd.writable_usd_file_exts():
keep -= 1
except Exception:
pass
# OM-84454: strip out file extensions from filename if the current filename ends with any of the file extensions
# available in the current instance of dialog
available_options = [item.lstrip("*.") for item, _ in dialog.get_file_extension_options()]
if keep > 0 and splits[keep] in available_options:
keep -= 1
# strip out postfix from filename
if keep > 0 and splits[keep] in dialog.get_file_postfix_options():
keep -= 1
basename = '.'.join(splits[:keep+1]) if keep >= 0 else ""
extension = ""
if file_postfix:
extension += f".{file_postfix}"
if file_extension:
extension += f"{file_extension.strip('*')}"
return basename, extension
if export_fn:
basename, extension = normalize_filename_parts(filename, file_postfix, file_extension)
export_fn(basename, dirname, extension=extension, selections=selections)
def file_filter_handler(filename: str, filter_postfix: str, filter_ext: str) -> bool:
if not filename:
return True
if not filter_ext:
return True
filter_ext = filter_ext.replace('*', '')
# Show only files whose names end with: *<postfix>.<ext>
if not filter_ext:
filename = os.path.splitext(filename)[0]
elif filename.endswith(filter_ext):
filename = filename[:-len(filter_ext)].strip('.')
else:
return False
if not filter_postfix or filename.endswith(filter_postfix):
return True
return False
def _save_default_settings(default_settings: Dict):
settings = carb.settings.get_settings()
default_settings_path = settings.get_as_string("/exts/omni.kit.window.file_exporter/appSettings")
settings.set_string(f"{default_settings_path}/directory", default_settings['directory'] or "")
def _filename_validation_handler(filename):
"""Validates the filename being exported. Currently only checking if it's empty."""
if not filename:
msg = "Filename is empty! Please specify the filename first."
try:
import omni.kit.notification_manager as nm
nm.post_notification(msg, status=nm.NotificationStatus.WARNING)
except ModuleNotFoundError:
import carb
carb.log_warn(msg)
return False
return True
# 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 FileExporterExtension(omni.ext.IExt):
"""A Standardized file export dialog."""
def __init__(self):
super().__init__()
self._dialog = None
self._title = None
self._ui_ready = False
self._ui_ready_event_sub = None
def on_startup(self, ext_id):
# Save away this instance as singleton for the editor window
global g_singleton
g_singleton = self
# Listen for filepicker events
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._ui_ready_event_sub = event_stream.create_subscription_to_pop_by_type(UI_READY_EVENT, self._on_ui_ready)
self._destroy_dialog_task = None
def show_window(
self,
title: str = None,
width: int = 1080,
height: int = 450,
show_only_collections: List[str] = None,
show_only_folders: bool = False,
file_postfix_options: List[str] = None,
file_extension_types: List[Tuple[str, str]] = None,
export_button_label: str = "Export",
export_handler: Callable[[str, str, str, List[str]], None] = None,
filename_url: str = None,
file_postfix: str = None,
file_extension: str = None,
should_validate: bool = False,
enable_filename_input: bool = True,
focus_filename_input: bool = True, # OM-91056: file exporter should focus filename input field
):
"""
Displays the export dialog with the specified settings.
Keyword Args:
title (str): The name of the dialog
width (int): Width of the window (Default=1250)
height (int): Height of the window (Default=450)
show_only_collections (List[str]): Which of these collections, ["bookmarks", "omniverse", "my-computer"] to display.
show_only_folders (bool): Show only folders in the list view.
file_postfix_options (List[str]): A list of filename postfix options. Nvidia defaults.
file_extension_types (List[Tuple[str, str]]): A list of filename extension options. Each list
element is a (extension name, description) pair, e.g. (".usdc", "Binary format"). Nvidia defaults.
export_button_label (str): Label for the export button (Default="Export")
export_handler (Callable): The callback to handle the export. Function signature is
export_handler(filename: str, dirname: str, extension: str, selections: List[str]) -> None
filename_url (str): Url of the target file, excluding filename extension.
file_postfix (str): Sets selected postfix to this value if specified.
file_extension (str): Sets selected extension to this value if specified.
should_validate (bool): Whether filename validation should be performed.
enable_filename_input (bool): Whether filename field input is enabled, default to True.
"""
if self._dialog:
self.destroy_dialog()
# Load saved settings as defaults
default_settings = self._load_default_settings()
basename = ""
directory = default_settings.get('directory')
if filename_url:
dirname, filename = os.path.split(filename_url)
basename = os.path.basename(filename)
# override directory name only if explicitly given from filename_url
if dirname:
directory = dirname
file_postfix_options = file_postfix_options or DEFAULT_FILE_POSTFIX_OPTIONS
file_extension_types = file_extension_types or DEFAULT_FILE_EXTENSION_TYPES
self._title = title or WINDOW_NAME
self._dialog = FilePickerDialog(
self._title,
width=width,
height=height,
splitter_offset=260,
enable_file_bar=True,
enable_filename_input=enable_filename_input,
enable_checkpoints=False,
show_detail_view=True,
show_only_collections=show_only_collections or [],
file_postfix_options=file_postfix_options,
file_extension_options=file_extension_types,
filename_changed_handler=partial(self._on_filename_changed, show_only_folders=show_only_folders),
apply_button_label=export_button_label,
current_directory=directory,
current_filename=basename,
current_file_postfix=file_postfix,
current_file_extension=file_extension,
focus_filename_input=focus_filename_input,
)
self._dialog.set_item_filter_fn(partial(on_filter_item, self._dialog, show_only_folders))
self._dialog.set_click_apply_handler(
partial(on_export, export_handler, self._dialog, should_validate=should_validate)
)
self._dialog.set_visibility_changed_listener(self._visibility_changed_fn)
# don't disable apply button if we are showing folders only
self._dialog._widget.file_bar.enable_apply_button(enable=show_only_folders)
self._dialog.show()
def _visibility_changed_fn(self, visible: bool):
async def destroy_dialog_async():
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
try:
await omni.kit.app.get_app().next_update_async()
if self._dialog:
self._dialog.destroy()
self._dialog = None
finally:
self._destroy_dialog_task = None
if not visible:
# Destroy the window, since we are creating new window in show_window
if not self._destroy_dialog_task or self._destroy_dialog_task.done():
self._destroy_dialog_task = asyncio.ensure_future(
destroy_dialog_async()
)
def _load_default_settings(self) -> Dict:
settings = carb.settings.get_settings()
default_settings_path = settings.get_as_string("/exts/omni.kit.window.file_exporter/appSettings")
default_settings = {}
default_settings['directory'] = settings.get_as_string(f"{default_settings_path}/directory")
return default_settings
def _on_filename_changed(self, filename, show_only_folders=False):
# OM-78341: Disable apply button if no file is selected, if we are not showing only folders
if self._dialog and self._dialog._widget and not show_only_folders:
self._dialog._widget.file_bar.enable_apply_button(enable=bool(filename))
def _on_ui_ready(self, event: events.IEvent):
try:
payload = event.payload.get_dict()
title = payload.get('title', None)
except Exception:
return
if event.type == UI_READY_EVENT and title == self._title:
self._ui_ready = True
@property
def is_ui_ready(self) -> bool:
return self._ui_ready
@property
def is_window_visible(self) -> bool:
if self._dialog and self._dialog._window:
return self._dialog._window.visible
return False
def hide_window(self):
"""Hides and destroys the dialog window."""
self.destroy_dialog()
def add_export_options_frame(self, name: str, delegate: ExportOptionsDelegate):
"""
Adds a set of export options to the dialog. Should be called after show_window.
Args:
name (str): Title of the options box.
delegate (ExportOptionsDelegate): Subclasses specified delegate and overrides the
_build_ui_impl method to provide a custom widget for getting user input.
"""
if self._dialog:
self._dialog.add_detail_frame_from_controller(name, delegate)
def click_apply(self, filename_url: str = None, postfix: str = None, extension: str = None):
"""Helper function to progammatically execute the apply callback. Useful in unittests"""
if self._dialog:
if filename_url:
dirname, filename = os.path.split(filename_url)
self._dialog.set_current_directory(dirname)
self._dialog.set_filename(filename)
if postfix:
self._dialog.set_file_postfix(postfix)
if extension:
self._dialog.self_file_extension(extension)
self._dialog._widget._file_bar._on_apply()
def click_cancel(self, cancel_handler: Callable[[str, str], None] = None):
"""Helper function to progammatically execute the cancel callback. Useful in unittests"""
if cancel_handler:
self._dialog._widget._file_bar._click_cancel_handler = cancel_handler
self._dialog._widget._file_bar._on_cancel()
async def select_items_async(self, url: str, filenames: List[str] = []) -> List[FileBrowserItem]:
"""Helper function to programatically select multiple items in filepicker. Useful in unittests."""
if self._dialog:
return await self._dialog._widget.api.select_items_async(url, filenames=filenames)
return []
def detach_from_main_window(self):
"""Detach the current file importer dialog from main window."""
if self._dialog:
self._dialog._window.move_to_new_os_window()
def destroy_dialog(self):
# handles the case for detached window
if self._dialog and self._dialog._window:
carb.windowing.acquire_windowing_interface().hide_window(self._dialog._window.app_window.get_window())
if self._dialog:
self._dialog.destroy()
self._dialog = None
self._ui_ready = False
if self._destroy_dialog_task:
self._destroy_dialog_task.cancel()
self._destroy_dialog_task = None
def on_shutdown(self):
self.destroy_dialog()
self._ui_ready_event_sub = None
global g_singleton
g_singleton = None
def get_instance():
return g_singleton
| 15,396 | Python | 39.518421 | 128 | 0.637178 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""A standardized dialog for exporting files"""
__all__ = ['FileExporterExtension', 'get_file_exporter']
from carb import log_warn
from omni.kit.window.filepicker import DetailFrameController as ExportOptionsDelegate
from .extension import FileExporterExtension, get_instance
def get_file_exporter() -> FileExporterExtension:
"""Returns the singleton file_exporter extension instance"""
instance = get_instance()
if instance is None:
log_warn("File exporter extension is no longer alive.")
return instance
| 966 | Python | 41.043476 | 85 | 0.779503 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/test_helper.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import asyncio
import omni.kit.app
import omni.kit.ui_test as ui_test
from .extension import get_instance
from typing import List, Callable
from omni.kit.widget.filebrowser import FileBrowserItem, LISTVIEW_PANE, TREEVIEW_PANE
class FileExporterTestHelper:
"""Test helper for the file export dialog"""
# NOTE Since the file dialog is a singleton, use an async lock to ensure mutex access in unit tests.
# During run-time, this is not a issue because the dialog is effectively modal.
__async_lock = asyncio.Lock()
async def __aenter__(self):
await self.__async_lock.acquire()
return self
async def __aexit__(self, *args):
self.__async_lock.release()
async def wait_for_popup(self, timeout_frames: int = 20):
"""Waits for dialog to be ready"""
file_exporter = get_instance()
if file_exporter:
for _ in range(timeout_frames):
if file_exporter.is_ui_ready:
for _ in range(4):
# Wait a few extra frames to settle before returning
await omni.kit.app.get_app().next_update_async()
return
await omni.kit.app.get_app().next_update_async()
raise Exception("Error: The file export window did not open.")
async def click_apply_async(self, filename_url: str = None):
"""Helper function to progammatically execute the apply callback. Useful in unittests"""
file_exporter = get_instance()
if file_exporter:
file_exporter.click_apply(filename_url=filename_url)
await omni.kit.app.get_app().next_update_async()
async def click_cancel_async(self, cancel_handler: Callable[[str, str], None] = None):
"""Helper function to progammatically execute the cancel callback. Useful in unittests"""
file_exporter = get_instance()
if file_exporter:
file_exporter.click_cancel(cancel_handler=cancel_handler)
await omni.kit.app.get_app().next_update_async()
async def select_items_async(self, dir_url: str, names: List[str]) -> List[FileBrowserItem]:
file_exporter = get_instance()
selections = []
if file_exporter:
selections = await file_exporter.select_items_async(dir_url, names)
return selections
async def get_item_async(self, treeview_identifier: str, name: str, pane: int = LISTVIEW_PANE):
# Return item from the specified pane, handles both tree and grid views
file_exporter = get_instance()
if not file_exporter:
return
if name:
pane_widget = None
if pane == TREEVIEW_PANE:
pane_widget = ui_test.find_all(f"{file_exporter._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}_folder_view'")
elif file_exporter._dialog._widget._view.filebrowser.show_grid_view:
# LISTVIEW selected + showing grid view
pane_widget = ui_test.find_all(f"{file_exporter._title}//Frame/**/VGrid[*].identifier=='{treeview_identifier}_grid_view'")
else:
# LISTVIEW selected + showing tree view
pane_widget = ui_test.find_all(f"{file_exporter._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}'")
if pane_widget:
widget = pane_widget[0].find(f"**/Label[*].text=='{name}'")
if widget:
widget.widget.scroll_here(0.5, 0.5)
await ui_test.human_delay(4)
return widget
return None
| 4,054 | Python | 44.561797 | 143 | 0.633202 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/tests/__init__.py | ## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .test_extension import * | 470 | Python | 51.333328 | 77 | 0.793617 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/tests/test_extension.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.test
import omni.kit.ui_test as ui_test
import asyncio
import omni.appwindow
from unittest.mock import Mock, patch, ANY
from carb.settings import ISettings
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.test_suite.helpers import get_test_data_path
from .. import get_file_exporter
from ..test_helper import FileExporterTestHelper
from ..extension import on_export, file_filter_handler, DEFAULT_FILE_POSTFIX_OPTIONS
class TestFileExporter(omni.kit.test.AsyncTestCase):
"""
Testing omni.kit.window.file_exporter extension. NOTE that since the dialog is a singleton, we use an async
lock to ensure that only one test runs at a time. In practice, this is not a issue because only one extension
is accessing the dialog at any given time.
"""
__lock = asyncio.Lock()
async def setUp(self):
self._settings_path = "my_settings"
self._test_settings = {
"/exts/omni.kit.window.file_exporter/appSettings": self._settings_path,
f"{self._settings_path}/directory": "C:/temp/folder",
f"{self._settings_path}/filename": "my-file",
}
async def tearDown(self):
pass
def _mock_settings_get_string_impl(self, name: str) -> str:
return self._test_settings.get(name)
def _mock_settings_set_string_impl(self, name: str, value: str):
self._test_settings[name] = value
async def test_show_window_destroys_previous(self):
"""Testing show_window destroys previously allocated dialog"""
async with self.__lock:
under_test = get_file_exporter()
with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog,\
patch("carb.windowing.IWindowing.hide_window"):
under_test.show_window(title="first")
under_test.show_window(title="second")
mock_destroy_dialog.assert_called()
dialog = mock_destroy_dialog.call_args[0][0]
self.assertEqual(str(dialog._window), "first")
async def test_hide_window_destroys_it(self):
"""Testing that hiding the window destroys it"""
async with self.__lock:
under_test = get_file_exporter()
with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog:
under_test.show_window(title="test")
under_test._dialog.hide()
# Dialog is destroyed after a couple frames
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
mock_destroy_dialog.assert_called()
dialog = mock_destroy_dialog.call_args[0][0]
self.assertEqual(str(dialog._window), "test")
async def test_hide_window_destroys_detached_window(self):
"""Testing that hiding the window destroys detached window."""
async with self.__lock:
under_test = get_file_exporter()
with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog:
under_test.show_window(title="test_detached")
await omni.kit.app.get_app().next_update_async()
under_test.detach_from_main_window()
main_window = omni.appwindow.get_default_app_window().get_window()
self.assertFalse(main_window is under_test._dialog._window.app_window.get_window())
under_test.hide_window()
# Dialog is destroyed after a couple frames
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
mock_destroy_dialog.assert_called()
dialog = mock_destroy_dialog.call_args[0][0]
self.assertEqual(str(dialog._window), "test_detached")
async def test_load_default_settings(self):
"""Testing that dialog applies saved settings"""
async with self.__lock:
under_test = get_file_exporter()
with patch('omni.kit.window.file_exporter.extension.FilePickerDialog') as mock_dialog,\
patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl):
under_test.show_window(title="test_dialog")
# Retrieve keyword args for the constructor (first call), and confirm called with expected values
constructor_kwargs = mock_dialog.call_args_list[0][1]
self.assertEqual(constructor_kwargs['current_directory'], self._test_settings[f"{self._settings_path}/directory"])
self.assertEqual(constructor_kwargs['current_filename'], "")
async def test_override_default_settings(self):
"""Testing that user values override default settings"""
async with self.__lock:
test_url = "Omniverse://ov-test/my-folder/my-file.usd"
under_test = get_file_exporter()
with patch('omni.kit.window.file_exporter.extension.FilePickerDialog') as mock_dialog,\
patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl),\
patch("carb.windowing.IWindowing.hide_window"):
under_test.show_window(title="test_dialog", filename_url=test_url)
# Retrieve keyword args for the constructor (first call), and confirm called with expected values
constructor_kwargs = mock_dialog.call_args_list[0][1]
dirname, filename = os.path.split(test_url)
self.assertEqual(constructor_kwargs['current_directory'], dirname)
self.assertEqual(constructor_kwargs['current_filename'], filename)
async def test_save_settings_on_export(self):
"""Testing that settings are saved on export"""
my_settings = {
'filename': "my-file",
'directory': "Omniverse://ov-test/my-folder",
}
mock_dialog = Mock()
with patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl),\
patch.object(ISettings, "set_string", side_effect=self._mock_settings_set_string_impl):
on_export(None, mock_dialog, my_settings['filename'], my_settings['directory'])
# Retrieve keyword args for the constructor (first call), and confirm called with expected values
self.assertEqual(my_settings['filename'], self._test_settings[f"{self._settings_path}/filename"])
self.assertEqual(my_settings['directory'], self._test_settings[f"{self._settings_path}/directory"])
async def test_show_only_folders(self):
"""Testing show only folders option."""
mock_handler = Mock()
async with self.__lock:
under_test = get_file_exporter()
test_path = get_test_data_path(__name__).replace("\\", '/')
async with FileExporterTestHelper() as helper:
with patch("carb.windowing.IWindowing.hide_window"):
# under normal circumstance, files will be shown and could be selected.
# under_test.show_window(title="test", filename_url=test_path)
under_test.show_window(title="test", filename_url=test_path + "/")
await ui_test.human_delay(10)
item = await helper.get_item_async(None, "dummy.usd")
self.assertIsNotNone(item)
# apply button should be disabled
self.assertFalse(under_test._dialog._widget.file_bar._apply_button.enabled)
await helper.click_cancel_async()
# if shown with show_only_folders, files will not be shown
under_test.show_window(title="test", show_only_folders=True, export_handler=mock_handler)
await ui_test.human_delay(10)
item = await helper.get_item_async(None, "dummy.usd")
self.assertIsNone(item)
# try selecting a folder
selections = await under_test.select_items_async(test_path, filenames=['folder'])
self.assertEqual(len(selections), 1)
selected = selections[0]
# apply button should not be disabled
self.assertTrue(under_test._dialog._widget.file_bar._apply_button.enabled)
await ui_test.human_delay()
await helper.click_apply_async()
mock_handler.assert_called_once_with('', selected.path + "/", extension=".usd", selections=[selected.path])
async def test_cancel_handler(self):
"""Testing cancel handler."""
mock_handler = Mock()
async with self.__lock:
under_test = get_file_exporter()
test_path = get_test_data_path(__name__).replace("\\", '/')
async with FileExporterTestHelper() as helper:
under_test.show_window("test_cancel_handler", filename_url=test_path + "/")
await helper.wait_for_popup()
await ui_test.human_delay(10)
await helper.click_cancel_async(cancel_handler=mock_handler)
await ui_test.human_delay(10)
mock_handler.assert_called_once()
class TestFileFilterHandler(omni.kit.test.AsyncTestCase):
"""Testing default_file_filter_handler correctly shows/hides files."""
async def setUp(self):
ext_type = {
'usd': "*.usd",
'usda': "*.usda",
'usdc': "*.usdc",
'usdz': "*.usdz",
}
self.test_filenames = [
("test.anim.usd", "anim", ext_type['usd'], True),
("test.anim.usdz", "anim", ext_type['usdz'], True),
("test.anim.usdc", "anim", ext_type['usdz'], False),
("test.anim.usda", None, ext_type['usda'], True),
("test.material.", None, ext_type['usda'], False),
("test.materials.usd", "material", ext_type['usd'], False),
]
async def tearDown(self):
pass
async def test_file_filter_handler(self):
"""Testing file filter handler"""
for test_filename in self.test_filenames:
filename, postfix, ext, expected = test_filename
result = file_filter_handler(filename, postfix, ext)
self.assertEqual(result, expected)
class TestOnExport(omni.kit.test.AsyncTestCase):
"""Testing on_export function correctly parses filename parts from dialog."""
async def setUp(self):
self.test_sets = [
("test", "anim", "*.usdc", "test", ".anim.usdc"),
("test.usd", "anim", "*.usdc", "test", ".anim.usdc"),
("test.cache.usdc", "geo", "*.usdz", "test", ".geo.usdz"),
("test.cache.any", "geo", "*.usd", "test.cache.any", ".geo.usd"),
("test.geo.usd", None, "*.usda", "test", ".usda"),
("test.png", "anim", "*.jpg", "test", ".anim.jpg"),
]
async def tearDown(self):
pass
async def test_on_export(self):
"""Testing file filter handler"""
mock_callback = Mock()
mock_dialog = Mock()
mock_extension_options = [
('*.usd', 'Can be Binary or Ascii'),
('*.usda', 'Human-readable text format'),
('*.usdc', 'Binary format'),
('*.png', 'test'),
('*.jpg', 'another test')
]
for test_set in self.test_sets:
filename = test_set[0]
mock_dialog.get_file_postfix.return_value = test_set[1]
mock_dialog.get_file_extension.return_value = test_set[2]
mock_dialog.get_file_postfix_options.return_value = DEFAULT_FILE_POSTFIX_OPTIONS
mock_dialog.get_file_extension_options.return_value = mock_extension_options
mock_dialog.get_current_selections.return_value = []
on_export(mock_callback, mock_dialog, filename, "C:/temp/test/")
expected_basename = test_set[3]
expected_extension = test_set[4]
mock_callback.assert_called_with(expected_basename, "C:/temp/test/", extension=expected_extension, selections=ANY)
async def test_export_filename_validation(self):
"""Test export with and without validation."""
mock_callback = Mock()
mock_dialog = Mock()
mock_dialog.get_file_postfix.return_value = None
mock_dialog.get_file_extension.return_value = ".usd"
mock_dialog.get_file_extension_options.return_value = [('*.usd', 'Can be Binary or Ascii')]
on_export(mock_callback, mock_dialog, "", "", should_validate=True)
mock_callback.assert_not_called()
on_export(mock_callback, mock_dialog, "", "C:/temp/test/", should_validate=False)
mock_callback.assert_called_once()
| 13,329 | Python | 47.827839 | 127 | 0.607998 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.10] - 2022-11-14
### Changed
- Updated the docs.
## [1.0.9] - 2022-10-21
### Changed
- Add flag for show_window if file name input should be enabled.
## [1.0.8] - 2022-10-01
### Changed
- Add flag for if file name validation should be performed.
## [1.0.7] - 2022-09-19
### Added
- Added file name validation for file exports, do not allow empty filenames when exporting.
## [1.0.6] - 2022-07-07
### Added
- Added test helper function that waits for UI to be ready.
## [1.0.5] - 2022-06-15
### Added
- Adds test helper.
## [1.0.4] - 2022-04-06
### Added
- Disable unittests from loading at startup.
## [1.0.3] - 2022-03-17
### Added
- Disabled checkpoints.
## [1.0.2] - 2022-02-09
### Added
- Adds click_apply and click_cancel methods.
## [1.0.1] - 2022-02-02
### Added
- Adds postfix and extension options.
## [1.0.0] - 2021-11-05
### Added
- Initial add.
| 970 | Markdown | 19.229166 | 91 | 0.645361 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/docs/README.md | # Kit File Exporter Extension [omni.kit.window.file_exporter]
The File Exporter extension
| 91 | Markdown | 21.999995 | 61 | 0.802198 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/docs/index.rst | omni.kit.window.file_exporter
#############################
.. toctree::
:maxdepth: 1
CHANGELOG
.. automodule:: omni.kit.window.file_exporter
:platform: Windows-x86_64, Linux-x86_64
:members:
:show-inheritance:
:undoc-members:
:imported-members:
| 275 | reStructuredText | 17.399999 | 45 | 0.596364 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/docs/Overview.md | # Overview
The file_exporter extension provides a standardized dialog for exporting files. It is a wrapper around the {obj}`FilePickerDialog`,
but with reasonable defaults for common settings, so it's a higher-level entry point to that interface.
Nevertheless, users will still have the ability to customize some parts but we've boiled them down to just the essential ones.
Why you should use this extension:
* Present a consistent file export experience across the app.
* Customize only the essential parts while inheriting sensible defaults elsewhere.
* Reduce boilerplate code.
* Inherit future improvements.
* Checkpoints fully supported if available on the server.
```{image} ../../../../source/extensions/omni.kit.window.file_exporter/data/preview.png
---
align: center
---
```
## Quickstart
You can pop-up a dialog in just 2 steps. First, retrieve the extension.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-get_instance
end-before: END-DOC-get_instance
dedent: 8
---
```
Then, invoke its show_window method.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-show_window
end-before: END-DOC-show_window
dedent: 8
---
```
Note that the extension is a singleton, meaning there's only one instance of it throughout the app. Basically, we are assuming that you'd
never open more than one instance of the dialog at any one time. The advantage is that we can channel any development through this
single extension and all users will inherit the same changes.
## Customizing the Dialog
You can customize these parts of the dialog.
* Title - The title of the dialog.
* Collections - Which of these collections, ["bookmarks", "omniverse", "my-computer"] to display.
* Filename Url - Url to open the dialog with.
* Postfix options - List of content labels appended to the filename.
* Extension options - List of filename extensions.
* Export options - Options to apply during the export process.
* Export label - Label for the export button.
* Export handler - User provided callback to handle the export process.
Note that these settings are applied when you show the window. Therefore, each time it's displayed, the dialog can be tailored
to the use case.
## Filename postfix options
Users might want to set up data libraries of just animations, materials, etc. However, one challenge of working in Omniverse is that
everything is a USD file. To facilitate this workflow, we suggest adding a postfix to the filename, e.g. "file.animation.usd". The
file bar contains a dropdown that lists the postfix labels. A default list is provided but you can also provide your own.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/omni/kit/window/file_exporter/extension.py
---
language: python
start-after: BEGIN-DOC-file_postfix_options
end-before: END-DOC-file_postfix_options
dedent: 0
---
```
A list of file extensions, furthermore, allows the user to specify what flavor of USD to export.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/omni/kit/window/file_exporter/extension.py
---
language: python
start-after: BEGIN-DOC-file_extension_types
end-before: END-DOC-file_extension_types
dedent: 0
---
```
When the user selects a combination of postfix and extension types, the file view will filter out all other file types, leaving only
the matching ones.
## Export options
A common need is to provide user options for the export process. You create the widget for accepting those inputs,
then add it to the details pane of the dialog. Do this by subclassing from {obj}`ExportOptionsDelegate`
and overriding the methods, :meth:`ExportOptionsDelegate._build_ui_impl` and (optionally) :meth:`ExportOptionsDelegate._destroy_impl`.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-export_options
end-before: END-DOC-export_options
dedent: 0
---
```
Then provide the controller to the file picker for display.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-add_export_options
end-before: END-DOC-add_export_options
dedent: 8
---
```
## Export handler
Pprovide a handler for when the Export button is clicked. In additon to :attr:`filename` and :attr:`dirname`, the handler
should expect a list of :attr:`selections` made from the UI.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-export_handler
end-before: END-DOC-export_handler
dedent: 4
---
```
## Demo app
A complete demo, that includes the code snippets above, is included with this extension at "scripts/demo_file_exporter.py".
| 5,021 | Markdown | 35.92647 | 139 | 0.756622 |
omniverse-code/kit/exts/omni.kit.property.bundle/PACKAGE-LICENSES/omni.kit.property.bundle-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.property.bundle/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.2.6"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "Property Widgets Bundle"
description="Load all property widgets"
feature = true
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "usd", "property"]
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# 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"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
[dependencies]
"omni.usd" = {}
"omni.ui" = {}
"omni.kit.window.property" = {}
"omni.kit.property.camera" = {}
"omni.kit.property.light" = {}
"omni.kit.property.material" = {}
"omni.kit.property.usd" = {}
"omni.kit.property.geometry" = {}
"omni.kit.property.audio" = {}
"omni.kit.property.transform" = {}
"omni.kit.property.render" = {}
"omni.kit.property.skel" = {}
[[python.module]]
name = "omni.kit.property.bundle"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers"
]
| 1,702 | TOML | 25.609375 | 93 | 0.699177 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/widgets.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.usd
from pathlib import Path
from .geom_scheme_delegate import GeomPrimSchemeDelegate
from .path_scheme_delegate import PathPrimSchemeDelegate
from .material_scheme_delegate import MaterialPrimSchemeDelegate, ShaderPrimSchemeDelegate
TEST_DATA_PATH = ""
class BundlePropertyWidgets(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
w = p.get_window()
w.register_scheme_delegate("prim", "xformable_prim", GeomPrimSchemeDelegate())
w.register_scheme_delegate("prim", "path_prim", PathPrimSchemeDelegate())
w.register_scheme_delegate("prim", "material_prim", MaterialPrimSchemeDelegate())
w.register_scheme_delegate("prim", "shade_prim", ShaderPrimSchemeDelegate())
physics_widgets = [
"physics_components",
"physics_prim",
"joint_prim",
"vehicle_prim",
"physics_material",
"custom_properties",
]
anim_graph_widgets = ["anim_graph", "anim_graph_node"]
w.set_scheme_delegate_layout(
"prim",
[
"path_prim",
"basis_curves_prim",
"point_instancer_prim",
"material_prim",
"xformable_prim",
"shade_prim",
"audio_settings",
]
+ physics_widgets
+ anim_graph_widgets,
)
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
w.reset_scheme_delegate_layout("prim")
w.unregister_scheme_delegate("prim", "xformable_prim")
w.unregister_scheme_delegate("prim", "path_prim")
w.unregister_scheme_delegate("prim", "material_prim")
w.unregister_scheme_delegate("prim", "shade_prim")
| 2,730 | Python | 34.467532 | 90 | 0.632234 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .widgets import *
| 457 | Python | 40.63636 | 76 | 0.803063 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/material_scheme_delegate.py | import carb
import omni.usd
from pxr import Sdf, UsdShade
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
class MaterialPrimSchemeDelegate(PropertySchemeDelegate):
def get_widgets(self, payload):
widgets_to_build = []
if self._should_enable_delegate(payload):
widgets_to_build.append("path")
widgets_to_build.append("material")
return widgets_to_build
def get_unwanted_widgets(self, payload):
unwanted_widgets_to_build = []
if self._should_enable_delegate(payload):
unwanted_widgets_to_build.append("transform")
return unwanted_widgets_to_build
def _should_enable_delegate(self, payload):
stage = payload.get_stage()
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if not prim.IsA(UsdShade.Material):
return False
return True
return False
class ShaderPrimSchemeDelegate(PropertySchemeDelegate):
def get_widgets(self, payload):
widgets_to_build = []
if self._should_enable_delegate(payload):
widgets_to_build.append("path")
widgets_to_build.append("shader")
return widgets_to_build
def get_unwanted_widgets(self, payload):
unwanted_widgets_to_build = []
if self._should_enable_delegate(payload):
unwanted_widgets_to_build.append("transform")
return unwanted_widgets_to_build
def _should_enable_delegate(self, payload):
stage = payload.get_stage()
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if not prim.IsA(UsdShade.Shader):
return False
return True
return False
| 1,922 | Python | 32.155172 | 84 | 0.60666 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/path_scheme_delegate.py | import carb
import omni.usd
from pxr import Sdf, UsdGeom
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
class PathPrimSchemeDelegate(PropertySchemeDelegate):
def get_widgets(self, payload):
widgets_to_build = []
if len(payload):
widgets_to_build.append("path")
return widgets_to_build
| 367 | Python | 23.533332 | 84 | 0.719346 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/geom_scheme_delegate.py | import carb
import omni.usd
from pxr import Sdf, UsdMedia, OmniAudioSchema, UsdGeom, UsdLux, UsdSkel
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
class GeomPrimSchemeDelegate(PropertySchemeDelegate):
def get_widgets(self, payload):
widgets_to_build = []
anchor_prim = None
stage = payload.get_stage()
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if not prim.IsA(UsdGeom.Imageable):
return widgets_to_build
anchor_prim = prim
if anchor_prim is None:
return widgets_to_build
if (
anchor_prim
and anchor_prim.IsA(UsdMedia.SpatialAudio)
or anchor_prim.IsA(OmniAudioSchema.OmniSound)
or anchor_prim.IsA(OmniAudioSchema.OmniListener)
):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("media")
widgets_to_build.append("audio_sound")
widgets_to_build.append("audio_listener")
widgets_to_build.append("audio_settings")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdSkel.Root): # pragma: no cover
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("character_api")
widgets_to_build.append("anim_graph_api")
widgets_to_build.append("omni_graph_api")
widgets_to_build.append("kind")
elif anchor_prim.IsA(UsdSkel.Skeleton): # pragma: no cover
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("control_rig")
widgets_to_build.append("skel_animation")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Camera):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("camera")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("kind")
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
elif anchor_prim and ((hasattr(UsdLux, 'LightAPI') and anchor_prim.HasAPI(UsdLux.LightAPI)) or ((hasattr(UsdLux, 'Light') and anchor_prim.IsA(UsdLux.Light)))):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("light")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Scope):
widgets_to_build.append("path")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("character_motion_library")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Mesh):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("material_binding")
widgets_to_build.append("geometry")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("character_interactive_object_api")
widgets_to_build.append("mesh_skel_binding")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Xform):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("material_binding")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Xformable):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("material_binding")
widgets_to_build.append("geometry")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("character_interactive_object_api")
widgets_to_build.append("kind")
return widgets_to_build
def get_unwanted_widgets(self, payload):
unwanted_widgets_to_build = []
anchor_prim = None
stage = payload.get_stage()
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if not prim.IsA(UsdGeom.Imageable):
return unwanted_widgets_to_build
anchor_prim = prim
if anchor_prim is None:
return unwanted_widgets_to_build
if anchor_prim and anchor_prim.IsA(UsdGeom.Scope):
unwanted_widgets_to_build.append("transform")
unwanted_widgets_to_build.append("geometry")
unwanted_widgets_to_build.append("kind")
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
elif anchor_prim and ((hasattr(UsdLux, 'LightAPI') and anchor_prim.HasAPI(UsdLux.LightAPI)) or ((hasattr(UsdLux, 'Light') and anchor_prim.IsA(UsdLux.Light)))):
unwanted_widgets_to_build.append("geometry")
elif (
anchor_prim
and anchor_prim.IsA(UsdMedia.SpatialAudio)
or anchor_prim.IsA(OmniAudioSchema.Sound)
or anchor_prim.IsA(OmniAudioSchema.Listener)
):
unwanted_widgets_to_build.append("geometry_imageable")
elif anchor_prim and anchor_prim.IsA(UsdSkel.Skeleton) or anchor_prim.IsA(UsdSkel.Root):
unwanted_widgets_to_build.append("geometry")
unwanted_widgets_to_build.append("geometry_imageable")
return unwanted_widgets_to_build
| 5,906 | Python | 41.496403 | 167 | 0.614968 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/tests/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .test_bundle import *
| 461 | Python | 40.999996 | 76 | 0.802603 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/tests/test_bundle.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import platform
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows, wait_stage_loading, get_prims
from pxr import Kind, Sdf, Gf
import pathlib
class TestBundleWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
await arrange_windows()
from omni.kit.property.bundle.widgets import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
await super().tearDown()
# Test(s)
async def test_bundle_ui(self):
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("bundle.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await wait_stage_loading()
stage = usd_context.get_stage()
for prim_path in ['/World/Cube', '/World/Cone', '/World/OmniSound', '/World/Camera', '/World/DomeLight', '/World/Scope', '/World/Xform']:
await self.docked_test_window(
window=self._w._window,
width=450,
height=995,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
# Select the prim.
usd_context.get_selection().set_selected_prim_paths([prim_path], True)
prim = stage.GetPrimAtPath(prim_path)
type = prim.GetTypeName().lower()
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"test_bundle_ui_{type}.png")
# allow window to be restored to full size
await ui_test.human_delay(50)
| 2,673 | Python | 37.199999 | 145 | 0.66517 |
omniverse-code/kit/exts/omni.kit.property.bundle/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.2.6] - 2022-05-13
### Changes
- Update test golden image
## [1.2.5] - 2022-05-05
### Changes
- Update test golden image
## [1.2.4] - 2021-04-15
### Changes
- Changed how material input is populated.
## [1.2.3] - 2021-02-19
### Changes
- Added UI test
## [1.2.2] - 2020-12-09
### Changes
- Added extension icon
- Added readme
- Updated preview image
## [1.2.1] - 2020-11-10
### Changes
- Added layer widget to ordering
## [1.2.0] - 2020-10-27
### Changes
- Added physics widgets to ordering
## [1.1.0] - 2020-10-21
### Changes
- Property schemas moved into bundle
## [1.0.3] - 2020-10-19
### Changes
- Loads property.transform
## [1.0.2] - 2020-10-13
### Changes
- Loads property.audio
## [1.0.1] - 2020-10-09
### Changes
- created
- Loads property.geometry
## [1.0.0] - 2020-09-23
### Changes
- created
- Loads property.camera, property.light, property.material & property.usd
| 989 | Markdown | 16.678571 | 80 | 0.645096 |
omniverse-code/kit/exts/omni.kit.property.bundle/docs/README.md | # omni.kit.property.bundle
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension loads;
- omni.kit.window.property
- omni.kit.property.camera
- omni.kit.property.light
- omni.kit.property.material
- omni.kit.property.usd
- omni.kit.property.geometry
- omni.kit.property.audio
- omni.kit.property.transform
## so is a convenient way to load all the property extensions.
## This is also controls what properties are shown and in what order
| 500 | Markdown | 21.772726 | 74 | 0.774 |
omniverse-code/kit/exts/omni.kit.property.bundle/docs/index.rst | omni.kit.property.bundle
###########################
Property Widget Loader
.. toctree::
:maxdepth: 1
CHANGELOG
| 123 | reStructuredText | 9.333333 | 27 | 0.536585 |
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/execution_debug_page.py | """EF Execution Debugging Page"""
import omni.ui as ui
from omni.kit.exec.core.unstable import dump_graph_topology
from omni.kit.window.preferences import PreferenceBuilder, SettingType
class ExecutionDebugPage(PreferenceBuilder):
"""EF Execution Debugging Page"""
def __init__(self):
super().__init__("Execution")
# Setting keys. When changing, make sure to update ExecutionController.cpp as well.
self.serial_eg = "/app/execution/debug/forceSerial"
self.parallel_eg = "/app/execution/debug/forceParallel"
# ID counter for file path write-out.
self.id = 0
self.file_name = "ExecutionGraph_"
def build(self):
"""Build the EF execution debugging page"""
with ui.VStack(height=0):
with self.add_frame("Execution Debugging"):
with ui.VStack():
dump_graph_topology_button = ui.Button("Dump execution graph", width=24)
dump_graph_topology_button.set_clicked_fn(self._dump_graph_topology)
dump_graph_topology_button.set_tooltip(
"Writes the execution graph topology out as a GraphViz (.dot) file. File location\n"
+ "will differ depending on the kit app being run, whether the button was pressed\n"
+ "in a unit test, etc., but typically it can be found under something like\n"
+ "kit/_compiler/omni.app.dev; if not, then just search for .dot files containing\n"
+ "the name ExecutionGraph in the kit directory.\n"
)
self.create_setting_widget("Force serial execution", self.serial_eg, SettingType.BOOL)
self.create_setting_widget("Force parallel execution", self.parallel_eg, SettingType.BOOL)
def _dump_graph_topology(self):
"""Dump graph topology with incremented file"""
dump_graph_topology(self.file_name + str(self.id))
self.id += 1
| 2,021 | Python | 46.023255 | 110 | 0.617516 |
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/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 omni.ext
from omni.kit.window.preferences import register_page, unregister_page
from .execution_debug_page import ExecutionDebugPage
class ExecutionDebugExtension(omni.ext.IExt):
# The entry point for this extension (generates a page within the Preferences
# tab with debugging flags for the Execution Framework).
def on_startup(self):
self.execution_debug_page = ExecutionDebugPage()
register_page(self.execution_debug_page)
def on_shutdown(self):
unregister_page(self.execution_debug_page)
| 970 | Python | 39.458332 | 81 | 0.778351 |
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/__init__.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from .extension import *
| 452 | Python | 44.299996 | 76 | 0.807522 |
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/tests/test_exec_debug.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.settings
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.kit.app
import omni.kit.window.preferences as preferences
from omni.kit.viewport.window import ViewportWindow
import omni.ui as ui
CURRENT_PATH = Path(__file__).parent
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests")
TEST_WIDTH, TEST_HEIGHT = 1280, 600
class TestExecutionDebugWindow(OmniUiTest):
"""Test the EF Debugging Page"""
async def setUp(self):
"""Test set-up before running each test"""
await super().setUp()
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
self._vw = ViewportWindow("TestWindow", width=TEST_WIDTH, height=TEST_HEIGHT)
async def tearDown(self):
"""Test tear-down after running each test"""
await super().tearDown()
async def test_execution_page(self):
"""Test the EF Debugging Page"""
title = "Execution"
for page in preferences.get_page_list():
if page.get_title() == title:
# Setting keys for the test. Flag some stuff to be true to make sure toggles work.
carb.settings.get_settings().set(page.serial_eg, False)
carb.settings.get_settings().set(page.parallel_eg, True)
preferences.select_page(page)
preferences.show_preferences_window()
await omni.kit.app.get_app().next_update_async()
pref_window = ui.Workspace.get_window("Preferences")
await self.docked_test_window(
window=pref_window,
width=TEST_WIDTH,
height=TEST_HEIGHT,
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"{title}.png")
| 2,383 | Python | 36.841269 | 101 | 0.68569 |
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/tests/__init__.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from .test_exec_debug import TestExecutionDebugWindow
| 481 | Python | 47.199995 | 76 | 0.817048 |
omniverse-code/kit/exts/omni.kit.exec.debug/docs/index.rst | omni.kit.exec.debug
###########################
.. toctree::
:maxdepth: 1
CHANGELOG
| 94 | reStructuredText | 8.499999 | 27 | 0.43617 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/welcome_page_item.py | from typing import Callable
import carb
import omni.kit.app
import omni.ui as ui
class WelcomePageItem(ui.AbstractItem):
def __init__(self, raw_data: dict):
super().__init__()
self.text = raw_data.get("text", "")
self.icon = raw_data.get("icon", "")
self.active_icon = raw_data.get("active_icon", self.icon)
self.extension_id = raw_data.get("extension_id")
self.order = raw_data.get("order", 0xFFFFFFFF)
self.build_fn: Callable[[None], None] = None
carb.log_info(f"Register welcome page: {self}")
def build_ui(self) -> None:
# Enable page extension and call build_ui
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate(self.extension_id, True)
try:
if self.build_fn:
self.build_fn()
else:
carb.log_error(f"Failed to build page for `{self.text}` because build entry point not defined!")
except Exception as e:
carb.log_error(f"Failed to build page for `{self.text}`: {e}")
def __repr__(self):
return f"{self.text}:{self.extension_id}" | 1,175 | Python | 35.749999 | 112 | 0.6 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/welcome_window.py | from typing import Dict, List, Optional
import carb.settings
import omni.ui as ui
from omni.ui import constant as fl
from .style import WELCOME_STYLE
from .welcome_model import WelcomeModel
from .welcome_page_item import WelcomePageItem
SETTING_SHOW_AT_STARTUP = "/persistent/exts/omni.kit.welcome.window/visible_at_startup"
SETTING_SHOW_SAS_CHECKBOX = "/exts/omni.kit.welcome.window/show_sas_checkbox"
class WelcomeWindow(ui.Window):
"""
Window to show welcome content.
Args:
visible (bool): If visible when window created.
"""
def __init__(self, model: WelcomeModel, visible: bool=True):
self._model = model
self._delegates: List[WelcomePageItem] = []
self.__page_frames: Dict[WelcomePageItem, ui.Frame] = {}
self.__page_buttons: Dict[WelcomePageItem, ui.Button] = {}
self.__selected_page: Optional[WelcomePageItem] = None
# TODO: model window?
# If model window and open extensions manager, new extensions window unavailable
# And if model window, checkpoing combobox does not pop up droplist because it is a popup window
flags = (ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_MODAL)
super().__init__("Welcome Screen", flags=flags, width=1380, height=780, padding_x=2, padding_y=2, visible=visible)
self.frame.set_build_fn(self._build_ui)
self.frame.set_style(WELCOME_STYLE)
def destroy(self) -> None:
super().destroy()
self.__page_frames = {}
self.visible = False
self.__sub_show_at_startup = None
def _build_ui(self):
self._pages = self._model.get_item_children(None)
button_height = fl._find("welcome_page_button_height")
with self.frame:
with ui.HStack():
# Left for buttons to switch different pages
with ui.VStack(width=250, spacing=0):
for page in self._pages:
self.__page_buttons[page] = ui.Button(
page.text.upper(),
height=button_height,
image_width=button_height,
image_height=button_height,
spacing=4,
image_url=page.icon,
clicked_fn=lambda d=page: self.__show_page(d), style_type_name_override="Page.Button"
)
ui.Spacer()
self.__build_show_at_startup()
# Right for page content
with ui.ZStack():
for page in self._pages:
self.__page_frames[page] = ui.Frame(build_fn=lambda p=page: p.build_ui(), visible=False)
# Default always show first page
self.__show_page(self._pages[0])
def __build_show_at_startup(self) -> None:
settings = carb.settings.get_settings()
self.__show_at_startup_model = ui.SimpleBoolModel(settings.get(SETTING_SHOW_AT_STARTUP))
def __on_show_at_startup_changed(model: ui.SimpleBoolModel):
settings.set(SETTING_SHOW_AT_STARTUP, model.as_bool)
self.__sub_show_at_startup = self.__show_at_startup_model.subscribe_value_changed_fn(__on_show_at_startup_changed)
if settings.get_as_bool(SETTING_SHOW_SAS_CHECKBOX):
with ui.HStack(height=0, spacing=5):
ui.Spacer(width=5)
ui.CheckBox(self.__show_at_startup_model, width=0)
ui.Label("Show at Startup", width=0)
ui.Spacer(height=5)
def __show_page(self, page: WelcomePageItem):
if self.__selected_page:
self.__page_frames[self.__selected_page].visible = False
self.__page_buttons[self.__selected_page].selected = False
self.__page_buttons[self.__selected_page].image_url = self.__selected_page.icon
if page:
self.__page_frames[page].visible = True
self.__page_buttons[page].selected = True
self.__page_buttons[page].image_url = page.active_icon
self.__selected_page = page
| 4,148 | Python | 42.21875 | 122 | 0.592575 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/style.py | from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data/icons")
cl.welcome_window_background = cl.shade(cl("#363636"))
cl.welcome_content_background = cl.shade(cl("#1F2123"))
cl.welcome_button_text = cl.shade(cl("#979797"))
cl.welcome_button_text_selected = cl.shade(cl("#E3E3E3"))
cl.welcome_label = cl.shade(cl("#A1A1A1"))
cl.welcome_label_selected = cl.shade(cl("#34C7FF"))
fl.welcome_page_button_size = 24
fl.welcome_title_font_size = 18
fl.welcome_page_button_height = 80
fl.welcome_page_title_height = fl._find("welcome_page_button_height") + 8
fl.welcome_content_padding_x = 10
fl.welcome_content_padding_y = 10
WELCOME_STYLE = {
"Window": {
"background_color": cl.welcome_window_background,
"border_width": 0,
"padding": 0,
"marging" : 0,
"padding_width": 0,
"margin_width": 0,
},
"Page.Button": {
"background_color": cl.welcome_window_background,
"stack_direction": ui.Direction.LEFT_TO_RIGHT,
"padding_x": 10,
"margin": 0,
},
"Page.Button:hovered": {
"background_color": cl.welcome_content_background,
},
"Page.Button:pressed": {
"background_color": cl.welcome_content_background,
},
"Page.Button:selected": {
"background_color": cl.welcome_content_background,
},
"Page.Button.Label": {
"font_size": fl.welcome_page_button_size,
"alignment": ui.Alignment.LEFT_CENTER,
"color": cl.welcome_button_text,
},
"Page.Button.Label:selected": {
"color": cl.welcome_button_text_selected,
},
"Content": {
"background_color": cl.welcome_content_background,
},
"Title.Button": {
"background_color": cl.transparent,
"stack_direction": ui.Direction.RIGHT_TO_LEFT,
},
"Title.Button.Label": {
"font_size": fl.welcome_title_font_size,
},
"Title.Button.Image": {
"color": cl.welcome_label_selected,
"alignment": ui.Alignment.LEFT_CENTER,
},
"Doc.Background": {"background_color": cl.white},
"CheckBox": {
"background_color": cl.welcome_button_text,
"border_radius": 0,
},
"Label": {"color": cl.welcome_button_text},
}
| 2,375 | Python | 29.075949 | 73 | 0.622737 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/extension.py | import asyncio
from typing import Callable, Optional
import carb
import carb.settings
import omni.ext
import omni.kit.app
import omni.kit.menu.utils
import omni.kit.ui
import omni.ui as ui
from omni.kit.menu.utils import MenuItemDescription
from .actions import deregister_actions, register_actions
from .welcome_model import WelcomeModel
from .welcome_window import WelcomeWindow
WELCOME_MENU_ROOT = "File"
_extension_instance = None
class WelcomeExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._ext_name = omni.ext.get_extension_name(ext_id)
self.__stage_opened = False
# Window
self._model = WelcomeModel()
visible = carb.settings.get_settings().get("/persistent/exts/omni.kit.welcome.window/visible_at_startup")
self._window = WelcomeWindow(self._model, visible=visible)
self._window.set_visibility_changed_fn(self.__on_visibility_changed)
if visible:
self.__center_window()
else:
# Listen for the app ready event
def _on_app_ready(event):
self.__on_close()
self._app_ready_sub = None
startup_event_stream = omni.kit.app.get_app().get_startup_event_stream()
self._app_ready_sub = startup_event_stream.create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, _on_app_ready, name="Welcome window"
)
# Menu item
self._register_menuitem()
global _extension_instance
_extension_instance = self
# Action
register_actions(self._ext_name, _extension_instance)
def on_shutdown(self):
self._hooks = None
self._app_ready_sub = None
deregister_actions(self._ext_name)
self._model = None
if self._menu_list is not None:
omni.kit.menu.utils.remove_menu_items(self._menu_list, WELCOME_MENU_ROOT)
self._menu_list = None
if self._window is not None:
self._window.destroy()
self._window = None
global _extension_instance
_extension_instance = self
def toggle_window(self):
self._window.visible = not self._window.visible
def _register_menuitem(self):
self._menu_list = [
MenuItemDescription(
name="Welcome",
glyph="none.svg",
ticked=True,
ticked_fn=self._on_tick,
onclick_action=(self._ext_name, "toggle_window"),
appear_after="Open",
)
]
omni.kit.menu.utils.add_menu_items(self._menu_list, WELCOME_MENU_ROOT)
def _on_tick(self):
if self._window:
return self._window.visible
else:
return False
def _on_click(self, *args):
self._window.visible = not self._window.visible
def __on_visibility_changed(self, visible: bool):
omni.kit.menu.utils.refresh_menu_items(WELCOME_MENU_ROOT)
if visible:
# Always center. Cannot use layout file to change window position because window may be invisible when startup
self.__center_window()
return
self.__on_close()
def __open_default_stage(self):
self.__execute_action("omni.kit.stage.templates", "create_new_stage_empty")
def __on_close(self):
# When welcome window is closed, setup the Viewport to a complete state
settings = carb.settings.get_settings()
if settings.get("/exts/omni.kit.welcome.window/autoSetupOnClose"):
self.__execute_action("omni.app.setup", "enable_viewport_rendering")
# Do not open default stage if stage already opened
if not self.__stage_opened and not omni.usd.get_context().get_stage():
self.__open_default_stage()
workflow = settings.get("/exts/omni.kit.welcome.window/default_workflow")
if workflow:
self.__active_workflow(workflow)
def __active_workflow(self, workflow: str):
carb.log_info(f"Trying to active workflow '{workflow}'...")
self.__execute_action("omni.app.setup", "active_workflow", workflow)
def __center_window(self):
async def __delay_center():
await omni.kit.app.get_app().next_update_async()
app_width = ui.Workspace.get_main_window_width()
app_height = ui.Workspace.get_main_window_height()
self._window.position_x = (app_width - self._window.frame.computed_width) / 2
self._window.position_y = (app_height - self._window.frame.computed_height) / 2
asyncio.ensure_future(__delay_center())
def __execute_action(self, ext_id: str, action_id: str, *args, **kwargs):
try:
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.execute_action(ext_id, action_id, *args, **kwargs)
except Exception as e:
carb.log_error(f"Failed to execute action '{ext_id}::{action_id}': {e}")
def register_page(self, ext_id: str, build_fn: Callable[[None], None]) -> bool:
return self._model.register_page(ext_id, build_fn)
def show_window(self, visible: bool = True, stage_opened: bool = False) -> None:
self.__stage_opened = stage_opened or self.__stage_opened
self._window.visible = visible
def register_page(ext_id: str, build_fn: Callable[[None], None]) -> bool:
if _extension_instance:
return _extension_instance.register_page(ext_id, build_fn)
else:
return False
def show_window(visible: bool = True, stage_opened: bool = False) -> None:
if _extension_instance:
_extension_instance.show_window(visible=visible, stage_opened=stage_opened)
| 5,793 | Python | 35.670886 | 122 | 0.619886 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/welcome_model.py | from typing import Callable, List, Optional
import carb
import carb.settings
import omni.ui as ui
from .welcome_page_item import WelcomePageItem
SETTING_WELCOME_PAGES = "/app/welcome/page"
class WelcomeModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self.__settings = carb.settings.get_settings()
self._items = [WelcomePageItem(page) for page in self.__settings.get(SETTING_WELCOME_PAGES)]
self._items.sort(key=lambda item: item.order)
def get_item_children(self, item: Optional[WelcomePageItem]) -> List[WelcomePageItem]:
return self._items
def register_page(self, ext_id: str, build_fn: Callable[[None], None]) -> bool:
for item in self._items:
if item.extension_id == ext_id:
item.build_fn = build_fn
return True
carb.log_warn(f"Extension {ext_id} not defined in welcome window.")
return False
| 945 | Python | 30.533332 | 100 | 0.65291 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/actions.py | def register_actions(extension_id, extension_inst):
try:
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Welcome"
action_registry.register_action(
extension_id,
"toggle_window",
extension_inst.toggle_window,
display_name="File->Welcome",
description="Show/Hide welcome window",
tag=actions_tag,
)
except ImportError:
pass
def deregister_actions(extension_id):
try:
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
except ImportError:
pass | 777 | Python | 28.923076 | 74 | 0.622909 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/tests/__init__.py | from .test_window import * | 26 | Python | 25.999974 | 26 | 0.769231 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/tests/test_window.py | from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.ui as ui
from ..extension import register_page, _extension_instance as welcome_instance
CURRENT_PATH = Path(__file__).parent
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests")
class TestWelcomeWindow(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
# Register page build function
register_page("omni.kit.welcome.window", self.__build_ui)
# Show window
self._window = welcome_instance._window
self._window.visible = True
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_window(self):
await self.docked_test_window(window=self._window, width=1280, height=720, block_devices=False)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="window.png")
def __build_ui(self):
with ui.VStack():
ui.Label("PLACE PAGE WIDGETS HERE!", height=0) | 1,186 | Python | 32.914285 | 103 | 0.680438 |
omniverse-code/kit/exts/omni.kit.welcome.window/docs/index.rst | omni.kit.welcome.window
###########################
.. toctree::
:maxdepth: 1
CHANGELOG
| 96 | reStructuredText | 11.124999 | 27 | 0.46875 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/PACKAGE-LICENSES/omni.kit.widget.live_session_management-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/config/extension.toml | [package]
version = "1.1.3"
title = "Live Session Management Widgets"
category = "Internal"
description = "This extension includes shared live session widgets used by other extentions to re-use widgets for session management."
keywords = ["Live Session", "Layers", "Widget"]
changelog = "docs/CHANGELOG.md"
authors = ["NVIDIA"]
repository = ""
[dependencies]
"omni.ui" = {}
"omni.client" = {}
"omni.kit.usd.layers" = {}
"omni.kit.widget.prompt" = {}
"omni.kit.window.filepicker" = {}
"omni.kit.notification_manager" = {}
"omni.kit.collaboration.channel_manager" = {}
"omni.kit.window.file" = {}
[[python.module]]
name = "omni.kit.widget.live_session_management"
[[test]]
waiver = "Tests covered in omni.kit.widget.layers" | 725 | TOML | 26.923076 | 134 | 0.704828 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/share_session_link_window.py | import carb
import omni.kit.usd.layers as layers
import omni.ui as ui
import omni.kit.clipboard
from .live_session_model import LiveSessionModel
from .layer_icons import LayerIcons
class ShareSessionLinkWindow:
def __init__(self, layers_interface: layers.Layers, layer_identifier):
self._window = None
self._layers_interface = layers_interface
self._base_layer_identifier = layer_identifier
self._buttons = []
self._existing_sessions_combo = None
self._existing_sessions_model = LiveSessionModel(self._layers_interface, layer_identifier, False)
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def _on_layer_event(event: carb.events.IEvent):
payload = layers.get_layer_event_payload(event)
if payload.event_type == layers.LayerEventType.LIVE_SESSION_LIST_CHANGED:
if self._base_layer_identifier not in payload.identifiers_or_spec_paths:
return
self._existing_sessions_model.refresh_sessions(force=True)
self._update_dialog_states()
self._layers_event_subscription = layers_interface.get_event_stream().create_subscription_to_pop(
_on_layer_event, name="Session Start Window Events"
)
def destroy(self):
self._layers_interface = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
if self._window:
self._window.visible = False
self._window = None
if self._existing_sessions_model:
self._existing_sessions_model.destroy()
self._existing_sessions_model = None
self._layers_event_subscription = None
self._existing_sessions_combo = None
self._existing_sessions_empty_hint = None
self._error_label = None
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
if not self._window.visible:
self._existing_sessions_model.stop_channel()
def _on_ok_button_fn(self):
current_session = self._existing_sessions_model.current_session
if not current_session or self._existing_sessions_model.empty():
self._error_label.text = "No Valid Session Selected."
return
omni.kit.clipboard.copy(current_session.shared_link)
self._error_label.text = ""
self.visible = False
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _update_dialog_states(self):
if self._existing_sessions_model.empty():
self._existing_sessions_empty_hint.visible = True
else:
self._existing_sessions_empty_hint.visible = False
self._error_label.text = ""
def _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window(
"SHARE LIVE SESSION LINK", visible=False, height=0,
auto_resize=True, dockPreference=ui.DockPreference.DISABLED
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
self._existing_sessions_model.refresh_sessions(True)
STYLES = {
"Button.Image::confirm_button": {
"image_url": LayerIcons.get("link"), "alignment" : ui.Alignment.RIGHT_CENTER
},
"Label::copy_link": {"font_size": 14},
"Rectangle::hovering": {"border_radius": 2, "margin": 0, "padding": 0},
"Rectangle::hovering:hovered": {"background_color": 0xCC9E9E9E},
}
with self._window.frame:
with ui.VStack(height=0, style=STYLES):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(width=20)
self._error_label = ui.Label(
"", name="error_label", style={"color": 0xFF0000CC},
alignment=ui.Alignment.LEFT, word_wrap=True
)
ui.Spacer(width=20)
ui.Spacer(width=0, height=5)
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(height=0):
self._existing_sessions_combo = ui.ComboBox(
self._existing_sessions_model, width=self._window.width - 40, height=0
)
self._existing_sessions_empty_hint = ui.Label(
" No Existing Sessions", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F}
)
ui.Spacer(width=20)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer()
with ui.ZStack(width=120, height=30):
ui.Rectangle(name="hovering")
with ui.HStack():
ui.Spacer()
ui.Label("Copy Link", width=0, name="copy_link")
ui.Spacer(width=8)
ui.Image(LayerIcons.get("link"), width=20)
ui.Spacer()
ok_button = ui.InvisibleButton(name="confirm_button")
ok_button.set_clicked_fn(self._on_ok_button_fn)
self._buttons.append(ok_button)
ui.Spacer()
ui.Spacer(width=0, height=20)
self._update_dialog_states()
| 6,306 | Python | 38.41875 | 116 | 0.550428 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/layer_icons.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
class LayerIcons:
"""A singleton that scans the icon folder and returns the icon depending on the type"""
_icons = {}
@staticmethod
def on_startup(extension_path):
current_path = Path(extension_path)
icon_path = current_path.joinpath("icons")
# Read all the svg files in the directory
LayerIcons._icons = {icon.stem: icon for icon in icon_path.glob("*.svg")}
@staticmethod
def get(name, default=None):
"""Checks the icon cache and returns the icon if exists"""
found = LayerIcons._icons.get(name)
if not found and default:
found = LayerIcons._icons.get(default)
if found:
return str(found)
return None
| 1,194 | Python | 34.147058 | 91 | 0.688442 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_user_list.py | __all__ = ["LiveSessionUserList"]
import carb
import omni.usd
import omni.client.utils as clientutils
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
from .utils import build_live_session_user_layout, is_extension_loaded
from omni.ui import color as cl
TOOLTIP_STYLE = {
"color": cl("#979797"),
"Tooltip": {"background_color": 0xEE222222}
}
PRESENTER_STYLE = {"background_color": 0xff2032dc} # blue alternative: 0xffff851a
class LiveSessionUserList:
"""Widget to build an user list to show all live session users of interested layer."""
def __init__(self, usd_context: omni.usd.UsdContext, base_layer_identifier: str, **kwargs):
"""
Constructor.
Args:
usd_context (omni.usd.UsdContext): USD Context instance.
base_layer_identifier (str): Interested layer to listen to.
follow_user_with_double_click (bool): Whether to enable follow user function of double click.
Kwargs:
icon_size (int): The width and height of the user icon. 16 pixel by default.
spacing (int): The horizonal spacing between two icons. 2 pixel by default.
show_myself (int): Whether to show local user or not. True by default
show_myself_to_leftmost (bool): Whether to show local user to the left most, or right most otherwise.
True by default.
maximum_users (int): The maximum users to show, and show others with overflow. Unlimited by default.
prim_path (Sdf.Path): Track Live Session for this prim only.
"""
self.__icon_size = kwargs.get("icon_size", 16)
self.__spacing = kwargs.get("spacing", 2)
self.__show_myself = kwargs.get("show_myself", True)
self.__show_myself_to_leftmost = kwargs.get("show_myself_to_leftmost", True)
self.__maximum_count = kwargs.get("maximum_users", None)
self.__follow_user_with_double_click = kwargs.get("follow_user_with_double_click", False)
timeline_ext_loaded = is_extension_loaded("omni.timeline.live_session")
self.__allow_timeline_settings = kwargs.get("allow_timeline_settings", False) and timeline_ext_loaded
self.__prim_path = kwargs.get("prim_path", None)
self.__base_layer_identifier = base_layer_identifier
self.__usd_context = usd_context
self.__layers = layers.get_layers(usd_context)
self.__live_syncing = layers.get_live_syncing()
self.__layers_event_subscriptions = []
self.__main_layout: ui.HStack = ui.HStack(width=0, height=0)
self.__all_user_layouts = {}
self.__overflow = None
self.__overflow_button = None
self.__initialize()
@property
def layout(self) -> ui.HStack:
return self.__main_layout
def track_layer(self, layer_identifier):
"""Switches the base layer to listen to."""
if self.__base_layer_identifier != layer_identifier:
self.__base_layer_identifier = layer_identifier
self.__initialize()
def empty(self):
return len(self.__all_user_layouts) == 0
def __initialize(self):
if not clientutils.is_local_url(self.__base_layer_identifier):
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
]:
layers_event_subscription = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event,
name=f"omni.kit.widget.live_session_management.LiveSessionUserList {str(event)}"
)
self.__layers_event_subscriptions.append(layers_event_subscription)
else:
self.__layers_event_subscriptions = []
self.__build_ui()
def __is_in_session(self):
if self.__prim_path:
return self.__live_syncing.is_prim_in_live_session(self.__prim_path, self.__base_layer_identifier)
else:
return self.__live_syncing.is_layer_in_live_session(self.__base_layer_identifier)
def __build_myself(self):
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
if not current_live_session:
return
logged_user = current_live_session.logged_user
with ui.ZStack(width=0, height=0):
with ui.HStack():
ui.Spacer()
self.__build_user_layout_or_overflow(current_live_session, logged_user, True, spacing=0)
ui.Spacer()
if self.__is_presenting(logged_user):
with ui.VStack():
ui.Spacer()
with ui.HStack(height=2, width=24):
ui.Rectangle(
height=2, width=12, alignment=ui.Alignment.BOTTOM, style={"background_color": 0xff00b86b}
)
ui.Rectangle(
height=2, width=12, alignment=ui.Alignment.BOTTOM, style=PRESENTER_STYLE
)
else:
with ui.VStack():
ui.Spacer()
ui.Rectangle(
height=2, width=24, alignment=ui.Alignment.BOTTOM, style={"background_color": 0xff00b86b}
)
def __build_ui(self):
# Destroyed
if not self.__main_layout:
return
self.__overflow = False
self.__main_layout.clear()
self.__all_user_layouts.clear()
self.__overflow_button = None
if not self.__is_in_session():
return
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
with self.__main_layout:
if self.__show_myself and self.__show_myself_to_leftmost:
self.__build_myself()
for peer_user in current_live_session.peer_users:
self.__build_user_layout_or_overflow(current_live_session, peer_user, False, self.__spacing)
if self.__overflow:
break
if self.__show_myself and not self.__show_myself_to_leftmost:
ui.Spacer(self.__spacing)
self.__build_myself()
if self.empty():
self.__main_layout.visible = False
else:
self.__main_layout.visible = True
@carb.profiler.profile
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self.__base_layer_identifier):
return
if self.__allow_timeline_settings:
import omni.timeline.live_session
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None:
timeline_session.add_presenter_changed_fn(self.__on_presenter_changed)
self.__build_ui()
elif (
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED or
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT
):
if not payload.is_layer_influenced(self.__base_layer_identifier):
return
if not self.__is_in_session():
return
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
user_id = payload.user_id
if payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
self.__all_user_layouts.pop(user_id, None)
# FIXME: omni.ui does not support to remove single child.
self.__build_ui()
else:
if user_id in self.__all_user_layouts or self.__overflow:
# OMFP-2909: Refresh overflow button to rebuild tooltip.
if self.__overflow and self.__overflow_button:
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
return
user_info = current_live_session.get_peer_user_info(user_id)
if not user_info:
return
self.__main_layout.add_child(
self.__build_user_layout_or_overflow(current_live_session, user_info, False, self.__spacing)
)
def destroy(self): # pragma: no cover
self.__overflow_button = None
self.__main_layout = None
self.__layers_event_subscriptions = []
self.__layers = None
self.__live_syncing = None
self.__user_menu = None
self.__all_user_layouts.clear()
def __on_follow_user(
self, x : float, y : float, button : int, modifier, user_info: layers.LiveSessionUser
):
if button != int(carb.input.MouseInput.LEFT_BUTTON): # only left MB click
return
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
if not current_live_session or current_live_session.logged_user_id == user_info.user_id:
return
presence_layer = pl.get_presence_layer_interface(self.__usd_context)
if presence_layer:
presence_layer.enter_follow_mode(user_info.user_id)
def __on_mouse_clicked(
self, x : float, y : float, button : int, modifier, user_info: layers.LiveSessionUser
):
if button == int(carb.input.MouseInput.RIGHT_BUTTON): # right click to open menu
import omni.timeline.live_session
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None and timeline_session.am_i_owner():
self.__user_menu = ui.Menu("global_live_timeline_user")
show = False
with self.__user_menu:
if timeline_session.is_presenter(user_info) and not timeline_session.is_owner(user_info):
ui.MenuItem(
"Withdraw Timeline Presenter",
triggered_fn=lambda *args: self.__set_presenter(timeline_session, timeline_session.owner)
)
show = True
elif not timeline_session.is_presenter(user_info):
ui.MenuItem(
"Set as Timeline Presenter",
triggered_fn=lambda *args: self.__set_presenter(timeline_session, user_info)
)
show = True
if show:
self.__user_menu.show()
def __set_presenter(self, timeline_session, user_info: layers.LiveSessionUser):
timeline_session.presenter = user_info
def __is_presenting(self, user_info: layers.LiveSessionUser) -> bool:
if not self.__allow_timeline_settings:
return False
timeline_session = omni.timeline.live_session.get_timeline_session()
return timeline_session.is_presenter(user_info) if timeline_session is not None else False
def __on_presenter_changed(self, _):
self.__build_ui()
def __build_user_layout(
self, live_session: layers.LiveSession, user_info: layers.LiveSessionUser, me: bool, spacing=2
):
if me:
tooltip = f"{user_info.user_name} - Me"
if live_session.merge_permission:
tooltip += " (owner)"
else:
tooltip = f"{user_info.user_name} ({user_info.from_app})"
if not live_session.merge_permission and live_session.owner == user_info.user_name:
tooltip += " - owner"
layout = ui.ZStack(width=0, height=0)
with layout:
with ui.HStack():
ui.Spacer(width=spacing)
user_layout = build_live_session_user_layout(
user_info, self.__icon_size, tooltip, self.__on_follow_user if self.__follow_user_with_double_click else None,
self.__on_mouse_clicked if self.__allow_timeline_settings else None
)
user_layout.set_style(TOOLTIP_STYLE)
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
logged_user = current_live_session.logged_user
if logged_user.user_id != user_info.user_id and self.__is_presenting(user_info):
with ui.VStack():
ui.Spacer()
ui.Rectangle(
height=2, width=24, alignment=ui.Alignment.BOTTOM, style=PRESENTER_STYLE
)
return layout
def __build_tooltip(self): # pragma: no cover
live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
if not live_session:
return
total_users = len(live_session.peer_users)
if self.__show_myself:
total_users += 1
with ui.VStack():
with ui.HStack(style={"color": cl("#757575")}):
ui.Spacer()
ui.Label(f"{total_users} Users Connected", style={"font_size": 12})
ui.Spacer()
ui.Spacer(height=0)
ui.Separator(style={"color": cl("#4f4f4f")})
ui.Spacer(height=4)
all_users = []
if self.__show_myself:
all_users = [live_session.logged_user]
all_users.extend(live_session.peer_users)
for user in all_users:
item_title = f"{user.user_name} ({user.from_app})"
if live_session.owner == user.user_name:
item_title += " - owner"
with ui.HStack():
build_live_session_user_layout(
user, self.__icon_size, "", self.__on_follow_user if self.__follow_user_with_double_click else None,
self.__on_mouse_clicked if self.__allow_timeline_settings else None
)
ui.Spacer(width=4)
ui.Label(item_title, style={"font_size": 14})
ui.Spacer(height=2)
@carb.profiler.profile
def __build_user_layout_or_overflow(
self, live_session: layers.LiveSession, user_info: layers.LiveSessionUser, me: bool, spacing=2
): # pragma: no cover
current_count = len(self.__all_user_layouts)
if self.__overflow:
return None
if self.__maximum_count is not None and current_count >= self.__maximum_count:
layout = ui.HStack(width=0)
with layout:
ui.Spacer(width=4)
with ui.ZStack():
ui.Label("...", style={"font_size": 16}, aligment=ui.Alignment.V_CENTER)
self.__overflow_button = ui.InvisibleButton(style=TOOLTIP_STYLE)
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
self.__overflow = True
else:
layout = self.__build_user_layout(live_session, user_info, me, spacing)
self.__all_user_layouts[user_info.user_id] = layout
self.__main_layout.visible = True
self.__overflow_button = None
return layout
| 15,529 | Python | 42.379888 | 130 | 0.57267 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_preferences.py | from .utils import QUICK_JOIN_ENABLED
from .utils import SESSION_LIST_SELECT, SESSION_LIST_SELECT_DEFAULT_SESSION, SESSION_LIST_SELECT_LAST_SESSION
import carb.settings
import omni.ui as ui
from omni.kit.widget.settings import SettingType
from omni.kit.window.preferences import PreferenceBuilder
class LiveSessionPreferences(PreferenceBuilder):
SETTING_PAGE_NAME = "Live"
def __init__(self):
super().__init__(LiveSessionPreferences.SETTING_PAGE_NAME)
self._settings = carb.settings.get_settings()
self._checkbox_quick_join_enabled = None
self._combobox_session_list_select = None
def destroy(self):
self._settings = None
self._checkbox_quick_join_enabled = None
self._combobox_session_list_select = None
def build(self):
self._checkbox_quick_join_enabled = None
self._combobox_session_list_select = None
with ui.VStack(height=0):
with self.add_frame("Join"):
with ui.VStack():
checkbox = self.create_setting_widget(
"Quick Join Enabled",
QUICK_JOIN_ENABLED,
SettingType.BOOL,
tooltip="Quick Join, creates and joins a Default session and bypasses dialogs."
)
self._checkbox_quick_join_enabled = checkbox
ui.Spacer()
combo = self.create_setting_widget_combo(
"Session List Select",
SESSION_LIST_SELECT,
[SESSION_LIST_SELECT_DEFAULT_SESSION, SESSION_LIST_SELECT_LAST_SESSION]
)
self._combobox_session_list_select = combo
ui.Spacer()
ui.Spacer(height=10)
| 1,823 | Python | 37.80851 | 109 | 0.582556 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/extension.py | __all__ = ["stop_or_show_live_session_widget", "LiveSessionWidgetExtension"]
import asyncio
import os
import carb
import omni.ext
import omni.kit.app
import omni.usd
import omni.client
import omni.ui as ui
import omni.kit.notification_manager as nm
import omni.kit.usd.layers as layers
import omni.kit.clipboard
from typing import Union
from enum import Enum
from omni.kit.widget.prompt import PromptButtonInfo, PromptManager
from .layer_icons import LayerIcons
from .live_session_start_window import LiveSessionStartWindow
from .live_session_end_window import LiveSessionEndWindow
from .utils import is_extension_loaded, join_live_session, is_viewer_only_mode, is_quick_join_enabled
from .join_with_session_link_window import JoinWithSessionLinkWindow
from .share_session_link_window import ShareSessionLinkWindow
from pxr import Sdf
from .live_style import Styles
_extension_instance = None
_debugCollaborationWindow = None
class LiveSessionMenuOptions(Enum):
QUIT_ONLY = 0
MERGE_AND_QUIT = 1
class LiveSessionWidgetExtension(omni.ext.IExt):
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
self._settings = None
LayerIcons.on_startup(extension_path)
self._live_session_end_window = None
self._live_session_start_window = None
self._join_with_session_link_window = None
self._share_session_link_window = None
self._live_session_menu = None
self._app = omni.kit.app.get_app()
try:
from omni.kit.window.preferences import register_page
from .live_session_preferences import LiveSessionPreferences
self._settings = register_page(LiveSessionPreferences())
except ImportError: # pragma: no cover
pass
Styles.on_startup()
def on_shutdown(self):
global _extension_instance
_extension_instance = None
self._live_session_menu = None
if self._live_session_end_window:
self._live_session_end_window.destroy()
self._live_session_end_window = None
if self._live_session_start_window:
self._live_session_start_window.destroy()
self._live_session_start_window = None
if self._join_with_session_link_window:
self._join_with_session_link_window.destroy()
self._join_with_session_link_window = None
if self._share_session_link_window:
self._share_session_link_window.destroy()
self._share_session_link_window = None
if self._settings:
try:
from omni.kit.window.preferences import unregister_page
unregister_page(self._settings)
except ImportError:
pass
self._settings = None
@staticmethod
def get_instance():
global _extension_instance
return _extension_instance
def _show_live_session_end_window(self, layers_interface: layers.Layers, layer_identifier):
if self._live_session_end_window:
self._live_session_end_window.destroy()
async def show_dialog():
self._live_session_end_window = LiveSessionEndWindow(layers_interface, layer_identifier)
async with self._live_session_end_window:
pass
asyncio.ensure_future(show_dialog())
def _show_join_with_session_link_window(self, layers_interface):
current_session_link = None
# Destroys it to center the window.
if self._join_with_session_link_window:
current_session_link = self._join_with_session_link_window.current_session_link
self._join_with_session_link_window.destroy()
self._join_with_session_link_window = JoinWithSessionLinkWindow(layers_interface)
self._join_with_session_link_window.visible = True
if current_session_link:
self._join_with_session_link_window.current_session_link = current_session_link
def _show_share_session_link_window(self, layers_interface, layer_identifier):
# Destroys it to center the window.
if self._share_session_link_window:
self._share_session_link_window.destroy()
self._share_session_link_window = ShareSessionLinkWindow(layers_interface, layer_identifier)
self._share_session_link_window.visible = True
def _show_live_session_menu_options(self, layers_interface, layer_identifier, is_stage_session, prim_path=None):
live_syncing = layers_interface.get_live_syncing()
current_session = live_syncing.get_current_live_session(layer_identifier)
self._live_session_menu = ui.Menu("global_live_update")
is_omniverse_stage = layer_identifier.startswith("omniverse://")
is_live_prim = prim_path or live_syncing.is_layer_in_live_session(layer_identifier, live_prim_only=True)
with self._live_session_menu:
if is_omniverse_stage:
if current_session:
# If layer is in the live session already, showing `leave` and `end and merge`
ui.MenuItem(
"Leave Session",
triggered_fn=lambda *args: self._on_leave_live_session_menu_options(
layers_interface, LiveSessionMenuOptions.QUIT_ONLY, layer_identifier
),
)
if not is_viewer_only_mode():
ui.MenuItem(
"End and Merge",
triggered_fn=lambda *args: self._on_leave_live_session_menu_options(
layers_interface, LiveSessionMenuOptions.MERGE_AND_QUIT, layer_identifier
),
)
ui.Separator()
else:
# If it's not in the live session, show `join` and `create`.
ui.MenuItem(
"Join Session",
triggered_fn=lambda *args: self._show_live_session_start_window(
layers_interface, layer_identifier, True, prim_path
),
)
ui.MenuItem(
"Create Session",
triggered_fn=lambda *args: self._show_live_session_start_window(
layers_interface, layer_identifier, False, prim_path
),
)
# Don't show those options for live prim
if not is_live_prim:
# If layer_identifier is given, it's to show menu options for sublayer.
# Show `copy` to copy session link. Otherwise, show share session dialog
# to choose session to share.
if is_stage_session:
ui.Separator()
ui.MenuItem(
"Share Session Link",
triggered_fn=lambda *args: self._show_share_session_link_window(
layers_interface, layer_identifier
),
)
elif current_session:
ui.Separator()
ui.MenuItem(
"Copy Session Link",
triggered_fn=lambda *args: self._copy_session_link(layers_interface),
)
# If layer identifier is gven, it will not show `join with session link` menu option.
if is_stage_session and not is_live_prim:
ui.MenuItem(
"Join With Session Link",
triggered_fn=lambda *args: self._show_join_with_session_link_window(layers_interface),
)
if is_extension_loaded("omni.kit.collaboration.debug_options"): # pragma: no cover
ui.Separator()
ui.MenuItem(
"Open Debug Window",
triggered_fn=lambda *args: self._on_open_debug_window(),
)
if is_omniverse_stage and current_session and is_extension_loaded("omni.timeline.live_session"):
ui.Separator()
import omni.timeline.live_session
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None:
session_window = omni.timeline.live_session.get_session_window()
ui.MenuItem(
"Synchronize Timeline",
triggered_fn=lambda *args: self._on_timeline_sync_triggered(
layers_interface, layer_identifier, timeline_session
),
checkable=True,
checked=timeline_session.is_sync_enabled()
)
if timeline_session.am_i_owner():
ui.MenuItem(
"Set Timeline Owner",
triggered_fn=lambda *args: self._on_open_timeline_session_window(
layers_interface, layer_identifier, timeline_session, session_window
),
)
elif not timeline_session.am_i_presenter():
if not self._requested_timeline_control(timeline_session):
ui.MenuItem(
"Request Timeline Ownership",
triggered_fn=lambda *args: self._on_request_timeline_control(timeline_session),
)
else:
ui.MenuItem(
"Withdraw Timeline Ownership Request",
triggered_fn=lambda *args: self._on_withdraw_timeline_control(timeline_session),
)
self._live_session_menu.show()
def _show_live_session_start_window(self, layers_interface, layer_identifier, join_session=None, prim_path=None):
if self._live_session_start_window:
self._live_session_start_window.destroy()
self._live_session_start_window = LiveSessionStartWindow(layers_interface, layer_identifier, prim_path)
self._live_session_start_window.visible = True
if join_session is not None:
self._live_session_start_window.set_focus(join_session)
def _show_session_start_window_or_menu(
self, layers_interface: layers.Layers, show_join_options, layer_identifier, is_stage_session, join_session=None, prim_path=None
):
if show_join_options:
return self._show_live_session_menu_options(
layers_interface, layer_identifier, is_stage_session, prim_path
)
else:
self._show_live_session_start_window(layers_interface, layer_identifier, join_session, prim_path)
return None
def _requested_timeline_control(self, timeline_session) -> bool:
return timeline_session is not None and\
timeline_session.live_session_user in timeline_session.get_request_controls()
def _on_request_timeline_control(self, timeline_session):
if timeline_session is not None:
timeline_session.request_control(True)
def _on_withdraw_timeline_control(self, timeline_session):
if timeline_session is not None:
timeline_session.request_control(False)
def _on_timeline_sync_triggered(
self, layers_interface: layers.Layers,
layer_identifier: str,
timeline_session
):
timeline_session.enable_sync(not timeline_session.is_sync_enabled())
def _on_open_timeline_session_window(
self, layers_interface: layers.Layers,
layer_identifier: str,
timeline_session,
session_window,
):
session_window.show()
def _on_open_debug_window(
self,
): # pragma: no cover
import omni.kit.collaboration.debug_options
from omni.kit.collaboration.debug_options import CollaborationWindow
global _debugCollaborationWindow
if _debugCollaborationWindow is None :
_debugCollaborationWindow = CollaborationWindow(width=480, height=320)
_debugCollaborationWindow.visible = True
def _on_leave_live_session_menu_options(
self, layers_interface: layers.Layers,
options: LiveSessionMenuOptions,
layer_identifier: str,
):
live_syncing = layers_interface.get_live_syncing()
current_session = live_syncing.get_current_live_session(layer_identifier)
if current_session:
if options == LiveSessionMenuOptions.QUIT_ONLY:
if self._can_quit_session_directly(live_syncing, layer_identifier):
live_syncing.stop_live_session(layer_identifier)
else:
PromptManager.post_simple_prompt(
"Leave Session",
f"You are about to leave '{current_session.name}' session.",
PromptButtonInfo("LEAVE", lambda: live_syncing.stop_live_session(layer_identifier)),
PromptButtonInfo("CANCEL")
)
elif options == LiveSessionMenuOptions.MERGE_AND_QUIT:
layers_state = layers_interface.get_layers_state()
is_read_only_on_disk = layers_state.is_layer_readonly_on_disk(layer_identifier)
if current_session.merge_permission and not is_read_only_on_disk:
self._show_live_session_end_window(layers_interface, layer_identifier)
else:
if is_read_only_on_disk:
owner = layers_state.get_layer_owner(layer_identifier)
else:
owner = current_session.owner
logged_user_name = current_session.logged_user_name
if logged_user_name == owner and current_session.merge_permission:
message = f"You currently do not have merge privileges as base layer is read-only on disk."\
" Do you want to quit this live session?"
else:
if is_read_only_on_disk:
message = f"You currently do not have merge privileges as base layer is read-only on disk."\
f" Please contact '{owner}' to grant you write access. Do you want to quit this live session?"
else:
message = f"You currently do not have merge privileges, please contact '{owner}'"\
" to merge any changes from the live session. Do you want to quit this live session?"
PromptManager.post_simple_prompt(
"Permission Denied",
message,
PromptButtonInfo("YES", lambda: live_syncing.stop_live_session(layer_identifier)),
PromptButtonInfo("NO")
)
def _can_quit_session_directly(self, live_syncing: layers.LiveSyncing, layer_identifier):
current_live_session = live_syncing.get_current_live_session(layer_identifier)
if current_live_session:
if current_live_session.peer_users:
return False
layer = Sdf.Find(current_live_session.root)
if layer and len(layer.rootPrims) > 0:
return False
return True
def _copy_session_link(self, layers_interface):
live_syncing = layers_interface.get_live_syncing()
current_session = live_syncing.get_current_live_session()
if not current_session:
return
omni.kit.clipboard.copy(current_session.shared_link)
def _stop_or_show_live_session_widget_internal(
self, layers_interface: layers.Layers,
stop_session_only,
stop_session_forcely,
show_join_options,
layer_identifier,
quick_join="",
prim_path=None
):
usd_context = layers_interface.usd_context
stage = usd_context.get_stage()
# Skips it if stage is not opened.
if not stage:
return None
# By default, it will join live session of tht root layer.
if not layer_identifier:
# If layer identifier is not provided, it's to show global
# menu that includes share sesison link and join session with link.
# Otherwise, it will show menu for the sublayer session only.
is_stage_session = True
root_layer = stage.GetRootLayer()
layer_identifier = root_layer.identifier
else:
is_stage_session = False
layer_handle = Sdf.Find(layer_identifier)
if (
not layer_handle or
(not prim_path and not stage.HasLocalLayer(layer_handle)) or
(prim_path and layer_handle not in stage.GetUsedLayers())
):
nm.post_notification(
"Only a layer opened in the current stage can start a live-sync session.",
status=nm.NotificationStatus.WARNING
)
return None
if not layer_identifier.startswith("omniverse://"):
if is_stage_session and not prim_path:
return self._show_live_session_menu_options(layers_interface, layer_identifier, is_stage_session)
else:
nm.post_notification(
"Only a layer in Nucleus can start a live-sync session.",
status=nm.NotificationStatus.WARNING
)
return None
live_syncing = layers_interface.get_live_syncing()
if not live_syncing.is_layer_in_live_session(layer_identifier):
if not quick_join and not show_join_options:
quick_join = "Default"
elif quick_join and show_join_options:
show_join_options = False
if quick_join:
# This runs when the main live button is pressed.
live_syncing = layers_interface.get_live_syncing()
quick_session = live_syncing.find_live_session_by_name(layer_identifier, quick_join)
if is_quick_join_enabled():
if not quick_session:
quick_session = live_syncing.create_live_session(
layer_identifier=layer_identifier,
name=quick_join
)
if not quick_session:
nm.post_notification(
"Cannot create a Live session on a read only location. Please\n"
"save root file in a writable location.",
status=nm.NotificationStatus.WARNING
)
return None
join_live_session(
layers_interface, layer_identifier, quick_session, prim_path,
is_viewer_only_mode()
)
return None
else:
join_session = True if quick_session is not None else False
return self._show_session_start_window_or_menu(
layers_interface, False, layer_identifier, False, join_session, prim_path
)
else:
return self._show_session_start_window_or_menu(
layers_interface, show_join_options, layer_identifier, is_stage_session, prim_path
)
elif stop_session_forcely:
live_syncing.stop_live_session(layer_identifier)
elif stop_session_only:
self._on_leave_live_session_menu_options(
layers_interface, LiveSessionMenuOptions.QUIT_ONLY, layer_identifier
)
else:
return self._show_live_session_menu_options(layers_interface, layer_identifier, is_stage_session, prim_path)
return None
def stop_or_show_live_session_widget(
usd_context: Union[str, omni.usd.UsdContext] = "",
stop_session_only: bool = False,
stop_session_forcely: bool = False,
show_join_options: bool = True,
layer_identifier: str = None,
quick_join: str = False,
prim_path: Union[str, Sdf.Path] = None,
):
"""Stops current live session or shows widget to join/leave session. If current session is empty, it will show
the session start dialog. If current session is not empty, it will stop session directly or show stop session menu.
Args:
usd_context: The current usd context to operate on.
stop_session_only: If it's true, it will ask user to stop session if session is not empty without showing merge options.
If it's false, it will show both leave and merge session options.
stop_session_forcely: If it's true, it will stop session forcely even if current sesison is not empty.
Otherwise, it will show leave session or both leave and merge options that's dependent on
if stop_session_only is true or false.
show_join_options: If it's true, it will show menu options.
If it's false, it will show session dialog directly.
This option is only used when layer is not in a live session. If both quick_join and
this param have the same value, it will do quick join.
layer_identifier: By default, it will join/stop the live session of the root layer.
If layer_identifier is not None, it will join/stop the live session for the specific sublayer.
quick_join: Quick Join / Leave a session without bringing up a dialog.
This option is only used when layer is not in a live session. If both show_join_options and
this param have the same value, this param will be True.
prim_path: If prim path is specified, it will join live session for the prim instead of sublayers. Only prim with
references or payloads supports to join a live session. Prim path is not needed when it's to
stop a live session.
Returns:
It will return the menu widgets created if it needs to create options menu. Otherwise, it will return None.
"""
instance = LiveSessionWidgetExtension.get_instance()
if not instance: # pragma: no cover
carb.log_error("omni.kit.widget.live_session_management extension must be enabled.")
return
layers_interface = layers.get_layers(usd_context)
return instance._stop_or_show_live_session_widget_internal(
layers_interface,
stop_session_only,
stop_session_forcely,
show_join_options,
layer_identifier,
quick_join=quick_join,
prim_path=prim_path
)
| 23,531 | Python | 44.34104 | 135 | 0.576984 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/__init__.py | from .extension import *
from .utils import *
from .live_session_user_list import *
from .live_session_model import *
from .live_session_camera_follower_list import * | 166 | Python | 32.399994 | 48 | 0.771084 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/file_picker.py | import omni
import carb
import os
import omni.client
import omni.kit.notification_manager as nm
from omni.kit.widget.prompt import PromptButtonInfo, PromptManager
from .filebrowser import FileBrowserMode, FileBrowserSelectionType, FileBrowserUI
class FilePicker:
def __init__(self, title, mode, file_type, filter_options, save_extensions=None):
self._mode = mode
self._ui_handler = None
self._app = omni.kit.app.get_app()
self._open_handler = None
self._cancel_handler = None
self._save_extensions = save_extensions
self._ui_handler = FileBrowserUI(
title, mode, file_type, filter_options, enable_versioning_pane=(mode == FileBrowserMode.OPEN)
)
def _show_prompt(self, file_path, file_save_handler):
def _on_file_save():
if file_save_handler:
file_save_handler(file_path, True)
PromptManager.post_simple_prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Overwrite',
f"File {os.path.basename(file_path)} already exists, do you want to overwrite it?",
ok_button_info=PromptButtonInfo("YES", _on_file_save),
cancel_button_info=PromptButtonInfo("NO")
)
def _save_and_prompt_if_exists(self, file_path, file_save_handler=None):
result, _ = omni.client.stat(file_path)
if result == omni.client.Result.OK:
self._show_prompt(file_path, file_save_handler)
elif file_save_handler:
file_save_handler(file_path, False)
def _on_file_open(self, path, filter_index=-1):
if self._mode == FileBrowserMode.SAVE:
_, ext = os.path.splitext(path)
if (
filter_index >= 0
and self._save_extensions
and filter_index < len(self._save_extensions)
and ext not in self._save_extensions
):
path += self._save_extensions[filter_index]
self._save_and_prompt_if_exists(path, self._open_handler)
elif self._open_handler:
self._open_handler(path, False)
def _on_cancel_open(self):
if self._cancel_handler:
self._cancel_handler()
def set_file_selected_fn(self, file_open_handler):
self._open_handler = file_open_handler
def set_cancel_fn(self, cancel_handler):
self._cancel_handler = cancel_handler
def show(self, dir=None, filename=None):
if self._ui_handler:
if dir:
self._ui_handler.set_current_directory(dir)
if filename:
self._ui_handler.set_current_filename(filename)
self._ui_handler.open(self._on_file_open, self._on_cancel_open)
def hide(self):
if self._ui_handler:
self._ui_handler.hide()
def set_current_directory(self, dir):
if self._ui_handler:
self._ui_handler.set_current_directory(dir)
def set_current_filename(self, filename):
if self._ui_handler:
self._ui_handler.set_current_filename(filename)
def get_current_filename(self):
if self._ui_handler:
return self._ui_handler.get_current_filename()
return None
def destroy(self):
if self._ui_handler:
self._ui_handler.destroy()
self._ui_handler = None
| 3,413 | Python | 33.836734 | 105 | 0.600938 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/utils.py | __all__ = ["build_live_session_user_layout", "is_viewer_only_mode", "VIEWER_ONLY_MODE_SETTING"]
import asyncio
import carb
import os
import omni.usd
import omni.kit.app
import omni.ui as ui
import omni.kit.usd.layers as layers
from omni.kit.async_engine import run_coroutine
from omni.kit.widget.prompt import PromptManager, PromptButtonInfo
from pxr import Sdf
from typing import Union, List
# When this setting is True, it will following the rules:
# * When joining a live session, if the user has unsaved changes,
# skip the dialog and automatically reload the stage, then join the session.
# * When creating a live session, if the user has unsaved changes,
# skip the dialog and automatically reload the stage, then create the session.
# * When leaving a live session, do not offer to merge changes,
# instead reload the stage to its original state
VIEWER_ONLY_MODE_SETTING = "/exts/omni.kit.widget.live_session_management/viewer_only_mode"
# When this setting is True, it will show the Join/Create Session dialog wqhen the quick live button is pressed.
# When this setting if False, it will auto Create Session or Join with no dialog shown.
QUICK_JOIN_ENABLED = "/exts/omni.kit.widget.live_session_management/quick_join_enabled"
SESSION_LIST_SELECT = "/exts/omni.kit.widget.live_session_management/session_list_select"
SESSION_LIST_SELECT_DEFAULT_SESSION = "DefaultSession"
SESSION_LIST_SELECT_LAST_SESSION = "LastSession"
def is_viewer_only_mode():
return carb.settings.get_settings().get(VIEWER_ONLY_MODE_SETTING) or False
def is_quick_join_enabled():
return carb.settings.get_settings().get(QUICK_JOIN_ENABLED) or False
def get_session_list_select():
return carb.settings.get_settings().get(SESSION_LIST_SELECT)
def join_live_session(layers_interface, layer_identifier, current_session, prim_path=None, force_reload=False):
layers_state = layers_interface.get_layers_state()
live_syncing = layers_interface.get_live_syncing()
layer_handle = Sdf.Find(layer_identifier)
def fetch_and_join(layer_identifier):
with Sdf.ChangeBlock():
layer = Sdf.Find(layer_identifier)
if layer:
layer.Reload(True)
if layers_state.is_auto_reload_layer(layer_identifier):
layers_state.remove_auto_reload_layer(layer_identifier)
return live_syncing.join_live_session(current_session, prim_path)
async def post_simple_prompt(title, text, ok_button_info, cancel_button_info):
await omni.kit.app.get_app().next_update_async()
PromptManager.post_simple_prompt(
title, text,
ok_button_info=ok_button_info,
cancel_button_info=cancel_button_info
)
is_outdated = layers_state.is_layer_outdated(layer_identifier)
if force_reload and (is_outdated or layer_handle.dirty):
fetch_and_join(layer_identifier)
elif is_outdated:
asyncio.ensure_future(
post_simple_prompt(
"Join Session",
"The file you would like to go live on is not up to date, "
"a newer version must be fetched for joining a live session. "
"Press Fetch to get the most recent version or use Cancel "
"if you would like to save a copy first.",
ok_button_info=PromptButtonInfo(
"Fetch",
lambda: fetch_and_join(layer_identifier)
),
cancel_button_info=PromptButtonInfo("Cancel")
)
)
elif layer_handle.dirty:
asyncio.ensure_future(
post_simple_prompt(
"Join Session",
"There are unsaved changes to your file. Joining this live session will discard any unsaved changes.",
ok_button_info=PromptButtonInfo(
"Join",
lambda: fetch_and_join(layer_identifier)
),
cancel_button_info=PromptButtonInfo("Cancel")
)
)
else:
if layers_state.is_auto_reload_layer(layer_identifier):
layers_state.remove_auto_reload_layer(layer_identifier)
return live_syncing.join_live_session(current_session, prim_path)
return True
def is_extension_loaded(extansion_name: str) -> bool:
"""
Returns True if the extension with the given name is loaded.
"""
def is_ext(id: str, extension_name: str) -> bool:
id_name = id.split("-")[0]
return id_name == extension_name
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
extensions = ext_manager.get_extensions()
loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None)
return not not loaded
def build_live_session_user_layout(user_info: layers.LiveSessionUser, size=16, tooltip = "", on_double_click_fn: callable = None, on_mouse_click_fn: callable = None) -> ui.ZStack:
"""Builds user icon."""
user_layout = ui.ZStack(width=size, height=size)
with user_layout:
circle = ui.Circle(
style={"background_color": ui.color(*user_info.user_color)}
)
if on_double_click_fn:
circle.set_mouse_double_clicked_fn(lambda x, y, b, m, user_info_t=user_info: on_double_click_fn( x, y, b, m, user_info_t))
if on_mouse_click_fn:
circle.set_mouse_pressed_fn(lambda x, y, b, m, user_info_t=user_info: on_mouse_click_fn( x, y, b, m, user_info_t))
ui.Label(
layers.get_short_user_name(user_info.user_name), style={"font_size": size - 5, "color": 0xFFFFFFFF},
alignment=ui.Alignment.CENTER
)
if tooltip:
user_layout.set_tooltip(tooltip)
return user_layout
def reload_outdated_layers(
layer_identifiers: Union[str, List[str]], usd_context_name_or_instance: Union[str, omni.usd.UsdContext] = None
) -> None:
"""Reloads outdated layer. It will show prompt to user if layer is in a Live Session."""
if isinstance(usd_context_name_or_instance, str):
usd_context = omni.usd.get_context(usd_context_name_or_instance)
elif isinstance(usd_context_name_or_instance, omni.usd.UsdContext):
usd_context = usd_context_name_or_instance
elif not usd_context_name_or_instance:
usd_context = omni.usd.get_context()
if not usd_context:
carb.log_error("Failed to reload layer as usd context is not invalid.")
return
if isinstance(layer_identifiers, str):
layer_identifiers = [layer_identifiers]
live_syncing = layers.get_live_syncing(usd_context)
layers_state = layers.get_layers_state(usd_context)
all_layer_ids = layers_state.get_all_outdated_layer_identifiers()
if not all_layer_ids:
return
layer_identifiers = [layer_id for layer_id in layer_identifiers if layer_id in all_layer_ids]
if not layer_identifiers:
return
count = 0
for layer_identifier in layer_identifiers:
if live_syncing.is_layer_in_live_session(layer_identifier):
count += 1
if count == 1:
title = f"{os.path.basename(layer_identifier)} is in a Live Session"
else:
title = "Reload Layers In Live Session"
def reload_layers(layer_identifiers):
async def reload(layer_identifiers):
layers.LayerUtils.reload_all_layers(layer_identifiers)
run_coroutine(reload(layer_identifiers))
if count != 0:
PromptManager.post_simple_prompt(
title,
"Reloading live layers has performance implications and some live edits may be lost - OK to proceed?",
PromptButtonInfo("YES", lambda: reload_layers(layer_identifiers)),
PromptButtonInfo("NO")
)
else:
reload_layers(layer_identifiers)
| 7,853 | Python | 36.4 | 179 | 0.657328 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/join_with_session_link_window.py | __all__ = ["JoinWithSessionLinkWindow"]
import asyncio
import carb
import omni.kit.usd.layers as layers
import omni.ui as ui
import omni.kit.notification_manager as nm
import omni.kit.app
import omni.kit.clipboard
from pxr import Usd
from .layer_icons import LayerIcons
class JoinWithSessionLinkWindow:
def __init__(self, layers_interface: layers.Layers):
self._window = None
self._layers_interface = layers_interface
self._buttons = []
self._session_link_input_field = None
self._session_link_input_hint = None
self._error_label = None
self._session_link_begin_edit_cb = None
self._session_link_end_edit_cb = None
self._session_link_edit_cb = None
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def destroy(self):
self._layers_interface = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
if self._window:
self._window.visible = False
self._window = None
self._session_link_input_hint = None
self._session_link_input_field = None
self._session_link_begin_edit_cb = None
self._session_link_end_edit_cb = None
self._session_link_edit_cb = None
self._error_label = None
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
if value:
async def focus_field():
await omni.kit.app.get_app().next_update_async()
if self._session_link_input_field:
self._session_link_input_field.focus_keyboard()
asyncio.ensure_future(focus_field())
@property
def current_session_link(self):
if self._session_link_input_field:
return self._session_link_input_field.model.get_value_as_string()
return ""
@current_session_link.setter
def current_session_link(self, value):
if self._session_link_input_field:
self._session_link_input_field.model.set_value(value)
def _validate_session_link(self, str):
return str and Usd.Stage.IsSupportedFile(str)
def _on_ok_button_fn(self):
if not self._update_button_status():
return
self._error_label.text = ""
self.visible = False
session_link = self._session_link_input_field.model.get_value_as_string()
session_link = session_link.strip()
live_syncing = self._layers_interface.get_live_syncing()
async def open_stage_with_live_session(live_syncing, session_link):
(success, error) = await live_syncing.open_stage_with_live_session_async(session_link)
if not success:
nm.post_notification(f"Failed to open stage {session_link} with live session: {error}.")
asyncio.ensure_future(open_stage_with_live_session(live_syncing, session_link))
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _update_button_status(self):
if not self._session_link_input_field:
return False
session_link = self._session_link_input_field.model.get_value_as_string()
session_link = session_link.strip()
join_button = self._buttons[0]
if not self._validate_session_link(session_link):
if session_link:
self._error_label.text = "The link is not supported for USD."
else:
self._error_label.text = ""
join_button.enabled = False
else:
self._error_label.text = ""
join_button.enabled = True
if not session_link:
self._session_link_input_hint.visible = True
else:
self._session_link_input_hint.visible = False
return join_button.enabled
def _on_session_link_begin_edit(self, model):
self._update_button_status()
def _on_session_link_end_edit(self, model):
self._update_button_status()
def _on_session_link_edit(self, model):
self._update_button_status()
def _on_paste_link_fn(self):
link = omni.kit.clipboard.paste()
if link:
self._session_link_input_field.model.set_value(link)
def _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window(
"JOIN LIVE SESSION WITH LINK", visible=False, width=500, height=0,
auto_resize=True, dockPreference=ui.DockPreference.DISABLED
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
STYLES = {
"Rectangle::hovering": {"background_color": 0x0, "border_radius": 2, "margin": 0, "padding": 0},
"Rectangle::hovering:hovered": {"background_color": 0xFF9E9E9E},
"Button.Image::paste_button": {"image_url": LayerIcons().get("paste"), "color": 0xFFD0D0D0},
"Button::paste_button": {"background_color": 0x0, "margin": 0},
"Button::paste_button:checked": {"background_color": 0x0},
"Button::paste_button:hovered": {"background_color": 0x0},
"Button::paste_button:pressed": {"background_color": 0x0},
}
with self._window.frame:
with ui.VStack(height=0, style=STYLES):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(width=20)
self._error_label = ui.Label("", name="error_label", style={"color": 0xFF0000CC}, alignment=ui.Alignment.LEFT, word_wrap=True)
ui.Spacer(width=20)
ui.Spacer(width=0, height=5)
with ui.ZStack(height=0):
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(width=20, height=20):
ui.Rectangle(name="hovering")
paste_link_button = ui.ToolButton(name="paste_button", image_width=20, image_height=20)
paste_link_button.set_clicked_fn(self._on_paste_link_fn)
ui.Spacer(width=4)
with ui.VStack():
ui.Spacer()
with ui.ZStack(height=0):
self._session_link_input_field = ui.StringField(
name="new_session_link_field", width=self._window.width - 40, height=0
)
self._session_link_input_hint = ui.Label(
" Paste Live Session Link Here", alignment=ui.Alignment.LEFT_CENTER,
style={"color": 0xFF3F3F3F}
)
self._session_link_begin_edit_cb = self._session_link_input_field.model.subscribe_begin_edit_fn(
self._on_session_link_begin_edit
)
self._session_link_end_edit_cb = self._session_link_input_field.model.subscribe_end_edit_fn(
self._on_session_link_end_edit
)
self._session_link_edit_cb = self._session_link_input_field.model.subscribe_value_changed_fn(
self._on_session_link_edit
)
ui.Spacer()
ui.Spacer(width=20)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer(height=0)
ok_button = ui.Button("JOIN", name="confirm_button", width=120, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
cancel_button = ui.Button("CANCEL", name="cancel_button", width=120, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(ok_button)
self._buttons.append(cancel_button)
ui.Spacer(height=0, width=20)
ui.Spacer(width=0, height=20)
# 0 for ok button, 0 for cancel button and appends paste link button at last
self._buttons.append(paste_link_button)
self._update_button_status()
| 9,226 | Python | 40.008889 | 146 | 0.54574 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/reload_widget.py | __all__ = ["build_reload_widget"]
import carb
import omni.usd
import omni.kit.app
import omni.ui as ui
import omni.kit.usd.layers as layers
import weakref
from functools import partial
from typing import Union
from .live_style import Styles
from .layer_icons import LayerIcons
from .utils import reload_outdated_layers
from omni.kit.async_engine import run_coroutine
class ReloadWidgetWrapper(ui.ZStack):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.auto_reload_menu = None
def __del__(self):
if self.auto_reload_menu:
self.auto_reload_menu.hide()
self.auto_reload_menu = None
def show_reload_menu(layer_identifier, usd_context, widget, button, global_auto):
"""Creates and shows a reload menu relative to widget position"""
layers_state = layers.get_layers_state(usd_context)
live_syncing = layers.get_live_syncing()
is_outdated = layers_state.is_layer_outdated(layer_identifier)
in_session = live_syncing.is_layer_in_live_session(layer_identifier)
def toggle_auto_reload(layer_identifier, widget):
async def toggle(layer_identifier):
is_auto = layers_state.is_auto_reload_layer(layer_identifier)
if not is_auto:
layers_state.add_auto_reload_layer(layer_identifier)
widget.set_style(Styles.RELOAD_AUTO)
button.tooltip = "Auto Reload Enabled"
else:
layers_state.remove_auto_reload_layer(layer_identifier)
widget.set_style(Styles.RELOAD_BTN)
button.tooltip = "Reload"
run_coroutine(toggle(layer_identifier))
def reload_layer(layer_identifier):
reload_outdated_layers(layer_identifier, layers_state._usd_context)
auto_reload_menu = ui.Menu("auto_reload_menu")
with auto_reload_menu:
ui.MenuItem(
"Reload Layer",
triggered_fn=lambda *args: reload_layer(layer_identifier),
enabled=is_outdated,
visible=not global_auto
)
ui.MenuItem(
"Auto Reload",
triggered_fn=lambda *args: toggle_auto_reload(layer_identifier, widget),
checkable=True,
checked=layers_state.is_auto_reload_layer(layer_identifier),
visible=not global_auto,
enabled=not in_session
)
_x = widget.screen_position_x
_y = widget.screen_position_y
_h = widget.computed_height
auto_reload_menu.show_at(_x - 95, _y + _h / 2 + 2)
return auto_reload_menu
def build_reload_widget(
layer_identifier: str,
usd_context_name_or_instance: Union[str, omni.usd.UsdContext] = None,
is_outdated=False,
is_auto=False,
global_auto=False
) -> None:
"""Builds reload widget."""
if isinstance(usd_context_name_or_instance, str):
usd_context = omni.usd.get_context(usd_context_name_or_instance)
elif isinstance(usd_context_name_or_instance, omni.usd.UsdContext):
usd_context = usd_context_name_or_instance
elif not usd_context_name_or_instance:
usd_context = omni.usd.get_context()
if not usd_context:
carb.log_error("Failed to reload layer as usd context is not invalid.")
return
reload_stack = ReloadWidgetWrapper(width=0, height=0)
if global_auto:
is_auto = global_auto
reload_stack.name = "reload-auto" if is_auto else "reload-outd" if is_outdated else "reload"
reload_stack.set_style(Styles.RELOAD_AUTO if is_auto and not is_outdated else Styles.RELOAD_OTD if is_outdated else Styles.RELOAD_BTN)
with reload_stack:
with ui.VStack(width=0, height=0):
ui.Spacer(width=22, height=12)
with ui.HStack(width=0):
ui.Spacer(width=16)
ui.Image(
LayerIcons.get("drop_down"),
width=6, height=6, alignment=ui.Alignment.RIGHT_BOTTOM,
name="drop_down"
)
ui.Image(LayerIcons.get("reload"), width=20, name="reload")
tooltip = "Auto Reload All Enabled" if global_auto else "Auto Reload Enabled" if is_auto else "Reload"
if is_outdated:
tooltip = "Reload Outdated"
reload_button = ui.InvisibleButton(width=20, tooltip=tooltip)
def on_reload_clicked(layout_weakref, x, y, b, m):
if (b == 0):
reload_outdated_layers(layer_identifier, usd_context)
return
auto_reload_menu = show_reload_menu(layer_identifier, usd_context, reload_stack, reload_button, global_auto)
if layout_weakref():
# Hold the menu handle to release it along with the stack.
layout_weakref().auto_reload_menu = auto_reload_menu
layout_weakref = weakref.ref(reload_stack)
reload_button.set_mouse_pressed_fn(partial(on_reload_clicked, layout_weakref))
return reload_stack
| 4,919 | Python | 34.142857 | 138 | 0.639561 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_start_window.py | import asyncio
import carb
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.ui as ui
import re
from .layer_icons import LayerIcons
from .utils import join_live_session, is_viewer_only_mode, get_session_list_select, SESSION_LIST_SELECT_DEFAULT_SESSION
from omni.kit.widget.prompt import PromptButtonInfo, PromptManager
from pxr import Sdf
from .live_session_model import LiveSessionModel
class LiveSessionStartWindow:
def __init__(self, layers_interface: layers.Layers, layer_identifier, prim_path):
self._window = None
self._layers_interface = layers_interface
self._base_layer_identifier = layer_identifier
self._live_prim_path = prim_path
self._buttons = []
self._existing_sessions_combo = None
self._session_name_input_field = None
self._session_name_input_hint = None
self._error_label = None
self._session_name_begin_edit_cb = None
self._session_name_end_edit_cb = None
self._session_name_edit_cb = None
self._existing_sessions_model = LiveSessionModel(self._layers_interface, layer_identifier)
self._participants_list = None
self._participants_layout = None
self._existing_sessions_model.set_user_update_callback(self._on_channel_users_update)
self._existing_sessions_model.add_value_changed(self._on_session_list_changed)
self._update_user_list_task: asyncio.Future = None
self._join_create_radios = None
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def _on_layer_event(event: carb.events.IEvent):
payload = layers.get_layer_event_payload(event)
if payload.event_type == layers.LayerEventType.LIVE_SESSION_LIST_CHANGED:
if self._base_layer_identifier not in payload.identifiers_or_spec_paths:
return
self._existing_sessions_model.refresh_sessions(force=True)
self._update_dialog_states()
self._layers_event_subscription = layers_interface.get_event_stream().create_subscription_to_pop(
_on_layer_event, name="Session Start Window Events"
)
def destroy(self):
self._layers_interface = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
self._participants_list = None
if self._window:
self._window.visible = False
self._window = None
if self._existing_sessions_model:
self._existing_sessions_model.set_user_update_callback(None)
self._existing_sessions_model.destroy()
self._existing_sessions_model = None
self._participants_layout = None
self._layers_event_subscription = None
self._existing_sessions_combo = None
self._existing_sessions_empty_hint = None
self._join_create_radios = None
self._session_name_input_hint = None
self._session_name_input_field = None
self._session_name_begin_edit_cb = None
self._session_name_end_edit_cb = None
self._session_name_edit_cb = None
self._error_label = None
if self._update_user_list_task:
try:
self._update_user_list_task.cancel()
except Exception:
pass
self._update_user_list_task = None
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
if not self._window.visible:
if self._update_user_list_task:
try:
self._update_user_list_task.cancel()
except Exception:
pass
self._update_user_list_task = None
self._existing_sessions_model.stop_channel()
def set_focus(self, join_session):
if not self._join_create_radios:
return
if join_session:
self._join_create_radios.model.set_value(0)
if get_session_list_select() == SESSION_LIST_SELECT_DEFAULT_SESSION:
self._existing_sessions_model.select_default_session()
else:
self._join_create_radios.model.set_value(1)
async def async_focus_keyboard():
await omni.kit.app.get_app().next_update_async()
self._session_name_input_field.focus_keyboard()
omni.kit.async_engine.run_coroutine(async_focus_keyboard())
def _on_channel_users_update(self):
async def _update_users():
all_users = self._existing_sessions_model.all_users
current_session = self._existing_sessions_model.current_session
if not current_session:
return
self._participants_list.clear()
with self._participants_list:
if len(all_users) > 0:
for _, user in all_users.items():
is_owner = current_session.owner == user.user_name
with ui.VStack(height=0):
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=10)
if is_owner:
ui.Label(f"{user.user_name} - {user.from_app} (owner)", style={"color": 0xFF808080})
else:
ui.Label(f"{user.user_name} - {user.from_app}", style={"color": 0xFF808080})
else:
self._build_empty_participants_list()
if not self._update_user_list_task or self._update_user_list_task.done():
self._update_user_list_task = asyncio.ensure_future(_update_users())
def _validate_session_name(self, str):
if re.match(r'^[a-zA-Z][a-zA-Z0-9-_]*$', str):
return True
return False
def _on_join_session(self, current_session):
layer_identifier = self._base_layer_identifier
layers_interface = self._layers_interface
prim_path = self._live_prim_path
return join_live_session(
layers_interface, layer_identifier, current_session, prim_path, is_viewer_only_mode()
)
def _on_ok_button_fn(self): # pragma: no cover
live_syncing = self._layers_interface.get_live_syncing()
current_option = self._join_create_radios.model.as_int
join_session = current_option == 0
if join_session:
current_session = self._existing_sessions_model.current_session
if not current_session:
self._error_label.text = "No Valid Session Selected"
self._error_label.visible = True
elif self._on_join_session(current_session):
self._error_label.text = ""
self._error_label.visible = False
self.visible = False
else:
self._error_label.text = "Failed to join session, please check console for more details."
self._error_label.visible = True
else:
session_name = self._session_name_input_field.model.get_value_as_string()
session_name = session_name.strip()
if not session_name or not self._validate_session_name(session_name):
self._update_button_status(session_name)
self._error_label.text = "Session name must be given."
self._error_label.visible = True
else:
session = live_syncing.create_live_session(layer_identifier=self._base_layer_identifier, name=session_name)
if not session:
self._error_label.text = "Failed to create session, please check console for more details."
self._error_label.visible = True
elif not self._on_join_session(session):
self._error_label.text = "Failed to join session, please check console for more details."
self._error_label.visible = True
else:
self._error_label.text = ""
self._error_label.visible = False
self.visible = False
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _build_option_checkbox(self, name, text, default_value, tooltip=""): # pragma: no cover
with ui.HStack(height=0, width=0):
checkbox = ui.CheckBox(width=20, name=name)
checkbox.model.set_value(default_value)
label = ui.Label(text, alignment=ui.Alignment.LEFT)
if tooltip:
label.set_tooltip(tooltip)
return checkbox, label
def _build_option_radio(self, collection, name, text, tooltip=""):
style = {
"": {"background_color": 0x0, "image_url": LayerIcons.get("radio_off")},
":checked": {"image_url": LayerIcons.get("radio_on")},
}
with ui.HStack(height=0, width=0):
radio = ui.RadioButton(radio_collection=collection, width=28, height=28, name=name, style=style)
ui.Spacer(width=4)
label = ui.Label(text, alignment=ui.Alignment.LEFT_CENTER)
if tooltip:
label.set_tooltip(tooltip)
return radio
def _update_button_status(self, session_name):
join_button = self._buttons[0]
if session_name and not self._validate_session_name(session_name):
if not str.isalpha(session_name[0]):
self._error_label.text = "Session name must be prefixed with letters."
else:
self._error_label.text = "Only alphanumeric letters, hyphens, or underscores are supported."
self._error_label.visible = True
join_button.enabled = False
else:
self._error_label.text = ""
self._error_label.visible = False
join_button.enabled = True
def _on_session_name_begin_edit(self, model):
self._session_name_input_hint.visible = False
session_name = model.get_value_as_string().strip()
self._update_button_status(session_name)
def _on_session_name_end_edit(self, model):
if len(model.get_value_as_string()) == 0:
self._session_name_input_hint.visible = True
session_name = model.get_value_as_string().strip()
self._update_button_status(session_name)
def _on_session_name_edit(self, model):
session_name = model.get_value_as_string().strip()
self._update_button_status(session_name)
def _update_dialog_states(self):
self._error_label.text = ""
current_option = self._join_create_radios.model.as_int
show_join_session = current_option == 0
join_button = self._buttons[0]
if show_join_session:
self._existing_sessions_combo.visible = True
self._session_name_input_field.visible = False
self._session_name_input_hint.visible = False
self._participants_layout.visible = True
self._existing_sessions_model.refresh_sessions()
if self._existing_sessions_model.empty():
self._existing_sessions_empty_hint.visible = True
else:
self._existing_sessions_empty_hint.visible = False
join_button.text = "JOIN"
else:
self._participants_layout.visible = False
self._existing_sessions_combo.visible = False
self._session_name_input_field.visible = True
self._session_name_input_hint.visible = False
self._existing_sessions_empty_hint.visible = False
self._existing_sessions_model.clear()
join_button.text = "CREATE"
new_session_name = self._existing_sessions_model.create_new_session_name()
self._session_name_input_field.model.set_value(new_session_name)
self._session_name_input_field.focus_keyboard()
def _on_radios_changed_fn(self, model):
self._update_dialog_states()
self._on_checkbox_changed_called = False
def _on_session_list_changed(self, model):
if self._participants_list:
self._participants_list.clear()
def _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window("Live Session", visible=False, height=0, auto_resize=True, dockPreference=ui.DockPreference.DISABLED)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
self._existing_sessions_model.refresh_sessions()
empty_sessions = self._existing_sessions_model.empty()
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
self._join_create_radios = ui.RadioCollection()
self._build_option_radio(self._join_create_radios, "join_session_radio_button", "Join Session")
ui.Spacer(width=20)
self._build_option_radio(self._join_create_radios, "create_session_radio_button", "Create Session")
ui.Spacer()
self._join_create_radios.model.add_value_changed_fn(lambda _: self._update_dialog_states())
ui.Spacer(width=0, height=15)
with ui.HStack(height=0):
ui.Spacer(width=20)
self._error_label = ui.Label("", name="error_label", style={"color": 0xFF0000CC}, alignment=ui.Alignment.LEFT, word_wrap=True)
ui.Spacer(width=20)
ui.Spacer(width=0, height=5)
with ui.ZStack(height=0):
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(height=0):
self._session_name_input_field = ui.StringField(
name="new_session_name_field", width=self._window.width - 40, height=0
)
self._session_name_input_hint = ui.Label(
" New Session Name", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F}
)
self._session_name_begin_edit_cb = self._session_name_input_field.model.subscribe_begin_edit_fn(
self._on_session_name_begin_edit
)
self._session_name_end_edit_cb = self._session_name_input_field.model.subscribe_end_edit_fn(
self._on_session_name_end_edit
)
self._session_name_edit_cb = self._session_name_input_field.model.subscribe_value_changed_fn(
self._on_session_name_edit
)
ui.Spacer(width=20)
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(height=0):
self._existing_sessions_combo = ui.ComboBox(
self._existing_sessions_model, width=self._window.width - 40, height=0
)
self._existing_sessions_empty_hint = ui.Label(
" No Existing Sessions", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F}
)
ui.Spacer(width=20)
ui.Spacer(width=0, height=10)
self._participants_layout = ui.VStack(height=0)
with self._participants_layout:
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.VStack(height=0, width=0):
with ui.HStack(height=0, width=0):
ui.Label("Participants: ", alignment=ui.Alignment.CENTER)
with ui.HStack():
ui.Spacer()
ui.Image(LayerIcons.get("participants"), width=28, height=28)
ui.Spacer()
ui.Spacer(width=0, height=5)
with ui.HStack(height=0):
with ui.ScrollingFrame(height=120, style={"background_color": 0xFF24211F}):
self._participants_list = ui.VStack(height=0)
with self._participants_list:
self._build_empty_participants_list()
ui.Spacer(width=20)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer(height=0)
ok_button = ui.Button("JOIN", name="confirm_button", width=120, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
cancel_button = ui.Button("CANCEL", name="cancel_button", width=120, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(ok_button)
self._buttons.append(cancel_button)
ui.Spacer(height=0, width=20)
ui.Spacer(width=0, height=20)
if empty_sessions:
self._join_create_radios.model.set_value(1)
else:
self._update_dialog_states()
def _build_empty_participants_list(self):
with ui.VStack(height=0):
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=10)
ui.Label("No users currently in session.", style={"color": 0xFF808080})
| 18,527 | Python | 44.635468 | 146 | 0.559454 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_end_window.py | import carb
import asyncio
import omni.ui as ui
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.kit.notification_manager as nm
from omni.kit.widget.prompt import PromptManager
from pxr import Sdf
from .file_picker import FilePicker, FileBrowserMode, FileBrowserSelectionType
class LiveSessionEndWindow:
def __init__(self, layers_interface: layers.Layers, layer_identifier):
self._window = None
self._live_syncing = layers_interface.get_live_syncing()
self._base_layer_identifier = layer_identifier
self._buttons = []
self._options_combo = None
self._file_picker = None
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def destroy(self):
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
if self._window:
self._window.visible = False
self._window = None
self._options_combo = None
if self._file_picker:
self._file_picker.destroy()
self._file_picker = None
async def __aenter__(self):
await self._live_syncing.broadcast_merge_started_message_async(self._base_layer_identifier)
self.visible = True
# Wait until dialog disappears
while self.visible:
await asyncio.sleep(0.1)
async def __aexit__(self, exc_type, exc, tb):
self.visible = False
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
def _on_ok_button_fn(self):
self.visible = False
if not self._live_syncing.is_layer_in_live_session(self._base_layer_identifier):
return
prompt = None
async def pre_merge(current_session):
nonlocal prompt
app = omni.kit.app.get_app()
await app.next_update_async()
await app.next_update_async()
prompt = PromptManager.post_simple_prompt(
"Merging",
"Merging live layers into base layers...",
None,
shortcut_keys=False
)
async def post_merge(success):
nonlocal prompt
if prompt:
prompt.destroy()
prompt = None
if success:
await self._live_syncing.broadcast_merge_done_message_async(
layer_identifier=self._base_layer_identifier
)
current_session = self._live_syncing.get_current_live_session(self._base_layer_identifier)
comment = self._description_field.model.get_value_as_string()
option = self._options_combo.model.get_item_value_model().as_int
if option == 1:
def save_model(file_path: str, overwrite_existing: bool):
layer = Sdf.Layer.FindOrOpen(file_path)
if not layer:
layer = Sdf.Layer.CreateNew(file_path)
if not layer:
error = f"Failed to save live changes to layer {file_path} as it's not writable."
carb.log_error(error)
nm.post_notification(error, status=nm.NotificationStatus.WARNING)
return
asyncio.ensure_future(
self._live_syncing.merge_and_stop_live_session_async(
file_path, comment, pre_merge=pre_merge, post_merge=post_merge,
layer_identifier=self._base_layer_identifier
)
)
usd_context = self._live_syncing.usd_context
stage = usd_context.get_stage()
root_layer_identifier = stage.GetRootLayer().identifier
root_layer_name = current_session.name
self._show_file_picker(save_model, root_layer_identifier, root_layer_name)
elif option == 0:
asyncio.ensure_future(
self._live_syncing.merge_and_stop_live_session_async(
comment=comment, pre_merge=pre_merge, post_merge=post_merge,
layer_identifier=self._base_layer_identifier
)
)
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _create_file_picker(self):
filter_options = [
(r"^(?=.*.usd$)((?!.*\.(sublayer)\.usd).)*$", "USD File (*.usd)"),
(r"^(?=.*.usda$)((?!.*\.(sublayer)\.usda).)*$", "USDA File (*.usda)"),
(r"^(?=.*.usdc$)((?!.*\.(sublayer)\.usdc).)*$", "USDC File (*.usdc)"),
("(.*?)", "All Files (*.*)"),
]
layer_file_picker = FilePicker(
"Save Live Changes",
FileBrowserMode.SAVE,
FileBrowserSelectionType.FILE_ONLY,
filter_options,
[".usd", ".usda", ".usdc", ".usd"],
)
return layer_file_picker
def _show_file_picker(self, file_handler, default_location=None, default_filename=None):
if not self._file_picker:
self._file_picker = self._create_file_picker()
self._file_picker.set_file_selected_fn(file_handler)
self._file_picker.show(default_location, default_filename)
def _on_description_begin_edit(self, model):
self._description_field_hint_label.visible = False
def _on_description_end_edit(self, model):
if len(model.get_value_as_string()) == 0:
self._description_field_hint_label.visible = True
def _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window("Merge Options", visible=False, height=0, dockPreference=ui.DockPreference.DISABLED)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
current_session = self._live_syncing.get_current_live_session(self._base_layer_identifier)
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
ui.Label(
"Live Session is ending.", word_wrap=True, alignment=ui.Alignment.CENTER, width=self._window.width - 80, height=0
)
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Label(
f"How do you want to merge changes from '{current_session.name}' session?",
alignment=ui.Alignment.CENTER, word_wrap=True, width=self._window.width - 80, height=0
)
ui.Spacer()
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
self._options_combo = ui.ComboBox(
0, "Merge to corresponding layers", "Merge to a new layer",
word_wrap=True, width=self._window.width - 80, height=0
)
ui.Spacer()
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(width=40)
self._checkpoint_comment_frame = ui.Frame()
with self._checkpoint_comment_frame:
with ui.VStack(height=0, spacing=5):
ui.Label("Checkpoint Description")
with ui.ZStack():
self._description_field = ui.StringField(multiline=True, height=80)
self._description_field_hint_label = ui.Label(
" Description", alignment=ui.Alignment.LEFT_TOP, style={"color": 0xFF3F3F3F}
)
self._description_begin_edit_sub = self._description_field.model.subscribe_begin_edit_fn(
self._on_description_begin_edit
)
self._description_end_edit_sub = self._description_field.model.subscribe_end_edit_fn(
self._on_description_end_edit
)
ui.Spacer(width=40)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer(height=0)
ok_button = ui.Button("CONTINUE", name="confirm_button", width=120, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
cancel_button = ui.Button("CANCEL", name="cancel_button", width=120, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(ok_button)
self._buttons.append(cancel_button)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
| 9,633 | Python | 39.649789 | 137 | 0.534517 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_style.py | class Styles:
RELOAD_BTN = None
RELOAD_AUTO = None
RELOAD_OTD = None
LIVE_TOOL_TIP = None
@staticmethod
def on_startup():
# from .layer_icons import LayerIcons as li
from omni.ui import color as cl
c_otd = cl("#eb9d00")
c_otdh = cl("#ffaa00")
c_live = cl("#76B900")
c_liveh = cl("#9bf400")
c_lived = cl("#76B900")
c_auto = cl("#34C7FF")
c_autoh = cl("#82dcff")
c_white = cl("#ffffff")
c_rel = cl("#888888")
c_relh = cl("#BBBBBB")
c_disabled = cl("#555555")
Styles.LIVE_TOOL_TIP = {"background_color": 0xEE222222, "color": 0x33333333}
Styles.LIVE_GREEN = {"color": c_live, "Tooltip": Styles.LIVE_TOOL_TIP}
Styles.LIVE_SEL = {"color": c_liveh, "Tooltip": Styles.LIVE_TOOL_TIP}
Styles.LIVE_GREEN_DARKER = {"color": c_lived, "Tooltip": Styles.LIVE_TOOL_TIP}
Styles.RELOAD_BTN = {
"color": c_rel,
":hovered": {"color": c_relh},
":pressed": {"color": c_white},
":disabled": {"color": c_disabled},
}
Styles.RELOAD_AUTO = {
"color": c_auto, "Tooltip": Styles.LIVE_TOOL_TIP,
":hovered": {"color": c_autoh},
":pressed": {"color": c_white},
":disabled": {"color": c_disabled},
}
Styles.RELOAD_OTD = {
"color": c_otd, "Tooltip": Styles.LIVE_TOOL_TIP,
":hovered": {"color": c_otdh},
":pressed": {"color": c_white},
":disabled": {"color": c_disabled},
}
| 1,602 | Python | 29.245282 | 86 | 0.500624 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_model.py | __all__ = ["LiveSessionItem", "LiveSessionModel"]
import asyncio
import omni.kit.usd.layers as layers
import omni.ui as ui
from typing import Callable
import itertools
_last_sessions = {}
class LiveSessionItem(ui.AbstractItem):
def __init__(self, session: layers.LiveSession) -> None:
super().__init__()
self._session = session
self.model = ui.SimpleStringModel(session.name)
@property
def session(self):
return self._session
def __str__(self) -> str:
return self._session.name
class LiveSessionModel(ui.AbstractItemModel):
def __init__(self, layers_interface: layers.Layers, layer_identifier, update_users=True) -> None:
super().__init__()
self._layers_interface = layers_interface
self._base_layer_identifier = layer_identifier
self._current_index = ui.SimpleIntModel()
self._current_index.set_value(-1)
id = self._current_index.add_value_changed_fn(self._value_changed_fn)
self._items = []
self._current_session = None
self._current_session_channel = None
self._channel_subscriber = None
self._join_channel_task = None
self._all_users = {}
self._user_update_callback: Callable[[], None] = None
self._all_value_changed_fns = [id]
self._update_users = update_users
self._refreshing_item = False
self._is_default_session_selected = False
def __del__(self):
self.destroy()
@property
def all_users(self):
return self._all_users
@property
def is_default_session_selected(self):
return self._is_default_session_selected
def set_user_update_callback(self, callback: Callable[[], None]):
self._user_update_callback = callback
def stop_channel(self):
self._cancel_current_task()
def _join_current_channel(self):
if not self._current_session or not self._update_users:
return
try:
# OM-108516: Make channel_manager optional
import omni.kit.collaboration.channel_manager as cm
except ImportError:
return
if not self._current_session_channel or self._current_session_channel.url != self._current_session.url:
self._cancel_current_task()
async def join_stage_async(url):
self._current_session_channel = await cm.join_channel_async(url, True)
if not self._current_session_channel:
return
self._channel_subscriber = self._current_session_channel.add_subscriber(self._on_channel_message)
self._join_channel_task = asyncio.ensure_future(join_stage_async(self._current_session.channel_url))
def _on_channel_message(self, message):
try:
# OM-108516: Make channel_manager optional
import omni.kit.collaboration.channel_manager as cm
except ImportError:
return
user = message.from_user
if message.message_type == cm.MessageType.LEFT and user.user_id in self._all_users:
self._all_users.pop(user.user_id, None)
changed = True
elif user.user_id not in self._all_users:
self._all_users[user.user_id] = user
changed = True
else:
changed = False
if changed and self._user_update_callback:
self._user_update_callback()
def _cancel_current_task(self):
if self._join_channel_task and not self._join_channel_task.done():
try:
self._join_channel_task.cancel()
except Exception:
pass
if self._current_session_channel:
self._current_session_channel.stop()
self._current_session_channel = None
self._join_channel_task = None
self._channel_subscriber = None
def add_value_changed(self, fn):
if self._current_index:
id = self._current_index.add_value_changed_fn(fn)
self._all_value_changed_fns.append(id)
def _value_changed_fn(self, model):
if self._refreshing_item:
return
global _last_sessions
index = self._current_index.as_int
if index < 0 or index >= len(self._items):
return
self._current_session = self._items[index].session
self._is_default_session_selected = (self._current_session and self._current_index.as_int == 0)
_last_sessions[self._base_layer_identifier] = self._current_session.url
self._all_users.clear()
if self._user_update_callback:
self._user_update_callback()
self._join_current_channel()
self._refreshing_item = True
self._item_changed(None)
self._refreshing_item = False
def destroy(self):
self._user_update_callback = None
self._cancel_current_task()
if self._current_index:
for fn in self._all_value_changed_fns:
self._current_index.remove_value_changed_fn(fn)
self._all_value_changed_fns.clear()
self._current_index = None
self._layers_interface = None
self._current_session = None
self._items = []
self._all_users = {}
self._layers_event_subscription = None
def clear(self):
self._items = []
self._current_session = None
self._current_index.set_value(-1)
def empty(self):
return len(self._items) == 0
def get_item_children(self, item):
return self._items
@property
def current_session(self):
return self._current_session
def refresh_sessions(self, force=False):
global _last_sessions
live_syncing = self._layers_interface.get_live_syncing()
current_live_session = live_syncing.get_current_live_session(self._base_layer_identifier)
live_sessions = live_syncing.get_all_live_sessions(self._base_layer_identifier)
live_sessions.sort(key=lambda s: s.get_last_modified_time(), reverse=True)
identifier = self._base_layer_identifier
pre_sort = []
for session in live_sessions:
if session.name == "Default":
pre_sort.insert(0, session)
else:
pre_sort.append(session)
self._items.clear()
index = 0 if live_sessions else -1
for i, session in enumerate(pre_sort):
item = LiveSessionItem(session)
if current_live_session and current_live_session.url == session.url:
index = i
elif identifier in _last_sessions and _last_sessions[identifier] == session.url:
index = i
self._items.append(item)
current_index = self._current_index.as_int
if current_index != index:
self._current_index.set_value(index)
elif force:
self._item_changed(None)
self._is_default_session_selected = (self._current_session and self._current_index.as_int == 0)
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def select_default_session(self):
live_syncing = self._layers_interface.get_live_syncing()
live_sessions = live_syncing.get_all_live_sessions(self._base_layer_identifier)
if live_sessions and self._current_index.as_int != 0:
self._current_index.set_value(0)
self._item_changed(None)
return
def create_new_session_name(self) -> str:
live_syncing = self._layers_interface.get_live_syncing()
live_sessions = live_syncing.get_all_live_sessions(self._base_layer_identifier)
# first we attempt creating a "Default" as the first new session.
default_session_name = "Default"
if not live_syncing.find_live_session_by_name(self._base_layer_identifier, default_session_name):
return default_session_name
# if there already is a `Default`, then we use <username>_01, <username>_02, ...
layers_instance = live_syncing._layers_instance
live_syncing_interface = live_syncing._live_syncing_interface
logged_user_name = live_syncing_interface.get_logged_in_user_name_for_layer(layers_instance, self._base_layer_identifier)
if "@" in logged_user_name:
logged_user_name = logged_user_name.split('@')[0]
for i in itertools.count(start=1):
user_session_name = "{}_{:02d}".format(logged_user_name, i)
if not live_syncing.find_live_session_by_name(self._base_layer_identifier, user_session_name):
return user_session_name
| 8,699 | Python | 35.708861 | 129 | 0.613174 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_camera_follower_list.py | __all__ = ["LiveSessionCameraFollowerList"]
import carb
import omni.usd
import omni.client.utils as clientutils
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
from .utils import build_live_session_user_layout
from pxr import Sdf
from omni.ui import color as cl
TOOLTIP_STYLE = {
"color": cl("#979797"),
"Tooltip": {"background_color": 0xEE222222}
}
class LiveSessionCameraFollowerList:
"""Widget to build an user list to show all followers to the specific camera."""
def __init__(self, usd_context: omni.usd.UsdContext, camera_path: Sdf.Path, **kwargs):
"""
Constructor.
Args:
usd_context (omni.usd.UsdContext): USD Context instance.
camera_path (str): Interested camera.
Kwargs:
icon_size (int): The width and height of the user icon. 16 pixel by default.
spacing (int): The horizonal spacing between two icons. 2 pixel by default.
maximum_users (int): The maximum users to show, and show others with overflow.
show_my_following_users (bool): Whether it should show the users that are following me or not.
"""
self.__icon_size = kwargs.get("icon_size", 16)
self.__spacing = kwargs.get("spacing", 2)
self.__maximum_count = kwargs.get("maximum_users", 3)
self.__show_my_following_users = kwargs.get("show_my_following_users", True)
self.__camera_path = camera_path
self.__usd_context = usd_context
self.__presence_layer = pl.get_presence_layer_interface(self.__usd_context)
self.__layers = layers.get_layers(usd_context)
self.__live_syncing = layers.get_live_syncing()
self.__layers_event_subscriptions = []
self.__main_layout: ui.HStack = ui.HStack(width=0, height=0)
self.__all_user_layouts = {}
self.__initialize()
self.__overflow = False
self.__overflow_button = None
@property
def layout(self) -> ui.HStack:
return self.__main_layout
def empty(self):
return len(self.__all_user_layouts) == 0
def track_camera(self, camera_path: Sdf.Path):
"""Switches the camera path to listen to."""
if self.__camera_path != camera_path:
self.__camera_path = camera_path
self.__initialize()
def __initialize(self):
layer_identifier = self.__usd_context.get_stage_url()
if self.__camera_path and not clientutils.is_local_url(layer_identifier):
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED
]:
layers_event_subscription = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event,
name=f"omni.kit.widget.live_session_management.LiveSessionCameraFollowerList {str(event)}"
)
self.__layers_event_subscriptions.append(layers_event_subscription)
else:
self.__layers_event_subscriptions = []
self.__build_ui()
def __build_ui(self):
# Destroyed
if not self.__main_layout:
return
self.__main_layout.clear()
self.__all_user_layouts.clear()
self.__overflow = False
self.__overflow_button = None
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session or not self.__camera_path:
return
with self.__main_layout:
for peer_user in current_live_session.peer_users:
self.__add_user(current_live_session, peer_user.user_id, False)
if self.__overflow:
break
if self.empty():
self.__main_layout.visible = False
else:
self.__main_layout.visible = True
def __build_tooltip(self): # pragma: no cover
live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
if not live_session:
return
with ui.VStack():
with ui.HStack(style={"color": cl("#757575")}):
ui.Spacer()
title_label = ui.Label(
"Following by 0 Users", style={"font_size": 12}, width=0
)
ui.Spacer()
ui.Spacer(height=0)
ui.Separator(style={"color": cl("#4f4f4f")})
ui.Spacer(height=4)
valid_users = 0
for user in live_session.peer_users:
if not self.__show_my_following_users:
following_user_id = self.__presence_layer.get_following_user_id(user.user_id)
if following_user_id == live_session.logged_user_id:
continue
bound_camera_prim = self.__presence_layer.get_bound_camera_prim(user.user_id)
if not bound_camera_prim or bound_camera_prim.GetPath() != self.__camera_path:
continue
valid_users += 1
item_title = f"{user.user_name} ({user.from_app})"
with ui.HStack():
build_live_session_user_layout(user, self.__icon_size, "")
ui.Spacer(width=4)
ui.Label(item_title, style={"font_size": 14})
ui.Spacer(height=2)
title_label.text = f"Following by {valid_users} Users"
@carb.profiler.profile
def __add_user(self, current_live_session, user_id, add_child=False):
bound_camera_prim = self.__presence_layer.get_bound_camera_prim(user_id)
if not bound_camera_prim:
return False
if bound_camera_prim.GetPath() == self.__camera_path:
user_info = current_live_session.get_peer_user_info(user_id)
if not user_info:
return False
if not self.__show_my_following_users:
following_user_id = self.__presence_layer.get_following_user_id(user_id)
if following_user_id == current_live_session.logged_user_id:
return False
if user_id not in self.__all_user_layouts:
current_count = len(self.__all_user_layouts)
if current_count > self.__maximum_count or self.__overflow:
# OMFP-2909: Refresh overflow button to rebuild tooltip.
if self.__overflow and self.__overflow_button:
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
return True
elif current_count == self.__maximum_count:
self.__overflow = True
layout = ui.HStack(width=0)
with layout:
ui.Spacer(width=4)
with ui.ZStack():
ui.Label("...", style={"font_size": 16}, aligment=ui.Alignment.V_CENTER)
self.__overflow_button = ui.InvisibleButton(style=TOOLTIP_STYLE)
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
if add_child:
self.__main_layout.add_child(layout)
else:
if self.empty():
spacer = 0
else:
spacer = self.__spacing
layout = self.__build_user_layout(user_info, spacer)
if add_child:
self.__main_layout.add_child(layout)
self.__main_layout.visible = True
self.__all_user_layouts[user_id] = layout
return True
return False
@carb.profiler.profile
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
stage_url = self.__usd_context.get_stage_url()
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if stage_url not in payload.identifiers_or_spec_paths:
return
self.__build_ui()
elif (
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED or
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT
):
if stage_url != payload.layer_identifier:
return
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session:
self.__build_ui()
return
user_id = payload.user_id
if payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
user = self.__all_user_layouts.pop(user_id, None)
if user:
# FIXME: omni.ui does not support to remove single child.
self.__build_ui()
else:
self.__add_user(current_live_session, user_id, True)
else:
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session:
return
payload = pl.get_presence_layer_event_payload(event)
if not payload or not payload.event_type:
return
if payload.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED:
changed_user_ids = payload.changed_user_ids
needs_rebuild = False
for user_id in changed_user_ids:
if not self.__add_user(current_live_session, user_id, True):
# It's not bound to this camera already.
needs_rebuild = user_id in self.__all_user_layouts
break
if needs_rebuild:
self.__build_ui()
def destroy(self): # pragma: no cover
self.__main_layout = None
self.__layers_event_subscriptions = []
self.__layers = None
self.__live_syncing = None
self.__all_user_layouts.clear()
self.__overflow_button = None
def __build_user_layout(self, user_info: layers.LiveSessionUser, spacing=2):
tooltip = f"{user_info.user_name} ({user_info.from_app})"
layout = ui.HStack()
with layout:
ui.Spacer(width=spacing)
build_live_session_user_layout(user_info, self.__icon_size, tooltip)
return layout
| 10,669 | Python | 39.264151 | 112 | 0.556472 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/filebrowser/__init__.py | from .app_filebrowser import FileBrowserUI, FileBrowserSelectionType, FileBrowserMode | 85 | Python | 84.999915 | 85 | 0.894118 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/filebrowser/app_filebrowser.py | import asyncio
import re
import omni.client
import omni.client.utils as clientutils
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.widget.filebrowser import FileBrowserItem
from typing import Iterable, Tuple, Union
class FileBrowserSelectionType:
FILE_ONLY = 0
DIRECTORY_ONLY = 1
ALL = 2
class FileBrowserMode:
OPEN = 0
SAVE = 1
class FileBrowserUI:
def __init__(self, title, mode, selection_type, filter_options, **kwargs):
if mode == FileBrowserMode.OPEN:
confirm_text = "Open"
else:
confirm_text = "Save"
self._file_picker = FilePickerApp(title, confirm_text, selection_type, filter_options, **kwargs)
def set_current_directory(self, dir):
self._file_picker.set_current_directory(dir)
def set_current_filename(self, filename):
self._file_picker.set_current_filename(filename)
def get_current_filename(self):
return self._file_picker.get_current_filename()
def open(self, select_fn, cancel_fn):
self._file_picker.set_custom_fn(select_fn, cancel_fn)
self._file_picker.show_dialog()
def destroy(self):
self._file_picker.set_custom_fn(None, None)
self._file_picker = None
def hide(self):
self._file_picker.hide_dialog()
class FilePickerApp:
"""
Standalone app to demonstrate the use of the FilePicker dialog.
Args:
title (str): Title of the window.
apply_button_name (str): Name of the confirm button.
selection_type (FileBrowserSelectionType): The file type that confirm event will respond to.
item_filter_options (list): Array of filter options. Element of array
is a tuple that first element of this tuple is the regex string for filtering,
and second element of this tuple is the descriptions, like ("*.*", "All Files").
By default, it will list all files.
kwargs: additional keyword arguments to be passed to FilePickerDialog.
"""
def __init__(
self,
title: str,
apply_button_name: str,
selection_type: FileBrowserSelectionType = FileBrowserSelectionType.ALL,
item_filter_options: Iterable[Tuple[Union[re.Pattern, str], str]] = ((
re.compile(".*"), "All Files (*.*)")),
**kwargs,
):
self._title = title
self._filepicker = None
self._selection_type = selection_type
self._custom_select_fn = None
self._custom_cancel_fn = None
self._apply_button_name = apply_button_name
self._filter_regexes = []
self._filter_descriptions = []
self._current_directory = None
for regex, desc in item_filter_options:
if not isinstance(regex, re.Pattern):
regex = re.compile(regex, re.IGNORECASE)
self._filter_regexes.append(regex)
self._filter_descriptions.append(desc)
self._build_ui(**kwargs)
def set_custom_fn(self, select_fn, cancel_fn):
self._custom_select_fn = select_fn
self._custom_cancel_fn = cancel_fn
def show_dialog(self):
self._filepicker.show(self._current_directory)
self._current_directory = None
def hide_dialog(self):
self._filepicker.hide()
def set_current_directory(self, dir: str):
self._current_directory = dir
if not self._current_directory.endswith("/"):
self._current_directory += "/"
def set_current_filename(self, filename: str):
self._filepicker.set_filename(filename)
def get_current_filename(self):
return self._filepicker.get_filename()
def _build_ui(self, **kwargs):
on_click_open = lambda f, d: asyncio.ensure_future(self._on_click_open(f, d))
on_click_cancel = lambda f, d: asyncio.ensure_future(self._on_click_cancel(f, d))
# Create the dialog
self._filepicker = FilePickerDialog(
self._title,
allow_multi_selection=False,
apply_button_label=self._apply_button_name,
click_apply_handler=on_click_open,
click_cancel_handler=on_click_cancel,
item_filter_options=self._filter_descriptions,
item_filter_fn=lambda item: self._on_filter_item(item),
error_handler=lambda m: self._on_error(m),
**kwargs,
)
# Start off hidden
self.hide_dialog()
def _on_filter_item(self, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if self._filepicker.current_filter_option >= len(self._filter_regexes):
return False
regex = self._filter_regexes[self._filepicker.current_filter_option]
if regex.match(item.path):
return True
else:
return False
def _on_error(self, msg: str):
"""
Demonstrates error handling. Instead of just printing to the shell, the App can
display the error message to a console window.
"""
print(msg)
async def _on_click_open(self, filename: str, dirname: str):
"""
The meat of the App is done in this callback when the user clicks 'Accept'. This is
a potentially costly operation so we implement it as an async operation. The inputs
are the filename and directory name. Together they form the fullpath to the selected
file.
"""
dirname = dirname.strip()
if dirname and not dirname.endswith("/"):
dirname += "/"
fullpath = clientutils.make_absolute_url_if_possible(dirname, filename)
result, entry = omni.client.stat(fullpath)
if result == omni.client.Result.OK and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
is_folder = True
else:
is_folder = False
if not is_folder and self._selection_type == FileBrowserSelectionType.DIRECTORY_ONLY:
return
self.hide_dialog()
await omni.kit.app.get_app().next_update_async()
if self._custom_select_fn:
self._custom_select_fn(fullpath, self._filepicker.current_filter_option)
async def _on_click_cancel(self, filename: str, dirname: str):
"""
This function is called when the user clicks 'Cancel'.
"""
self.hide_dialog()
await omni.kit.app.get_app().next_update_async()
if self._custom_cancel_fn:
self._custom_cancel_fn()
| 6,490 | Python | 33.343915 | 104 | 0.623729 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/tests/mock_utils.py | import carb
import asyncio
import os
import functools
import uuid
import omni.usd
import omni.client
import omni.kit.usd.layers as layers
from typing import Callable, Awaitable
from omni.kit.collaboration.channel_manager.types import PeerUser
from omni.kit.usd.layers import LayersState, LiveSyncing, LiveSession
from ..live_session_model import LiveSessionModel
from ..file_picker import FilePicker
from omni.kit.usd.layers._omni_kit_usd_layers import IWorkflowLiveSyncing
from unittest.mock import Mock, MagicMock
from pxr import Sdf, Usd
_mock_sdf_save_layer_api = None
_mock_layer_states_get_all_outdated_layer_identifiers_api = None
_mock_live_session_model_all_users_api = None
_mock_live_syncing_merge_and_stop_live_session_async_api = None
_mock_filepicker_show_api = None
_mock_filepicker_set_file_selected_fn_api = None
_mock_outdated_layers = []
file_save_handler = None
merge_and_stop_live_session_async_called = False
def append_outdated_layers(layer_id):
global _mock_outdated_layers
_mock_outdated_layers.append(layer_id)
def clear_outdated_layers():
global _mock_outdated_layers
_mock_outdated_layers = []
def get_merge_and_stop_live_session_async_called():
global merge_and_stop_live_session_async_called
return merge_and_stop_live_session_async_called
def _start_mock_api_for_live_session_management():
carb.log_info("Start mock api for live session management...")
def __mock_sdf_save_layer(force):
pass
global _mock_sdf_save_layer_api
_mock_sdf_save_layer_api = Sdf.Layer.Save
Sdf.Layer.Save = Mock(side_effect=__mock_sdf_save_layer)
def __mock_layer_states_get_all_outdated_layer_identifiers_():
global _mock_outdated_layers
return _mock_outdated_layers
global _mock_layer_states_get_all_outdated_layer_identifiers_api
_mock_layer_states_get_all_outdated_layer_identifiers_api = LayersState.get_all_outdated_layer_identifiers
LayersState.get_all_outdated_layer_identifiers = Mock(side_effect=__mock_layer_states_get_all_outdated_layer_identifiers_)
global _mock_live_session_model_all_users_api
_mock_live_session_model_all_users_api = LiveSessionModel.all_users
LiveSessionModel.all_users = {f"user_{i}": PeerUser(f"user_{i}", f"user_{i}", "Kit") for i in range(3)}
async def __mock_live_syncing_merge_and_stop_live_session_async(
self, target_layer: str = None, comment="",
pre_merge: Callable[[LiveSession], Awaitable] = None,
post_merge: Callable[[bool], Awaitable] = None,
layer_identifier: str = None
) -> bool:
global merge_and_stop_live_session_async_called
merge_and_stop_live_session_async_called = True
return True
global _mock_live_syncing_merge_and_stop_live_session_async_api
_mock_live_syncing_merge_and_stop_live_session_async_api = LiveSyncing.merge_and_stop_live_session_async
LiveSyncing.merge_and_stop_live_session_async = Mock(side_effect=__mock_live_syncing_merge_and_stop_live_session_async)
def __mock_filepicker_show(dummy1, dummy2):
global file_save_handler
if file_save_handler:
file_save_handler(dummy1, False)
global _mock_filepicker_show_api
_mock_filepicker_show_api = FilePicker.show
FilePicker.show = Mock(side_effect=__mock_filepicker_show)
def __mock_filepicker_set_file_selected_fn(fn):
global file_save_handler
file_save_handler = fn
global _mock_filepicker_set_file_selected_fn_api
_mock_filepicker_set_file_selected_fn_api = FilePicker.set_file_selected_fn
FilePicker.set_file_selected_fn = Mock(side_effect=__mock_filepicker_set_file_selected_fn)
def _end_mock_api_for_live_session_management():
carb.log_info("Start mock api for live session management...")
global _mock_sdf_save_layer_api
Sdf.Layer.Save = _mock_sdf_save_layer_api
_mock_sdf_save_layer_api = None
global _mock_layer_states_get_all_outdated_layer_identifiers_api
LayersState.get_all_outdated_layer_identifiers = _mock_layer_states_get_all_outdated_layer_identifiers_api
_mock_layer_states_get_all_outdated_layer_identifiers_api = None
global _mock_live_session_model_all_users_api
LiveSessionModel.all_users = _mock_live_session_model_all_users_api
_mock_live_session_model_all_users_api = None
global _mock_live_syncing_merge_and_stop_live_session_async_api
LiveSyncing.merge_and_stop_live_session_async = _mock_live_syncing_merge_and_stop_live_session_async_api
_mock_live_syncing_merge_and_stop_live_session_async_api = None
global _mock_filepicker_show_api
FilePicker.show = _mock_filepicker_show_api
_mock_filepicker_show_api = None
global _mock_filepicker_set_file_selected_fn_api
FilePicker.set_file_selected_fn = _mock_filepicker_set_file_selected_fn_api
_mock_filepicker_set_file_selected_fn_api = None
global merge_and_stop_live_session_async_called
merge_and_stop_live_session_async_called = False
def MockApiForLiveSessionManagement(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
func = args[0]
args = args[1:]
else:
func = None
def wrapper(func):
@functools.wraps(func)
def wrapper_api(*args, **kwargs):
try:
_start_mock_api_for_live_session_management()
return func(*args, **kwargs)
finally:
_end_mock_api_for_live_session_management()
@functools.wraps(func)
async def wrapper_api_async(*args, **kwargs):
try:
_start_mock_api_for_live_session_management()
return await func(*args, **kwargs)
finally:
_end_mock_api_for_live_session_management()
if asyncio.iscoroutinefunction(func):
return wrapper_api_async
else:
return wrapper_api
if func:
return wrapper(func)
else:
return wrapper
| 5,995 | Python | 37.435897 | 126 | 0.69975 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/tests/__init__.py | from .test_live_session_management import * | 43 | Python | 42.999957 | 43 | 0.813953 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/tests/test_live_session_management.py | import os
import carb
import omni.usd
import omni.kit.ui_test as ui_test
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.timeline.live_session
import omni.kit.collaboration.presence_layer as pl
import omni.kit.collaboration.presence_layer.utils as pl_utils
import unittest
import tempfile
import random
import uuid
from omni.kit.test import AsyncTestCase
from omni.kit.window.preferences import register_page, unregister_page
from pxr import Sdf, Usd
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi, join_new_simulated_user, quit_simulated_user, forbid_session_merge
from ..extension import LiveSessionWidgetExtension, stop_or_show_live_session_widget
from ..live_session_camera_follower_list import LiveSessionCameraFollowerList
from ..live_session_user_list import LiveSessionUserList
from ..file_picker import FilePicker, FileBrowserMode, FileBrowserSelectionType
from ..live_session_preferences import LiveSessionPreferences
from ..reload_widget import build_reload_widget
from ..live_session_start_window import LiveSessionStartWindow
from .mock_utils import (
MockApiForLiveSessionManagement,
append_outdated_layers,
clear_outdated_layers,
get_merge_and_stop_live_session_async_called
)
TEST_URL = "omniverse://__omni.kit.widget.live_session_management__/tests/"
LIVE_SESSION_CONFIRM_BUTTON_PATH = "Live Session//Frame/**/Button[*].name=='confirm_button'"
LIVE_SESSION_CANCEL_BUTTON_PATH = "Live Session//Frame/**/Button[*].name=='cancel_button'"
LEAVE_SESSION_CONFIRM_BUTTON_PATH = "Leave Session//Frame/**/Button[*].name=='confirm_button'"
JOIN_LIVE_SESSION_WITH_LINK_CANCEL_BUTTON_PATH = "JOIN LIVE SESSION WITH LINK//Frame/**/Button[*].name=='cancel_button'"
SHARE_LIVE_SESSION_LINK_COMBO_BOX_PATH = "SHARE LIVE SESSION LINK//Frame/**/ComboBox[0]"
SHARE_LIVE_SESSION_LINK_CONFIRM_BUTTON_PATH = "SHARE LIVE SESSION LINK//Frame/**/InvisibleButton[*].name=='confirm_button'"
MERGE_OPTIONS_CONFIRM_BUTTON_PATH = "Merge Options//Frame/**/Button[*].name=='confirm_button'"
MERGE_OPTIONS_COMBO_BOX_PATH = "Merge Options//Frame/**/ComboBox[0]"
MERGE_PROMPT_LEAVE_BUTTON_PATH = "Permission Denied//Frame/**/Button[*].name=='confirm_button'"
QUICK_JOIN_ENABLED = "/exts/omni.kit.widget.live_session_management/quick_join_enabled"
def _menu_items_as_string_list(items):
return [i.text for i in items]
def _find_menu_item(items, text):
for i in items:
if i.text == text:
return i
return None
def enable_server_tests():
settings = carb.settings.get_settings()
return True or settings.get_as_bool("/exts/omni.kit.widget.live_session_management/enable_server_tests")
class TestLiveSessionManagement(AsyncTestCase):
def get_live_syncing(self):
usd_context = omni.usd.get_context()
self.assertIsNotNone(layers.get_layers(usd_context))
self.assertIsNotNone(layers.get_layers(usd_context).get_live_syncing())
return layers.get_layers(usd_context).get_live_syncing()
async def setUp(self):
self._instance = LiveSessionWidgetExtension.get_instance()
self.assertIsNotNone(self._instance)
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
pass
async def _close_case(self):
if omni.usd.get_context().get_stage():
live_syncing = self.get_live_syncing()
if live_syncing:
if live_syncing.is_stage_in_live_session():
await self._leave_current_session()
live_syncing.stop_all_live_sessions()
await omni.usd.get_context().close_stage_async()
await ui_test.human_delay(6)
async def _click_menu_item(self, item, right_click=False):
offset = ui_test.Vec2(5, 5)
pos = ui_test.Vec2(item.screen_position_x, item.screen_position_y) + offset
await ui_test.emulate_mouse_move(pos, 4)
await ui_test.human_delay(6)
await ui_test.emulate_mouse_click(right_click=right_click)
await ui_test.human_delay(6)
async def _create_test_usd(self, filename = 'test'):
await omni.client.delete_async(TEST_URL)
stage_url = TEST_URL + f"{filename}.usd"
layer = Sdf.Layer.CreateNew(stage_url)
stage = Usd.Stage.Open(layer.identifier)
self.assertIsNotNone(stage)
return stage
async def _create_test_sublayer_usd(self, filename = 'sublayer'):
layer_url = TEST_URL + f"{filename}.usd"
layer = Sdf.Layer.CreateNew(layer_url)
return layer
async def _expand_live_session_menu(self,
layer_identifier: str=None,
quick_join: str=None):
stop_or_show_live_session_widget(layer_identifier=layer_identifier, quick_join=quick_join)
await ui_test.human_delay(6)
menu = self._instance._live_session_menu
self.assertIsNotNone(menu)
items = ui.Inspector.get_children(menu)
await ui_test.human_delay(6)
return items
def _get_current_menu_item_string_list(self):
menu = ui.Menu.get_current()
self.assertIsNotNone(menu)
items = ui.Inspector.get_children(menu)
return _menu_items_as_string_list(items)
async def _click_on_current_menu(self, text: str):
menu = ui.Menu.get_current()
self.assertIsNotNone(menu)
items = ui.Inspector.get_children(menu)
item_str_list = self._get_current_menu_item_string_list()
self.assertIn(text, item_str_list)
item = _find_menu_item(items, text)
self.assertIsNotNone(item)
await self._click_menu_item(item)
await ui_test.human_delay(6)
async def _click_live_session_menu_item(self,
text: str, layer_identifier = None,
quick_join: str = None):
items = await self._expand_live_session_menu(layer_identifier, quick_join)
self.assertTrue(len(items) > 0)
item_str_list = _menu_items_as_string_list(items)
self.assertIn(text, item_str_list)
item = _find_menu_item(items, text)
self.assertIsNotNone(item)
await self._click_menu_item(item)
await ui_test.human_delay(6)
@MockLiveSyncingApi
async def test_create_session_dialog(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._click_live_session_menu_item("Create Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
cancal_button = ui_test.find(LIVE_SESSION_CANCEL_BUTTON_PATH)
self.assertIsNotNone(cancal_button)
await cancal_button.click()
await self._close_case()
async def _create_session(self, session_name: str=None):
await self._click_live_session_menu_item("Create Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
if session_name:
name_field = ui_test.find("Live Session//Frame/**/StringField[0]")
self.assertIsNotNone(name_field)
name_field.model.set_value(session_name)
ok_button = ui_test.find(LIVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
async def _create_session_then_leave(self, session_name: str):
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
await self._create_session(session_name)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._leave_current_session()
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
async def _leave_current_session(self):
await self._click_live_session_menu_item("Leave Session")
if ui_test.find("Leave Session"):
button = ui_test.find(LEAVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(button)
await button.click()
await ui_test.human_delay(6)
@MockLiveSyncingApi
async def test_create_session(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
self.get_live_syncing().stop_all_live_sessions()
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
await self._close_case()
@MockLiveSyncingApi
async def test_leave_session(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._close_case()
@MockLiveSyncingApi
async def test_join_session(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session_then_leave("test")
await self._click_live_session_menu_item("Join Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
ok_button = ui_test.find(LIVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._close_case()
@MockLiveSyncingApi
@MockApiForLiveSessionManagement
async def test_join_session_participants(self):
stage = await self._create_test_usd("test")
await omni.usd.get_context().attach_stage_async(stage)
live_session_start_window = LiveSessionStartWindow(layers.get_layers(),
stage.GetRootLayer().identifier,
None)
await self._create_session("test")
live_session_start_window.visible = True
live_session_start_window.set_focus(True)
await ui_test.human_delay(6)
live_session_start_window.visible = False
await self._close_case()
@MockLiveSyncingApi
async def test_join_session_quick(self):
settings = carb.settings.get_settings()
before = settings.get_as_bool(QUICK_JOIN_ENABLED)
settings.set(QUICK_JOIN_ENABLED, True)
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session_then_leave("test")
await self._expand_live_session_menu(quick_join="test")
self.assertEqual("test", self.get_live_syncing().get_current_live_session().name)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
settings.set(QUICK_JOIN_ENABLED, before)
await self._close_case()
@MockLiveSyncingApi
async def test_join_session_quick_create(self):
settings = carb.settings.get_settings()
before = settings.get_as_bool(QUICK_JOIN_ENABLED)
settings.set(QUICK_JOIN_ENABLED, True)
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._expand_live_session_menu(quick_join="test")
self.assertEqual("test", self.get_live_syncing().get_current_live_session().name)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
settings.set(QUICK_JOIN_ENABLED, before)
await self._close_case()
@MockLiveSyncingApi
async def test_join_session_options(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session_then_leave(None)
await self._create_session_then_leave(None)
for i in range(3):
await self._create_session_then_leave(f"test_{i}")
await self._click_live_session_menu_item("Join Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
combo_box = ui_test.find("Live Session//Frame/**/ComboBox[0]")
items = combo_box.model.get_item_children(None)
names = [i.session.name for i in items]
carb.log_warn(names)
self.assertIn("Default", names)
self.assertIn("simulated_user_name___01", names)
for i in range(3):
self.assertIn(f"test_{i}", names)
index_of_second_test_usd = names.index('test_1')
self.assertTrue(index_of_second_test_usd > -1)
combo_box.model.get_item_value_model(None, 0).set_value(index_of_second_test_usd)
await ui_test.human_delay(6)
ok_button = ui_test.find(LIVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
self.assertEqual("test_1", self.get_live_syncing().get_current_live_session().name)
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_join_with_session_link_without_stage(self):
self.assertIsNone(stop_or_show_live_session_widget())
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_join_with_session_link_dialog(self):
await omni.usd.get_context().new_stage_async()
await self._click_live_session_menu_item("Join With Session Link")
frame = ui_test.find("JOIN LIVE SESSION WITH LINK")
self.assertIsNotNone(frame)
cancal_button = ui_test.find(JOIN_LIVE_SESSION_WITH_LINK_CANCEL_BUTTON_PATH)
self.assertIsNotNone(cancal_button)
await cancal_button.click()
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_copy_session_link(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
layer = stage.GetRootLayer()
await self._click_live_session_menu_item("Copy Session Link", layer.identifier)
current_session = self.get_live_syncing().get_current_live_session()
live_session_link = omni.kit.clipboard.paste()
self.assertEqual(live_session_link, current_session.shared_link)
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_share_session_link(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
for i in range(3):
await self._create_session_then_leave(f"test_{i}")
await self._click_live_session_menu_item("Share Session Link")
frame = ui_test.find("SHARE LIVE SESSION LINK")
self.assertIsNotNone(frame)
combo_box = ui_test.find(SHARE_LIVE_SESSION_LINK_COMBO_BOX_PATH)
items = combo_box.model.get_item_children(None)
names = [i.session.name for i in items]
index_of_second_test_usd = -1
for i in range(3):
self.assertIn(f"test_{i}", names)
if names[i] == "test_1":
index_of_second_test_usd = i
self.assertTrue(index_of_second_test_usd > -1)
combo_box.model.get_item_value_model(None, 0).set_value(index_of_second_test_usd)
await ui_test.human_delay(6)
confirm_button = ui_test.find(SHARE_LIVE_SESSION_LINK_CONFIRM_BUTTON_PATH)
await confirm_button.click()
live_session_link = omni.kit.clipboard.paste()
self.assertEqual(live_session_link, items[index_of_second_test_usd].session.shared_link)
await self._close_case()
def _create_test_camera(self, name: str='camera'):
camera_path = f"/{name}"
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Camera", prim_path=camera_path)
return Sdf.Path(camera_path)
async def _setup_camera_follower_list(self, camera_path, maximum_users=3):
camera = omni.usd.get_context().get_stage().GetPrimAtPath(camera_path)
self.assertIsNotNone(camera)
return LiveSessionCameraFollowerList(omni.usd.get_context(), camera_path, maximum_users=maximum_users)
@MockLiveSyncingApi
async def test_live_session_camera_follower_list(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
camera_path = self._create_test_camera()
camera_follower_list = await self._setup_camera_follower_list(camera_path)
await self._close_case()
async def _bound_camera(self, shared_stage: Usd.Stage, user_id: str, camera_path: Sdf.Path):
if not camera_path:
camera_path = Sdf.Path.emptyPath
camera_path = Sdf.Path(camera_path)
bound_camera_property_path = pl_utils.get_bound_camera_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
builtin_camera_name = pl_utils.is_local_builtin_camera(camera_path)
if not builtin_camera_name:
property_spec.default = str(camera_path)
else:
property_spec.default = builtin_camera_name
if builtin_camera_name:
persp_camera = pl_utils.get_user_shared_root_path(user_id).AppendChild(builtin_camera_name)
camera_prim = shared_stage.DefinePrim(persp_camera, "Camera")
await ui_test.human_delay(12)
def _get_shared_stage(self, current_session: layers.LiveSession):
shared_data_stage_url = current_session.url + "/shared_data/users.live"
layer = Sdf.Layer.FindOrOpen(shared_data_stage_url)
if not layer:
layer = Sdf.Layer.CreateNew(shared_data_stage_url)
return Usd.Stage.Open(layer)
async def _follow_user(
self, shared_stage: Usd.Stage, user_id: str, following_user_id: str
):
following_user_property_path = pl_utils.get_following_user_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), following_user_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = following_user_id
await ui_test.human_delay(6)
def _create_shared_stage(self):
current_session = self.get_live_syncing().get_current_live_session()
self.assertIsNotNone(current_session)
shared_stage = self._get_shared_stage(current_session)
self.assertIsNotNone(shared_stage)
return shared_stage
def _create_users(self, count):
return [f"user_{i}" for i in range(count)]
@MockLiveSyncingApi
async def test_live_session_camera_follower_list_user_join(self):
stage = await self._create_test_usd("test_camera")
usd_context = omni.usd.get_context()
presence_layer = pl.get_presence_layer_interface(usd_context)
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test_camera")
stage_url = usd_context.get_stage_url()
presence_layer = pl.get_presence_layer_interface(usd_context)
shared_stage = self._create_shared_stage()
camera_path = self._create_test_camera()
camera_follower_list = await self._setup_camera_follower_list(camera_path)
user_list = LiveSessionUserList(usd_context, stage_url)
users = self._create_users(3)
await self._bound_camera(shared_stage, users[0], camera_path)
for user_id in users:
join_new_simulated_user(user_id, user_id)
await ui_test.human_delay(6)
self.assertIsNotNone(presence_layer.get_bound_camera_prim(users[0]))
user_0 = self._get_user_in_session(users[0])
user_list._LiveSessionUserList__on_follow_user(
0.0,
0.0,
int(carb.input.MouseInput.LEFT_BUTTON),
None,
user_0
)
await ui_test.human_delay(6)
async def right_click_on(user):
user_list._LiveSessionUserList__on_mouse_clicked(
0.0,
0.0,
int(carb.input.MouseInput.RIGHT_BUTTON),
None,
user
)
await ui_test.human_delay(6)
timeline_session = omni.timeline.live_session.get_timeline_session()
self.assertFalse(timeline_session.is_presenter(user_0))
await right_click_on(user_0)
await self._click_on_current_menu("Set as Timeline Presenter")
self.assertTrue(timeline_session.is_presenter(user_0))
await right_click_on(user_0)
await self._click_on_current_menu("Withdraw Timeline Presenter")
self.assertFalse(timeline_session.is_presenter(user_0))
self.assertEqual(users[0], presence_layer.get_following_user_id())
await ui_test.human_delay(600)
for user_id in users:
quit_simulated_user(user_id)
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_live_session_camera_follower_list_bound_change(self):
stage = await self._create_test_usd("test_camera")
usd_context = omni.usd.get_context()
presence_layer = pl.get_presence_layer_interface(usd_context)
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test_camera")
stage_url = usd_context.get_stage_url()
presence_layer = pl.get_presence_layer_interface(usd_context)
shared_stage = self._create_shared_stage()
camera_path_1 = self._create_test_camera("camera1")
camera_path_2 = self._create_test_camera("camera2")
camera_follower_list = await self._setup_camera_follower_list(camera_path_1)
user_list = LiveSessionUserList(usd_context, stage_url)
users = self._create_users(2)
for user_id in users:
join_new_simulated_user(user_id, user_id)
await ui_test.human_delay(6)
await self._bound_camera(shared_stage, users[0], camera_path_1)
await self._bound_camera(shared_stage, users[1], camera_path_2)
await self._bound_camera(shared_stage, users[0], camera_path_2)
await self._bound_camera(shared_stage, users[1], camera_path_1)
for user_id in users:
quit_simulated_user(user_id)
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_live_session_camera_follower_list_user_join_exceed_maximum(self):
stage = await self._create_test_usd("test_camera")
usd_context = omni.usd.get_context()
presence_layer = pl.get_presence_layer_interface(usd_context)
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test_camera")
UI_MAXIMUM_USERS = 3
stage_url = usd_context.get_stage_url()
presence_layer = pl.get_presence_layer_interface(usd_context)
shared_stage = self._create_shared_stage()
camera_path = self._create_test_camera()
camera_follower_list = await self._setup_camera_follower_list(camera_path, maximum_users=UI_MAXIMUM_USERS)
user_list = LiveSessionUserList(usd_context, stage_url)
users = self._create_users(UI_MAXIMUM_USERS + 1)
for user in users:
await self._bound_camera(shared_stage, user, camera_path)
for user_id in users:
join_new_simulated_user(user_id, user_id)
await ui_test.human_delay(6)
for user_id in users:
quit_simulated_user(user_id)
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_end_and_merge(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._click_live_session_menu_item("End and Merge")
frame = ui_test.find("Merge Options")
self.assertIsNotNone(frame)
combo = ui_test.find(MERGE_OPTIONS_COMBO_BOX_PATH)
combo.model.get_item_value_model(None, 0).set_value(0)
ok_button = ui_test.find(MERGE_OPTIONS_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
@MockApiForLiveSessionManagement
async def test_end_and_merge_save_file(self):
self.assertFalse(get_merge_and_stop_live_session_async_called())
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._click_live_session_menu_item("End and Merge")
frame = ui_test.find("Merge Options")
self.assertIsNotNone(frame)
combo = ui_test.find(MERGE_OPTIONS_COMBO_BOX_PATH)
combo.model.get_item_value_model(None, 0).set_value(1)
ok_button = ui_test.find(MERGE_OPTIONS_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
self.assertTrue(get_merge_and_stop_live_session_async_called())
await self._close_case()
@MockLiveSyncingApi
async def test_end_and_merge_without_permission(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
current_session = self.get_live_syncing().get_current_live_session()
forbid_session_merge(current_session)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._click_live_session_menu_item("End and Merge")
frame = ui_test.find("Permission Denied")
self.assertIsNotNone(frame)
ok_button = ui_test.find(MERGE_PROMPT_LEAVE_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_reload_widget_on_layer(self):
stage = await self._create_test_usd("test")
usd_context = omni.usd.get_context()
await usd_context.attach_stage_async(stage)
await self._create_session("test")
layer = stage.GetSessionLayer()
window = omni.ui.Window(title='test_reload')
with window.frame:
reload_widget = build_reload_widget(layer.identifier, usd_context, True, True, False)
self.assertIsNotNone(reload_widget)
reload_widget.visible = True
await ui_test.human_delay(10)
window.width, window.height = 50, 50
reload_button = ui_test.find("test_reload//Frame/**/InvisibleButton[0]")
self.assertIsNotNone(reload_button)
await reload_button.click(right_click=True)
await ui_test.human_delay(6)
item_str_list = self._get_current_menu_item_string_list()
self.assertIn("Auto Reload", item_str_list)
self.assertIn("Reload Layer", item_str_list)
self.assertFalse(layers.get_layers_state(usd_context).is_auto_reload_layer(layer.identifier))
await self._click_on_current_menu("Auto Reload")
self.assertTrue(layers.get_layers_state(usd_context).is_auto_reload_layer(layer.identifier))
await reload_button.click(right_click=True)
await ui_test.human_delay(6)
await self._click_on_current_menu("Auto Reload")
self.assertFalse(layers.get_layers_state(usd_context).is_auto_reload_layer(layer.identifier))
await reload_button.click()
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
@MockApiForLiveSessionManagement
async def test_reload_widget_on_outdated_layer(self):
stage = await self._create_test_usd("test")
usd_context = omni.usd.get_context()
await usd_context.attach_stage_async(stage)
await self._create_session("test")
all_layers = []
for i in range(3):
layer = await self._create_test_sublayer_usd(f"layer_{i}")
self.assertIsNotNone(layer)
all_layers.append(layer)
stage.GetRootLayer().subLayerPaths.append(layer.identifier)
window = omni.ui.Window(title='test_reload')
with window.frame:
reload_widget = build_reload_widget(all_layers[0].identifier, usd_context, True, True, False)
self.assertIsNotNone(reload_widget)
reload_widget.visible = True
await ui_test.human_delay(10)
window.width, window.height = 50, 50
reload_button = ui_test.find("test_reload//Frame/**/InvisibleButton[0]")
self.assertIsNotNone(reload_button)
layer = all_layers[0]
custom_data = layer.customLayerData
custom_data['test'] = random.randint(0, 10000000)
layer.customLayerData = custom_data
layer.Save(True)
await ui_test.human_delay(6)
append_outdated_layers(all_layers[0].identifier)
await reload_button.click()
await ui_test.human_delay(6)
clear_outdated_layers()
await self._close_case()
async def test_live_session_preferences(self):
preferences = register_page(LiveSessionPreferences())
omni.kit.window.preferences.show_preferences_window()
await ui_test.human_delay(6)
label = ui_test.find("Preferences//Frame/**/ScrollingFrame[0]/TreeView[0]/Label[*].text=='Live'")
await label.click()
await ui_test.human_delay(6)
self.assertIsNotNone(preferences._checkbox_quick_join_enabled)
self.assertIsNotNone(preferences._combobox_session_list_select)
await ui_test.human_delay(6)
omni.kit.window.preferences.hide_preferences_window()
unregister_page(preferences)
def _get_user_in_session(self, user_id):
current_session = self.get_live_syncing().get_current_live_session()
session_channel = current_session._session_channel()
return session_channel._peer_users.get(user_id, None)
@MockLiveSyncingApi
async def test_file_picker(self):
temp_dir = tempfile.TemporaryDirectory()
def file_save_handler(file_path: str, overwrite_existing: bool):
prefix = "file:/"
self.assertTrue(file_path.startswith(prefix))
nonlocal called
called = True
def file_open_handler(file_path: str, overwrite_existing: bool):
nonlocal called
called = True
filter_options = [
("(.*?)", "All Files (*.*)"),
]
FILE_PICKER_DIALOG_TITLE = "test file picker"
file_picker = FilePicker(
FILE_PICKER_DIALOG_TITLE,
FileBrowserMode.SAVE,
FileBrowserSelectionType.FILE_ONLY,
filter_options,
)
called = False
file_picker.set_file_selected_fn(file_save_handler)
file_picker.show(temp_dir.name, 'test_file_picker')
await ui_test.human_delay(6)
button = ui_test.find(f"{FILE_PICKER_DIALOG_TITLE}//Frame/**/Button[*].text=='Save'")
self.assertIsNotNone(button)
await button.click()
await ui_test.human_delay(6)
self.assertTrue(called)
file_picker = FilePicker(
FILE_PICKER_DIALOG_TITLE,
FileBrowserMode.OPEN,
FileBrowserSelectionType.FILE_ONLY,
filter_options,
)
called = False
file_picker.set_file_selected_fn(file_open_handler)
file_picker.show(temp_dir.name)
await ui_test.human_delay(6)
button = ui_test.find(f"{FILE_PICKER_DIALOG_TITLE}//Frame/**/Button[*].text=='Open'")
self.assertIsNotNone(button)
await button.click()
await ui_test.human_delay(6)
self.assertTrue(called)
| 32,194 | Python | 38.024242 | 135 | 0.647139 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/docs/CHANGELOG.md | # Changelog
Omniverse Kit Shared Live Session Widgets
## [1.1.3] - 2022-11-21
### Changed
- Prompt if layer is outdate or dirty before live.
## [1.1.2] - 2022-10-27
### Changed
- Fix deprecated API warnings.
## [1.1.1] - 2022-10-15
### Changed
- Fix issue to refresh session list.
## [1.1.0] - 2022-09-29
### Changed
- Supports sublayer live session workflow.
## [1.0.6] - 2022-09-02
### Changed
- Add name validator for session name input.
## [1.0.5] - 2022-08-30
### Changed
- Show menu options for join.
## [1.0.4] - 2022-08-25
### Changed
- Notifications for read-only stage.
## [1.0.3] - 2022-08-09
### Changed
- Notify user before quitting application that session is live still.
## [1.0.2] - 2022-07-19
### Changed
- Shows menu still even session is empty when it's not forcely quit.
## [1.0.1] - 2022-06-29
### Changed
- Supports more options to control session menus.
## [1.0.0] - 2022-06-15
### Fixed
- Initialize extension. | 946 | Markdown | 19.148936 | 69 | 0.657505 |
omniverse-code/kit/exts/omni.kit.property.camera/PACKAGE-LICENSES/omni.kit.property.camera-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.property.camera/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.3"
category = "Internal"
feature = true
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "Camera Property Widget"
description="View and Edit Camera Property Values"
# URL of the extension source repository.
repository = ""
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Keywords for the extension
keywords = ["kit", "usd", "property", "camera"]
# 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"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
[dependencies]
"omni.usd" = {}
"omni.ui" = {}
"omni.kit.window.property" = {}
"omni.kit.property.usd" = {}
[[python.module]]
name = "omni.kit.property.camera"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers"
]
stdoutFailPatterns.exclude = [
"*Failed to acquire interface*while unloading all plugins*"
]
| 1,582 | TOML | 25.383333 | 93 | 0.709229 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/__init__.py | from .scripts import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/scripts/camera_properties.py | import os
import carb
import omni.ext
from typing import List
from pathlib import Path
from pxr import Kind, Sdf, Usd, UsdGeom, Vt
from omni.kit.property.usd.usd_property_widget import MultiSchemaPropertiesWidget, UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import create_primspec_token, create_primspec_float, create_primspec_bool, create_primspec_string
TEST_DATA_PATH = ""
class CameraPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from . import CameraSchemaAttributesWidget
w = p.get_window()
if w:
w.register_widget(
"prim",
"camera",
CameraSchemaAttributesWidget(
"Camera",
UsdGeom.Camera,
[],
[
"cameraProjectionType",
"fthetaWidth",
"fthetaHeight",
"fthetaCx",
"fthetaCy",
"fthetaMaxFov",
"fthetaPolyA",
"fthetaPolyB",
"fthetaPolyC",
"fthetaPolyD",
"fthetaPolyE",
"fthetaPolyF",
"p0",
"p1",
"s0",
"s1",
"s2",
"s3",
"fisheyeResolutionBudget",
"fisheyeFrontFaceResolutionScale",
"interpupillaryDistance", # Only required for 'omniDirectionalStereo'
"isLeftEye", # Only required for 'omniDirectionalStereo'
"cameraSensorType",
"sensorModelPluginName",
"sensorModelConfig",
"sensorModelSignals",
"crossCameraReferenceName"
],
[],
),
)
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "camera")
self._registered = False
class CameraSchemaAttributesWidget(MultiSchemaPropertiesWidget):
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
# custom attributes
cpt_tokens = Vt.TokenArray(9, ("pinhole", "fisheyeOrthographic", "fisheyeEquidistant", "fisheyeEquisolid", "fisheyePolynomial", "fisheyeSpherical", "fisheyeKannalaBrandtK3", "fisheyeRadTanThinPrism", "omniDirectionalStereo"))
cst_tokens = Vt.TokenArray(4, ("camera", "radar", "lidar", "rtxsensor"))
self.add_custom_schema_attribute("cameraProjectionType", lambda p: p.IsA(UsdGeom.Camera), None, "Projection Type", create_primspec_token(cpt_tokens, "pinhole"))
self.add_custom_schema_attribute("fthetaWidth", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1936.0))
self.add_custom_schema_attribute("fthetaHeight", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1216.0))
self.add_custom_schema_attribute("fthetaCx", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(970.942444))
self.add_custom_schema_attribute("fthetaCy", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(600.374817))
self.add_custom_schema_attribute("fthetaMaxFov", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(200.0))
self.add_custom_schema_attribute("fthetaPolyA", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(0.0))
self.add_custom_schema_attribute("fthetaPolyB", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(2.45417095720768e-3))
self.add_custom_schema_attribute("fthetaPolyC", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(3.72747912535942e-8))
self.add_custom_schema_attribute("fthetaPolyD", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-1.43520517692508e-9))
self.add_custom_schema_attribute("fthetaPolyE", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(9.76061787817672e-13))
self.add_custom_schema_attribute("fthetaPolyF", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(0.0))
self.add_custom_schema_attribute("p0", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0003672190538065101))
self.add_custom_schema_attribute("p1", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0007413905358394097))
self.add_custom_schema_attribute("s0", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0005839984838196491))
self.add_custom_schema_attribute("s1", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0002193412417918993))
self.add_custom_schema_attribute("s2", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(0.0001936268547567258))
self.add_custom_schema_attribute("s3", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0002042473404798113))
self.add_custom_schema_attribute("fisheyeResolutionBudget", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1.5))
self.add_custom_schema_attribute("fisheyeFrontFaceResolutionScale", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1.0))
self.add_custom_schema_attribute("interpupillaryDistance", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(6.4))
self.add_custom_schema_attribute("isLeftEye", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("sensorModelPluginName", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("sensorModelConfig", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("sensorModelSignals", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("crossCameraReferenceName", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("cameraSensorType", lambda p: p.IsA(UsdGeom.Camera), None, "Sensor Type", create_primspec_token(cst_tokens, "camera"))
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim or not prim.IsA(self._schema):
return False
used += [attr for attr in prim.GetAttributes() if attr.GetName() in self._schema_attr_names and not attr.IsHidden()]
camProjTypeAttr = prim.GetAttribute("cameraProjectionType")
if prim.IsA(UsdGeom.Camera) and camProjTypeAttr.GetTypeName() == Sdf.ValueTypeNames.Token:
tokens = camProjTypeAttr.GetMetadata("allowedTokens")
if not tokens:
camProjTypeAttr.SetMetadata("allowedTokens", ["pinhole", "fisheyeOrthographic", "fisheyeEquidistant", "fisheyeEquisolid", "fisheyePolynomial", "fisheyeSpherical", "fisheyeKannalaBrandtK3", "fisheyeRadTanThinPrism", "omniDirectionalStereo"])
if self.is_custom_schema_attribute_used(prim):
used.append(None)
camSensorTypeAttr = prim.GetAttribute("cameraSensorType")
if prim.IsA(UsdGeom.Camera) and camSensorTypeAttr.GetTypeName() == Sdf.ValueTypeNames.Token:
tokens = camSensorTypeAttr.GetMetadata("allowedTokens")
if not tokens:
camSensorTypeAttr.SetMetadata("allowedTokens", ["camera", "radar", "lidar", "rtxsensor"])
return used
def _customize_props_layout(self, attrs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.window.property.templates import (
SimplePropertyWidget,
LABEL_WIDTH,
LABEL_HEIGHT,
HORIZONTAL_SPACING,
)
self.add_custom_schema_attributes_to_props(attrs)
anchor_prim = self._get_prim(self._payload[-1])
frame = CustomLayoutFrame(hide_extra=False)
with frame:
with CustomLayoutGroup("Lens"):
CustomLayoutProperty("focalLength", "Focal Length")
CustomLayoutProperty("focusDistance", "Focus Distance")
CustomLayoutProperty("fStop", "fStop")
CustomLayoutProperty("projection", "Projection")
CustomLayoutProperty("stereoRole", "Stereo Role")
with CustomLayoutGroup("Horizontal Aperture"):
CustomLayoutProperty("horizontalAperture", "Aperture")
CustomLayoutProperty("horizontalApertureOffset", "Offset")
with CustomLayoutGroup("Vertical Aperture"):
CustomLayoutProperty("verticalAperture", "Aperture")
CustomLayoutProperty("verticalApertureOffset", "Offset")
with CustomLayoutGroup("Clipping"):
CustomLayoutProperty("clippingPlanes", "Clipping Planes")
CustomLayoutProperty("clippingRange", "Clipping Range")
with CustomLayoutGroup("Fisheye Lens", collapsed=True):
CustomLayoutProperty("cameraProjectionType", "Projection Type")
CustomLayoutProperty("fthetaWidth", "Nominal Width")
CustomLayoutProperty("fthetaHeight", "Nominal Height")
CustomLayoutProperty("fthetaCx", "Optical Center X")
CustomLayoutProperty("fthetaCy", "Optical Center Y")
CustomLayoutProperty("fthetaMaxFov", "Max FOV")
CustomLayoutProperty("fthetaPolyA", "Poly k0")
CustomLayoutProperty("fthetaPolyB", "Poly k1")
CustomLayoutProperty("fthetaPolyC", "Poly k2")
CustomLayoutProperty("fthetaPolyD", "Poly k3")
CustomLayoutProperty("fthetaPolyE", "Poly k4")
CustomLayoutProperty("fthetaPolyF", "Poly k5")
CustomLayoutProperty("p0", "p0")
CustomLayoutProperty("p1", "p1")
CustomLayoutProperty("s0", "s0")
CustomLayoutProperty("s1", "s1")
CustomLayoutProperty("s2", "s2")
CustomLayoutProperty("s3", "s3")
CustomLayoutProperty("fisheyeResolutionBudget", "Max Fisheye Resolution (% of Viewport Resolution")
CustomLayoutProperty("fisheyeFrontFaceResolutionScale", "Front Face Resolution Scale")
CustomLayoutProperty("interpupillaryDistance", "Interpupillary Distance (cm)")
CustomLayoutProperty("isLeftEye", "Is left eye")
with CustomLayoutGroup("Shutter", collapsed=True):
CustomLayoutProperty("shutter:open", "Open")
CustomLayoutProperty("shutter:close", "Close")
with CustomLayoutGroup("Sensor Model", collapsed=True):
CustomLayoutProperty("cameraSensorType", "Sensor Type")
CustomLayoutProperty("sensorModelPluginName", "Sensor Plugin Name")
CustomLayoutProperty("sensorModelConfig", "Sensor Config")
CustomLayoutProperty("sensorModelSignals", "Sensor Signals")
with CustomLayoutGroup("Synthetic Data Generation", collapsed=True):
CustomLayoutProperty("crossCameraReferenceName", "Cross Camera Reference")
return frame.apply(attrs)
def get_additional_kwargs(self, ui_prop: UsdPropertyUiEntry):
"""
Override this function if you want to supply additional arguments when building the label or ui widget.
"""
additional_widget_kwargs = None
if ui_prop.prop_name == "fisheyeResolutionBudget":
additional_widget_kwargs = {"min": 0, "max": 10}
if ui_prop.prop_name == "fisheyeFrontFaceResolutionScale":
additional_widget_kwargs = {"min": 0, "max": 10}
return None, additional_widget_kwargs
| 14,637 | Python | 57.087301 | 260 | 0.581813 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/scripts/__init__.py | from .camera_properties import *
| 33 | Python | 15.999992 | 32 | 0.787879 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/tests/__init__.py | from .test_camera import *
from .test_prim_edits_and_auto_target import *
| 74 | Python | 23.999992 | 46 | 0.756757 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/tests/test_prim_edits_and_auto_target.py |
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import carb
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf, Usd
class TestPrimEditsAndAutoTarget(omni.kit.test.AsyncTestCase):
def __init__(self, tests=()):
super().__init__(tests)
# Before running each test
async def setUp(self):
self._usd_context = omni.usd.get_context()
await self._usd_context.new_stage_async()
self._stage = self._usd_context.get_stage()
from omni.kit.test_suite.helpers import arrange_windows
await arrange_windows(topleft_window="Property", topleft_height=64, topleft_width=800.0)
await self.wait()
# After running each test
async def tearDown(self):
from omni.kit.test_suite.helpers import wait_stage_loading
await wait_stage_loading()
async def wait(self, updates=3):
for i in range(updates):
await omni.kit.app.get_app().next_update_async()
async def test_built_in_camera_editing(self):
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
# wait for material to load & UI to refresh
await wait_stage_loading()
prim_path = "/OmniverseKit_Persp"
await select_prims([prim_path])
# Loading all inputs
await self.wait()
all_widgets = ui_test.find_all("Property//Frame/**/.identifier!=''")
self.assertNotEqual(all_widgets, [])
for w in all_widgets:
id = w.widget.identifier
if id.startswith("float_slider_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
await w.input(str(0.3456))
await ui_test.human_delay()
elif id.startswith("integer_slider_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[15:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = old_value + 1
await w.input(str(new_value))
await ui_test.human_delay()
elif id.startswith("drag_per_channel_int"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/IntSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/IntDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
child.model.set_value(0)
await child.input("9999")
await ui_test.human_delay()
elif id.startswith("drag_per_channel_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/FloatSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/FloatDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
await child.input("0.12345")
await self.wait()
elif id.startswith("bool_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[5:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = not old_value
w.widget.model.set_value(new_value)
elif id.startswith("sdf_asset_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
new_value = "testpath/abc.png"
w.widget.model.set_value(new_value)
await ui_test.human_delay()
# All property edits to built-in cameras should be retargeted into session layer.
root_layer = self._stage.GetRootLayer()
prim_spec = root_layer.GetPrimAtPath("/OmniverseKit_Persp")
self.assertTrue(bool(prim_spec))
| 4,561 | Python | 39.371681 | 96 | 0.578163 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/tests/test_camera.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf
import pathlib
class TestCameraWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
from omni.kit.property.camera.scripts.camera_properties import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_camera_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=675,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("camera_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/Camera"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_camera_ui.png")
| 2,162 | Python | 35.661016 | 107 | 0.691489 |
omniverse-code/kit/exts/omni.kit.property.camera/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.3] - 2021-02-19
### Changes
- Added UI test
## [1.0.2] - 2020-12-09
### Changes
- Added extension icon
- Added readme
- Updated preview image
## [1.0.1] - 2020-10-22
### Changes
- Improved layout
## [1.0.0] - 2020-09-17
### Changes
- Created
| 348 | Markdown | 14.863636 | 80 | 0.632184 |
omniverse-code/kit/exts/omni.kit.property.camera/docs/README.md | # omni.kit.property.camera
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension supports editing of these Usd Types;
- UsdGeom.Camera
| 195 | Markdown | 16.81818 | 74 | 0.784615 |
omniverse-code/kit/exts/omni.kit.property.camera/docs/index.rst | omni.kit.property.camera
###########################
Property Camera Values
.. toctree::
:maxdepth: 1
CHANGELOG
| 123 | reStructuredText | 9.333333 | 27 | 0.536585 |
omniverse-code/kit/exts/omni.rtx.multinode.dev/PACKAGE-LICENSES/omni.rtx.multinode.dev-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.rtx.multinode.dev/config/extension.toml | [package]
title = "RTX Multi-Node Prototype"
description="Developer prototype controls for RTX multi-node rendering."
authors = ["NVIDIA"]
version = "0.1.0"
category = "Rendering"
keywords = ["kit", "rtx", "rendering", "multi-node"]
repository = ""
[dependencies]
"omni.gpu_foundation" = {}
"omni.graph.core" = {}
"omni.physx.bundle" = {}
"omni.physx.flatcache" = {}
[[python.module]]
name = "omni.rtx.multinode.dev"
[[test]]
waiver = "Extension is tested externally" | 471 | TOML | 21.476189 | 72 | 0.685775 |
omniverse-code/kit/exts/omni.rtx.multinode.dev/omni/rtx/multinode/dev/multinode.py | import traceback
import uuid
import carb
import carb.settings
import omni.ext
import omni.ui as ui
import omni.gpu_foundation_factory
import omni.client
from random import random
import math
from omni.physx.scripts import physicsUtils
from pxr import UsdLux, UsdGeom, Gf, UsdPhysics
def print_exception(exc_info):
print(f"===== Exception: {exc_info[0]}, {exc_info[1]}. Begin Stack Trace =====")
traceback.print_tb(exc_info[2])
print("===== End Stack Trace ===== ")
class Extension(omni.ext.IExt):
def on_startup(self):
# Obtain multi process info
gpu = omni.gpu_foundation_factory.get_gpu_foundation_factory_interface()
processIndex = gpu.get_process_index()
processCount = gpu.get_process_count()
# Settings
self._settings = carb.settings.get_settings()
self._settings.set("/persistent/physics/updateToUsd", False)
self._settings.set("/persistent/physics/updateVelocitiesToUsd", False)
self._settings.set("/persistent/omnihydra/useFastSceneDelegate", True)
self._settings.set("/app/renderer/sleepMsOutOfFocus", 0)
if processIndex > 0:
self._settings.set("/app/window/title", "Kit Worker {} //".format(processIndex))
# UI
self._window = ui.Window("RTX Multi-Node Prototype", dockPreference=ui.DockPreference.LEFT_BOTTOM)
self._window.deferred_dock_in("Console", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
with self._window.frame:
with omni.ui.HStack(height=0):
omni.ui.Spacer(width=6)
with omni.ui.VStack(height=0):
omni.ui.Spacer(height=10)
with omni.ui.HStack(height=0):
if processIndex == 0:
omni.ui.Label("Master process of {}".format(processCount))
else:
omni.ui.Label("Worker process {} of {}".format(processIndex, processCount))
if processIndex == 0:
omni.ui.Spacer(height=20)
with omni.ui.HStack():
with omni.ui.VStack(height=0):
omni.ui.Label("Settings")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=10)
with omni.ui.VStack(width = 200, height = 0):
with omni.ui.HStack():
omni.ui.Label("Fabric Replication")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/flatcacheReplication/enabled"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/flatcacheReplication/enabled", a.get_value_as_bool()))
omni.ui.Label("Enabled")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/flatcacheReplication/profile"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/flatcacheReplication/profile", a.get_value_as_bool()))
omni.ui.Label("Profile")
omni.ui.Spacer(height=10)
with omni.ui.HStack():
omni.ui.Label("Gather Render Results")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/gatherResults/enabled"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/gatherResults/enabled", a.get_value_as_bool()))
omni.ui.Label("Enabled")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/gatherResults/profile"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/gatherResults/profile", a.get_value_as_bool()))
omni.ui.Label("Profile")
with omni.ui.VStack(width = 200, height=0):
with omni.ui.HStack():
omni.ui.Label("Render Product Replication")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/enabled"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/enabled", a.get_value_as_bool()))
omni.ui.Label("Enabled")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/includeCameraAttributes"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/includeCameraAttributes", a.get_value_as_bool()))
omni.ui.Label("Include Camera Attributes")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/fullSessionLayer"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/fullSessionLayer", a.get_value_as_bool()))
omni.ui.Label("Full Session Layer")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/profile"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/profile", a.get_value_as_bool()))
omni.ui.Label("Profile")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/print"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/print", a.get_value_as_bool()))
omni.ui.Label("Print")
omni.ui.Spacer(width=200)
with omni.ui.VStack(height=0):
omni.ui.Label("Deprecated: Physics prototype")
omni.ui.Spacer(height=10)
with omni.ui.HStack(height=0):
load_button = omni.ui.Button("Load Stage", width=150, height=30)
load_button.set_clicked_fn(self._on_load_button_fn)
omni.ui.Spacer(height=5)
with omni.ui.HStack(height=0):
self._numBoxesDrag = omni.ui.IntDrag(min = 1, max = 1000000, step = 1, width = 100)
self._numBoxesDrag.model.set_value(1000)
omni.ui.Spacer(width=10)
omni.ui.Label("Boxes")
omni.ui.Spacer(height=5)
with omni.ui.HStack(height=0):
init_button = omni.ui.Button("Init Simulation", width=150, height=30)
init_button.set_clicked_fn(self._on_init_button_fn)
omni.ui.Spacer(height=5)
with omni.ui.HStack(height=0):
play_button = omni.ui.Button("Play Simulation", width=150, height=30)
play_button.set_clicked_fn(self._on_play_button_fn)
omni.ui.Spacer()
def on_shutdown(self):
pass
def _on_load_button_fn(self):
carb.log_warn("Load stage")
srcPath = "omniverse://content.ov.nvidia.com/Users/[email protected]/multi-node/empty.usd"
dstPath = "omniverse://content.ov.nvidia.com/Users/[email protected]/multi-node/gen/" + str(uuid.uuid4()) + ".usd"
# Create a temporary copy
try:
result = omni.client.copy(srcPath, dstPath, omni.client.CopyBehavior.OVERWRITE)
if result != omni.client.Result.OK:
carb.log_error(f"Cannot copy from {srcPath} to {dstPath}, error code: {result}.")
else:
carb.log_warn(f"Copied from {srcPath} to {dstPath}.")
except Exception as e:
traceback.print_exc()
carb.log_error(str(e))
# Load the temporary copy
omni.usd.get_context().open_stage(str(dstPath))
# FIXME: Add compatible API for legacy usage.
# Enable live sync
# omni.usd.get_context().set_stage_live(layers.LayerLiveMode.ALWAYS_ON)
def _on_init_button_fn(self):
carb.log_warn("Init simulation")
# Disable FlatCache replication
self._settings.set("/multiNode/flatcacheReplication/enabled", False)
# set up axis to z
stage = omni.usd.get_context().get_stage()
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(stage, 0.01)
# Disable default light
defaultPrimPath = str(stage.GetDefaultPrim().GetPath())
stage.RemovePrim(defaultPrimPath + "/defaultLight")
# light
sphereLight = UsdLux.SphereLight.Define(stage, defaultPrimPath + "/SphereLight")
sphereLight.CreateRadiusAttr(30)
sphereLight.CreateIntensityAttr(50000)
sphereLight.AddTranslateOp().Set(Gf.Vec3f(0.0, 0.0, 150.0))
# Boxes
numBoxes = self._numBoxesDrag.model.get_value_as_int()
size = 25.0
radius = 100.0
self._boxes = [None] * numBoxes
for i in range(numBoxes):
box = UsdGeom.Cube.Define(stage, defaultPrimPath + "/box_" + str(i))
box.CreateSizeAttr(size)
box.CreateExtentAttr([(-size / 2, -size / 2, -size / 2), (size / 2, size / 2, size / 2)])
box.AddTranslateOp().Set(Gf.Vec3f(radius * math.cos(0.5 * i), radius * math.sin(0.5 * i), size + (i * 0.2) * size))
box.AddOrientOp().Set(Gf.Quatf(random(), random(), random(), random()).GetNormalized())
box.CreateDisplayColorAttr().Set([Gf.Vec3f(random(), random(), random())])
self._boxes[i] = box.GetPrim()
# Plane
planeActorPath = defaultPrimPath + "/plane"
size = 1500.0
planeGeom = UsdGeom.Cube.Define(stage, planeActorPath)
self._plane = stage.GetPrimAtPath(planeActorPath)
planeGeom.CreateSizeAttr(size)
planeGeom.CreateExtentAttr([(-size / 2, -size / 2, -size / 2), (size / 2, size / 2, size / 2)])
planeGeom.AddTranslateOp().Set(Gf.Vec3f(0.0, 0.0, 0.0))
planeGeom.AddOrientOp().Set(Gf.Quatf(1.0))
planeGeom.AddScaleOp().Set(Gf.Vec3f(1.0, 1.0, 0.01))
planeGeom.CreateDisplayColorAttr().Set([Gf.Vec3f(0.5)])
def _on_play_button_fn(self):
carb.log_warn("Play simulation")
# FIXME: Add compatible API for legacy usage.
# Disable live sync
# omni.usd.get_context().set_stage_live(layers.LayerLiveMode.TOGGLE_OFF)
# Enable FlatCache replication
self._settings.set("/multiNode/flatcacheReplication/enabled", True)
# Add physics to scene
stage = omni.usd.get_context().get_stage()
defaultPrimPath = str(stage.GetDefaultPrim().GetPath())
scene = UsdPhysics.Scene.Define(stage, defaultPrimPath + "/physicsScene")
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(981.0)
for box in self._boxes:
UsdPhysics.CollisionAPI.Apply(box)
physicsAPI = UsdPhysics.RigidBodyAPI.Apply(box)
UsdPhysics.MassAPI.Apply(box)
UsdPhysics.CollisionAPI.Apply(self._plane)
# Play animation
omni.timeline.get_timeline_interface().play()
| 14,830 | Python | 53.127737 | 190 | 0.494066 |
omniverse-code/kit/exts/omni.rtx.multinode.dev/omni/rtx/multinode/dev/__init__.py | from .multinode import *
| 25 | Python | 11.999994 | 24 | 0.76 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ext
from .stage_listener import StageListener
_global_instance = None
class SelectionOutlineExtension(omni.ext.IExt):
def on_startup(self):
global _global_instance
_global_instance = self
self._stage_listener = StageListener()
self._stage_listener.start()
def on_shutdown(self):
global _global_instance
_global_instance = None
self._stage_listener.stop()
@staticmethod
def _get_instance():
global _global_instance
return _global_instance
| 989 | Python | 28.999999 | 76 | 0.723964 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import SelectionOutlineExtension
| 482 | Python | 47.299995 | 76 | 0.817427 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/stage_listener.py | import asyncio
import carb
import omni.client
import omni.usd
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
from omni.kit.async_engine import run_coroutine
from .manipulator import PeerUserList
from pxr import Sdf, Usd, UsdGeom, Tf, Trace
from typing import Dict, List, Union
SETTING_MULTI_USER_OUTLINE = "/app/viewport/multiUserOutlineMode"
SETTING_SAVED_OUTLINE_COLOR = "/persistent/app/viewport/live_session/saved_outline_color"
SETTING_OUTLINE_COLOR = "/persistent/app/viewport/outline/color"
SETTING_MAXIMUM_SELECTION_ICONS_PER_USER = "/exts/omni/kit/collaboration/selection_outline/maximum_selection_icons_per_user"
class MultiUserSelectionOutlineManager:
def __init__(self, usd_context: omni.usd.UsdContext) -> None:
self.__usd_context = usd_context
self.__settings = carb.settings.get_settings()
self.__user_last_selected_prims = {}
self.__prim_selection_queue = {}
self.__user_selection_group = {}
self.__selection_group_pool = []
self.__prim_viewport_widget = {}
self._delay_refresh_task_or_future = None
def clear_all_selection(self):
self.__user_last_selected_prims = {}
self.__prim_selection_queue = {}
self.__user_selection_group = {}
for widget in self.__prim_viewport_widget.values():
widget.destroy()
self.__prim_viewport_widget = {}
if self._delay_refresh_task_or_future:
self._delay_refresh_task_or_future.cancel()
self._delay_refresh_task_or_future = None
def clear_selection(self, user_id):
"""Deregister user from selection group."""
selection_group = self.__user_selection_group.pop(user_id, None)
if selection_group:
self.__update_selection_outline_internal(user_id, selection_group, {})
# Returns selection group to re-use as it supports 255 at maximum due to limitation of renderer.
self.__selection_group_pool.append(selection_group)
def on_usd_objects_changed(self, notice):
stage = self.__usd_context.get_stage()
to_remove_paths = []
to_update_paths = []
for widget_path, widget in self.__prim_viewport_widget.items():
prim = stage.GetPrimAtPath(widget_path)
if not prim or not prim.IsActive() or not prim.IsDefined():
to_remove_paths.append(widget_path)
elif notice.ResyncedObject(prim):
to_update_paths.append(widget_path)
else:
changed_info_only_paths = notice.GetChangedInfoOnlyPaths()
slice_object = Sdf.Path.FindPrefixedRange(changed_info_only_paths, widget_path)
if not slice_object:
continue
paths = changed_info_only_paths[slice_object]
if not paths:
continue
for path in paths:
if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name):
to_update_paths.append(widget_path)
break
for path in to_remove_paths:
widget = self.__prim_viewport_widget.pop(path, None)
widget.destroy()
for path in to_update_paths:
widget = self.__prim_viewport_widget.get(path, None)
widget.on_transform_changed()
def refresh_selection(self, selection_paths: List[Sdf.Path]):
"""
Calls this to refresh selection. This is normally called after selection changed, which will
override the outline of remote users.
"""
if not selection_paths:
return
for path in selection_paths:
self.__set_prim_outline(0, path)
async def delay_refresh(paths):
await omni.kit.app.get_app().next_update_async()
for path in paths:
selection_queue = self.__get_selection_queue(path)
for _, group in selection_queue.items():
self.__set_prim_outline(group, path)
break
self._delay_refresh_task_or_future = None
if self._delay_refresh_task_or_future and not self._delay_refresh_task_or_future.done():
self._delay_refresh_task_or_future.cancel()
self._delay_refresh_task_or_future = run_coroutine(delay_refresh(selection_paths))
def update_selection_outline(self, user_info: layers.LiveSessionUser, selection_paths: List[Sdf.Path]):
user_id = user_info.user_id
selection_group = self.__user_selection_group.get(user_id, None)
if not selection_group:
# Re-use selection group.
if self.__selection_group_pool:
selection_group = self.__selection_group_pool.pop(0)
else:
selection_group = self.__usd_context.register_selection_group()
self.__user_selection_group[user_id] = selection_group
# RGBA
color = (
user_info.user_color[0] / 255.0,
user_info.user_color[1] / 255.0,
user_info.user_color[2] / 255.0,
1.0
)
self.__usd_context.set_selection_group_outline_color(selection_group, color)
self.__usd_context.set_selection_group_shade_color(selection_group, (0.0, 0.0, 0.0, 0.0))
if selection_group == 0:
carb.log_error("The maximum number (255) of selection groups is reached.")
return
selection_paths = [Sdf.Path(path) for path in selection_paths]
selection_paths = Sdf.Path.RemoveDescendentPaths(selection_paths)
stage = self.__usd_context.get_stage()
# Find all renderable prims
all_renderable_prims = {}
for path in selection_paths:
prim = stage.GetPrimAtPath(path)
if not prim:
continue
renderable_prims = []
for prim in Usd.PrimRange(prim, Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)):
# Camera in Kit has special representation, which needs to be excluded.
if (
not prim.IsActive()
or omni.usd.editor.is_hide_in_ui(prim)
or omni.usd.editor.is_hide_in_stage_window(prim)
):
break
if (
not prim.GetPath().name == "CameraModel"
and not prim.GetPath().GetParentPath().name == "OmniverseKitViewportCameraMesh"
and prim.IsA(UsdGeom.Gprim)
):
renderable_prims.append(prim.GetPath())
if renderable_prims:
all_renderable_prims[path] = renderable_prims
selection_paths = all_renderable_prims
# Draw user icon
maximum_count = self.__settings.get(SETTING_MAXIMUM_SELECTION_ICONS_PER_USER)
if not maximum_count or maximum_count <= 0:
maximum_count = 3
for index, path in enumerate(selection_paths.keys()):
path = Sdf.Path(path)
widget = self.__prim_viewport_widget.get(path, None)
if not widget:
widget = PeerUserList(self.__usd_context, path)
self.__prim_viewport_widget[path] = widget
widget.add_user(user_info)
# OMFP-2736: Don't show all selections to avoid cluttering the viewport.
if index + 1 >= maximum_count:
break
self.__update_selection_outline_internal(user_id, selection_group, selection_paths)
def __update_selection_outline_internal(
self, user_id, selection_group,
all_renderable_paths: Dict[Sdf.Path, List[Sdf.Path]]
):
last_selected_prim_and_renderable_paths = self.__user_last_selected_prims.get(user_id, {})
last_selected_prim_paths = set(last_selected_prim_and_renderable_paths.keys())
selection_paths = set(all_renderable_paths.keys())
if last_selected_prim_paths == selection_paths:
return
if last_selected_prim_paths:
old_selected_paths = last_selected_prim_paths.difference(selection_paths)
new_selected_paths = selection_paths.difference(last_selected_prim_paths)
else:
old_selected_paths = set()
new_selected_paths = selection_paths
# Update selection outline for old paths
to_clear_paths = []
for path in old_selected_paths:
# Remove user icon
widget = self.__prim_viewport_widget.get(path, None)
if widget:
widget.remove_user(user_id)
if widget.empty_user_list():
self.__prim_viewport_widget.pop(path, None)
widget.destroy()
# Remove outline of all renderable prims under the selected path.
renderable_paths = last_selected_prim_and_renderable_paths.get(path, None)
for renderable_path in renderable_paths:
selection_queue = self.__get_selection_queue(renderable_path)
if selection_queue:
# FIFO queue that first user that selects the prim decides the color of selection.
group = next(iter(selection_queue.values()))
same_group = selection_group == group
# Pop this user and outline the prim with next user's selection color.
selection_queue.pop(user_id, None)
if same_group and selection_queue:
for _, group in selection_queue.items():
self.__set_prim_outline(group, renderable_path)
break
elif same_group:
to_clear_paths.append(renderable_path)
# Update selection outline for new paths
to_select_paths = []
for path in new_selected_paths:
renderable_paths = all_renderable_paths.get(path, None)
if not renderable_paths:
continue
for renderable_path in renderable_paths:
selection_queue = self.__get_selection_queue(renderable_path)
has_outline = not not selection_queue
selection_queue[user_id] = selection_group
if not has_outline:
to_select_paths.append(renderable_path)
if to_clear_paths:
self.__clear_prim_outline(to_clear_paths)
if to_select_paths:
self.__set_prim_outline(selection_group, to_select_paths)
self.__user_last_selected_prims[user_id] = all_renderable_paths
def __get_selection_queue(self, prim_path):
prim_path = Sdf.Path(prim_path)
if prim_path not in self.__prim_selection_queue:
# Value is dict to keep order of insertion.
self.__prim_selection_queue[prim_path] = {}
return self.__prim_selection_queue[prim_path]
def __set_prim_outline(self, selection_group, prim_path: Union[Sdf.Path, List[Sdf.Path]]):
if isinstance(prim_path, list):
paths = [str(path) for path in prim_path]
else:
paths = [str(prim_path)]
selection = self.__usd_context.get_selection().get_selected_prim_paths()
for path in paths:
# If it's locally selected, don't override the outline.
if path in selection:
continue
self.__usd_context.set_selection_group(selection_group, path)
def __clear_prim_outline(self, prim_path: Union[Sdf.Path, List[Sdf.Path]]):
self.__set_prim_outline(0, prim_path)
class StageListener:
def __init__(self, usd_context_name=""):
self.__usd_context = omni.usd.get_context(usd_context_name)
self.__presence_layer = pl.get_presence_layer_interface(self.__usd_context)
self.__live_syncing = layers.get_live_syncing(self.__usd_context)
self.__layers = layers.get_layers(self.__usd_context)
self.__layers_event_subscriptions = []
self.__stage_event_subscription = None
self.__settings = carb.settings.get_settings()
self.__selection_paths_initialized = False
self.__stage_objects_changed = None
self.__multi_user_selection_manager = MultiUserSelectionOutlineManager(self.__usd_context)
self.__delayed_task_or_future = None
self.__changed_user_ids = set()
def start(self):
self.__restore_local_outline_color()
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
pl.PresenceLayerEventType.SELECTIONS_CHANGED,
]:
layers_event_sub = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event, name=f"omni.kit.collaboration.selection_outline {str(event)}"
)
self.__layers_event_subscriptions.append(layers_event_sub)
self.__stage_event_subscription = self.__usd_context.get_stage_event_stream().create_subscription_to_pop(
self.__on_stage_event, name="omni.kit.collaboration.selection_outline stage event"
)
self.__start_subscription()
def __start_subscription(self):
self.__settings.set(SETTING_MULTI_USER_OUTLINE, True)
live_session = self.__live_syncing.get_current_live_session()
if not live_session:
return
for peer_user in live_session.peer_users:
selection_paths = self.__presence_layer.get_selections(peer_user.user_id)
self.__multi_user_selection_manager.update_selection_outline(peer_user, selection_paths)
if not self.__selection_paths_initialized:
self.__selection_paths_initialized = True
selection = self.__usd_context.get_selection().get_selected_prim_paths()
self.__on_selection_changed(selection)
root_layer_session = self.__live_syncing.get_current_live_session()
if root_layer_session:
logged_user = root_layer_session.logged_user
user_color = logged_user.user_color
rgba = (user_color[0] / 255.0, user_color[1] / 255.0, user_color[2] / 255.0, 1.0)
self.__save_and_set_local_outline_color(rgba)
self.__stage_objects_changed = Tf.Notice.Register(
Usd.Notice.ObjectsChanged, self.__on_usd_changed, self.__usd_context.get_stage()
)
@Trace.TraceFunction
@carb.profiler.profile
def __on_usd_changed(self, notice, sender):
if not sender or sender != self.__usd_context.get_stage():
return
self.__multi_user_selection_manager.on_usd_objects_changed(notice)
def __stop_subscription(self):
self.__changed_user_ids.clear()
if self.__delayed_task_or_future and not self.__delayed_task_or_future.done():
self.__delayed_task_or_future.cancel()
self.__delayed_task_or_future = None
self.__restore_local_outline_color()
self.__selection_paths_initialized = False
self.__multi_user_selection_manager.clear_all_selection()
self.__settings.set(SETTING_MULTI_USER_OUTLINE, False)
if self.__stage_objects_changed:
self.__stage_objects_changed.Revoke()
self.__stage_objects_changed = None
def stop(self):
self.__stop_subscription()
self.__layers_event_subscription = None
self.__stage_event_subscription = None
def __save_and_set_local_outline_color(self, color):
old_color = self.__settings.get(SETTING_OUTLINE_COLOR)
if old_color:
self.__settings.set(SETTING_SAVED_OUTLINE_COLOR, old_color)
old_color[-4:] = color
else:
# It has maximum 255 group + selection_outline
old_color = [0] * 256
old_color[-4:] = color
color = old_color
self.__settings.set(SETTING_OUTLINE_COLOR, color)
def __restore_local_outline_color(self):
# It's possible that Kit is shutdown abnormally. So it can
# be used to restore the outline color before live session or abort.
color = self.__settings.get(SETTING_SAVED_OUTLINE_COLOR)
if not color:
return
self.__settings.set(SETTING_OUTLINE_COLOR, color)
# Clear saved color
self.__settings.set(SETTING_SAVED_OUTLINE_COLOR, None)
def __on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
if not self.__live_syncing.get_current_live_session():
return
selection = self.__usd_context.get_selection().get_selected_prim_paths()
self.__on_selection_changed(selection)
elif event.type == int(omni.usd.StageEventType.CLOSING):
self.__stop_subscription()
def __on_selection_changed(self, selection_paths):
self.__multi_user_selection_manager.refresh_selection(selection_paths)
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
if self.__live_syncing.get_current_live_session():
self.__start_subscription()
else:
self.__stop_subscription()
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED:
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
user_id = payload.user_id
live_session = self.__live_syncing.get_current_live_session()
user_info = live_session.get_peer_user_info(user_id)
selection_paths = self.__presence_layer.get_selections(user_id)
self.__multi_user_selection_manager.update_selection_outline(user_info, selection_paths)
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
user_id = payload.user_id
self.__multi_user_selection_manager.clear_selection(user_id)
else:
payload = pl.get_presence_layer_event_payload(event)
if payload.event_type == pl.PresenceLayerEventType.SELECTIONS_CHANGED:
self.__changed_user_ids.update(payload.changed_user_ids)
# Delay the selection updates.
if not self.__delayed_task_or_future or self.__delayed_task_or_future.done():
self.__delayed_task_or_future = run_coroutine(self.__handle_selection_changes())
async def __handle_selection_changes(self):
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session:
return
for user_id in self.__changed_user_ids:
user_info = current_live_session.get_peer_user_info(user_id)
if not user_info:
continue
selection_paths = self.__presence_layer.get_selections(user_id)
self.__multi_user_selection_manager.update_selection_outline(user_info, selection_paths)
self.__changed_user_ids.clear()
self.__delayed_task_or_future = None
| 19,602 | Python | 41.522776 | 124 | 0.604173 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/manipulator/peer_user_list_manipulator_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["PeerUserListManipulatorModel"]
import carb
import omni.usd
import omni.kit.usd.layers as layers
from omni.ui import scene as sc
from pxr import Gf, UsdGeom, Usd, Sdf, Tf, Trace
class PeerUserListManipulatorModel(sc.AbstractManipulatorModel):
"""The model tracks the position of peer user's camera in a live session."""
class PositionItem(sc.AbstractManipulatorItem):
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class UserListItem(sc.AbstractManipulatorItem):
def __init__(self):
super().__init__()
self.value = {}
def __init__(self, prim_path, usd_context: omni.usd.UsdContext):
super().__init__()
self.position = PeerUserListManipulatorModel.PositionItem()
self.user_list = PeerUserListManipulatorModel.UserListItem()
self.__prim_path = Sdf.Path(prim_path)
self.__usd_context = usd_context
self.__update_position = True
def destroy(self):
self.position = None
self.__usd_context = None
def add_user(self, user_info: layers.LiveSessionUser):
if user_info.user_id in self.user_list.value:
return
self.user_list.value[user_info.user_id] = user_info
# This makes the manipulator updated
self._item_changed(self.user_list)
def remove_user(self, user_id):
item = self.user_list.value.pop(user_id, None)
if not item:
# This makes the manipulator updated
self._item_changed(self.user_list)
def empty_user_list(self):
return len(self.user_list.value) == 0
def get_item(self, identifier):
if identifier == "position":
return self.position
elif identifier == "user_list":
return self.user_list
return None
def get_as_floats(self, item):
if item == self.position:
# Requesting position
if self.__update_position:
self.position.value = self._get_position()
self.__update_position = False
return self.position.value
return []
def set_floats(self, item, value):
if item != self.position:
return
if not value or item.value == value:
return
# Set directly to the item
item.value = value
self.__update_position = False
# This makes the manipulator updated
self._item_changed(item)
def on_transform_changed(self, position=None):
"""When position is provided, it will not re-calculate position but use provided value instead."""
# Position is changed
if position:
self.set_floats(self.position, position)
else:
self.__update_position = True
self._item_changed(self.position)
def _get_position(self):
"""Returns center position at the top of the bbox for the current selected object."""
stage = self.__usd_context.get_stage()
prim = stage.GetPrimAtPath(self.__prim_path)
if not prim:
return []
# Get bounding box from prim
aabb_min, aabb_max = self.__usd_context.compute_path_world_bounding_box(
str(self.__prim_path)
)
gf_range = Gf.Range3d(
Gf.Vec3d(aabb_min[0], aabb_min[1], aabb_min[2]),
Gf.Vec3d(aabb_max[0], aabb_max[1], aabb_max[2])
)
if gf_range.IsEmpty():
# May be empty (UsdGeom.Xform for example), so build a scene-scaled constant box
world_units = UsdGeom.GetStageMetersPerUnit(stage)
if Gf.IsClose(world_units, 0.0, 1e-6):
world_units = 0.01
xformable_prim = UsdGeom.Xformable(prim)
world_xform = xformable_prim.ComputeLocalToWorldTransform(Usd.TimeCode.Default())
ref_position = world_xform.ExtractTranslation()
extent = Gf.Vec3d(0.1 / world_units) # 10cm by default
gf_range.SetMin(ref_position - extent)
gf_range.SetMax(ref_position + extent)
bboxMin = gf_range.GetMin()
bboxMax = gf_range.GetMax()
position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1], (bboxMin[2] + bboxMax[2]) * 0.5]
return position
| 4,784 | Python | 32 | 106 | 0.607232 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.