file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/docs/README.md | # ackermann AMR Trainer [omni.sample.ackermann_AMR_Trainer]
<div style="text-align: center;">
<img src="Images/ackermann_AMR_Trainer.png" alt="ackermann_AMR_Trainer" width="400"/>
</div>
This is a sample extension that helps train an AI model to drive an ackermann-based autonomous mobile robot (AMR) in NVIDIA Isaac Sim. The full source code along with assets can be found [here](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ackermann-amr-trainer).
## [Tutorial](../tutorial/tutorial.md)
This extension sample includes a step-by-step tutorial to demonstrate portions of how it was written. [Learn how with the tutorial.](../tutorial/tutorial.md)
## Usage
In order to use this sample you must install *Omniverse*, clone this repository, and configure *Omniverse* to include the provided extension. Then the extension can be used as described below.
### Install Omniverse Launcher and an Omniverse App
1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/Omniverse/download)
2. Install and launch an *Omniverse* app through the launcher such as *Omniverse Code*.
## Adding This Extension to your *Omniverse App*
### Directly from Github
To add a this extension to your Omniverse app directly from github:
1. Go into: Extension Manager → Hamburger Menu → Settings → Extension Search Paths
<div style="text-align: center;">
<img src="Images/add-ext-search-path.gif" alt="extension search path" width="400"/>
</div>
2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims.git?branch=main&dir=exts`
### With Source
#### Adding the Source to Omniverse
1. Fork and clone this repo, for example in `C:\projects\kit-extension-sample-ackermann-amr-trainer`
2. In the *Omniverse App* open extension manager: *Window* → *Extensions*.
3. In the *Extension Manager Window* click on the *hamburger menu* → *settings*.
4. In the settings page there is a list of *Extension Search Paths*. Click on the *plus* button and add the cloned repo's `exts` subfolder. If you used the example clone path, the `exts` filder would be here: `C:\projects\kit-extension-sample-ackermann-amr-trainer\exts`
<div style="text-align: center;">
<img src="Images/add-ext-search-path.gif" alt="extension search path" width="400"/>
</div>
5. Now you can find `omni.sample.excel_amr_trainer` extension in the top left search bar. Select and enable it.
6. The "ackermann AMR Trainer" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload.
#### Linking with an Omniverse app
For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included.
Run:
```bash
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```bash
> link_app.bat --app code
```
You can also just pass a path to create link to:
```bash
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3"
```
## Using the Extension
### Open the Scene
Use the *Omniverse* app installed previously to open *Racing_Grid.usd* included in the *Assets* folder of the repository.
### Activate the ackermann_AMR_Controller
Activate the *ackermann_AMR_Controller* Extension by clicking on the `+` button.
### Start a Physics Simulation
Start the Isaac Sim simulation by pressing the `play` button or by pressing the `spacebar`. Press the forward arrow on your keyboard or the `a` button on your game pad to start the car driving forward. Steer the car within the cones as it drives forward.
### Collect Annotated Data
Press the `Capture` button to save the current viewport to file. Then click the point in the distance on the image where you would steer the car. This will rename the image file by prepending the `x` and `y` coodinates you have clicked.
<div style="text-align: center;">
<img src="Images/Annotate.gif" alt="Excel connected" width="400"/>
</div>
You can see how many images you have collected in the `Count` field.
> **_Note_**: Remember that you are collecting this data to teach an AI to drive! Do not just collect data along a perfect driving line; collect data off of the ideal line in order to teach the AI how to get back on course if it gets a little lost.
### Train the Model
To train your model set the number of epochs you would like to train in the `epochs` field. If you are not sure what to use, five epochs is a good start.
Next, click on the `train` button. You can see the loss after each epoch printed in the Isaac Sim command prompt as it trains or all printed at once in the Isaac Sim console after training has completed.
If you are unhappy with the loss value, simply click on the train button again and the model will continue to train for as many epochs as are indicated in the `epochs` field.
### Load and Save the Model
The model can be loaded and saved from the path indicated in the `model path` field by clicking on the `load model` and `save model` fields respectively.
A saved model can be used in future sessions or deployed to a ROS node so that the car can drive itself! | 5,397 | Markdown | 46.769911 | 274 | 0.753196 |
NVIDIA-Omniverse/sample-ackermann-amr/exts/omni.sample.ackermann_amr_trainer/docs/index.rst | omni.sample.ackermann_amr_trainer
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"omni.sample.ackermann_amr_trainer"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 367 | reStructuredText | 16.523809 | 50 | 0.637602 |
NVIDIA-Omniverse/sample-ackermann-amr/ros2_f1_tenth_trainer/model_evaluate_start.py | #!/usr/bin/env python3
# Copyright (c) 2020-2024, 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 rclpy
from rclpy.node import Node
from ackermann_msgs.msg import AckermannDriveStamped
from sensor_msgs.msg import Image
import numpy as np
from ackermann_amr_policy import ackermann_amr_policy
import PIL.Image
import torch
import torchvision
import torchvision.transforms as transforms
import os
class MinimalSubscriber(Node):
def __init__(self):
super().__init__('minimal_subscriber')
self.subscription = self.create_subscription(
Image,
'rgb',
self.image_callback,
1)
self.subscription # prevent unused variable warning
self.publisher = self.create_publisher(AckermannDriveStamped, 'ackermann_cmd', 10)
# Initialize AI Model
self.device = torch.device('cuda')
self.model = ackermann_amr_policy()
self.model = self.model.to(self.device)
self.save_dir = os.path.dirname(os.path.realpath(__file__))
self.model_file = "road_following_model.pth"
model_path = os.path.join(self.save_dir, self.model_file)
self.model.load_state_dict(torch.load(model_path))
def image_callback(self, msg):
width = msg.width
height = msg.height
# Evaluate Model
self.model.eval()
img = PIL.Image.frombuffer('RGB', (width, height), msg.data.tobytes())
tensor_image = transforms.functional.to_tensor(img)
image = tensor_image[:3, ...].to(self.device)
mean = torch.Tensor([0.485, 0.456, 0.406]).cuda()
std = torch.Tensor([0.229, 0.224, 0.225]).cuda()
image.sub_(mean[:, None, None]).div_(std[:, None, None])
img = image[None, ...]
prediction = self.model(img)
prediction_x, prediction_y = self.xy2rowcol(*prediction.squeeze().cpu())
# 3.2. Compute Steering Angle
# 3.3. Create and Send Message
def xy2rowcol(self, x, y):
return x, y
def main(args=None):
rclpy.init(args=args)
evaluate_node = MinimalSubscriber()
try:
rclpy.spin(evaluate_node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
except KeyboardInterrupt:
evaluate_node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
| 2,809 | Python | 27.673469 | 90 | 0.656105 |
NVIDIA-Omniverse/sample-ackermann-amr/ros2_f1_tenth_trainer/teleop_ackermann_key.py | #!/usr/bin/env python3
# Copyright (c) 2020-2024, 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 rclpy
from rclpy.node import Node
from pynput import keyboard
from ackermann_msgs.msg import AckermannDriveStamped
class KeyboardTeleopNode(Node):
def __init__(self):
super().__init__('keyboard_teleop')
# 1. Create the publisher and message
self.publisher_ = self.create_publisher(AckermannDriveStamped, 'ackermann_cmd', 10)
self.drive_msg = AckermannDriveStamped()
self.listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release)
self.listener.start()
self.timer_period = 0.1 # seconds
self.timer = self.create_timer(self.timer_period, self.publish_cmd)
def on_press(self, key):
try:
# 2. Create ROS Messages based on keys pressed
if key.char == 'w':
self.drive_msg.drive.speed = 2.0
elif key.char == 's':
self.drive_msg.drive.speed = -2.0
elif key.char == 'a':
self.drive_msg.drive.steering_angle = 0.523599 # Turn left by 30 degrees
elif key.char == 'd':
self.drive_msg.drive.steering_angle = -0.523599 # Turn right by 30 degrees
except AttributeError:
pass
def on_release(self, key):
try:
# 3. If no keys are pressed, stop the car
if key.char in ['w', 's']:
self.drive_msg.drive.speed = 0.0
elif key.char in ['a', 'd']:
self.drive_msg.drive.steering_angle = 0.0
except AttributeError:
pass
def publish_cmd(self):
# 4. Publish the Message
self.drive_msg.header.frame_id = "f1_tenth"
self.drive_msg.header.stamp = self.get_clock().now().to_msg()
self.publisher_.publish(self.drive_msg)
def main(args=None):
rclpy.init(args=args)
keyboard_teleop_node = KeyboardTeleopNode()
keyboard_teleop_node.get_logger().info('Listening to keyboard. Use WASD to drive!')
try:
rclpy.spin(keyboard_teleop_node)
except KeyboardInterrupt:
keyboard_teleop_node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
| 2,616 | Python | 36.927536 | 93 | 0.632645 |
NVIDIA-Omniverse/sample-ackermann-amr/ros2_f1_tenth_trainer/ackermann_amr_policy.py | # Copyright (c) 2020-2024, 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 torch import nn
from torchvision import transforms
from torchvision.models import resnet18, ResNet18_Weights
class ackermann_amr_policy(nn.Module):
def __init__(self):
super().__init__()
# Initialize Base Model
full_model = resnet18(weights=ResNet18_Weights.DEFAULT)
# Configure Layer Connections
self.model = nn.Sequential(*list(full_model.children())[:-1])
self.fc = nn.Linear(512, 2)
# Node Activation Function
self.sigma = nn.Tanh()
# Image Processing Transform
self.transform = transforms.Compose([transforms.ColorJitter(0.2,
0.2,
0.2,
0.2),
transforms.Resize((224,
224)),
transforms.Normalize([0.485,
0.456,
0.406],
[0.229,
0.224,
0.225])])
# Forward Propogation
def forward(self, x):
x = self.transform(x)
x = self.model(x)
x = x.view(x.size(0),-1)
x = self.sigma(self.fc(x))
return x
| 2,060 | Python | 41.061224 | 76 | 0.451942 |
NVIDIA-Omniverse/sample-ackermann-amr/ros2_f1_tenth_trainer/teleop_ackermann_key_start.py | #!/usr/bin/env python3
# Copyright (c) 2020-2024, 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 rclpy
from rclpy.node import Node
from pynput import keyboard
from ackermann_msgs.msg import AckermannDriveStamped
class KeyboardTeleopNode(Node):
def __init__(self):
super().__init__('keyboard_teleop')
# Create the publisher and message
self.publisher_ = self.create_publisher(AckermannDriveStamped, 'ackermann_cmd', 10)
self.drive_msg = AckermannDriveStamped()
self.listener = keyboard.Listener(on_press=self.on_press, on_release=self.on_release)
self.listener.start()
self.timer_period = 0.1 # seconds
self.timer = self.create_timer(self.timer_period, self.publish_cmd)
def on_press(self, key):
try:
# 1.5.3 Create ROS Messages based on keys pressed
pass
except AttributeError:
pass
def on_release(self, key):
try:
# 3. If no keys are pressed, stop the car
if key.char in ['w', 's']:
self.drive_msg.drive.speed = 0.0
elif key.char in ['a', 'd']:
self.drive_msg.drive.steering_angle = 0.0
except AttributeError:
pass
def publish_cmd(self):
# Publish the Message
self.drive_msg.header.frame_id = "f1_tenth"
self.drive_msg.header.stamp = self.get_clock().now().to_msg()
self.publisher_.publish(self.drive_msg)
def main(args=None):
rclpy.init(args=args)
keyboard_teleop_node = KeyboardTeleopNode()
keyboard_teleop_node.get_logger().info('Listening to keyboard. Use WASD to drive!')
try:
rclpy.spin(keyboard_teleop_node)
except KeyboardInterrupt:
keyboard_teleop_node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
| 2,215 | Python | 34.741935 | 93 | 0.65553 |
NVIDIA-Omniverse/sample-ackermann-amr/ros2_f1_tenth_trainer/model_evaluate.py | #!/usr/bin/env python3
# Copyright (c) 2020-2024, 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 rclpy
from rclpy.node import Node
from ackermann_msgs.msg import AckermannDriveStamped
from sensor_msgs.msg import Image
import numpy as np
from ackermann_amr_policy import ackermann_amr_policy
import PIL.Image
import torch
import torchvision
import torchvision.transforms as transforms
import os
import math
class MinimalSubscriber(Node):
def __init__(self):
super().__init__('minimal_subscriber')
self.subscription = self.create_subscription(
Image,
'rgb',
self.image_callback,
1)
self.subscription # prevent unused variable warning
self.publisher = self.create_publisher(AckermannDriveStamped, 'ackermann_cmd', 10)
# Initialize AI Model
self.device = torch.device('cuda')
self.model = ackermann_amr_policy()
self.model = self.model.to(self.device)
self.save_dir = os.path.dirname(os.path.realpath(__file__))
self.model_file = "road_following_model.pth"
model_path = os.path.join(self.save_dir, self.model_file)
self.model.load_state_dict(torch.load(model_path))
def image_callback(self, msg):
width = msg.width
height = msg.height
# Evaluate Model
self.model.eval()
img = PIL.Image.frombuffer('RGB', (width, height), msg.data.tobytes())
tensor_image = transforms.functional.to_tensor(img)
image = tensor_image[:3, ...].to(self.device)
mean = torch.Tensor([0.485, 0.456, 0.406]).cuda()
std = torch.Tensor([0.229, 0.224, 0.225]).cuda()
image.sub_(mean[:, None, None]).div_(std[:, None, None])
img = image[None, ...]
prediction = self.model(img)
prediction_x, prediction_y = self.xy2rowcol(*prediction.squeeze().cpu())
# 3.2. Compute Steering Angle
forward = np.array([0.0, -1.0])
offset = np.array([0.0, 1.0])
traj = np.array([prediction_x.item(), prediction_y.item()]) - offset
unit_traj = traj / np.linalg.norm(traj)
unit_forward = forward / np.linalg.norm(forward)
steering_angle = np.arccos(np.dot(unit_traj, unit_forward)) / 2.0 - np.deg2rad(15.0)
# 3.3. Create and Send Message
msg = AckermannDriveStamped()
msg.header.frame_id = "f1_tenth"
msg.header.stamp = self.get_clock().now().to_msg()
msg.drive.steering_angle = steering_angle
# Challenge: Increase the drive speed as much as you can!
msg.drive.speed = 2.0
self.publisher.publish(msg)
def xy2rowcol(self, x, y):
return x, y
def main(args=None):
rclpy.init(args=args)
evaluate_node = MinimalSubscriber()
try:
rclpy.spin(evaluate_node)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
except KeyboardInterrupt:
evaluate_node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
| 3,509 | Python | 28.745762 | 92 | 0.642918 |
NVIDIA-Omniverse/kit-extension-sample-gestures/README.md | # UI Gestures Extension Sample

## [UI Gestures for omni.ui (omni.example.gesture_window)](exts/omni.example.gesture_window)

### About
This extension shows how to create gestures using omni.ui. The focus of this sample extension is to show how to register and create a scene view within a Window.
### [README](exts/omni.example.gesture_window)
See the [README for this extension](exts/omni.example.gesture_window) to learn more about it including how to use it.
## [UI Gestures for Viewport (omni.example.gesture_viewport)](exts/omni.example.gesture_viewport)

### About
This extension shows how to create a simple manipulator with gestures using omni.ui.scene. The focus of this sample extension is to show how to create a simple manipulator and register gestures in the viewport.
### [README](exts/omni.example.gesture_viewport)
See the [README for this extension](exts/omni.example.gesture_viewport) to learn more about it including how to use it.
## [Tutorial](docs/tutorial.md)
Follow a [step-by-step tutorial](docs/tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
## Adding This Extension
To add a this extension to your Omniverse app:
1. Go into: Extension Manager -> Hamburger Icon -> Settings -> Extension Search Path
2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-gestures.git?branch=main&dir=exts`
Alternatively:
1. Download or Clone the extension, unzip the file if downloaded
2. Copy the `exts` folder path within the extension folder
- i.e. home/.../kit-extension-sample-gestures/exts (Linux) or C:/.../kit-extension-sample-gestures/exts (Windows)
3. Go into: Extension Manager -> Hamburger Icon -> Settings -> Extension Search Path
4. Add the `exts` folder path as a search path
## Linking with an Omniverse app
For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included.
Run:
```bash
# Windows
> link_app.bat
```
```shell
# Linux
~$ ./link_app.sh
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps are installed the script will select the recommended one. Or you can explicitly pass an app:
```bash
# Windows
> link_app.bat --app code
```
```shell
# Linux
~$ ./link_app.sh --app code
```
You can also pass a path that leads to the Omniverse package folder to create the link:
```bash
# Windows
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3"
```
```shell
# Linux
~$ ./link_app.sh --path "home/bob/.local/share/ov/pkg/create-2022.1.3"
```
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions. | 2,921 | Markdown | 32.976744 | 210 | 0.748374 |
NVIDIA-Omniverse/kit-extension-sample-gestures/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
NVIDIA-Omniverse/kit-extension-sample-gestures/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
NVIDIA-Omniverse/kit-extension-sample-gestures/tools/packman/bootstrap/install_package.py | # Copyright 2023 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_viewport/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "omni example gesture viewport"
description="A simple python extension example to use as a starting point for your extensions."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import omni.example.gesture".
[[python.module]]
name = "omni.example.gesture_viewport"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,604 | TOML | 32.437499 | 118 | 0.747506 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_viewport/omni/example/gesture_viewport/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.viewport.registry import RegisterScene
from .line import LineManipulator
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[omni.example.gesture] some_public_function was called with x: ", x)
return x ** x
# 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 OmniExampleGestureExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[omni.example.gesture] omni example gesture startup")
self._line = RegisterScene(LineManipulator, "Line Gesture")
def on_shutdown(self):
print("[omni.example.gesture] omni example gesture shutdown")
self._line = None | 1,562 | Python | 47.843749 | 119 | 0.757362 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_viewport/omni/example/gesture_viewport/__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 *
| 453 | Python | 44.399996 | 76 | 0.80574 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_viewport/omni/example/gesture_viewport/line.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.ui as ui
from omni.ui import scene as sc
from omni.ui_scene._scene import AbstractGesture
def setcolor(sender, color):
"""
Sets the color of the sender
Args:
`sender : omni.ui.scene.Manipulator`
The shape driving the gesture
`color : omni.ui.color`
The color that will be assigned to the shape
"""
sender.color = color
class Manager(sc.GestureManager):
"""
The object that controls batch processing and preventing of gestures.
See more here: https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/omni.ui.scene/omni.ui.scene.GestureManager.html
"""
def should_prevent(self, gesture: AbstractGesture, preventer: AbstractGesture) -> bool:
"""
Called per gesture. Determines if the gesture should be prevented with another gesture.
Useful to resolve intersections.
Args:
`gesture : AbstractGesture`
Gesture that is occurring
`preventer : AbstractGesture`
Gesture preventing `gesture`
Returns:
bool: Whether or not the gesture should be prevented.
If True gesture will be prevented otherwise the gesture will overtake the last gesture used.
"""
if gesture.name == "SelectionDrag" and preventer.state == sc.GestureState.BEGAN:
return True
if gesture.name == "SelectionClick" and preventer.name == "color_change":
return True
class Move(sc.DragGesture):
"""
Inherits from `DragGesture`, the gesture that provides a way to capture click-and-drag mouse event.
See more here: https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/omni.ui.scene/omni.ui.scene.DragGesture.html
"""
def __init__(self, transform: sc.Transform, **kwargs):
"""
Construct the gesture to track mouse drags
Args:
`transform : sc.Transform` The transform parent of the shape.
`kwargs : dict`
See below
### Keyword Arguments:
`mouse_button : `
Mouse button that should be active to start the gesture.
`modifiers : `
The keyboard modifier that should be active ti start the gesture.
`check_mouse_moved : `
The check_mouse_moved property is a boolean flag that determines whether the DragGesture should verify if the 2D screen position of the mouse has changed before invoking the on_changed method. This property is essential in a 3D environment, as changes in the camera position can result in the mouse pointing to different locations in the 3D world even when the 2D screen position remains unchanged.
Usage
When check_mouse_moved is set to True, the DragGesture will only call the on_changed method if the actual 2D screen position of the mouse has changed. This can be useful when you want to ensure that the on_changed method is only triggered when there is a genuine change in the mouse's 2D screen position.
If check_mouse_moved is set to False, the DragGesture will not check for changes in the mouse's 2D screen position before calling the on_changed method. This can be useful when you want the on_changed method to be invoked even if the mouse's 2D screen position hasn't changed, such as when the camera position is altered, and the mouse now points to a different location in the 3D world.
`on_began_fn : `
Called if the callback is not set when the user clicks the mouse button.
`on_changed_fn : `
Called if the callback is not set when the user moves the clicked button.
`on_ended_fn : `
Called if the callback is not set when the user releases the mouse button.
`name : `
The name of the object. It's used for debugging.
`manager : `
The Manager that controld this gesture.
"""
super().__init__(**kwargs)
self.__transform = transform
def on_changed(self):
"""
Called when the user moves the clicked button. Moves the sender in the direction the mouse was moved.
"""
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
manager = Manager()
class LineManipulator(sc.Manipulator):
"""
Class that holds a custom Manipulator. Inherits from omni.ui.scene.Manipulator class.
See more here: https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/omni.ui.scene/omni.ui.scene.Manipulator.html
"""
def __init__(self, desc: dict, **kwargs) -> None:
"""
### Arguments:
`desc : dict`
Description of the manipulator
`kwargs : dict`
See below
### Keyword Arguments:
`gestures : `
All the gestures assigned to this shape.
`model : `
The model of the class.
"""
super().__init__(**kwargs)
def on_build(self) -> None:
"""
Builds the Scene UI.
Consists of a beige line that stretches in the X-axis.
Called when Manipulator is dirty to build the content. It's another way to build the manipulator's content on the case the user doesn't want to reimplement the class.
"""
transform = sc.Transform()
with transform:
sc.Line(
[-50, 0, 0],
[50, 0, 0],
color=ui.color.beige,
thickness=10,
gestures=[
sc.ClickGesture(
lambda s: setcolor(s, ui.color.green), mouse_button=0, name="color_change", manager=manager
),
sc.DoubleClickGesture(
lambda s: setcolor(s, ui.color.beige), mouse_button=0, name="color_change", manager=manager
),
Move(transform, manager=manager),
],
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 20, 0)):
sc.Label(
"Click and Drag the Line to Move me\nClick or Double Click to Change color",
size=18,
alignment=ui.Alignment.CENTER,
color=ui.color.blue,
)
| 6,980 | Python | 39.824561 | 414 | 0.621633 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_viewport/omni/example/gesture_viewport/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_hello_world import * | 458 | Python | 56.374993 | 76 | 0.80786 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_viewport/omni/example/gesture_viewport/tests/test_hello_world.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.
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import omni.example.gesture
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = omni.example.gesture.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 2,103 | Python | 37.962962 | 142 | 0.708512 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_viewport/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2023-10-11
### Added
- Initial version of extension
| 163 | Markdown | 15.399998 | 80 | 0.668712 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_viewport/docs/README.md | # Gestures Viewport (omni.example.gesture_viewport)

## Overview
This Extension displays the a simple manipulator in the Viewport. This manipulator can be dragged and clicked on.
See [Adding the Extension](../../../README.md#adding-this-extension) on how to add the extension to your project.
## [Tutorial](../../../docs/tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions.
Learn how to create a simple scene manipulator and how to apply gestures to the manipulator.
[Get started with the tutorial here.](../../../docs/tutorial.md)
## Usage
Once the extension is enabled in the *Extension Manager*, you should see a similar line inside the viewport like in the to the image before [Overview section](#overview).
There is beige line that will start at the origin (0,0,0) in the Viewport. This line can be dragged left and right along the X-axis. When clicking on the line it changes the color to green and double clicking changes the color back to beige. | 1,115 | Markdown | 49.72727 | 241 | 0.75426 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_viewport/docs/index.rst | omni.example.gesture
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"omni.example.gesture"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 341 | reStructuredText | 15.285714 | 43 | 0.621701 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_window/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "omni example gesture window"
description="A simple python extension example to use as a starting point for your extensions."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import omni.example.gesture".
[[python.module]]
name = "omni.example.gesture_window"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,600 | TOML | 32.354166 | 118 | 0.746875 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_window/omni/example/gesture_window/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 .window import GestureWindowExample
# 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 OmniExampleGestureExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[omni.example.gesture] omni example gesture startup")
self._window = GestureWindowExample("Gesture Example", width=500, height=500)
def on_shutdown(self):
print("[omni.example.gesture] omni example gesture shutdown")
if self._window:
self._window.destroy()
self._window = None
| 1,345 | Python | 45.413792 | 119 | 0.747955 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_window/omni/example/gesture_window/__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 *
| 453 | Python | 44.399996 | 76 | 0.80574 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_window/omni/example/gesture_window/window.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.ui as ui
from omni.ui import scene as sc
from omni.ui_scene._scene import AbstractGesture
proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1]
def setcolor(sender, color):
"""
Sets the color of the sender
Args:
`sender : omni.ui.scene.Manipulator`
The shape driving the gesture
`color : omni.ui.color`
The color that will be assigned to the shape
"""
sender.color = color
class Manager(sc.GestureManager):
"""
The object that controls batch processing and preventing of gestures.
See more here: https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/omni.ui.scene/omni.ui.scene.GestureManager.html
"""
def should_prevent(self, gesture: AbstractGesture, preventer: AbstractGesture) -> bool:
"""
Called per gesture. Determines if the gesture should be prevented with another gesture.
Useful to resolve intersections.
Args:
`gesture : AbstractGesture`
Gesture that is occurring
`preventer : AbstractGesture`
Gesture preventing `gesture`
Returns:
bool: Whether or not the gesture should be prevented.
If True gesture will be prevented otherwise the gesture will overtake the last gesture used.
"""
if gesture.name != "gesture_name" and preventer.state == sc.GestureState.BEGAN:
return True
manager = Manager()
class Move(sc.DragGesture):
"""
Inherits from `DragGesture`, the gesture that provides a way to capture click-and-drag mouse event.
See more here: https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/omni.ui.scene/omni.ui.scene.DragGesture.html
"""
def __init__(self, transform: sc.Transform, **kwargs):
"""
Construct the gesture to track mouse drags
Args:
`transform : sc.Transform` The transform parent of the shape.
`kwargs : dict`
See below
### Keyword Arguments:
`mouse_button : `
Mouse button that should be active to start the gesture.
`modifiers : `
The keyboard modifier that should be active ti start the gesture.
`check_mouse_moved : `
The check_mouse_moved property is a boolean flag that determines whether the DragGesture should verify if the 2D screen position of the mouse has changed before invoking the on_changed method. This property is essential in a 3D environment, as changes in the camera position can result in the mouse pointing to different locations in the 3D world even when the 2D screen position remains unchanged.
Usage
When check_mouse_moved is set to True, the DragGesture will only call the on_changed method if the actual 2D screen position of the mouse has changed. This can be useful when you want to ensure that the on_changed method is only triggered when there is a genuine change in the mouse's 2D screen position.
If check_mouse_moved is set to False, the DragGesture will not check for changes in the mouse's 2D screen position before calling the on_changed method. This can be useful when you want the on_changed method to be invoked even if the mouse's 2D screen position hasn't changed, such as when the camera position is altered, and the mouse now points to a different location in the 3D world.
`on_began_fn : `
Called if the callback is not set when the user clicks the mouse button.
`on_changed_fn : `
Called if the callback is not set when the user moves the clicked button.
`on_ended_fn : `
Called if the callback is not set when the user releases the mouse button.
`name : `
The name of the object. It's used for debugging.
`manager : `
The Manager that controld this gesture.
"""
super().__init__(**kwargs)
self.__transform = transform
def on_changed(self):
"""
Called when the user moves the clicked button. Moves the sender in the direction the mouse was moved.
"""
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
class GestureWindowExample(ui.Window):
"""
omni.ui.Window that hold two Rectangles
Both Rectangles can be hovered, clicked, and dragged
As each gesture is being used the label in the middle of the window will update with the current gesture being used.
See more here: https://docs.omniverse.nvidia.com/kit/docs/omni.ui/latest/omni.ui/omni.ui.Window.html
"""
def __init__(self, title: str, **kwargs) -> None:
"""
Construct the window, add it to the underlying windowing system, and makes it appear.
### Arguments:
`title :`
The window title. It's also used as an internal window ID.
`kwargs : dict`
See below
### Keyword Arguments:
`flags : `
This property set the Flags for the Window.
`visible : `
This property holds whether the window is visible.
`title : `
This property holds the window's title.
`padding_x : `
This property set the padding to the frame on the X axis.
`padding_y : `
This property set the padding to the frame on the Y axis.
`width : `
This property holds the window Width.
`height : `
This property holds the window Height.
`position_x : `
This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
`position_y : `
This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
`auto_resize : `
setup the window to resize automatically based on its content
`noTabBar : `
setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically
`raster_policy : `
Determine how the content of the window should be rastered.
`width_changed_fn : `
This property holds the window Width.
`height_changed_fn : `
This property holds the window Height.
`visibility_changed_fn : `
This property holds whether the window is visible.
"""
super().__init__(title, **kwargs)
self.label = None
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
"""
The callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load.
"""
with self.frame:
with ui.VStack():
self.label = ui.Label("Sender: None\nAction: None", alignment=ui.Alignment.CENTER, size=16)
scene_view = sc.SceneView(
sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT
)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gestures=[
sc.ClickGesture(
lambda s: setcolor(s, ui.color.blue), manager=manager, name="gesture_name"
),
sc.DoubleClickGesture(
lambda s: setcolor(s, ui.color.beige), manager=manager, name="gesture_name"
),
Move(transform, manager=manager, name="gesture_name"),
sc.HoverGesture(
on_began_fn=lambda s: setcolor(s, ui.color.black),
on_changed_fn=lambda s: self.print_action(s, "Hover Changed"),
on_ended_fn=lambda s: self.print_action(s, "Hover End"),
),
],
)
transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, -1))
with transform:
sc.Rectangle(
2,
2,
color=ui.color.olive,
thickness=5,
gestures=[
sc.ClickGesture(lambda s: setcolor(s, ui.color.red)),
sc.DoubleClickGesture(lambda s: setcolor(s, ui.color.olive)),
Move(transform),
sc.HoverGesture(
on_began_fn=lambda s: setcolor(s, ui.color.black),
on_changed_fn=lambda s: self.print_action(s, "Hover Changed"),
on_ended_fn=lambda s: self.print_action(s, "Hover End"),
),
],
)
def print_action(self, sender, action):
"""
Prints the action / gesture to the label in the middle of the window
Args:
sender : Where the gesture is coming from
action : The type of gesture being used
"""
self.label.text = f"Sender: {sender}\nAction: {action}"
| 10,881 | Python | 43.05668 | 414 | 0.577796 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_window/omni/example/gesture_window/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_hello_world import * | 458 | Python | 56.374993 | 76 | 0.80786 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_window/omni/example/gesture_window/tests/test_hello_world.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.
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import omni.example.gesture
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = omni.example.gesture.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 2,103 | Python | 37.962962 | 142 | 0.708512 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_window/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2023-10-11
### Added
- Initial version of extension
| 163 | Markdown | 15.399998 | 80 | 0.668712 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_window/docs/README.md | # Gestures Window (omni.example.gesture_window)

## Overview
This Extension displays the a Window with two Rectangles that can be interacted with by hovering, clicking, and dragging.
See [Adding the Extension](../../../README.md#adding-this-extension) on how to add the extension to your project.
## [Tutorial](../../docs/tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions.
Learn how to create a scene view within an omni.ui.Window element and how to apply gestures to items in the scene view.
[Get started with the tutorial here.](../../docs/tutorial.md)
## Usage
Once the extension is enabled in the *Extension Manager*, you should see a similar window in the to the image before [Overview section](#overview).
There is text refering to which object is recieving the gestures as well as the action. The actions that display are `Hover Changed` and `Hover Ended` where, `Hover Changed` refers to the change in location of the mouse on the object and `Hover Ended` refers to when the mouse has exitted the objects bounds. When the mouse first enters the object or `Hover Began`, the color of the Rectangles will turn black.
Both Rectangles can be dragged in the scene by clicking and dragging them. This utilitzing the `omni.ui.scene.DragGesture` functionality.
You can click on each Rectangle to change the color (red and blue) or double click to change to their original colors (beige and olive).
| 1,562 | Markdown | 54.821427 | 410 | 0.765685 |
NVIDIA-Omniverse/kit-extension-sample-gestures/exts/omni.example.gesture_window/docs/index.rst | omni.example.gesture
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"omni.example.gesture"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 341 | reStructuredText | 15.285714 | 43 | 0.621701 |
NVIDIA-Omniverse/kit-extension-sample-gestures/docs/tutorial.md | # How to make an extension with UI Gestures in a UI Window and the Viewport
The Gestures extensions show the basics of how gestures work in Omniverse and how users can start creating their own scene manipulators. This guide is great for extension builders who want to start creating their own scene manipulator tools in Omniverse.
> NOTE: Visual Studio Code is the preferred IDE, hence forth we will be referring to it throughout this guide.
> NOTE: Omniverse Code is the preferred platform, hence forth we will be referring to it throughout this guide.
# Learning Objectives
In this tutorial you learn how to:
- How to create/register a scene view
- Use the omni.ui.scene API
- How to use Gestures
- What Gesture States are
- Prioritizing Gestures
- Creating a Gesture Manager
# Prerequisites
We recommend that you complete these tutorials before moving forward:
- [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial)
- [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims)
# Step 1: Create an Extension
> **Note:** This is a review, if you know how to create an extension, feel free to skip this step.
For this guide, we will briefly go over how to create an extension. If you have not completed [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) we recommend you pause here and complete that before moving forward.
## Step 1.1: Create the extension template
In Omniverse Code navigate to the `Extensions` tab and create a new extension by clicking the ➕ icon in the upper left corner and select `New Extension Template Project`.
Name the project to `kit-ext-gestures` and the extension name to `my.gestures.window`.

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

Inside of this file, there is a title and description for how the extension will look in the **Extension Manager**. Change the title and description for the extension.
``` python
title = "Gesture Window"
description="Example on how Gestures work in omni.ui"
```
# Step 2: Create `omni.ui` Window
## Step 2.1: Create `window.py`
In VS Code, **create** a file called `window.py` in `exts/my.gestures.window/my/gestures/window/`..

This file will hold our logic for creating an `omni.ui` Window
## Step 2.2: Set Up UI Window Class
With `window.py` created, **add** the following code block inside:
``` python
import omni.ui as ui
# Inherits from omni.ui.Window
class GestureWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
# Sets the build function so when the frame refreshes / rebuilds it will run the corresponding function
self.frame.set_build_fn(self._build_fn)
# Build function for our Window
def _build_fn(self):
with self.frame:
with ui.VStack():
ui.Label("Hello World")
```
**Save** `window.py`.
This only sets up our Window class. To have the window created we will head into `extension.py`.
## Step 2.3: Create the UI Window
Open `extension.py` and **replace** all of the code inside with the following:
```python
import omni.ext
from .window import GestureWindowExample
# 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 OmniExampleGestureExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[omni.example.gesture] omni example gesture startup")
self._window = GestureWindowExample("Gesture Example", width=500, height=500)
def on_shutdown(self):
print("[omni.example.gesture] omni example gesture shutdown")
if self._window:
self._window.destroy()
self._window = None
```
**Save** `extension.py` and **go back** to Omniverse and your window should look like the following:

So far we have created a UI Window that can be docked or dragged within Omniverse.
# Step 3: Create a SceneView
[SceneUI](https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/Scene.html) helps build 3D manipulators and 3D helpers. It provides shapes and controls for declaring the UI in 3D Space.
## Step 3.1: Import scene tools
**Go back** to VS Code and **open** `window.py`.
In order to use the Scene API **add** the following line under `import omni.ui as ui`:
```python
from omni.ui import scene as sc
```
After adding your code will read:
```python
import omni.ui as ui
from omni.ui import scene as sc
```
## Step 3.2: Create SceneView and Project in the Window
1. **Create** the projection matrix, this will indicate the position of the camera for our scene in the UI. **Add** the following code under `from omni.ui import scene as sc` but before `class GestureWindowExample(ui.Window)`:
```python
proj = [0.5,0,0,0,0,0.5,0,0,0,0,2e-7,0,0,0,1,1]
```
2. **Remove** `ui.Label("Hello World")` and **replace it** with the following:
```python
scene_view = sc.SceneView(sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
```
Saving `window.py` now will result in an empty UI window. With the scene established other UI elements can now be populated inside.
## Step 3.3: Add a Rectangle
To add a rectangle to the Scene add the following under where `scene_view` was declared:
```python
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2, # width
2, # height
color = ui.color.beige,
thickness=5
)
```
After editing `window.py` should look like the following:
```python
import omni.ui as ui
from omni.ui import scene as sc
proj = [0.5,0,0,0,0,0.5,0,0,0,0,2e-7,0,0,0,1,1]
class GestureWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.VStack():
scene_view = sc.SceneView(sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5
)
```
**Save** `window.py` and go back to Omniverse. You will see that our window now has a beige square.

# Step 4: Add a Gesture
Currently, the square does nothing. No actions will occur when hovering, dragging, or clicking on it. To add actions we will be adding [Gestures](https://docs.omniverse.nvidia.com/kit/docs/omni.ui.scene/latest/Gestures.html).
## Step 4.1 Create `setcolor()`
In `window.py`, under `proj=[...]` **add** the following lines after:
```python
def setcolor(sender, color):
sender.color = color
```
This function will be used to change the color of the shape.
## Step 4.2: Add Gesture Callback
**Add** a comma after `thickness=5` then **add** the following line after:
```python
gesture=sc.ClickGesture(lambda s: setcolor(s, ui.color.blue))
```
After editing `window.py` should look like the following:
```python
import omni.ui as ui
from omni.ui import scene as sc
proj = [0.5,0,0,0,0,0.5,0,0,0,0,2e-7,0,0,0,1,1]
def setcolor(sender, color):
sender.color = color
class GestureWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.VStack():
scene_view = sc.SceneView(sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gesture=sc.ClickGesture(lambda s: setcolor(s, ui.color.blue))
)
```
**Save** `window.py` and go back to Omniverse. When you click on the Rectangle now it should change from beige to blue.

## Step 4.3: Gesture States
Some Gestures have different states. To show how the different states work **change** the gesture for the Rectangle to the following:
```python
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gesture=
sc.DragGesture(
on_began_fn=lambda s: setcolor(s, ui.color.indigo),
on_changed_fn=lambda s: setcolor(s, ui.color.lightblue),
on_ended_fn=lambda s: setcolor(s, ui.color.beige)
)
)
```
After editing `window.py` should look like the following:
```python
import omni.ui as ui
from omni.ui import scene as sc
proj = [0.5,0,0,0,0,0.5,0,0,0,0,2e-7,0,0,0,1,1]
def setcolor(sender, color):
sender.color = color
class GestureWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.VStack():
scene_view = sc.SceneView(sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gesture=
sc.DragGesture(
on_began_fn=lambda s: setcolor(s, ui.color.indigo),
on_changed_fn=lambda s: setcolor(s, ui.color.lightblue),
on_ended_fn=lambda s: setcolor(s, ui.color.beige)
)
)
```
**Save** `window.py` and go back to Omniverse. Click on the Rectangle and Click and Drag. Notice how it changes colors based on what was set for each function.
- `on_began_fn` occurs when first clicking and no mouse movement occurs.
- `on_changed_fn` occurs when the gesture starts and the mouse is dragged.
- `on_ended_fn` occurs when the mouse is released.

## Step 4.4: Moving by Dragging
Next we will look into how the Rectangle can move using DragGesture.
1. Back in `window.py` **add** the following function before `setcolor()`:
```python
def move(transform, shape):
translate = shape.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
```
2. **Add** the following import at the top of the `window.py`:
- `from functools import partial`
- Partial functions allow for a more limited function with fewer parameters and fixed values.
3. **Update** DragGesture's `on_changed_fn` to look like the following:
```python
sc.DragGesture(
on_began_fn=lambda s: setcolor(s, ui.color.indigo),
on_changed_fn=partial(move, transform),
on_ended_fn=lambda s: setcolor(s, ui.color.beige)
)
```
After editing `window.py` should look like the following:
```python
import omni.ui as ui
from omni.ui import scene as sc
from functools import partial
proj = [0.5,0,0,0,0,0.5,0,0,0,0,2e-7,0,0,0,1,1]
def move(transform, shape):
translate = shape.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
transform.transform *= current
def setcolor(sender, color):
sender.color = color
class GestureWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.VStack():
scene_view = sc.SceneView(sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5
gesture=
sc.DragGesture(
on_began_fn=lambda s: setcolor(s, ui.color.indigo),
on_changed_fn=partial(move, transform),
on_ended_fn=lambda s: setcolor(s, ui.color.beige)
)
)
```
**Save** `window.py` and go back to Omniverse. Notice that now when the Rectangle is dragged it will now move based on the mouse's position.

## Step 4.5: Extending `sc.DragGesture`
We can extend any gesture by reimplementing its class.
1. In `window.py` after `proj`, **create** a new class called `Move`:
- `class Move(sc.DragGesture):`
2. Inside of `Move` **add** the following code:
- ```python
def __init__(self, transform: sc.Transform, **kwargs):
super().__init__(**kwargs)
self.__transform = transform
```
3. After `__init__()` **add** the following code:
- ```python
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
```
> **Note:** The above code is similar to the `move()` function. For future code references this will be **removed**.
4. **Change** the value passed to `gesture` when creating the Rectangle to `Move(transform)`
- ```python
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gesture=
Move(transform)
)
```
5. **Save** `window.py`.
After editing `window.py` should look like the following:
```python
import omni.ui as ui
from omni.ui import scene as sc
from functools import partial
proj = [0.5,0,0,0,0,0.5,0,0,0,0,2e-7,0,0,0,1,1]
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform, **kwargs):
super().__init__(**kwargs)
self.__transform = transform
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
def setcolor(sender, color):
sender.color = color
class GestureWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.VStack():
scene_view = sc.SceneView(sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gesture=
Move(transform)
)
```
There are multiple ways that a Gesture Callback can be added.
1. Adding the Gesture Callback with a single function
2. Adding a function for each state in the Gesture Callback
3. Reimplementing Gesture
# Step 5: Multiple Gestures and Multiple Shapes
Shapes are not limited to having one Gesture, they can have more than one. There is also no limit to how many shapes as well.
## Step 5.1: Add Multiple Gestures
In `window.py`, **update** the parameters inside Rectangle to the following:
```python
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gestures=[
Move(transform),
sc.ClickGesture(lambda s: setcolor(s, ui.color.red)),
sc.DoubleClickGesture(lambda s: setcolor(s, ui.color.beige))
]
)
```
> **Note:** that instead of using `gesture`, use `gestures` and pass in a list of gestures.
After editing `window.py` should look like the following:
```python
import omni.ui as ui
from omni.ui import scene as sc
from functools import partial
proj = [0.5,0,0,0,0,0.5,0,0,0,0,2e-7,0,0,0,1,1]
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform, **kwargs):
super().__init__(**kwargs)
self.__transform = transform
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
def setcolor(sender, color):
sender.color = color
class GestureWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.VStack():
scene_view = sc.SceneView(sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gestures=[
Move(transform),
sc.ClickGesture(lambda s: setcolor(s, ui.color.red)),
sc.DoubleClickGesture(lambda s: setcolor(s, ui.color.beige))
]
)
```
**Save** `window.py` and go back to Omniverse. We are now able to Click, Double Click, and Drag the rectangle in the window.
The default behavior is that only one gesture will occur at a time.

## Step 5.2: Handling Multiple Shapes
Knowing that only one gesture can occur at a time, we will see what happens when adding a second shape on top.
In `window.py`, **add** the following code below where we created the first Rectangle:
```python
transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(0,0,-1))
with transform:
sc.Rectangle(
2,
2,
color=ui.color.olive,
thickness=5,
gestures=[
Move(transform),
sc.ClickGesture(lambda s: setcolor(s, ui.color.blue)),
sc.DoubleClickGesture(lambda s: setcolor(s, ui.color.olive))
]
)
```
After editing `window.py` should look like the following:
```python
import omni.ui as ui
from omni.ui import scene as sc
from functools import partial
proj = [0.5,0,0,0,0,0.5,0,0,0,0,2e-7,0,0,0,1,1]
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform, **kwargs):
super().__init__(**kwargs)
self.__transform = transform
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
def setcolor(sender, color):
sender.color = color
class GestureWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.VStack():
scene_view = sc.SceneView(sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gestures=[
Move(transform),
sc.ClickGesture(lambda s: setcolor(s, ui.color.red)),
sc.DoubleClickGesture(lambda s: setcolor(s, ui.color.beige))
]
)
transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(0,0,-1))
with transform:
sc.Rectangle(
2,
2,
color=ui.color.olive,
thickness=5,
gestures=[
Move(transform),
sc.ClickGesture(lambda s: setcolor(s, ui.color.blue)),
sc.DoubleClickGesture(lambda s: setcolor(s, ui.color.olive))
]
)
```
The above code creates an olive Rectangle that is infront of the beige rectangle.
**Save** `window.py` and go back to Omniverse. Try clicking, double clicking, or dragging the rectangles.

This demonstrates that the Gesture closer to the camera will fire. If all the shapes are under the same transform it will move all of them. However, since each rectangle is under their own transform it will move them seperately.
# Step 6: Gesture Manager
Gestures track incoming input events separately, but it’s normally necessary to let only one gesture be executed because it prevents user input from triggering more than one action at a time.
GestureManager controls the priority of gestures if they are processed at the same time. It prioritizes the desired gestures and prevents unintended gestures from being executed.
## Step 6.1: Create the Gesture Manager
To demonstrate the Gesture Manager we will give the beige priority through a Gesture Manager.
**Add** the following code block after `setcolor()`:
```python
class Manager(sc.GestureManager):
def should_prevent(self, gesture: sc.AbstractGesture, preventer: sc.AbstractGesture) -> bool:
if gesture.name != 'gesture_name' and preventer.state == sc.GestureState.BEGAN:
return True
manager = Manager()
```
A Gesture Manager will inherit from `sc.GestureManager`. The Gesture Manager contains the function `should_prevent()` which can state whether or not the gesture should not run. If it returns `True` it will be prevented and if it returns `False` it will override the last gesture triggered.
## Step 6.2: Add the Gesture Manager to the Gestures
With a Gesture Manager defined we will need to pass it to the Gestures. To also avoid the olive rectangle's gestures from always being prevented a name will be assigned to the gestures as well.
**Update** the Gestures for the beige rectangle by passing in the following parameters:
```python
Move(transform, manager=manager, name="gesture_name"),
sc.ClickGesture(lambda s: setcolor(s, ui.color.red), manager=manager, name="gesture_name"),
sc.DoubleClickGesture(lambda s: setcolor(s, ui.color.beige), manager=manager, name="gesture_name")
```
After editing `window.py` should look like the following:
```python
import omni.ui as ui
from omni.ui import scene as sc
from functools import partial
proj = [0.5,0,0,0,0,0.5,0,0,0,0,2e-7,0,0,0,1,1]
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform, **kwargs):
super().__init__(**kwargs)
self.__transform = transform
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
def setcolor(sender, color):
sender.color = color
class Manager(sc.GestureManager):
def should_prevent(self, gesture: sc.AbstractGesture, preventer: sc.AbstractGesture) -> bool:
if gesture.name != 'gesture_name' and preventer.state == sc.GestureState.BEGAN:
return True
manager = Manager()
class GestureWindowExample(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.VStack():
scene_view = sc.SceneView(sc.CameraModel(proj, 1), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with scene_view.scene:
transform = sc.Transform()
with transform:
sc.Rectangle(
2,
2,
color=ui.color.beige,
thickness=5,
gestures=[
Move(transform, manager=manager, name="gesture_name"),
sc.ClickGesture(lambda s: setcolor(s, ui.color.red), manager=manager, name="gesture_name"),
sc.DoubleClickGesture(lambda s: setcolor(s, ui.color.beige), manager=manager, name="gesture_name")
]
)
transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(0,0,-1))
with transform:
sc.Rectangle(
2,
2,
color=ui.color.olive,
thickness=5,
gestures=[
Move(transform),
sc.ClickGesture(lambda s: setcolor(s, ui.color.blue)),
sc.DoubleClickGesture(lambda s: setcolor(s, ui.color.olive))
]
)
```
**Save** `window.py` and go back to Omniverse. Now when you click and drag the beige rectangle will take priority over the olive rectangle. Even though the beige rectangle is behind the olive rectangle with the Gesture Manager we prevent the olive rectangle's gestures and prioritize the beige rectangle.

# Step 7: Simple Scene Manipulator
Knowing how gestures work we can apply it to create a simple scene manipulator.
## Step 7.1: Create a new Extension
1. **Follow** the same steps from [Step 1](#step-1-create-an-extension)
2. Similar to [Step 2](#step-2-create-omniui-window), **create** a new file called `line.py`.

## Step 7.2: Create the Line Manipulator
In `line.py` **add** the following code and **save** the file:
```python
# line.py
import omni.ui as ui
from omni.ui import scene as sc
class LineManipulator(sc.Manipulator):
def __init__(self, desc: dict, **kwargs) -> None:
super().__init__(**kwargs)
def on_build(self) -> None:
transform = sc.Transform()
with transform:
sc.Line(
[-50, 0, 0],
[50, 0, 0],
color = ui.color.beige,
thickness=10
)
```
**Open** `extension.py` and **replace** the code with the following:
```python
# extension.py
import omni.ext
from omni.kit.viewport.registry import RegisterScene
from .line import LineManipulator
# 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 OmniExampleGestureExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[omni.example.gesture] omni example gesture startup")
self._line = RegisterScene(LineManipulator, "Line Gesture")
def on_shutdown(self):
print("[omni.example.gesture] omni example gesture shutdown")
self._line = None
```
**Save** `extension.py` and go back to Omniverse. You should see a beige line in the scene at the origin(0,0,0).

Notice that to add the Scene Manipulator is similar to how we create Rectangles in a Window frame. The difference is we registered it to the Viewport using `RegisterScene`.
# Step 7.3: Add a Gesture to the Line
1. Similiar to `window.py` **add** the following code to `line.py`:
```python
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform, **kwargs):
super().__init__(**kwargs)
self.__transform = transform
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
```
2. **Pass** the parameter `gesture=Move(transform)` into `sc.Line()`.
After editing `window.py` should look like the following:
```python
# line.py
import omni.ui as ui
from omni.ui import scene as sc
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform, **kwargs):
super().__init__(**kwargs)
self.__transform = transform
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
class LineManipulator(sc.Manipulator):
def __init__(self, desc: dict, **kwargs) -> None:
super().__init__(**kwargs)
def on_build(self) -> None:
transform = sc.Transform()
with transform:
sc.Line(
[-50, 0, 0],
[50, 0, 0],
color = ui.color.beige,
thickness=10,
gesture=Move(transform)
)
```
**Save** `line.py` and go back to Omniverse. When trying to drag the Line the Selection Gesture occurs instead. We can prevent this gesture using a Gesture Manager.

## Step 7.4: Add a Gesture Manager
The Gesture Manager works the same way when added in `line.py`. However, this time we will specify which gesture to prevent.
1. **Add** the following code after the imports:
```python
class Manager(sc.GestureManager):
def should_prevent(self, gesture: sc.AbstractGesture, preventer: sc.AbstractGesture) -> bool:
if gesture.name == "SelectionDrag" and preventer.state == sc.GestureState.BEGAN:
return True
manager=Manager()
```
Since we want to prevent the `SelectionDrag` gesture we check to see if the gesture name is "SelectionDrag".
2. Inside `Line()`, **locate** `Move()` and **add** the argument `manager=manager` into `Move()`.
After editing `window.py` should look like the following:
```python
# line.py
import omni.ui as ui
from omni.ui import scene as sc
class Manager(sc.GestureManager):
def should_prevent(self, gesture: sc.AbstractGesture, preventer: sc.AbstractGesture) -> bool:
if gesture.name == "SelectionDrag" and preventer.state == sc.GestureState.BEGAN:
return True
manager=Manager()
class Move(sc.DragGesture):
def __init__(self, transform: sc.Transform, **kwargs):
super().__init__(**kwargs)
self.__transform = transform
def on_changed(self):
translate = self.sender.gesture_payload.moved
# Move transform to the direction mouse moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
class LineManipulator(sc.Manipulator):
def __init__(self, desc: dict, **kwargs) -> None:
super().__init__(**kwargs)
def on_build(self) -> None:
transform = sc.Transform()
with transform:
sc.Line(
[-50, 0, 0],
[50, 0, 0],
color = ui.color.beige,
thickness=10,
gesture=Move(transform, manager=manager)
)
```
**Save** `line.py` and go back to Omniverse. Now we can freely drag the line along the X-Axis in the viewport.

Scene manipulators are essential tools in NVIDIA Omniverse for controlling, editing, and arranging 3D scenes. Explore [advanced scene manipulator](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene) options to deepen your understanding of creating custom scene manipulation tools. | 34,817 | Markdown | 34.857878 | 338 | 0.620473 |
AccelerationAgency/omniverse-cameracreator/exts/taa.omniverse.cameracreator/taa/omniverse/cameracreator/extension.py | import omni.ext
import omni.ui as ui
import omni.kit.commands as commands
class MyExtension(omni.ext.IExt):
# Lifecycle
def on_startup(self, ext_id):
print("[taa.omniverse.viewport] Extension starting up")
self._window = ui.Window("TAA Quick Camera", width=200, height = 200)
with self._window.frame:
with ui.VStack(height = 0, spacing = 4):
self.perspectiveButton = ui.Button("Perspective", height=40, clicked_fn=lambda: self.create_perspective_camera(), style={"background_color":"black"})
self.topButton = ui.Button("Top", height=40, clicked_fn=lambda: self.create_top_camera(), style={"background_color":"black"})
self.frontButton = ui.Button("Front", height=40, clicked_fn=lambda: self.create_front_camera(), style={"background_color":"black"})
self.rightButton = ui.Button("Right", height=40, clicked_fn=lambda: self.create_right_camera(), style={"background_color":"black"})
print("[taa.omniverse.viewport] Extension start up complete")
def on_shutdown(self):
print("[taa.omniverse.viewport] Extension shutting down")
self.stop()
print("[taa.omniverse.viewport] Extension shutdown complete")
# Custom methods
def set_camera(self, path):
omni.kit.viewport_legacy.get_viewport_interface().get_viewport_window().set_active_camera(path)
def rename_camera(self, name):
cameraPath = omni.kit.viewport_legacy.get_viewport_interface().get_viewport_window().get_active_camera()
omni.kit.commands.execute('MovePrims', paths_to_move={cameraPath: f'/World/Camera_{name}'})
def create_perspective_camera(self):
print("[taa.omniverse.viewport] Creating new perspective camera")
self.set_camera("/OmniverseKit_Persp")
commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport')
self.rename_camera("Perspective")
def create_top_camera(self):
print("[taa.omniverse.viewport] Creating new top-down camera")
self.set_camera("/OmniverseKit_Top")
commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport')
self.rename_camera("Top")
def create_front_camera(self):
print("[taa.omniverse.viewport] Creating new front view camera")
self.set_camera("/OmniverseKit_Front")
commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport')
self.rename_camera("Front")
def create_right_camera(self):
print("[taa.omniverse.viewport] Creating new right view camera")
self.set_camera("/OmniverseKit_Right")
commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport')
self.rename_camera("Right")
def start(self):
print("[taa.omniverse.viewport] Starting...")
def stop(self):
print("[taa.omniverse.viewport] Stopping...")
| 2,974 | Python | 44.76923 | 165 | 0.675521 |
AccelerationAgency/omniverse-cameracreator/exts/taa.omniverse.cameracreator/taa/omniverse/cameracreator/__init__.py | from .extension import *
| 26 | Python | 7.999997 | 24 | 0.730769 |
AccelerationAgency/omniverse-cameracreator/exts/taa.omniverse.cameracreator/config/extension.toml | [package]
version = "1.0.0"
title = "TAA - Omniverse Camera Creator"
description = "An simple extension that lets you quickly create cameras with a single click."
readme = "docs/README.md"
repository = ""
category = "Other"
keywords = ["taa", "viewport", "create", "camera", "view"]
icon = "data/taa-logo.png"
[dependencies]
"omni.kit.uiapp" = {}
[[python.module]]
name = "taa.omniverse.cameracreator" | 405 | TOML | 24.374998 | 93 | 0.693827 |
ArtecGroup/omni-artec-asset-browser/README.md | # Artec Cloud asset browser
Provides access to Artec Cloud models for Omniverse
 | 144 | Markdown | 27.999994 | 62 | 0.784722 |
ArtecGroup/omni-artec-asset-browser/tools/scripts/link_app.py | import os
import argparse
import sys
import json
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,813 | Python | 32.5 | 133 | 0.562389 |
ArtecGroup/omni-artec-asset-browser/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
ArtecGroup/omni-artec-asset-browser/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import zipfile
import tempfile
import sys
import shutil
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(
package_src_path, allowZip64=True
) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning(
"Directory %s already present, packaged installation aborted" % package_dst_path
)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,888 | Python | 31.568965 | 103 | 0.68697 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/PACKAGE-LICENSES/omni.services.browser.asset-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 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/PACKAGE-LICENSES/dependencies/pybind11-LICENSE.md | Copyright (c) 2016 Wenzel Jakob <[email protected]>, All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Please also refer to the file CONTRIBUTING.md, which clarifies licensing of
external contributions to this project including patches, pull requests, etc.
| 1,676 | Markdown | 54.899998 | 79 | 0.809666 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/PACKAGE-LICENSES/dependencies/fmt-LICENSE.md | Copyright (c) 2012 - 2016, Victor Zverovich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| 1,310 | Markdown | 53.624998 | 79 | 0.809924 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/config/extension.toml | [package]
authors = ["NVIDIA"]
category = "services"
changelog = "docs/CHANGELOG.md"
description = "Artec asset browser service"
icon = "data/icon.png"
keywords = ["kit", "service", "browsers", "assets"]
preview_image = "data/preview.png"
readme = "docs/README.md"
repository = ""
title = "Omniverse Artec Asset Service"
toggleable = false
version = "1.0.5"
[dependencies]
"omni.services.core" = {}
"omni.services.facilities.base" = {}
"omni.client" = {}
[[python.module]]
name = "artec.services.browser.asset"
[settings]
exts."artec.services.browser.asset".api_version = "v2"
[[test]]
dependencies = ["omni.services.client", "omni.client"]
| 645 | TOML | 22.071428 | 54 | 0.697674 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/config/extension.gen.toml | [package]
[package.publish]
date = 1661864119
kitVersion = "104.0+release.91154.beb7c507.tc"
buildNumber = "101.1.0+master.848.3bbd8284.tc"
repoName = "kit-browsers"
| 166 | TOML | 22.85714 | 46 | 0.753012 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# Forked from AssetServiceExtension from omni.services.browser.asset
import importlib
from typing import Optional
import carb
import carb.settings
import carb.tokens
import omni.ext
from omni.services.core import main
from .store.base import AssetStoreGroupFacility, BaseAssetStore
from .services.asset import router
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
ASSETS_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("assets")
_extension_instance = None
class AssetServiceExtension(omni.ext.IExt):
""" Asset service extension.
"""
def on_startup(self, ext_id):
settings = carb.settings.get_settings()
ext_name = ext_id.split("-")[0]
api_version = settings.get(f"exts/{ext_name}/api_version")
self._base_url = f"/{api_version}/artec-assets"
self._asset_store_group = AssetStoreGroupFacility()
router.register_facility("asset_store", self._asset_store_group)
main.register_router(router, prefix=self._base_url, tags=["assets"])
global _extension_instance
_extension_instance = self
def on_shutdown(self):
global _extension_instance
_extension_instance = None
main.deregister_router(router, prefix=self._base_url)
def resolve_cls(self, import_path):
cls_name = import_path.split(".")[-1]
import_path = import_path.replace(f".{cls_name}", "")
module = importlib.import_module(import_path)
return getattr(module, cls_name)
def register_store(self, asset_provider: BaseAssetStore) -> None:
self._asset_store_group.register_store(asset_provider.id(), asset_provider)
def unregister_store(self, asset_store: BaseAssetStore) -> None:
self._asset_store_group.unregister_store(asset_store)
def get_store(self, store_name: str) -> BaseAssetStore:
if store_name:
return self._asset_store_group.get_store(store_name)
return None
def get_instance() -> Optional[AssetServiceExtension]:
return _extension_instance
| 2,504 | Python | 31.115384 | 95 | 0.709665 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/__init__.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from .extension import AssetServiceExtension, get_instance
from .models import AssetModel, SearchCriteria, ProviderModel
from .store import BaseAssetStore, LocalFolderAssetProvider
from .collector import S3Collector
| 642 | Python | 52.583329 | 76 | 0.830218 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/models.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.
#
# Forked from ProviderModel, ConfigModel, AssetModel, _Page, _Filter, SearchCriteria from omni.services.browser.asset
from typing import List, Dict, Optional, Tuple
import pydantic
class ProviderModel(pydantic.BaseModel):
name: str = pydantic.Field(..., title="Provider name", description="Name of the provider")
icon: str = pydantic.Field("", title="Provider icon", description="Icon of the provider")
enable_common_categories: bool = pydantic.Field(
True, title="Use common categories", description="Use common categories for this provider"
)
private: bool = pydantic.Field(
False,
title="If private provider",
description="Search in private provider's category will not search other providers",
)
configurable: bool = pydantic.Field(
False, title="If provider could be configed", description="True to call /config to config the provider"
)
refresh_setting: str = pydantic.Field(
"", title="Provider refresh setting path", description="Setting path to notify refresh provider"
)
enable_setting: str = pydantic.Field(
"", title="Provider enable setting path", description="Setting path to notify provider enable"
)
class ConfigModel(pydantic.BaseModel):
vendor: str = pydantic.Field(..., title="Vendor", description="Vendor providing the assets")
class AssetModel(pydantic.BaseModel):
identifier: str = pydantic.Field(
..., title="Asset identifier", description="Unique ID code, used for downloading and caching"
)
name: str = pydantic.Field(..., title="Asset name", description="Name of the asset")
version: str = pydantic.Field("", title="Asset version", description="Version of the asset")
published_at: str = pydantic.Field(
..., title="Publication date", description="Date the asset was published (in ISO-8601 format)."
)
categories: List[str] = pydantic.Field(
..., title="Asset categories", description="List of categories this asset is a part of"
)
tags: List[str] = pydantic.Field(list(), title="Asset tags", description="Tags describing the asset")
vendor: str = pydantic.Field(..., title="Vendor", description="Vendor providing the assets")
download_url: Optional[str] = pydantic.Field(
"", title="Download location", description="Location from where to download the asset"
)
product_url: str = pydantic.Field(
"", title="Product url", description="Product url for assets that might not be available to download directly"
)
price: float = pydantic.Field(0.0, title="Price", description="Price of the asset in US Dollars")
thumbnail: str = pydantic.Field(..., title="Thumbnail path", description="Public endpoint for the thumbnail")
user: str = pydantic.Field(..., title="Asset suer name", description="Name of the user of the asset")
fusions: List[dict] = pydantic.Field(..., title="Fusions", description="Dict of name and download url")
class Config:
schema_extra = {
"example": {
"identifier": "1c54053d-49dd-4e18-ba46-abbe49a905b0",
"name": "Astronaut",
"version": "1.0.1-beta",
"published_at": "2020-12-15T17:49:22+00:00",
"categories": ["/characters/clothing/work"],
"tags": ["space", "astronaut", "human"],
"vendor": "NVIDIA",
"download_url": "https://acme.org/downloads/character/astronaut.zip",
"product_url": "https://acme.org/products/purchase/astronaut",
"price": 10.99,
"thumbnail": "https://images.com/thumbnails/256x256/astronaut.png",
"fusions": [{"name": "Test", "download_url": "https://images.com/thumbnails/256x256/astronaut.png"}],
}
}
def to_dict(self) -> Dict:
return self.__dict__
class _Page(pydantic.BaseModel):
number: int = pydantic.Field(0, title="Page number", description="Page number to return from paginated search")
size: int = pydantic.Field(50, title="Number of results to return per page", ge=1, le=100)
class _Filter(pydantic.BaseModel):
categories: List[str] = pydantic.Field(
None, title="Filter by Category", description="List of categories to filter search results by"
)
class SearchCriteria(pydantic.BaseModel):
keywords: List[str] = pydantic.Field(None, title="Search terms", description="List of keywords for searching")
page: _Page = pydantic.Field(_Page(), title="Pagination options")
sort: Tuple = pydantic.Field(None, title="Sort order", description="Tuple sort order (ie: price,desc or price,asc")
filter: _Filter = pydantic.Field(_Filter(), title="Filter Options")
vendors: List[str] = pydantic.Field(
None, title="List of vendors", description="Query a subset of available vendors"
)
search_timeout: int = pydantic.Field(
60, title="Search timeout", description="Stop searches after timeout has been reached"
)
class Config:
schema_extra = {
"example": {
"keywords": ["GPU", "RTX"],
"page": {"number": 5, "size": 75},
"sort": ["price", "desc"],
"filter": {"categories": ["hardware", "electronics"]},
"vendors": ["Vendor1", "Vendor2"],
"search_timeout": 60,
}
}
| 5,849 | Python | 46.560975 | 119 | 0.652932 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/collector/abstract_collector.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.
#
# Forked from AbstractCollector from omni.services.browser.asset
import abc
from typing import List
from ..models import AssetModel
class AbstractCollector(abc.ABC):
def __init__(self):
pass
@abc.abstractmethod
async def collect(self) -> List[AssetModel]:
"""
Collect assets
"""
return []
| 773 | Python | 28.76923 | 76 | 0.734799 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/collector/__init__.py | from .s3_collector import S3Collector
| 38 | Python | 18.499991 | 37 | 0.842105 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/collector/s3_collector.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.
#
# Forked from AbstractCollector from omni.services.browser.asset
from typing import List, Optional, Tuple, Callable
import carb
import omni.client
from ..models import AssetModel
from .abstract_collector import AbstractCollector
THUMBNAIL_PATH = ".thumbs"
THUMBNAIL_SIZE = 256
THUMBNAIL_FULL_PATH = f"{THUMBNAIL_PATH}/{THUMBNAIL_SIZE}x{THUMBNAIL_SIZE}/"
class S3Collector(AbstractCollector):
def __init__(
self, url: str, vendor: str, filter_file_suffixes: Optional[List[str]] = [".usd", ".usda", ".usdc", ".usdz"]
) -> None:
self._url = url
if self._url.endswith("/"):
self._url = self._url[:-1]
self._filter_file_suffixes = filter_file_suffixes
self._vendor = vendor
self._asset_models = []
super().__init__()
async def collect(
self, default_thumbnail=None, on_folder_done_fn: Callable[[str, List[AssetModel]], None] = None
) -> List[AssetModel]:
await self._traverse_folder_async(
self._url, default_thumbnail=default_thumbnail, on_folder_done_fn=on_folder_done_fn
)
self._asset_models = [asset for asset in self._asset_models if asset.thumbnail != ""]
return self._asset_models
async def _traverse_folder_async(
self,
url: str,
recurse: bool = True,
default_thumbnail=None,
on_folder_done_fn: Callable[[str, List[AssetModel]], None] = None,
):
"""Traverse folder to retreive assets and thumbnails"""
if not url.endswith("/"):
url += "/"
entries = await self._list_folder_async(url)
if entries:
thumbnail_path = None
folder_asset_models = []
for entry in entries:
path = omni.client.combine_urls(url, entry.relative_path)
# "\" used in local path, convert to "/"
path = path.replace("\\", "/")
if entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
if recurse:
dirs = path.split("/")
sub_folder_name = dirs[-1]
if sub_folder_name == THUMBNAIL_PATH:
thumbnail_path = omni.client.combine_urls(url, THUMBNAIL_FULL_PATH)
else:
await self._traverse_folder_async(
path,
recurse=recurse,
default_thumbnail=default_thumbnail,
on_folder_done_fn=on_folder_done_fn,
)
else:
asset_model = self._add_asset_model(url, entry, default_thumbnail=default_thumbnail)
if asset_model is not None:
folder_asset_models.append(asset_model)
if thumbnail_path is not None:
# Only verify assets in same folder
await self._list_thumbnails(thumbnail_path, folder_asset_models)
if folder_asset_models and on_folder_done_fn:
on_folder_done_fn(url, folder_asset_models)
async def _list_folder_async(self, url: str) -> Optional[Tuple[omni.client.ListEntry]]:
"""List files on a s3 server folder"""
try:
(result, entries) = await omni.client.list_async(url)
if result == omni.client.Result.OK:
return entries
else:
carb.log_warn(f"Failed to access {url}")
return None
except Exception as e:
carb.log_error(str(e))
return None
def _add_asset_model(self, url: str, entry: omni.client.ListEntry, default_thumbnail=None) -> Optional[AssetModel]:
file_name = entry.relative_path
if self._filter_file_suffixes is not None:
pos = file_name.rfind(".")
file_suffix = file_name[pos:].lower()
if file_suffix not in self._filter_file_suffixes:
return None
# Use last path in url as first path of category url
pos = self._url.rfind("/")
if pos <= 0:
pos = 0
category = url[pos:]
if category[0] == "/":
category = category[1:]
if category and category[-1] == "/":
category = category[:-1]
# To match search by category, ignore unnecessary sub folders in category url
sub_categories = category.split("/")[0:3]
category = "/".join(sub_categories)
# TODO: identifier/version/tags need to be comfirmed
asset_model = AssetModel(
identifier=entry.hash or hash(url + entry.relative_path),
name=file_name,
version=entry.version or "",
published_at=entry.modified_time.timestamp(),
categories=[category],
tags=[],
vendor=self._vendor,
download_url=url + entry.relative_path,
product_url="",
price=0,
thumbnail=default_thumbnail or "", # Fill it later
user=entry.created_by or "",
fusions=[]
)
self._asset_models.append(asset_model)
return asset_model
async def _list_thumbnails(self, url: str, folder_assset_models: List[AssetModel]) -> None:
if len(folder_assset_models) == 0:
return
entries = await self._list_folder_async(url)
if entries:
for entry in entries:
thumbnail_name = entry.relative_path[:-4]
for asset_model in folder_assset_models:
if thumbnail_name == asset_model.name or thumbnail_name == asset_model.name + ".auto":
asset_model.thumbnail = omni.client.combine_urls(url, entry.relative_path)
break
| 6,287 | Python | 39.050955 | 119 | 0.566248 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/services/__init__.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
| 426 | Python | 52.374993 | 76 | 0.812207 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/services/asset.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.
#
# Forked from SortOrder from omni.services.browser.asset
import asyncio
from enum import Enum
from typing import Dict, List, Tuple
from fastapi import Depends
from omni.services.core import routers
from .dependencies import get_app_header, get_app_version
from ..store.base import AssetStoreGroupFacility
from ..models import AssetModel, ProviderModel, SearchCriteria, ConfigModel
router = routers.ServiceAPIRouter()
router.dependencies = [Depends(get_app_header), Depends(get_app_version)]
class SortOrder(str, Enum):
date = "date"
name = "name"
@router.get("/categories", response_model=Dict[str, Dict])
async def list_categories(
asset_store: AssetStoreGroupFacility = router.get_facility("asset_store"),
):
await asyncio.sleep(0)
return asset_store.get_categories()
@router.post("/search", response_model=Dict[str, Tuple[List[AssetModel], bool]])
async def search(search: SearchCriteria, asset_store: AssetStoreGroupFacility = router.get_facility("asset_store")):
return await asset_store.search(search, stores=search.vendors, search_timeout=60)
@router.get("/providers", response_model=Dict[str, ProviderModel])
async def list_vendors(
asset_store: AssetStoreGroupFacility = router.get_facility("asset_store"),
):
await asyncio.sleep(0)
return asset_store.get_providers()
@router.post("/config", response_model=None)
async def config(config_params: ConfigModel, asset_store: AssetStoreGroupFacility = router.get_facility("asset_store")):
await asyncio.sleep(0)
return asset_store.config(config_params.vendor)
| 2,002 | Python | 33.534482 | 120 | 0.77023 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/services/dependencies.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.
#
# Forked from omni.services.browser.asset
from fastapi import Header
def get_app_header(x_ov_app: str = Header("")):
pass
def get_app_version(x_ov_version: str = Header("")):
pass
| 621 | Python | 30.099998 | 76 | 0.766506 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/store/base.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.
#
# Forked from BaseAssetStore, AssetStoreGroupFacility from omni.services.browser.asset
import abc
import asyncio
import traceback
import omni.client
import zipfile
from typing import Dict, List, Tuple, Callable
import carb
from omni.services.facilities.base import Facility
from ..models import AssetModel, ProviderModel, SearchCriteria
class BaseAssetStore(Facility, abc.ABC):
def __init__(self, store_id: str) -> None:
super().__init__()
self._store_id = store_id
self._categories = {}
self._download_progress: Dict[str, float] = {}
def authorized(self) -> bool:
"""Override this method to force authentication flow."""
return True
async def authenticate(self, username: str, password: str):
"""Override this method to implement authentication method."""
pass
@abc.abstractmethod
async def _search(self, search_criteria: SearchCriteria) -> Tuple[List[AssetModel], bool]:
"""Searches the asset store.
This function needs to be implemented as part of an implementation of the BaseAssetStore.
This function is called by the public `search` function that will wrap this function in a timeout.
"""
pass
async def search(self, search_criteria: SearchCriteria, search_timeout: int) -> Tuple[List[AssetModel], bool]:
"""Search the asset store
Will error and stop the search if search_timeout is exceeded
Args:
search_criteria (SearchCriteria): Dictionary with support search fields.
search_timeout (int): Timeout a search after `search_timeout` seconds. (default: 60 seconds)
Returns:
List of asset models and if more.
Raises:
asyncio.TimeoutError
"""
return await asyncio.wait_for(self._search(search_criteria), timeout=search_timeout)
async def _download(self, asset: AssetModel, dest_url: str, on_progress_fn: Callable[[float], None] = None) -> Dict:
"""Default Download handler using omni.client.
This function needs to be implemented as part of an implementation of the BaseAssetStore.
This function is called by the public `download` function that will wrap this function in a timeout.
"""
ret_value = {"url": None}
if asset and asset.download_url:
file_name = asset.download_url.split("/")[-1]
dest_url = f"{dest_url}/{file_name}"
carb.log_info(f"Download {asset.download_url} to {dest_url}")
result = await omni.client.copy_async(
asset.download_url, dest_url, behavior=omni.client.CopyBehavior.OVERWRITE
)
ret_value["status"] = result
if result != omni.client.Result.OK:
carb.log_error(f"Failed to download {asset.download_url} to {dest_url}")
return ret_value
if asset.download_url.lower().endswith(".zip"):
# unzip
output_url = dest_url[:-4]
await omni.client.create_folder_async(output_url)
carb.log_info(f"Unzip {dest_url} to {output_url}")
with zipfile.ZipFile(dest_url, "r") as zip_ref:
zip_ref.extractall(output_url)
dest_url = output_url
ret_value["url"] = dest_url
return ret_value
async def download(
self, asset: AssetModel, dest_url: str, on_progress_fn: Callable[[float], None] = None, timeout: int = 600
) -> Dict:
"""Downloads an asset from the asset store.
Args:
asset (AssetModel): The asset descriptor.
dest_url (str): Url of the destination file.
Kwargs:
timeout (int): Timeout a download after this amount of time. (default: 10 mins.)
Returns:
Response Dict.
Raises:
asyncio.TimeoutError
"""
self._download_progress[asset.identifier] = 0
def __on_download_progress(progress):
self._download_progress[asset.identifier] = progress
if on_progress_fn:
on_progress_fn(progress)
download_future = asyncio.Task(self._download(asset, dest_url, on_progress_fn=__on_download_progress))
while True:
last_progress = self._download_progress[asset.identifier]
done, pending = await asyncio.wait([download_future], timeout=timeout)
if done:
return download_future.result()
else:
# download not completed
# if progress changed, continue to wait for completed
# otherwwise, treat as timeout
if self._download_progress[asset.identifier] == last_progress:
carb.log_warn(f"[{asset.name}]: download timeout")
download_future.cancel()
return {"status": omni.client.Result.ERROR_ACCESS_LOST}
def categories(self) -> Dict[str, List[str]]:
"""Return the list of predefined categories."""
return self._categories
def id(self) -> str:
"""Return store id."""
return self._store_id
def provider(self) -> ProviderModel:
"""Return provider info"""
return ProviderModel(name=self._store_id)
def config(self) -> None:
"""Entry point to config the provider"""
pass
class AssetStoreGroupFacility(Facility):
def __init__(self):
self._stores: Dict[str, BaseAssetStore] = {}
self._updated = True
super().__init__()
def register_store(self, name: str, store: BaseAssetStore) -> None:
self._stores[name] = store
self._updated = True
def unregister_store(self, store: BaseAssetStore) -> None:
self._stores.pop(store.id())
self._updated = True
def clear_stores(self) -> None:
self._stores = {}
def get_registered_stores(self) -> List[str]:
"""Return list of all registered stores."""
return list(self._stores.keys())
def get_store(self, store_name: str) -> BaseAssetStore:
return self._stores.get(store_name)
def get_providers(self) -> Dict[str, ProviderModel]:
providers = {}
for name, store in self._stores.items():
providers[store.id()] = store.provider()
return providers
def get_categories(self):
categories = {}
for store_name, store in self._stores.items():
categories[store_name] = store.categories()
return categories
def config(self, name: str):
if name in self._stores:
self._stores[name].config()
async def search(
self, search_criteria: SearchCriteria, stores: List[str] = None, search_timeout: int = 60
) -> Dict[str, Tuple[List[AssetModel], bool]]:
stores = stores or self.get_registered_stores()
queries: Dict[str, asyncio.Future] = {}
for store_name in stores:
queries[store_name] = asyncio.ensure_future(
# Use a deep copy of the ``search_criteria`` model in order to prevent one of the ``AssetStore``'s
# ``search()`` operation from mutating the object in the body of the function, which would end up
# affecting the search criterias of downstream ``AssetStore``s:
self._stores[store_name].search(
search_criteria=search_criteria.copy(deep=True), search_timeout=search_timeout
)
)
await asyncio.gather(*queries.values(), return_exceptions=True)
results = {}
for store, query in queries.items():
try:
results[store] = query.result()
except Exception:
carb.log_warn(f"Failed to fetch results for store {store}. Reason:")
carb.log_warn(traceback.format_exc())
return results
| 8,364 | Python | 36.34375 | 120 | 0.612984 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/store/__init__.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from .base import BaseAssetStore
from .local import LocalFolderAssetProvider
| 504 | Python | 44.909087 | 76 | 0.819444 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/store/local/local.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.
#
# Forked from omni.kit.browser.asset_provider.local class LocalFolderAssetProvider
import asyncio
import carb
import carb.settings
import json
from typing import Dict, List, Optional
from .static import StaticAssetStore
from ...models import AssetModel, ProviderModel
from ...collector import S3Collector
from pathlib import Path
import omni.kit.app
from .my_assets_paths import MyAssetsPathsWindow
from .constants import SETTING_ROOT, SETTING_STORE_ENABLE
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data")
PROVIDER_ID = "My Assets"
SETTING_STORE_RERESH = SETTING_ROOT + "refresh"
SETTING_STORE_SEARCH_SUB_FOLDERS = SETTING_ROOT + "searchSubFolders"
SETTING_STORE_FOLDER = SETTING_ROOT + "folders"
SETTING_PERSISTENT_STORE_FOLDER = "/persistent" + SETTING_STORE_FOLDER
SETTING_STORE_FOLDER_CHANGED = SETTING_ROOT + "folderChanged"
DEFAULT_THUMBNAIL = f"{DATA_PATH}/usd_stage_256.png"
CACHE_FILE = "${shared_documents}/my_assets_2.json"
class LocalFolderAssetProvider(StaticAssetStore):
""" Local file system asset provider
"""
def __init__(self):
super().__init__(PROVIDER_ID, [])
self._settings = carb.settings.get_settings()
self._my_assets_window: Optional[MyAssetsPathsWindow] = None
self._folders = self._get_local_folders()
self._assets: Dict[str, Dict[str, List[AssetModel]]] = {}
self._json_file = carb.tokens.get_tokens_interface().resolve(CACHE_FILE)
# First load assets from saved file
self._load_assets()
# Refresh assets in background
asyncio.ensure_future(self._collect_async(self._folders))
self._refresh_folders_sub = omni.kit.app.SettingChangeSubscription(
SETTING_PERSISTENT_STORE_FOLDER,
lambda item, event_type: self._on_path_changed(),
)
self._folder_changed_sub = omni.kit.app.SettingChangeSubscription(
SETTING_STORE_FOLDER_CHANGED,
lambda item, event_type: self._on_folder_changed(event_type),
)
def destroy(self):
self._refresh_folders_sub = None
self._folder_changed_sub = None
if self._my_assets_window:
self._my_assets_window.destroy()
self._my_assets_window = None
async def _collect_async(self, folders) -> List[AssetModel]:
# Collection assets from folders into json file
for url in folders:
await self._collect_folder_async(url)
self._save_assets()
async def _collect_folder_async(self, folder):
carb.log_info(f"Starting collecting {folder}...")
if folder not in self._assets:
self._assets[folder] = {}
self._scanned_categories = []
scanner = S3Collector(folder, self._store_id)
self.__refresh = False
await scanner.collect(default_thumbnail=DEFAULT_THUMBNAIL, on_folder_done_fn=self._on_folder_collected)
# OM-77818: Only refresh when whole folder collected instead of refresh every sub folder collected
if self.__refresh:
self._refresh_categories()
# Remove assets not found during collection
remove_categories = [category for category in self._assets[folder] if category not in self._scanned_categories]
if remove_categories:
carb.log_info(f" Remove {remove_categories} from {folder}")
for category in remove_categories:
self._assets[folder].pop(category)
self._refresh_categories()
def _filter_by_category(self, categories: List[str]) -> List[AssetModel]:
search_sub_folders = self._settings.get(SETTING_STORE_SEARCH_SUB_FOLDERS)
filtered: List[AssetModel] = []
for _, folder in self._assets.items():
for _, assets in folder.items():
if categories:
for item in assets:
for item_category in item.categories:
if search_sub_folders:
if any(item_category.lower().startswith(category.lower()) for category in categories):
filtered.append(item)
break
else:
# Here make sure category is match
if any(category.lower() == item_category.lower() for category in categories):
break
else:
filtered.extend(assets)
return filtered
def provider(self) -> ProviderModel:
"""Return provider info"""
return ProviderModel(
name=self._store_id,
icon=f"{DATA_PATH}/folder.svg",
private=True,
configurable=True,
refresh_setting=SETTING_STORE_RERESH,
enable_setting=SETTING_STORE_ENABLE,
)
def config(self) -> None:
"""Entry point to config the provider"""
if self._my_assets_window:
# Always destroy old window to make sure laod latest settings when show config window
self._my_assets_window.destroy()
self._my_assets_window = MyAssetsPathsWindow()
def _get_local_folders(self) -> List[str]:
folders = self._settings.get(SETTING_PERSISTENT_STORE_FOLDER)
if not folders:
folders = self._settings.get(SETTING_STORE_FOLDER)
return folders
def _on_path_changed(self):
folders = self._get_local_folders()
if folders != self._folders:
# Refresh assets
append_folders = [folder for folder in folders if folder not in self._folders]
remove_folders = [folder for folder in self._folders if folder not in folders]
self._folders = folders
if remove_folders:
for folder in remove_folders:
if folder in self._assets:
self._assets.pop(folder)
self._refresh_categories()
if append_folders:
asyncio.ensure_future(self._collect_async(append_folders))
def _on_folder_changed(self, event_type):
if event_type != carb.settings.ChangeEventType.CHANGED:
return
folder = self._settings.get(SETTING_STORE_FOLDER_CHANGED)
if folder:
asyncio.ensure_future(self._collect_async([folder]))
def _on_folder_collected(self, url: str, asset_models: List[AssetModel]) -> None:
carb.log_info(f"{url} collected with {len(asset_models)} assets")
self._scanned_categories.append(url)
for folder in self._folders:
if url.startswith(folder):
break
else:
return
# Append assets
if url in self._assets[folder]:
refresh_category = False
if self._assets[folder][url] == asset_models:
# Do nothind since assets no change
return
else:
refresh_category = True
self._assets[folder][url] = asset_models
self.__refresh = refresh_category
def _refresh_categories(self) -> None:
self._load_categories()
# Notify to refresh
self._settings.set(SETTING_STORE_RERESH, True)
def _load_categories(self) -> None:
# Update categories
categories = set()
for _, folder in self._assets.items():
for _, assets in folder.items():
for asset in assets:
categories.update(asset.categories)
# Generate category list
self._categories = {}
for category in categories:
folders = category.split("/")
root = folders[0]
if root not in self._categories:
self._categories[root] = []
if len(folders) > 1:
sub = "/".join(folders[1:])
self._categories[root].append(sub)
def _save_assets(self):
result = {}
for folder in self._assets:
result[folder] = {}
for category in self._assets[folder]:
result[folder][category] = []
for data in self._assets[folder][category]:
result[folder][category].append(data.to_dict())
try:
with open(self._json_file, "w") as json_file:
json.dump(result, json_file, indent=4)
json_file.close()
except FileNotFoundError:
carb.log_warn(f"Failed to open {self._json_file}!")
except PermissionError:
carb.log_warn(f"Cannot write to {self._json_file}: permission denied!")
except Exception as e:
carb.log_warn(f"Unknown failure to write to {self._json_file}: {e}")
finally:
if json_file:
json_file.close()
def _load_assets(self):
asset_json = None
try:
with open(self._json_file, "r") as json_file:
asset_json = json.load(json_file)
except FileNotFoundError:
carb.log_info(f"Failed to open {self._json_file}!")
except PermissionError:
carb.log_error(f"Cannot read {self._json_file}: permission denied!")
except Exception as exc:
carb.log_error(f"Unknown failure to read {self._json_file}: {exc}")
self._assets = {}
self._categories = {}
if asset_json is None:
return
for folder in asset_json:
if folder not in self._folders:
continue
self._assets[folder] = {}
for category in asset_json[folder]:
self._assets[folder][category] = []
for asset in asset_json[folder][category]:
asset_model = AssetModel(**asset)
self._assets[folder][category].append(asset_model)
self._load_categories()
| 10,379 | Python | 37.731343 | 119 | 0.596493 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/store/local/style.py | # Forked from omni.kit.browser.asset_provider.local
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("icons")
MY_ASSETS_STYLE = {
"TreeView": {"background_color": 0xFF23211F, "background_selected_color": 0xFF444444},
"TreeView.Item": {"margin": 14, "color": 0xFF000055},
# "Field": {"background_color": 0xFF333322},
"Label::header": {"margin": 4},
"Label": {"margin": 5},
"Label::builtin": {"color": 0xFF909090},
"Label::config": {"color": 0xFFDDDDDD},
"ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4},
"ItemButton.Image::add": {"image_url": f"{ICON_PATH}/plus.svg", "color": 0xFF06C66B},
"ItemButton.Image::remove": {"image_url": f"{ICON_PATH}/trash.svg", "color": 0xFF1010C6},
"ItemButton.Image::clean": {"image_url": f"{ICON_PATH}/broom.svg", "color": 0xFF5EDAFA},
"ItemButton.Image::update": {"image_url": f"{ICON_PATH}/refresh.svg", "color": 0xFF5EDAFA},
"ItemButton:hovered": {"background_color": 0xFF333333},
"ItemButton:pressed": {"background_color": 0xFF222222},
}
| 1,155 | Python | 45.239998 | 95 | 0.661472 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/store/local/constants.py | # Forked from omni.kit.browser.asset_provider.local
SETTING_ROOT = "/exts/omni.kit.browser.asset_provider.local/"
SETTING_STORE_ENABLE = SETTING_ROOT + "enable"
| 162 | Python | 31.599994 | 61 | 0.765432 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/store/local/__init__.py | from .local import LocalFolderAssetProvider
| 44 | Python | 21.499989 | 43 | 0.886364 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/store/local/my_assets_paths.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.
#
# Forked from omni.kit.browser.asset_provider.local
from functools import lru_cache
import asyncio
from typing import Optional, List, Callable
import carb
import carb.dictionary
import carb.settings
import omni.ui as ui
import omni.kit.app
from omni.kit.window.filepicker import FilePickerDialog
from .style import MY_ASSETS_STYLE
SETTING_MY_ASSET_FOLDERS = "/persistent/exts/omni.kit.browser.asset_provider.local/folders"
class PathItem(ui.AbstractItem):
def __init__(self, path, add_dummy=False):
super().__init__()
self.path_model = ui.SimpleStringModel(path)
self.add_dummy = add_dummy
def __repr__(self):
return f"[PathItem]: {self.path_model.as_string}"
class MyAssetPathsModel(ui.AbstractItemModel):
def __init__(self, on_path_changed_fn: Callable[[None], None]):
super().__init__()
self._on_path_changed_fn = on_path_changed_fn
self._settings = carb.settings.get_settings()
self._load()
self._add_dummy = PathItem("", add_dummy=True)
def destroy(self):
self._children = []
def get_item_children(self, item: Optional[ui.AbstractItem] = None) -> List[ui.AbstractItem]:
"""Returns all the children when the widget asks it."""
if item is not None:
return []
return self._children + [self._add_dummy]
def get_item_value_model_count(self, item: PathItem):
"""The number of columns"""
return 3
def get_item_value_model(self, item: PathItem, column_id: int):
if column_id == 1:
return item.path_model
return None
def _load(self):
self._children = []
folders = self._settings.get(SETTING_MY_ASSET_FOLDERS)
if folders:
for folder in folders:
item = PathItem(folder)
self._children.append(item)
self._item_changed(None)
def add_empty(self):
self._children.append(PathItem(""))
self._item_changed(None)
def add_item(self, item: PathItem):
self._children.append(item)
self.save()
self._item_changed(None)
def remove_item(self, item: PathItem):
self._children.remove(item)
self.save()
self._item_changed(None)
def save(self):
paths = [c.path_model.as_string for c in self._children]
self._settings.set(SETTING_MY_ASSET_FOLDERS, paths)
if self._on_path_changed_fn:
self._on_path_changed_fn()
class MyAssetPathDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
self._pick_folder_dialog: Optional[FilePickerDialog] = None
def destroy(self):
self._pick_folder_dialog = None
def build_widget(self, model: MyAssetPathsModel, item: PathItem, column_id: int, level, expanded):
"""Create a widget per column per item"""
if column_id == 0 and not item.add_dummy:
def open(item_=item):
# Import it here instead of on the file root because it has long import time.
path = item_.path_model.as_string
if path:
import webbrowser
webbrowser.open(path)
ui.Button("open", width=20, clicked_fn=open, tooltip="Open path using OS file explorer.")
elif column_id == 1 and not item.add_dummy:
value_model = model.get_item_value_model(item, column_id)
ui.StringField(value_model)
elif column_id == 2:
def on_click(item_=item):
if item.add_dummy:
if self._pick_folder_dialog is None:
self._pick_folder_dialog = self._create_filepicker(
"Select Directory for My Assets",
click_apply_fn=lambda url, m=model: self._on_folder_picked(url, m),
dir_only=True,
)
self._pick_folder_dialog.show()
else:
model.remove_item(item_)
with ui.HStack(width=60):
ui.Spacer(width=10)
ui.Button(
name=("add" if item.add_dummy else "remove"),
style_type_name_override="ItemButton",
width=20,
height=20,
clicked_fn=on_click,
)
ui.Spacer(width=4)
ui.Spacer()
def build_header(self, column_id: int):
COLUMNS = ["", "folder", "edit"]
with ui.HStack(height=24):
ui.Spacer(width=10)
ui.Label(COLUMNS[column_id], name="header")
def _create_filepicker(
self,
title: str,
filters: list = ["All Files (*)"],
click_apply_fn: Callable = None,
error_fn: Callable = None,
dir_only: bool = False,
) -> FilePickerDialog:
async def on_click_handler(
filename: str, dirname: str, dialog: FilePickerDialog, click_fn: Callable, dir_only: bool
):
fullpath = None
if dir_only:
fullpath = dirname
else:
if dirname:
fullpath = f"{dirname}/{filename}"
elif filename:
fullpath = filename
if click_fn:
click_fn(fullpath)
dialog.hide()
dialog = FilePickerDialog(
title,
allow_multi_selection=False,
apply_button_label="Select",
click_apply_handler=lambda filename, dirname: asyncio.ensure_future(
on_click_handler(filename, dirname, dialog, click_apply_fn, dir_only)
),
click_cancel_handler=lambda filename, dirname: dialog.hide(),
item_filter_options=filters,
error_handler=error_fn,
)
dialog.hide()
return dialog
def _on_folder_picked(self, url: Optional[str], model: ui.AbstractItemModel) -> None:
item = PathItem(url)
model.add_item(item)
class MyAssetsPathsWidget(object):
def __init__(self, on_path_changed_fn: Callable[[None], None]):
self._model = MyAssetPathsModel(on_path_changed_fn)
self._delegate = MyAssetPathDelegate()
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style_type_name_override="TreeView",
):
tree_view = ui.TreeView(self._model, delegate=self._delegate, root_visible=False, header_visible=True)
tree_view.column_widths = [ui.Pixel(46), ui.Fraction(1), ui.Pixel(60)]
def destroy(self):
self._model.destroy()
self._model = None
self._delegate.destroy()
self._delegate = None
class MyAssetsPathsWindow(ui.Window):
def __init__(self, on_path_changed_fn: Callable[[None], None] = None):
super().__init__("My Assets Folders", width=500, height=600)
self._on_path_changed_fn = on_path_changed_fn
self._widget: Optional[MyAssetsPathsWidget] = None
self.frame.set_build_fn(self._build_ui)
self.frame.set_style(MY_ASSETS_STYLE)
def destroy(self):
if self._widget is not None:
self._widget.destroy()
self._widget = None
self.visible = False
def _build_ui(self):
with self.frame:
self._widget = MyAssetsPathsWidget(self._on_path_changed_fn)
| 8,010 | Python | 32.659664 | 114 | 0.584644 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/store/local/static.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.
#
# Forked from StaticAssetStore from omni.services.browser.asset
from typing import List, Tuple
from ...models import AssetModel, SearchCriteria
from ..base import BaseAssetStore
class StaticAssetStore(BaseAssetStore):
def __init__(self, store_id, data=List[AssetModel]) -> None:
super().__init__(store_id=store_id)
self._data: List[AssetModel] = data
async def _search(self, search_criteria: SearchCriteria) -> Tuple[List[AssetModel], bool]:
keywords = search_criteria.keywords or []
categories = search_criteria.filter.categories or []
page = search_criteria.page
sort = search_criteria.sort
filtered = self._filter_by_category(categories)
selected: List[AssetModel] = []
if keywords:
for item in filtered:
if any(keyword in item.name for keyword in keywords) or any(
keyword in item.tags for keyword in keywords
):
selected.append(item)
else:
selected = filtered
if sort:
key, order = sort
reverse = True if order == "desc" else False
if key == "created_at":
key = "published_at"
selected = sorted(selected, key=lambda item: getattr(item, key), reverse=reverse)
start_index = 0
end_index = page.size
# For consistency with external vendors, page count starts at 1, not 0.
if page.number > 1:
start_index = page.size * (page.number - 1)
end_index = start_index + page.size
assets = selected[start_index:end_index]
return (assets, len(assets) == page.size)
def _filter_by_category(self, categories: List[str]) -> List[AssetModel]:
filtered: List[AssetModel] = []
if categories:
for item in self._data:
for item_category in item.categories:
if any(category.lower() in item_category.lower() for category in categories):
filtered.append(item)
break
else:
filtered = self._data
return filtered
| 2,602 | Python | 36.724637 | 97 | 0.621445 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/tests/dummy.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from ..models import AssetModel
from ..store.local import StaticAssetStore
class DummyAssetStore(StaticAssetStore):
""" Hard coded data set of assets.
This is a hardcoded list of assets used as a reference implementation.
This store gets instantiated as part of the extension and passed through as a facility to the various endpoints.
More advanced implementations can be added and as long as the API of the facility is followed they can be swapped without futher changes needed.
"""
def __init__(self) -> None:
data = [
AssetModel(
identifier="1c54053d-49dd-4e18-ba46-abbe49a905b0",
name="car-suv-1",
version="1.0.1-beta",
published_at="2020-12-15T17:49:22+00:00",
categories=["/vehicles/cars/suv"],
tags=["vehicle", "cars", "suv"],
vendor="NVIDIA",
download_url="https://acme.org/downloads/vehicles/cars/suv/car-suv-1.zip",
product_url="https://acme.org/products/purchase/car-suv-1",
price=10.99,
thumbnail="https://images.com/thumbnails/256x256/car-suv-1.png",
),
AssetModel(
identifier="3708fe73-6b82-449a-8e6f-96c6f443a93c",
name="car-suv-2",
version="1.0.1-beta",
published_at="2020-12-15T17:49:22+00:00",
categories=["/vehicles/cars/suv"],
tags=["vehicle", "cars", "suv"],
vendor="NVIDIA",
download_url="https://acme.org/downloads/vehicles/cars/suv/car-suv-2.zip",
product_url="https://acme.org/products/purchase/car-suv-2",
price=12.99,
thumbnail="https://images.com/thumbnails/256x256/car-suv-2.png",
),
AssetModel(
identifier="9dcf54e8-76f5-49e0-8155-c4529b5ed059",
name="car-sedan-1",
version="1.0.1-beta",
published_at="2020-12-15T17:49:22+00:00",
categories=["/vehicles/cars/sedan"],
tags=["vehicle", "cars", "sedan"],
vendor="NVIDIA",
download_url="https://acme.org/downloads/vehicles/cars/suv/car-sedan-1.zip",
product_url="https://acme.org/products/purchase/car-sedan-1",
price=13.99,
thumbnail="https://images.com/thumbnails/256x256/car-sedan-1.png",
),
AssetModel(
identifier="fc6d47b9-8243-4694-8c44-3b66cbbd7d24",
name="car-sedan-2",
version="1.0.1-beta",
published_at="2020-12-15T17:49:22+00:00",
categories=["/vehicles/cars/sedan"],
tags=["vehicle", "cars", "sedan"],
vendor="NVIDIA",
download_url="https://acme.org/downloads/vehicles/cars/suv/car-sedan-2.zip",
product_url="https://acme.org/products/purchase/car-sedan-2",
price=14.99,
thumbnail="https://images.com/thumbnails/256x256/car-sedan-2.png",
),
AssetModel(
identifier="fc6d47b9-8243-4694-8c44-3b66cbbd7d24",
name="car-sedan-3",
version="1.0.1-beta",
published_at="2020-12-15T17:49:22+00:00",
categories=["/vehicles/cars/sedan"],
tags=["vehicle", "cars", "sedan"],
vendor="NVIDIA",
download_url="https://acme.org/downloads/vehicles/cars/suv/car-sedan-3.zip",
product_url="https://acme.org/products/purchase/car-sedan-3",
price=15.99,
thumbnail="https://images.com/thumbnails/256x256/car-sedan-3.png",
),
]
super().__init__("DUMMY", data)
| 4,315 | Python | 45.408602 | 152 | 0.562225 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/tests/__init__.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited
from .test_service import *
| 454 | Python | 44.499996 | 76 | 0.80837 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/artec/services/browser/asset/tests/test_service.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import carb.settings
import omni.kit.test
from omni.services.client import AsyncClient
from omni.services.core import main
from ..models import SearchCriteria, _Filter
from .dummy import DummyAssetStore
from ..store.base import AssetStoreGroupFacility
from ..services.asset import router
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
ASSETS_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("assets")
class TestAssetGroupFacility(omni.kit.test.AsyncTestCaseFailOnLogError):
async def setUp(self):
self._asset_store_group = AssetStoreGroupFacility()
router.register_facility("asset_store", self._asset_store_group)
api_version = carb.settings.get_settings_interface().get("exts/artec.services.browser.asset/api_version")
self._client = AsyncClient(f"local:///{api_version}", app=main.get_app())
async def tearDown(self):
await self._client.stop_async()
self._client = None
async def test_search_multiple_stores(self):
self._asset_store_group.clear_stores()
self._asset_store_group.register_store("DUMMY", DummyAssetStore())
res = await self._client.assets.search.post(filter={"categories": ["/Vegetation/Plant_Tropical"]})
self.assertIn("NVIDIA", res)
self.assertIn("DUMMY", res)
self.assertEqual(len(res["NVIDIA"][0]), 17)
self.assertEqual(len(res["DUMMY"][0]), 0)
async def test_search_specific_store(self):
self._asset_store_group.clear_stores()
self._asset_store_group.register_store("DUMMY", DummyAssetStore())
res = await self._client.assets.search.post(
filter={"categories": ["/Vegetation/Plant_Tropical"]}, vendors=["NVIDIA"]
)
self.assertIn("NVIDIA", res)
self.assertNotIn("DUMMY", res)
self.assertEqual(len(res["NVIDIA"][0]), 17)
async def test_page_items(self):
self._asset_store_group.clear_stores()
res = await self._client.assets.search.post(
filter={"categories": ["/Vegetation/Plant_Tropical"]}, page={"size": 10}
)
self.assertEqual(len(res["NVIDIA"][0]), 10)
async def test_page_items_second_page_larger_size(self):
self._asset_store_group.clear_stores()
res = await self._client.assets.search.post(
filter={"categories": ["/Vegetation/Plant_Tropical"]}, page={"size": 10, "number": 2}
)
self.assertEqual(len(res["NVIDIA"][0]), 7)
async def test_item_order_by_price_ascending(self):
self._asset_store_group.clear_stores()
self._asset_store_group.register_store("DUMMY", DummyAssetStore())
res = await self._client.assets.search.post(keywords=["cars"], sort=["price", "asc"])
retrieved_prices = []
for item in res["DUMMY"][0]:
retrieved_prices.append(item["price"])
self.assertEqual(retrieved_prices, [10.99, 12.99, 13.99, 14.99, 15.99])
async def test_item_order_by_price_descending(self):
self._asset_store_group.clear_stores()
self._asset_store_group.register_store("DUMMY", DummyAssetStore())
res = await self._client.assets.search.post(keywords=["cars"], sort=["price", "desc"])
retrieved_prices = []
for item in res["DUMMY"][0]:
retrieved_prices.append(item["price"])
self.assertEqual(retrieved_prices, list(reversed([10.99, 12.99, 13.99, 14.99, 15.99])))
class TestDummyAssetStore(omni.kit.test.AsyncTestCaseFailOnLogError):
async def test_search_no_criteria(self):
store = DummyAssetStore()
(result, *_) = await store.search(search_criteria=SearchCriteria(), search_timeout=60)
self.assertEqual(len(result), 5)
async def test_search_category(self):
store = DummyAssetStore()
search = SearchCriteria(filter=_Filter(categories=["/vehicles/cars/sedan"]))
(result, *_) = await store.search(search_criteria=search, search_timeout=60)
self.assertEqual(len(result), 3)
async def test_search_order_by_name(self):
store = DummyAssetStore()
search = SearchCriteria(keywords=["sedan"], sort=["name", "desc"])
(result, *_) = await store.search(search_criteria=search, search_timeout=60)
retrieved_names = []
for item in result:
retrieved_names.append(item.name)
self.assertEqual(retrieved_names, ["car-sedan-3", "car-sedan-2", "car-sedan-1"])
| 4,909 | Python | 37.661417 | 113 | 0.667142 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2023-05-15
- Initial version of extension | 150 | Markdown | 20.571426 | 80 | 0.693333 |
ArtecGroup/omni-artec-asset-browser/exts/artec.services.browser.asset/docs/README.md | # Artec asset browser service [artec.services.browsers.asset]
## About
Complimentary extension for Artec Cloud asset browser
Forked from omni.services.browsers.asset
| 168 | Markdown | 23.142854 | 61 | 0.815476 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/PACKAGE-LICENSES/omni.kit.browser.asset_store-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 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/PACKAGE-LICENSES/dependencies/pybind11-LICENSE.md | Copyright (c) 2016 Wenzel Jakob <[email protected]>, All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Please also refer to the file CONTRIBUTING.md, which clarifies licensing of
external contributions to this project including patches, pull requests, etc.
| 1,676 | Markdown | 54.899998 | 79 | 0.809666 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/PACKAGE-LICENSES/dependencies/fmt-LICENSE.md | Copyright (c) 2012 - 2016, Victor Zverovich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| 1,310 | Markdown | 53.624998 | 79 | 0.809924 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.5"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["Artec"]
# The title and description fields are primarly for displaying extension info in UI
title = "Browser of Models on Artec Cloud"
description="omni kit browser artec cloud models extension."
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ['browser', 'asset', 'model', 'artec', 'cloud']
# 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"
category = "services"
readme = "docs/README.md"
preview_image = "data/preview.png"
icon = "data/artec_cloud.png"
[dependencies]
"omni.kit.browser.core" = {version="2.1.5"}
"artec.services.browser.asset" = {version="1.0.5"}
"omni.usd" = {}
"omni.services.client" = {version="0.4.0"}
"omni.kit.window.content_browser" = { optional=true }
"omni.kit.window.filepicker" = {}
# Main python module this extension provides, it will be publicly available as "import artec.asset.browser".
[[python.module]]
name = "artec.asset.browser"
[settings]
exts."artec.asset.browser".provider = "local://"
exts."artec.asset.browser".showCategory = ""
exts."artec.asset.browser".pageSize = 25
exts."artec.asset.browser".hoverWindow = false
exts."artec.asset.browser".singleProvider = true
exts."artec.asset.browser".appSettings = "/persistent/app/artec_asset_browser"
exts."artec.asset.browser".autoScroll = true
exts."artec.asset.browser".enable = true
exts."artec.asset.browser".providerId = "ArtecCloud"
exts."artec.asset.browser".maxCountPerPage = 20
exts."artec.asset.browser".modelsUrl = "https://cloud.artec3d.com/api/omni/1.0/projects"
exts."artec.asset.browser".cloudSearchUrl = "https://cloud.artec3d.com/api/omni/1.0/projects.json"
exts."artec.asset.browser".authorizeUrl = "https://cloud.artec3d.com/api/omni/1.0/sessions"
[[test]]
dependencies = [
"omni.kit.renderer.core",
"omni.kit.renderer.capture",
"artec.services.browser.asset",
"omni.kit.browser.asset_provider.s3"
]
args = [
"--no-window",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
]
stdoutFailPatterns.exclude = [
"*gpu.foundation.plugin'>: Failed to load texture*", # Leak
"*[gpu.foundation.plugin] Failed to load texture*",
"*[gpu.foundation.plugin] Failed to read texture file*",
]
| 2,532 | TOML | 33.229729 | 108 | 0.723539 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/popup_menu.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.
#
# Forked from AssetStore class AbstractPopupMenu, FilterMenu
import abc
from typing import Optional, List
from omni import ui
from .style import POPUP_MENU_STYLE
class AbstractPopupMenu(ui.Window):
"""
Represent a popup window to show popup menu with a title
"""
def __init__(self, title: str):
self._title = title
window_flags = (
ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_POPUP
| ui.WINDOW_FLAGS_NO_TITLE_BAR
| ui.WINDOW_FLAGS_NO_SCROLLBAR
)
super().__init__(title, width=0, height=0, padding_x=0, padding_y=0, flags=window_flags)
self.frame.set_build_fn(self._build_ui)
self.frame.set_style(POPUP_MENU_STYLE)
def destroy(self):
self.visible = False
def _build_ui(self) -> None:
with self.frame:
with ui.VStack(height=0):
with ui.ZStack(height=0):
ui.Rectangle(height=40, style_type_name_override="Title.Background")
with ui.HStack():
ui.Spacer(width=10)
ui.Label(self._title, style_type_name_override="Title.Label")
self._build_menu()
@abc.abstractmethod
def _build_menu(self) -> None:
"""Build menu items"""
pass
class MenuRadioButton(ui.RadioButton):
"""
Represent a menu radio button.
"""
def __init__(self, **kwargs):
super().__init__(
width=120,
height=30,
image_width=24,
image_height=24,
spacing=5,
style_type_name_override="MenuButton",
**kwargs,
)
class SortMenu(AbstractPopupMenu):
"""
Represent the sort by menu.
Args:
on_sort_changed_fn: Callback when sort field or sort order changed. Function signure:
void on_sort_changed_fn(sort_field: str, sort_order: str)
"""
SORT_BY_FIELDS = ["Name", "Date"]
SORT_BY_ORDERS = ["Ascending", "Descending"]
def __init__(self, on_sort_changed_fn: callable):
self._on_sort_changed_fn = on_sort_changed_fn
super().__init__("SORT BY")
self._sort_field = self.SORT_BY_FIELDS[0]
self._sort_order = self.SORT_BY_ORDERS[0]
def _build_menu(self) -> None:
field_collection = ui.RadioCollection()
with ui.VStack(height=0):
for field in self.SORT_BY_FIELDS:
MenuRadioButton(text=field, radio_collection=field_collection)
ui.Line(alignment=ui.Alignment.BOTTOM, style_type_name_override="MenuSeparator")
order_collection = ui.RadioCollection()
with ui.VStack(height=0):
for order in self.SORT_BY_ORDERS:
MenuRadioButton(text=order, radio_collection=order_collection)
field_collection.model.add_value_changed_fn(self._on_sort_field_changed)
order_collection.model.add_value_changed_fn(self._on_sort_order_changed)
def _on_sort_field_changed(self, model: ui.AbstractValueModel) -> None:
self._sort_field = self.SORT_BY_FIELDS[model.as_int]
self.visible = False
if self._on_sort_changed_fn is not None:
self._on_sort_changed_fn(self._sort_field, self._sort_order)
def _on_sort_order_changed(self, model: ui.AbstractValueModel) -> None:
self._sort_order = self.SORT_BY_ORDERS[model.as_int]
self.visible = False
if self._on_sort_changed_fn is not None:
self._on_sort_changed_fn(self._sort_field, self._sort_order)
class FilterMenu(AbstractPopupMenu):
"""
Represent the filter menu.
Args:
providers (List[str]): Provider list.
on_filter_changed_fn: Callback when filter changed. Function signure:
void on_filter_changed_fn(filter: str)
"""
def __init__(self, providers: List[str], on_filter_changed_fn: callable):
self._on_filter_changed_fn = on_filter_changed_fn
self._filter_provider = ""
self._container: Optional[ui.VStack] = None
super().__init__("Filter")
self.refresh(providers)
def refresh(self, providers: List[str]):
self._providers = providers
self._providers.insert(0, "All")
if self._filter_provider not in self._providers:
self._filter_vendor = self._providers[0]
if self._container is not None:
self._container.clear()
self._build_menu_internal()
def _build_menu(self) -> None:
self._container = ui.VStack(height=0)
self._build_menu_internal()
def _build_menu_internal(self) -> None:
vendor_collection = ui.RadioCollection()
with self._container:
for field in self._providers:
MenuRadioButton(text=field, radio_collection=vendor_collection)
vendor_collection.model.add_value_changed_fn(self._on_filter_changed)
def _on_filter_changed(self, model: ui.AbstractValueModel) -> None:
self._filter_provider = self._providers[model.as_int]
self.visible = False
if self._on_filter_changed_fn is not None:
self._on_filter_changed_fn(self._filter_provider)
| 5,614 | Python | 34.314465 | 96 | 0.620948 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/search_notification.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.
#
# Forked from AssetStore class SearchNotification
from typing import Callable
from omni import ui
from .style import EMPTY_NOTIFICATION_STYLE, ICON_PATH
class SearchNotification:
"""
When no results searched, show notification.
"""
def __init__(self, clear_search_fn: Callable[[None], None]):
self._clear_search_fn = clear_search_fn
self._build_ui()
def _build_ui(self):
self._container = ui.ZStack(style=EMPTY_NOTIFICATION_STYLE)
with self._container:
ui.Rectangle(style_type_name_override="EmptyNotification.Frame")
with ui.VStack(spacing=10):
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.ImageWithProvider(
f"{ICON_PATH}/search.png",
width=90,
height=60,
fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT,
style_type_name_override="EmptyNotification.Image",
)
ui.Spacer()
self._message_label = ui.Label(
"not found.",
height=0,
alignment=ui.Alignment.CENTER,
style_type_name_override="EmptyNotification.Label",
)
self._clear_container = ui.HStack(height=24)
with self._clear_container:
ui.Spacer()
ui.Button(
"Click to clear search",
width=192,
mouse_pressed_fn=lambda x, y, btn, a: self._clear_search_fn(),
style_type_name_override="EmptyNotification.Button",
)
ui.Spacer()
ui.Spacer()
@property
def visible(self) -> bool:
return self._container.visible
@visible.setter
def visible(self, value) -> None:
self._container.visible = value
def set_message(self, message: str, show_clear: bool = True) -> None:
self._message_label.text = message
self._clear_container.visible = show_clear
| 2,633 | Python | 36.098591 | 86 | 0.562856 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/style.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.
#
# Forked from AssetStore class Colors
from omni import ui
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.joinpath("icons")
class Colors:
Window = ui.color.shade(0xFF353535)
Selected = ui.color.shade(0xFFDDDDDD)
Text = ui.color.shade(0xFF929292)
Hint = ui.color.shade(0xFF6A6A6A)
Warn = ui.color.shade(0xCC2222FF)
Image = ui.color.shade(0xFFA8A8A8)
Background = ui.color.shade(0xFF23211F, light=0xFF535354)
ARTEC_CLOUD_BROWSER_STYLE = {
"Window": {"background_color": Colors.Window},
"CollectionList": {"background_color": 0, "selected_color": 0, "color": 0, "border_radius": 1},
"TreeView.Frame": {"background_color": 0, "padding": 10},
"TreeView.Item.Image": {"color": Colors.Text},
"TreeView.Item.Image:hovered": {"color": 0xFF131313},
"TreeView.Item.Button": {"background_color": 0, "padding": 0, "margin": 0, "spacing": 0},
"TreeView.Item.Button:hovered": {"background_color": 0xFF3A3A3A},
"TreeView.Item.Button.Image": {"image_url": f"{ICON_PATH}/options.svg", "color": Colors.Text},
"TreeView.Item.Name": {"background_color": 0, "color": Colors.Text},
"TreeView.Item.Name:selected": {"color": 0xFFE39724},
"GridView.Frame": {"background_color": Colors.Background},
"GridView.Item": {"background_color": 0, "color": Colors.Selected, "font_size": 16},
"GridView.Item.Selection": {"background_color": 0, "border_width": 0},
"GridView.Item.Selection:selected": {"border_width": 2, "border_color": 0xFFFFC734, "border_radius": 3.0},
"GridView.Image:selected": {"border_width": 2, "border_color": 0, "border_radius": 3.0},
"SearchBar.Button.Image::sort": {"image_url": f"{ICON_PATH}/sort_by_dark.svg", "color": Colors.Image},
"SearchBar.Button.Image::filter": {"image_url": f"{ICON_PATH}/filter.svg", "color": Colors.Image},
"GridView.Item.Vendor.Background": {"background_color": 0xFF151515},
"GridView.Item.Hover.Background": {"background_color": 0xFF131313},
"GridView.Item.Hover.BackgroundAll:hovered": {"background_color": 0xFF131313},
"GridView.Item.Hover.BackgroundAll": {"background_color": 0},
"GridView.Item.Tips.Background": {"background_color": 0xFF363636},
"GridView.Item.Tips.Text": {"background_color": 0xFFDADADA, "font_size": 14, "margin": 2, "color": 0xFFCCCCCC},
"GridView.Item.Tips.Text::Download": {"color": 0xFF00B976},
"GridView.Item.Tips.Text::ExternalLink": {"color": 0xFFF6A66B},
"GridView.Item.Tips.Text::Normal": {"color": 0xFFCCCCCC},
"GridView.Item.Price": {"color": Colors.Selected, "font_size": 12},
"GridView.Item.User": {"color": 0xFF328C6C, "font_size": 12},
"GridView.Item.Frame": {"color": 0xFFFF0000},
"GridView.Item.Download": {
"background_color": 0xFF2A2825,
"color": 0xFFE39724,
"secondary_color": 0,
"border_radius": 0,
"font_size": 10,
"padding": 0,
},
}
POPUP_MENU_STYLE = {
# "Window": {"background_color": 0xFFFF0000, "padding": 0, "margin": 0},
"Title.Background": {"background_color": Colors.Window},
"Title.Label": {"color": Colors.Selected, "font_size": 18},
"MenuButton": {"background_color": 0xFF4A4A4A, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "spacing": 20},
"MenuButton.Image": {"image_url": f"{ICON_PATH}/none.svg"},
"MenuButton.Image:checked": {"image_url": f"{ICON_PATH}/toggleCheck_dark.svg"},
"MenuButton.Label": {"color": 0xFFD4D4D4, "alignment": ui.Alignment.LEFT_CENTER},
"MenuSeparator": {"color": Colors.Window, "border_width": 4},
}
EMPTY_NOTIFICATION_STYLE = {
"EmptyNotification.Frame": {"background_color": Colors.Window},
"EmptyNotification.Label": {"background_color": Colors.Window, "color": 0xFF7C7C7C, "font_size": 20},
"EmptyNotification.Image": {"background_color": Colors.Window, "color": 0xFF7C7C7C},
"EmptyNotification.Button": {"background_color": 0xFF6C6C6C, "color": 0xFF9E9E9E},
}
HOVER_WINDOW_STYLE = {
**ARTEC_CLOUD_BROWSER_STYLE,
"Window": {"background_color": Colors.Window, "border_width": 0, "padding": 0},
}
AUTH_DIALOG_STYLE = {
"Window": {"background_color": Colors.Window, "border_radius": 2, "border_width": 0.5, "border_color": 0x55ADAC9F},
"Dialog": {"background_color": 0x0, "color": Colors.Text, "margin": 10},
"Message": {"background_color": 0x0, "color": Colors.Text, "margin": 0, "alignment": ui.Alignment.LEFT_CENTER},
"Label": {"background_color": 0x0, "color": Colors.Text, "margin": 0, "alignment": ui.Alignment.LEFT_CENTER},
"Field": {
"background_color": Colors.Background,
"color": Colors.Text,
"alignment": ui.Alignment.LEFT_CENTER,
"margin_height": 0,
},
"Field::overlay": {"background_color": 0x0, "border_color": Colors.Warn, "border_width": 1},
"Field::warn": {
"background_color": 0x0,
"margin_width": 8,
"color": Colors.Warn,
"alignment": ui.Alignment.RIGHT_CENTER,
},
"CheckBox": {
"background_color": Colors.Background,
"color": Colors.Text,
"margin": 4,
"alignment": ui.Alignment.LEFT_CENTER,
},
"Button": {
"background_color": Colors.Background,
"color": Colors.Text,
"margin": 4,
"alignment": ui.Alignment.CENTER,
},
}
| 5,783 | Python | 45.645161 | 119 | 0.658655 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/overview_delegate.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.
#
# Forked from AssetStore class OverviewDelegate
from typing import Optional
import carb.settings
from omni.kit.browser.core import DetailDelegate, CategoryItem
class OverviewDelegate(DetailDelegate):
def get_label(self, item: CategoryItem) -> Optional[str]:
return item.name.upper()
def on_double_click(self, item: CategoryItem) -> None:
# Show selected category
settings = carb.settings.get_settings()
settings.set("/exts/artec.asset.browser/showCategory", item.url)
| 940 | Python | 38.208332 | 76 | 0.767021 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/artec_cloud.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.
#
# Forked from SketchFabAssetProvider for asset store
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Callable, Optional, Tuple, Dict, List
import tempfile
from time import time
import zipfile
import aiohttp
import aiofiles
import carb
import carb.settings
import omni.client
import omni.kit.asset_converter as converter
from urllib.parse import urlparse, urlencode
from artec.services.browser.asset import BaseAssetStore, AssetModel, SearchCriteria, ProviderModel
from .models.asset_fusion import AssetFusion
SETTING_ROOT = "/exts/artec.asset.browser/"
SETTING_STORE_ENABLE = SETTING_ROOT + "enable"
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data")
class ConversionTaskStatus(Enum):
ENQUEUED = 1
IN_PROGRESS = 2
PROCESSED = 3
FAILED = -1
@dataclass
class ConversionResult:
status: ConversionTaskStatus
download_url: str
class ArtecCloudAssetProvider(BaseAssetStore):
def __init__(self) -> None:
settings = carb.settings.get_settings()
self._provider_id = settings.get_as_string(SETTING_ROOT + "providerId")
super().__init__(store_id=self._provider_id)
self._max_count_per_page = settings.get_as_int(SETTING_ROOT + "maxCountPerPage")
self._search_url = settings.get_as_string(SETTING_ROOT + "cloudSearchUrl")
self._auth_token = None
self._authorize_url = settings.get_as_string(SETTING_ROOT + "authorizeUrl")
self._auth_params: Dict = {}
def provider(self) -> ProviderModel:
return ProviderModel(
name=self._store_id, icon=f"{DATA_PATH}/artec_cloud.png", enable_setting=SETTING_STORE_ENABLE
)
def authorized(self) -> bool:
return self._auth_token is not None
async def authenticate(self, username: str, password: str):
params = {"user[email]": username, "user[password]": password}
async with aiohttp.ClientSession() as session:
async with session.post(self._authorize_url, params=params) as response:
self._auth_params = await response.json()
self._auth_token = self._auth_params.get("auth_token")
async def _search(self, search_criteria: SearchCriteria) -> Tuple[List[AssetModel], bool]:
assets: List[AssetModel] = []
params = {
"auth_token": self._auth_token,
"sort_field": "",
"sort_direction": "",
"term": "",
"slug": "",
"per_page": self._max_count_per_page,
"page": 0,
}
if search_criteria.sort:
params["sort_field"], params["sort_direction"] = search_criteria.sort
if search_criteria.keywords:
params["term"] = " ".join(search_criteria.keywords)
if search_criteria.filter.categories:
category = search_criteria.filter.categories[-1]
if category:
params["slug"] = category
to_continue = True
while to_continue:
params["page"] += 1
(page_assets, to_continue) = await self._search_one_page(params)
if page_assets:
assets.extend(page_assets)
if not to_continue:
break
else:
break
return (assets, to_continue)
async def _search_one_page(self, params: Dict) -> Tuple[List[AssetModel], bool]:
if not self.authorized():
return ([], False)
items = []
meta = {}
async with aiohttp.ClientSession() as session:
async with session.get(self._search_url, params=params) as response:
results = await response.json()
items = results.get("projects", [])
meta = results.get("meta")
assets: List[AssetModel] = []
for item in items:
item_categories = item.get("categories", [])
item_thumbnail = self.url_with_token(item.get("preview_presigned_url"))
assets.append(
AssetModel(
identifier=item.get("id"),
name=item.get("name"),
version="",
published_at=item.get("created_at"),
categories=item_categories,
tags=[],
vendor=self._provider_id,
download_url=item.get("download_url", ""),
product_url=item.get("viewer_url", ""),
thumbnail=item_thumbnail,
user=item.get("user"),
fusions=item.get("fusions", ""),
)
)
to_continue = meta["total_count"] > meta["current_page"] * meta["per_page"]
return (assets, to_continue)
def url_with_token(self, url: str) -> str:
params = {"auth_token": self._auth_token}
url += ('&' if urlparse(url).query else '?') + urlencode(params)
return url
def destroy(self):
self._auth_params = {}
async def download(self, fusion: AssetFusion, dest_path: str,
on_progress_fn: Optional[Callable[[float], None]] = None, timeout: int = 600,
on_prepared_fn: Optional[Callable[[float], None]] = None) -> Dict:
with tempfile.TemporaryDirectory() as tmp_dir:
zip_file_path = Path(tmp_dir) / f"{fusion.name}.zip"
snapshot_group_id, eta = await self._request_model(fusion)
conversion_start_time = time()
while True:
if on_progress_fn:
on_progress_fn(min((time() - conversion_start_time) / eta, 1))
conversion_result = await self._check_status(fusion, snapshot_group_id)
if conversion_result.status is ConversionTaskStatus.PROCESSED:
if on_prepared_fn:
on_prepared_fn()
async with aiohttp.ClientSession() as session:
content = bytearray()
downloaded = 0
async with session.get(conversion_result.download_url) as response:
size = int(response.headers.get("content-length", 0))
if size > 0:
async for chunk in response.content.iter_chunked(1024 * 512):
content.extend(chunk)
downloaded += len(chunk)
if on_progress_fn:
on_progress_fn(float(downloaded) / size)
else:
if on_progress_fn:
on_progress_fn(0)
content = await response.read()
if on_progress_fn:
on_progress_fn(1)
async with aiofiles.open(zip_file_path, "wb") as file:
await file.write(content)
break
elif conversion_result.status is ConversionTaskStatus.FAILED:
return {"url": None, "status": omni.client.Result.ERROR}
# unzip
output_path = zip_file_path.parent / fusion.name
await self._extract_zip(zip_file_path, output_path)
# convert model
try:
obj_path = next(output_path.glob("**/*.obj"))
except StopIteration:
return {"url": None, "status": omni.client.Result.ERROR}
converted_project_path = zip_file_path.parent / f"{obj_path.parent.name}-converted"
usd_path = converted_project_path / f"{obj_path.stem}.usd"
await omni.client.create_folder_async(str(converted_project_path))
if not await self.convert(obj_path, usd_path):
return {"url": None, "status": omni.client.Result.ERROR}
# prepare usdz
usdz_path = Path(dest_path) / f"{usd_path.name}z"
with zipfile.ZipFile(usdz_path, "w") as archive:
# usd file should be first in the USDZ package
archive.write(usd_path, arcname=usd_path.name)
for file_path in usd_path.parent.glob("**/*"):
if file_path != usd_path:
archive.write(file_path, arcname=file_path.relative_to(usd_path.parent))
await self._download_thumbnail(usdz_path, fusion.thumbnail_url)
return {"url": str(usdz_path), "status": omni.client.Result.OK}
async def _download_thumbnail(self, usd_path: Path, thumbnail_url: str):
thumbnail_out_dir_path = usd_path.parent / ".thumbs" / "256x256"
await omni.client.create_folder_async(str(thumbnail_out_dir_path))
thumbnail_out_path = thumbnail_out_dir_path / f"{Path(usd_path).name}.png"
async with aiohttp.ClientSession() as session:
async with session.get(self.url_with_token(thumbnail_url)) as response:
async with aiofiles.open(thumbnail_out_path, "wb") as file:
await file.write(await response.read())
@staticmethod
async def convert(input_asset_path: Path, output_asset_path: Path) -> bool:
task_manager = converter.get_instance()
task = task_manager.create_converter_task(str(input_asset_path), str(output_asset_path), None)
success = await task.wait_until_finished()
if not success:
carb.log_error(f"Conversion failed. Reason: {task.get_error_message()}")
return False
return True
@staticmethod
async def _extract_zip(input_path, output_path):
await omni.client.create_folder_async(str(output_path))
with zipfile.ZipFile(input_path, "r") as zip_ref:
zip_ref.extractall(output_path)
async def _check_status(self, fusion: AssetFusion, snapshot_group_id):
params = {
"auth_token": self._auth_token,
"snapshot_group_id": snapshot_group_id
}
url = f"{'/'.join(fusion.url.split('/')[:-1])}/conversion_status"
async with aiohttp.ClientSession() as session:
async with session.get(url=url, params=params) as response:
decoded_response = await response.json()
if response.status != 200:
return ConversionResult(ConversionTaskStatus.FAILED, "")
status = ConversionTaskStatus(int(decoded_response["project"]["conversion_status"]))
return ConversionResult(status, decoded_response["project"]["download_url"])
async def _request_model(self, fusion: AssetFusion):
async with aiohttp.ClientSession() as session:
async with session.get(url=self.url_with_token(fusion.url)) as response:
results = await response.json()
return results["project"]["snapshot_group_id"], results["project"]["eta"]
| 11,433 | Python | 41.191882 | 105 | 0.579201 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# Forked from AssetStore class AssetStoreExtension
import omni.ext
import omni.kit.ui
from .window import ArtecCloudWindow, ARTEC_CLOUD_WINDOW_NAME
from .artec_cloud import ArtecCloudAssetProvider
from artec.services.browser.asset import get_instance as get_asset_services
from artec.services.browser.asset.store.local.local import LocalFolderAssetProvider
ARTEC_CLOUD_BROWSER_MENU_PATH = "Window/Browsers/" + ARTEC_CLOUD_WINDOW_NAME
_extension_instance = None
class ArtecAssetBrowserExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._window = None
self._menu = omni.kit.ui.get_editor_menu().add_item(
ARTEC_CLOUD_BROWSER_MENU_PATH, self._on_click, toggle=True, value=True
)
self._window = ArtecCloudWindow()
self._window.set_visibility_changed_fn(self._on_visibility_changed)
global _extension_instance
_extension_instance = self
self._asset_provider = ArtecCloudAssetProvider()
self._asset_provider_local = LocalFolderAssetProvider()
self._asset_service = get_asset_services()
self._asset_service.register_store(self._asset_provider)
self._asset_service.register_store(self._asset_provider_local)
_extension_instance
def on_shutdown(self):
self._asset_service.unregister_store(self._asset_provider)
self._asset_service.unregister_store(self._asset_provider_local)
self._asset_provider = None
self._asset_provider_local = None
self._asset_service = None
if self._window is not None:
self._window.destroy()
self._window = None
global _extension_instance
_extension_instance = None
def _on_click(self, *args):
self._window.visible = not self._window.visible
def _on_visibility_changed(self, visible):
omni.kit.ui.get_editor_menu().set_value(ARTEC_CLOUD_BROWSER_MENU_PATH, visible)
| 2,369 | Python | 36.619047 | 87 | 0.712537 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/__init__.py | from .extension import * | 24 | Python | 23.999976 | 24 | 0.791667 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/hover_window.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.
#
# Forked from AssetStore class HoverWindow
from typing import Optional
from omni import ui
from .models import AssetDetailItem
from .style import HOVER_WINDOW_STYLE
class HoverWindow(ui.Window):
"""
Window to show hover for asset item.
"""
def __init__(self):
flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_TITLE_BAR
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_CLOSE
| ui.WINDOW_FLAGS_NO_DOCKING
)
super().__init__(
"ASSET HOVER WINDOW",
width=250,
height=200,
flags=flags,
padding_x=0,
padding_y=0,
dockPreference=ui.DockPreference.DISABLED,
)
self.frame.set_style(HOVER_WINDOW_STYLE)
self.frame.set_build_fn(self._build_ui)
self.visible = False
self._item: Optional[AssetDetailItem] = None
self._image: Optional[ui.Image] = None
def _build_ui(self) -> None:
with self.frame:
self._container = ui.VStack()
with self._container:
self._image = ui.Image(
self._item.thumbnail,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
style_type_name_override="GridView.Image",
)
self._build_tips(self._item)
self._container.set_mouse_hovered_fn(self._on_hover)
def show(self, item: AssetDetailItem, image_size: float, tips_height, x: float, y: float):
self._item = item
if self._image:
self._image.source_url = item.thumbnail
self._tips.text = item.tips
self._tips.name = item.asset_type
self.width = image_size
self.height = image_size + tips_height
self.position_x = x
self.position_y = y
self.visible = True
def _on_hover(self, hovered):
self.visible = hovered
def _build_tips(self, item: AssetDetailItem) -> None:
# Hover background and text
with ui.ZStack(height=self.height - self.width):
ui.Rectangle(style_type_name_override="GridView.Item.Hover.Background")
self._tips = ui.Label(
item.tips,
name=item.asset_type,
alignment=ui.Alignment.CENTER,
style_type_name_override="GridView.Item.Tips.Text",
)
| 2,915 | Python | 31.764045 | 94 | 0.594168 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/category_delegate.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.
#
# Forked from AssetStore MainNavigationDelegate
from omni import ui
from omni.kit.browser.core import CategoryDelegate, CategoryItem
from .models import MainNavigationItem, AssetStoreModel
class MainNavigationDelegate(CategoryDelegate):
def __init__(self, model: AssetStoreModel, **kwargs):
self._model = model
super().__init__(kwargs)
def get_label(self, item: CategoryItem) -> str:
return item.name.upper()
def build_widget(
self,
model: ui.AbstractItemModel,
item: MainNavigationItem,
index: int = 0,
level: int = 0,
expanded: bool = False,
):
"""
Create a widget per catetory item
Args:
model (AbstractItemModel): Category data model
item (CategoryItem): Category item
index (int): ignore
level (int): ignore
expand (int): ignore
"""
with ui.HStack():
if self._tree_mode:
ui.Label(" " * level, width=0)
ui.Label(
self.get_label(item),
width=0,
alignment=ui.Alignment.LEFT_CENTER,
style_type_name_override="TreeView.Item.Name",
)
ui.Spacer()
if item.configurable:
ui.Button(
"",
width=16,
height=16,
clicked_fn=lambda model=model, item=item: self._on_config(model, item),
style_type_name_override="TreeView.Item.Button",
)
def build_branch(
self,
model: ui.AbstractItemModel,
item: CategoryItem,
column_id: int = 0,
level: int = 0,
expanded: bool = False,
):
"""
Create a branch widget that opens or closes subtree
Args:
model (AbstractItemModel): Category data model
item (CategoryItem): Category item
column_id (int): ignore
level (int): ignore
expand (int): ignore
"""
if not self._tree_mode or len(item.children) == 0:
# In tree mode, if have children, show as branch
return
with ui.HStack(height=20, spacing=5):
ui.Label(" " * level, width=0)
if expanded:
ui.Label("- ", width=5)
else:
ui.Label("+ ", width=5)
def _on_config(self, model: AssetStoreModel, item: MainNavigationItem) -> None:
# Here item name is provider id
self._model.config_provider(item.name)
| 3,043 | Python | 32.450549 | 91 | 0.568189 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/options_menu.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.
#
# Forked from AssetStore class AssetOptionsMenu
from omni.kit.browser.core import OptionMenuDescription, OptionsMenu
from .models import AssetStoreModel
class AssetOptionsMenu(OptionsMenu):
"""
Represent options menu used in asset store.
"""
def __init__(self, model: AssetStoreModel):
super().__init__()
self._model = model
self._my_assets_window = None
self._menu_descs = []
def destroy(self) -> None:
if self._my_assets_window is not None:
self._my_assets_window.destroy()
self._my_assets_window = None
super().destroy()
def show(self) -> None:
if self._options_menu is None:
for provider, setting in self._model.providers.items():
if setting["configurable"]:
self._menu_descs.append(
OptionMenuDescription(
f"{provider} Setting", clicked_fn=lambda p=provider: self._model.config_provider(p)
)
)
super().show()
| 1,506 | Python | 33.249999 | 111 | 0.634794 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/download_helper.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.
#
# Forked from AssetStore class DownloadHelper
from typing import Dict, Optional
import os
import carb
import carb.tokens
import json
import omni.client
from artec.services.browser.asset import AssetModel
DOWNLOAD_RESULT_FILE = "asset_store_downloads.json"
def Singleton(class_):
"""A singleton decorator"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@Singleton
class DownloadHelper:
"""
Helper to download assets.
"""
def __init__(self):
self._download_root = os.path.abspath(carb.tokens.get_tokens_interface().resolve("${shared_documents}"))
self._download_result_file = self._download_root + "/" + DOWNLOAD_RESULT_FILE
self._download_stats: Dict[str, Dict[str, Dict]] = {}
self._load_download_assets()
def destroy(self):
pass
def get_download_url(self, asset: AssetModel) -> Optional[str]:
"""
Query asset local downloaded url.
Args:
asset (AssetModel): Asset model to query
Return:
Local url if found. Else None.
"""
if asset["vendor"] not in self._download_stats:
return None
if asset["identifier"] in self._download_stats[asset["vendor"]]:
url = self._download_stats[asset["vendor"]][asset["identifier"]]
(result, entry) = omni.client.stat(url)
if result == omni.client.Result.OK:
return url
else:
# File not found, clean download stats
del self._download_stats[asset["vendor"]][asset["identifier"]]
self._save_download_assets()
return None
def save_download_asset(self, asset: AssetModel, url: str) -> None:
"""
Save asset local downloaded url
Args:
asset (AssetModel): Asset model to save.
url (str): Local url of downloaded asset model.
"""
if asset["vendor"] not in self._download_stats:
self._download_stats[asset["vendor"]] = {}
self._download_stats[asset["vendor"]][asset["identifier"]] = url
self._save_download_assets()
def _save_download_assets(self):
json_file = None
try:
with open(self._download_result_file, "w") as json_file:
json.dump(self._download_stats, json_file, indent=4)
json_file.close()
except FileNotFoundError:
carb.log_warn(f"Failed to open {self._download_result_file}!")
except PermissionError:
carb.log_warn(f"Cannot write to {self._download_result_file}: permission denied!")
except Exception:
carb.log_warn(f"Unknown failure to write to {self._download_result_file}")
finally:
if json_file:
json_file.close()
def _load_download_assets(self):
result, entry = omni.client.stat(self._download_result_file)
if result != omni.client.Result.OK:
self._download_stats = {}
return
try:
with open(self._download_result_file, "r") as json_file:
self._download_stats = json.load(json_file)
except FileNotFoundError:
carb.log_error(f"Failed to open {self._download_result_file}!")
except PermissionError:
carb.log_error(f"Cannot read {self._download_result_file}: permission denied!")
except Exception as exc:
carb.log_error(f"Unknown failure to read {self._download_result_file}: {exc}")
| 4,117 | Python | 34.808695 | 112 | 0.615497 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/browser_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# Forked from AssetStore BrowserWidget
import asyncio
from typing import Optional, List, Callable
import carb.settings
import carb.dictionary
import omni.kit.app
from omni.kit.browser.core import BrowserSearchBar, BrowserWidget, CategoryItem
from omni import ui
from .search_notification import SearchNotification
from .popup_menu import SortMenu, FilterMenu
from .models import AssetDetailItem
from .style import ICON_PATH
from .auth_dialog import AuthDialog
from functools import partial
DEFAULT_THUMBNAIL_PADDING = 5
SETTING_ROOT = "/exts/artec.asset.browser/"
SETTING_AUTO_SCROLL = SETTING_ROOT + "autoScroll"
class ArtecCloudBrowserWidget(BrowserWidget):
def __init__(self, *args, **kwargs):
self._auth_dialog = None
super().__init__(*args, **kwargs)
self._sort_menu = None
self._filter_menu = None
self._filter_vendor = None
self._update_setting = omni.kit.app.SettingChangeSubscription(
"/exts/artec.asset.browser/showCategory", self._on_show_category_changed
)
self._load_future = None
self._more_details = True
self._thumbnail_sub_id = None
self._detail_kwargs["delegate"].set_request_more_fn(self._request_more_assets)
# Get categories from model
self._load_categories()
self._browser_model.on_refresh_provider_fn = self._on_refresh_provider
self._browser_model.on_enable_provider_fn = self._on_enable_provider
def destroy(self):
if self._load_future is not None:
if not self._load_future.done():
self._load_future.cancel()
self._update_setting = None
if self._sort_menu is not None:
self._sort_menu.destroy()
if self._thumbnail_sub_id:
self.remove_thumbnail_size_changed_fn(self._thumbnail_sub_id)
super().destroy()
def authorized(self) -> bool: # WIP working
provider = self._browser_model.artec_cloud_provider()
return provider.authorized()
def _build_results(self): # FIXME use other method
self.filter_details(None)
def trigger_authenticate(self):
if not self.authorized():
def on_authenticate(self, dialog: AuthDialog):
def check_authorized(self, dialog: AuthDialog):
if self.authorized():
self._build_results()
dialog.hide()
else:
dialog.warn_password()
asyncio.ensure_future(
self._browser_model.authenticate_async(
self._browser_model.artec_cloud_provider_id,
dialog.username,
dialog.password,
lambda: check_authorized(self, dialog)
)
)
pass
def on_cancel(dialog: AuthDialog):
dialog.hide()
if not self._auth_dialog:
self._auth_dialog = AuthDialog()
self._auth_dialog.show(
self._browser_model.artec_cloud_provider_id,
click_okay_handler=partial(on_authenticate, self),
click_cancel_handler=partial(on_cancel),
)
def _build_right_panel(self):
self.trigger_authenticate()
with ui.ZStack():
self._build_detail_panel()
if self._zoom_bar:
self._zoom_bar.set_on_hovered_fn(self._on_zoombar_hovered)
auto_scroll = carb.settings.get_settings().get(SETTING_AUTO_SCROLL)
if auto_scroll:
self._detail_scrolling_frame.set_scroll_y_changed_fn(self._on_detail_scroll_y_changed)
def _build_detail_panel(self):
# Add search bar
with ui.VStack(spacing=5):
with ui.HStack(spacing=4, height=26):
self._search_bar = BrowserSearchBar(options_menu=None, subscribe_edit_changed=False)
with ui.VStack(width=26):
ui.Spacer()
self._sort_button = ui.Button(
image_width=20,
image_height=20,
width=26,
height=26,
name="sort",
clicked_fn=self._trigger_sort_menu,
style_type_name_override="SearchBar.Button",
)
ui.Spacer()
with ui.ZStack():
super()._build_right_panel()
def __clear_search():
self._search_bar.clear_search()
self._search_notification = SearchNotification(__clear_search)
self._search_bar.bind_browser_widget(self)
self._thumbnail_sub_id = self.add_thumbnail_size_changed_fn(self._on_thumbnail_size_changed)
self._search_notification.visible = False
def _build_detail_view_internal(self):
self._thumbnail_padding = self._get_thumbnail_padding(self._detail_kwargs["thumbnail_size"])
self._detail_kwargs["thumbnail_padding_width"] = self._thumbnail_padding
self._detail_kwargs["thumbnail_padding_height"] = self._thumbnail_padding
super()._build_detail_view_internal()
self._detail_view.set_extra_filter_fn(self._on_extra_filter)
def _on_category_selected(self, category_item: Optional[CategoryItem]) -> None:
if category_item is None:
# Alway show "ALL" if nothing selected
self.category_selection = [self._browser_model._category_items[0]]
return
if category_item is not None:
super()._on_category_selected(category_item)
self._load_assets(category_item, lambda: self._detail_view.model._item_changed(None))
else:
super()._on_category_selected(category_item)
def show_widgets(
self,
collection: Optional[bool] = None,
category: Optional[bool] = None,
detail: Optional[bool] = None,
expand_root: Optional[bool] = None,
) -> None:
# Show collection control but disable it and make it transparent
super().show_widgets(collection=collection, category=category, detail=detail)
self._collection_combobox.enabled = False
# if expand_root:
# self._category_view.set_expanded(self._category_model.get_item_children()[0], True, False)
def filter_details(self, filter_words: Optional[List[str]]):
self._begin_search()
self._browser_model.search_words = filter_words
# Clean cache detail items in browser model
if self.category_selection:
for category_item in self.category_selection:
self._browser_model._item_changed(category_item)
def __show_filter_results():
self._detail_view.model._item_changed(None)
self._end_search()
if self.category_selection:
self._load_assets(self.category_selection[0], __show_filter_results)
else:
# Force to refresh detail view for new filter words
self._detail_view.model._item_changed(None)
def _trigger_sort_menu(self) -> None:
if self._sort_menu is None:
self._sort_menu = SortMenu(self._on_sort_changed)
else:
self._sort_menu.visible = True
self._sort_menu.position_x = self._sort_button.screen_position_x
self._sort_menu.position_y = self._sort_button.screen_position_y + self._sort_button.computed_height
def _on_sort_changed(self, sort_field: str, sort_order: str) -> None:
self._browser_model.change_sort_args(sort_field, sort_order)
if self.category_selection:
self._load_assets(self.category_selection[0], lambda: self._detail_view.model._item_changed(None))
def _on_filter_changed(self, filter_vendor: str) -> None:
self._browser_model.search_provider = None if filter_vendor == "All" else filter_vendor
if self.category_selection:
self._load_assets(self.category_selection[0], lambda: self._detail_view.model._item_changed(None))
def _on_show_category_changed(self, item: carb.dictionary.Item, event_type) -> None:
# Show and expand category
if event_type == carb.settings.ChangeEventType.CHANGED:
url = str(item)
if url:
full_chain = []
category_item = self._find_category_item(url, None, full_chain)
if category_item:
self.category_selection = [category_item]
# Expand to show selected category
for item in full_chain:
self._category_view.set_expanded(item, True, False)
def _on_refresh_provider(self, provider: str, item: carb.dictionary.Item, event_type) -> None:
# Refresh category
if event_type != carb.settings.ChangeEventType.CHANGED:
return
async def __refresh_categories_async():
await omni.kit.app.get_app().next_update_async()
await self._browser_model.list_categories_async()
# Refresh categories list
self._browser_model._item_changed(self.collection_selection)
self._category_view.model._item_changed(None)
# Default select "ALL"
self.category_selection = [self._browser_model._category_items[0]]
asyncio.ensure_future(__refresh_categories_async())
def _on_enable_provider(self, provider: str, item: carb.dictionary.Item, event_type) -> None:
if event_type != carb.settings.ChangeEventType.CHANGED:
return
async def __refresh_providers_async():
await self._browser_model.list_providers_async()
await self._browser_model.list_categories_async()
# Refresh provider filter menu
if self._filter_menu:
self._filter_menu.refresh(list(self._browser_model.providers.keys()))
# Refresh categories list
self._browser_model._item_changed(self.collection_selection)
await omni.kit.app.get_app().next_update_async()
self._category_view.model._item_changed(None)
self._on_category_selected(None)
asyncio.ensure_future(__refresh_providers_async())
def _find_category_item(
self, url: str, category_item: Optional[CategoryItem] = None, full_chain: Optional[List[CategoryItem]] = None
) -> Optional[CategoryItem]:
if category_item is None:
# Find in root
for child in self._category_model.get_item_children():
found_item = self._find_category_item(url, child, full_chain)
if found_item:
return found_item
else:
return None
else:
if category_item.url == url:
return category_item
else:
if full_chain is not None:
full_chain.append(category_item)
for child in category_item.children:
# Find in children
found_item = self._find_category_item(url, child, full_chain)
if found_item is not None:
return found_item
else:
if full_chain is not None:
full_chain.pop()
return None
def _on_extra_filter(self, item: AssetDetailItem) -> bool:
if self._filter_vendor is None:
return True
else:
if isinstance(item, AssetDetailItem):
return item.asset_model["vendor"] == self._filter_vendor
else:
return True
def _load_assets(
self, category_item: CategoryItem, callback: Callable[[None], None] = None, reset: bool = True
) -> None:
if reset:
self._begin_search()
self._browser_model.reset_assets()
self._detail_view.model._item_changed(None)
else:
self._detail_kwargs["delegate"].more_item_image.source_url = f"{ICON_PATH}/search.png"
self._detail_kwargs["delegate"].more_item_label.text = "Searching..."
self._detail_kwargs["delegate"].more_item_center_tips.text = "Searching..."
self._detail_kwargs["delegate"].more_item_right_tips.text = ""
if self._load_future is not None:
if not self._load_future.done():
self._load_future.cancel()
if reset:
self._more_details = True
def __assets_loaded():
self._detail_view.model._item_changed(None)
self._end_search()
self._load_future = asyncio.ensure_future(self._load_asset_async(category_item, __assets_loaded, reset=reset))
async def _load_asset_async(
self, category_item: CategoryItem, callback: Callable[[None], None] = None, reset: bool = True
):
self._more_details = await self._browser_model.list_assets_async(category_item, callback, reset=reset)
self._end_search()
def _on_thumbnail_size_changed(self, thumbnail_size: int) -> None:
self._detail_kwargs["delegate"].on_thumbnail_size_changed(thumbnail_size)
thumbnail_padding = self._get_thumbnail_padding(thumbnail_size)
if thumbnail_padding != self._thumbnail_padding:
self._thumbnail_padding = thumbnail_padding
self._detail_view.thumbnail_padding_height = thumbnail_padding
self._detail_view.thumbnail_padding_width = thumbnail_padding
def _load_categories(self):
async def __load_categories_async():
await self._browser_model.list_categories_async()
# Show categories list
self.collection_index = 0
self.category_selection = [self._browser_model._category_items[0]]
asyncio.ensure_future(__load_categories_async())
def _request_more_assets(self):
# Require more assets
if self.category_selection:
self._load_assets(
self.category_selection[0], lambda: self._detail_view.model._item_changed(None), reset=False
)
def _on_zoombar_hovered(self, hovered: bool) -> None:
# When zoombar hovered, disable hover window.
# Otherwise zoombar will lost focus and cannot change thumbnail size anymore.
self._detail_kwargs["delegate"].enable_hovered(not hovered)
def _get_thumbnail_padding(self, thumbnail_size):
if thumbnail_size > 384:
return 3 * DEFAULT_THUMBNAIL_PADDING
elif thumbnail_size > 192:
return 2 * DEFAULT_THUMBNAIL_PADDING
else:
return DEFAULT_THUMBNAIL_PADDING
def _begin_search(self) -> None:
self._search_notification.set_message("Searching...", show_clear=False)
self._search_notification.visible = True
def _end_search(self) -> None:
if len(self._browser_model._assets) == 0:
if self._browser_model.search_words is not None:
message = " ".join(self._browser_model.search_words)
message = f'"{message}" not found'
self._search_notification.set_message(message)
self._search_notification.visible = True
else:
if self._browser_model.search_provider:
message = f"No asset found ({self._browser_model.search_provider} only)!"
else:
message = "No assets found!"
self._search_notification.set_message(message, show_clear=False)
self._search_notification.visible = True
else:
self._search_notification.visible = False
def _on_detail_scroll_y_changed(self, y: float) -> None:
try:
if self._more_details and y >= self._detail_scrolling_frame.scroll_y_max and self.category_selection:
# Require more assets
self._request_more_assets()
except AttributeError:
# scroll_y_max required new kit
# carb.log_error("Update kit to enable scrolling event!")
pass
| 16,634 | Python | 39.474452 | 118 | 0.598593 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/download_progress_bar.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.
#
# Forked from AssetStore class DownloadProgressBar
import carb.events
from omni import ui
import omni.kit.app
class DownloadProgressBar(ui.ProgressBar):
"""
Represent the asset download progress bar.
Args:
real_progress (bool): True to display real progress. False to display progress when time changed.
"""
def __init__(self, real_progress: bool = True):
self._real_progress = real_progress
self._build_ui()
def destroy(self) -> None:
self._stop()
@property
def visible(self) -> bool:
return self._container.visible
@visible.setter
def visible(self, value: bool) -> bool:
self._container.visible = value
if value:
if self._real_progress:
self.progress = 0
else:
self._start()
else:
if self._real_progress:
self.progress = 1
else:
self._stop()
@property
def progress(self) -> float:
return self._progress_bar.model.as_float
@progress.setter
def progress(self, value: float) -> None:
self._progress_bar.model.set_value(value)
def _start(self) -> None:
self._progress_bar.model.set_value(0)
self._action_time = 0.0
self._current_time = 0.0
self._step = 0.01
self._threshold = self._get_threshold()
self._update_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._update_progress)
)
def _stop(self) -> None:
self._progress_bar.model.set_value(1)
self._update_sub = None
def _build_ui(self) -> None:
self._container = ui.VStack(visible=False)
with self._container:
ui.Spacer()
self._progress_bar = ui.ProgressBar(height=0, style_type_name_override="GridView.Item.Download")
def _update_progress(self, event: carb.events.IEvent):
self._current_time += event.payload["dt"]
if self._current_time - self._action_time >= 0.1:
value = self._progress_bar.model.as_float
value += self._step
if value > 1.0:
value = 0
self._progress_bar.model.set_value(value)
if value >= self._threshold:
self._step /= 10
self._threshold = self._get_threshold()
self._action_time = self._current_time
def _get_threshold(self):
value = self._progress_bar.model.as_float
return value + (1 - value) * 0.75
| 2,999 | Python | 31.258064 | 110 | 0.606202 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/window.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.
#
# Forked from AssetStore class AssetStoreWindow
import omni.ui as ui
from .browser_widget import ArtecCloudBrowserWidget
from .models import AssetStoreModel
from .category_delegate import MainNavigationDelegate
from .detail_delegate import AssetDetailDelegate
from .overview_delegate import OverviewDelegate
from .style import ARTEC_CLOUD_BROWSER_STYLE
ARTEC_CLOUD_WINDOW_NAME = "Artec Cloud models"
class ArtecCloudWindow(ui.Window):
"""
Represent a window to show Artec Cloud Models
"""
def __init__(self):
super().__init__(ARTEC_CLOUD_WINDOW_NAME, width=500, height=600)
self._widget = None
self.frame.set_build_fn(self._build_ui)
self.frame.set_style(ARTEC_CLOUD_BROWSER_STYLE)
# Dock it to the same space where Stage is docked, make it active.
self.deferred_dock_in("Content", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
def destroy(self):
if self._widget is not None:
self._widget.destroy()
super().destroy()
def _build_ui(self):
self._browser_model = AssetStoreModel()
with self.frame:
with ui.VStack(spacing=5):
self._widget = ArtecCloudBrowserWidget(
self._browser_model,
min_thumbnail_size=128,
category_delegate=MainNavigationDelegate(self._browser_model, tree_mode=True),
category_tree_mode=True,
detail_delegate=AssetDetailDelegate(self._browser_model),
overview_delegate=OverviewDelegate(model=self._browser_model),
style=ARTEC_CLOUD_BROWSER_STYLE,
always_select_category=False,
show_category_splitter=True,
category_width=180,
)
self._widget.show_widgets(collection=True)
| 2,291 | Python | 35.967741 | 98 | 0.666085 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/auth_dialog.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.
#
# Forked from AssetStore AuthDialog
import omni.ui as ui
import carb.settings
from typing import Callable
from .style import AUTH_DIALOG_STYLE
class AuthDialog:
def __init__(self, **kwargs):
self._window = None
self._message = None
self._username = None
self._password = None
self._password_overlay = None
self._remember = None
self._ok_button = None
self._cancel_button = None
self._sub_begin_edit = None
self._width = kwargs.get("width", 400)
self._build_ui()
def _build_ui(self):
window_flags = (
ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_POPUP
| ui.WINDOW_FLAGS_NO_TITLE_BAR
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_BACKGROUND
| ui.WINDOW_FLAGS_MODAL
)
self._window = ui.Window("Authentication", width=self._width, height=0, flags=window_flags)
with self._window.frame:
with ui.ZStack(style=AUTH_DIALOG_STYLE):
ui.Rectangle(style_type_name_override="Window")
with ui.VStack(style_type_name_override="Dialog", spacing=6):
self._message = ui.Label(
f"Please login to your account.", height=20, style_type_name_override="Message"
)
with ui.HStack(height=0):
ui.Label("Email: ", style_type_name_override="Label")
self._username = ui.StringField(
width=ui.Percent(75), height=20, style_type_name_override="Field"
)
with ui.HStack(height=0):
ui.Label("Password: ", style_type_name_override="Label")
with ui.ZStack(width=ui.Percent(75)):
self._password = ui.StringField(
height=20, password_mode=True, style_type_name_override="Field"
)
self._password_overlay = ui.ZStack()
with self._password_overlay:
ui.Rectangle(style_type_name_override="Field", name="overlay")
ui.Label("Invalid credentials.", style_type_name_override="Field", name="warn")
with ui.HStack(height=0):
ui.Spacer()
ui.Label("Remember My Password ", width=0, height=20, style_type_name_override="Label")
self._remember = ui.CheckBox(enabled=True, width=0, style_type_name_override="CheckBox")
with ui.HStack(height=20, spacing=4):
ui.Spacer()
self._okay_button = ui.Button("Okay", width=100, style_type_name_override="Button")
self._cancel_button = ui.Button("Cancel", width=100, style_type_name_override="Button")
ui.Spacer(height=2)
def on_begin_edit(_):
self._password_overlay.visible = False
self._sub_begin_edit = self._password.model.subscribe_begin_edit_fn(on_begin_edit)
@property
def username(self) -> str:
if self._username:
return self._username.model.get_value_as_string()
return ""
@property
def password(self) -> str:
if self._password:
return self._password.model.get_value_as_string()
return ""
def show(self, provider: str, **kwargs):
def on_okay(dialog, provider, callback: Callable):
self._save_default_settings(provider)
if callback:
callback(dialog)
else:
dialog.hide()
def on_cancel(dialog, provider, callback: Callable):
if callback:
callback(dialog)
else:
dialog.hide()
click_okay_handler = kwargs.get("click_okay_handler")
self._okay_button.set_clicked_fn(lambda: on_okay(self, provider, click_okay_handler))
click_cancel_handler = kwargs.get("click_cancel_handler")
self._cancel_button.set_clicked_fn(lambda: on_cancel(self, provider, click_cancel_handler))
self._message.text = f"Please login to your {provider} account."
self._load_default_settings(provider)
self._password_overlay.visible = False
self._window.visible = True
def _load_default_settings(self, provider: str):
settings = carb.settings.get_settings()
default_settings = settings.get_as_string("/exts/artec.asset.browser/appSettings")
username = settings.get_as_string(f"{default_settings}/providers/{provider}/username")
password = settings.get_as_string(f"{default_settings}/providers/{provider}/password")
remember = settings.get_as_bool(f"{default_settings}/providers/remember_password")
self._username.model.set_value(username)
self._password.model.set_value(password)
self._remember.model.set_value(remember)
def _save_default_settings(self, provider: str):
settings = carb.settings.get_settings()
default_settings = settings.get_as_string("/exts/artec.asset.browser/appSettings")
remember = self._remember.model.get_value_as_bool()
username = self._username.model.get_value_as_string()
password = self._password.model.get_value_as_string() if remember else ""
settings.set_string(f"{default_settings}/providers/{provider}/username", username)
settings.set_string(f"{default_settings}/providers/{provider}/password", password)
settings.set_bool(f"{default_settings}/providers/remember_password", remember)
def warn_password(self):
self._password_overlay.visible = True
def hide(self):
self._window.visible = False
def destroy(self):
self._message = None
self._username = None
self._password = None
self._password_overlay = None
self._remember = None
self._ok_button = None
self._cancel_button = None
self._sub_begin_edit = None
self._window = None
| 6,629 | Python | 41.5 | 112 | 0.590889 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/detail_delegate.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.
#
# Forked from AssetStore class AssetDetailDelegate
import carb
import carb.settings
import omni.ui as ui
import omni.client
import omni.kit.app
from omni.kit.browser.core import DetailDelegate, DetailItem, create_drop_helper
from omni.kit.window.filepicker import FilePickerDialog
from .models import AssetStoreModel, AssetDetailItem, AssetType, MoreDetailItem, SearchingDetailItem, AssetFusion
from .models.asset_detail_item import ASSET_TIPS
from .hover_window import HoverWindow
from .auth_dialog import AuthDialog
from .download_progress_bar import DownloadProgressBar
from .download_helper import DownloadHelper
from .style import ICON_PATH
import os
import asyncio
from pathlib import Path
from typing import Optional, Dict, Tuple, Callable
from functools import partial
import webbrowser
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.joinpath("icons")
SETTING_HOVER_WINDOW = "/exts/artec.asset.browser/hoverWindow"
SETTING_MY_ASSET_FOLDERS = "/persistent/exts/omni.kit.browser.asset_provider.local/folders"
SETTING_MY_ASSET_FOLDER_CHANGED = "/exts/omni.kit.browser.asset_provider.local/folderChanged"
MIN_THUMBNAIL_SIZE_HOVER_WINDOW = 192
LABEL_HEIGHT = 32
ASSET_PROVIDER_ICON_SIZE = 32
class AssetDetailDelegate(DetailDelegate):
"""
Delegate to show asset item in detail view
Args:
model (AssetBrowserModel): Asset browser model
"""
def __init__(self, model: AssetStoreModel):
super().__init__(model=model)
self._dragging_url = None
self._settings = carb.settings.get_settings()
self._context_menu: Optional[ui.Menu] = None
self._action_item: Optional[AssetDetailItem] = None
self._action_fusion: Optional[AssetFusion] = None
self._vendor_container: Dict[AssetDetailItem, ui.ZStack] = {}
self._hover_center_container: Dict[AssetDetailItem, ui.VStack] = {}
self._hover_center_label: Dict[AssetDetailItem, ui.Label] = {}
self._hover_container: Dict[AssetDetailItem, ui.VStack] = {}
self._hover_label: Dict[AssetDetailItem, ui.Label] = {}
self._hover_background: Dict[AssetDetailItem, ui.Widget] = {}
self._asset_type_container: Dict[AssetDetailItem, ui.Widget] = {}
self._asset_type_image: Dict[AssetDetailItem, ui.Image] = {}
self._download_progress_bar: Dict[AssetFusion, DownloadProgressBar] = {}
self._draggable_urls: Dict[str, str] = {}
self._auth_dialog: Optional[AuthDialog] = None
self._pick_folder_dialog: Optional[FilePickerDialog] = None
self._on_request_more_fn: Callable[[None], None] = None
self.more_item_image: Optional[ui.Image] = None
self.more_item_label: Optional[ui.Label] = None
self.more_item_center_tips: Optional[ui.Label] = None
self.more_item_right_tips: Optional[ui.Label] = None
self._enable_hovered = True
self._asset_type_image_multiple = self._get_asset_type_image_multiple(self.thumbnail_size)
self._show_hover_window = carb.settings.get_settings().get(SETTING_HOVER_WINDOW)
if self._show_hover_window:
self._hover_window = HoverWindow()
else:
self._hover_window = None
self._instanceable_categories = self._settings.get("/exts/omni.kit.browser.asset/instanceable")
if self._instanceable_categories:
self._drop_helper = create_drop_helper(
pickable=True,
add_outline=True,
on_drop_accepted_fn=self._on_drop_accepted,
on_drop_fn=self._on_drop,
)
self._download_helper = DownloadHelper()
def destroy(self):
self._drop_helper = None
if self._pick_folder_dialog is not None:
self._pick_folder_dialog.destroy()
self._pick_folder_dialog = None
if self._hover_window:
self._hover_window.visible = False
self._hover_window = None
for item in self._download_progress_bar:
self._download_progress_bar[item].destroy()
super().destroy()
def set_request_more_fn(self, request_more_fn: Callable[[None], None]) -> None:
self._on_request_more_fn = request_more_fn
def enable_hovered(self, enable: bool) -> None:
self._enable_hovered = enable
def get_thumbnail(self, item) -> str:
"""Set default sky thumbnail if thumbnail is None"""
if item.thumbnail is None:
return f"{ICON_PATH}/usd_stage_256.png"
else:
return item.thumbnail
def get_label_height(self) -> int:
# return 0 if self.hide_label else two lines for small thumbnail size and one line for large thumbnail size
return LABEL_HEIGHT
def on_drag(self, item: AssetDetailItem) -> str:
"""Could be dragged to viewport window"""
if item.asset_type != AssetType.NORMAL:
# Cannot drag if item to be downloaded or external link
return ""
thumbnail = self.get_thumbnail(item)
icon_size = 128
with ui.VStack(width=icon_size):
if thumbnail:
ui.Spacer(height=2)
with ui.HStack():
ui.Spacer()
ui.ImageWithProvider(thumbnail, width=icon_size, height=icon_size)
ui.Spacer()
ui.Label(
item.name,
word_wrap=False,
elided_text=True,
skip_draw_when_clipped=True,
alignment=ui.Alignment.TOP,
style_type_name_override="GridView.Item",
)
self._dragging_url = None
if self._instanceable_categories:
# For required categories, need to set instanceable after dropped
url = item.url
pos = url.rfind("/")
if pos > 0:
url = url[:pos]
for category in self._instanceable_categories:
if category in url:
self._dragging_url = item.url
break
return item.url
def _on_drop_accepted(self, url):
# Only hanlder dragging from asset browser
return url == self._dragging_url
def _on_drop(self, url, target, viewport_name, context_name):
saved_instanceable = self._settings.get("/persistent/app/stage/instanceableOnCreatingReference")
if not saved_instanceable and url == self._dragging_url:
# Enable instanceable for viewport asset drop handler
self._settings.set_bool("/persistent/app/stage/instanceableOnCreatingReference", True)
async def __restore_instanceable_flag():
# Waiting for viewport asset dropper handler completed
await omni.kit.app.get_app().next_update_async()
self._settings.set("/persistent/app/stage/instanceableOnCreatingReference", saved_instanceable)
asyncio.ensure_future(__restore_instanceable_flag())
self._dragging_url = None
# Let viewport do asset dropping
return None
def _single_item_changed(self, item: AssetDetailItem):
if self._cached_label_widgets[item] is not None:
label_height = self._cached_label_widgets[item].computed_height
super()._single_item_changed(item)
if self._cached_label_widgets[item] is not None:
self._cached_label_widgets[item].height = ui.Pixel(label_height)
def on_double_click(self, item: AssetDetailItem) -> None:
if isinstance(item, AssetDetailItem):
if item.asset_type == AssetType.EXTERNAL_LINK:
webbrowser.open(item.asset_model["product_url"])
elif item.asset_type == AssetType.DOWNLOAD:
fusion = AssetFusion(item, item.asset_model['name'],
item.asset_model['download_url'],
item.asset_model["thumbnail"])
self.download_fusion(fusion)
elif item.asset_type == AssetType.NORMAL:
return super().on_double_click(item)
else:
if self._on_request_more_fn:
self._on_request_more_fn()
def download_fusion(self, fusion: AssetFusion) -> None:
if fusion in self._download_progress_bar and self._download_progress_bar[fusion].visible:
# Already downloading, do nothing
return
self._download_fusion_asset(fusion)
def on_right_click(self, item: DetailItem) -> None:
"""Show context menu"""
self._action_item = item
if isinstance(item, AssetDetailItem):
show_web = item.asset_model.get("product_url", "") != ""
if show_web:
self._context_menu = ui.Menu("Asset browser context menu")
with self._context_menu:
if show_web:
ui.MenuItem(
"Open in Web Browser",
triggered_fn=partial(webbrowser.open, item.asset_model["product_url"]),
)
self._context_menu.show()
def build_thumbnail(self, item: AssetDetailItem, container: ui.Widget = None) -> Optional[ui.Image]:
if not container:
container = ui.ZStack()
if hasattr(item, "uid"):
if item.uid in self._draggable_urls:
item.url = self._draggable_urls[item.uid]
item.asset_type = AssetType.NORMAL
with container:
thumbnail = self.get_thumbnail(item)
image = ui.Image(
thumbnail or "",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT
if isinstance(item, SearchingDetailItem)
else ui.FillPolicy.PRESERVE_ASPECT_CROP,
style_type_name_override="GridView.Image",
)
if isinstance(item, MoreDetailItem):
self.more_item_image = image
# Vendor image
self._build_vendor_image(item)
# Asset type background and image
self._asset_type_container[item] = ui.VStack()
self._build_asset_type(item)
# For displaying download progress over the thumbnail
self._download_progress_bar[item] = DownloadProgressBar()
# Selection rectangle
ui.Rectangle(style_type_name_override="GridView.Item.Selection")
return image
def on_hover(self, item: DetailItem, hovered: bool) -> None:
if not self._enable_hovered:
return
if self.thumbnail_size < MIN_THUMBNAIL_SIZE_HOVER_WINDOW:
if self._show_hover_window:
image_size = self.thumbnail_size * 1.15
offset = self.thumbnail_size * 0.15 / 2
window_position_x = self._cached_thumbnail_widgets[item].screen_position_x - offset
window_position_y = self._cached_thumbnail_widgets[item].screen_position_y - offset
self._hover_window.show(item, image_size, LABEL_HEIGHT, window_position_x, window_position_y)
else:
if item in self._hover_center_container:
self._hover_center_container[item].visible = hovered
else:
if item in self._hover_container:
self._hover_container[item].visible = hovered
self._hover_background[item].visible = hovered
def on_thumbnail_size_changed(self, thumbnail_size: int) -> None:
new_multiple = self._get_asset_type_image_multiple(thumbnail_size)
if new_multiple != self._asset_type_image_multiple:
self._asset_type_image_multiple = new_multiple
for item in self._asset_type_container:
self._build_asset_type(item)
for item in self._vendor_container:
self._vendor_container[item].width = ui.Pixel(
ASSET_PROVIDER_ICON_SIZE * self._asset_type_image_multiple
)
self._vendor_container[item].height = ui.Pixel(
ASSET_PROVIDER_ICON_SIZE * self._asset_type_image_multiple
)
def _build_label(self, item: AssetDetailItem, container: ui.Widget = None) -> ui.Widget:
"""
Display label per detail item
Args:
item (AssetDetailItem): detail item to display
"""
if not container:
container = ui.ZStack(height=LABEL_HEIGHT)
with container:
ui.Rectangle(height=0, style_type_name_override="GridView.Item.Frame")
with ui.ZStack():
# TODO: fix hover
self._hover_background[item] = ui.Rectangle(
visible=False, style_type_name_override="GridView.Item.Hover.Background"
)
with ui.HStack(height=LABEL_HEIGHT):
label = self._build_name_and_owner(item)
self._build_tips_at_right(item)
if not self._show_hover_window:
self._build_tips_at_center(item)
return label
def _build_tips_at_right(self, item: AssetDetailItem) -> None:
self._hover_container[item] = ui.ZStack(width=0, visible=False)
with self._hover_container[item]:
self._hover_label[item] = ui.Label(
item.tips,
name=item.asset_type,
width=0,
alignment=ui.Alignment.RIGHT,
style_type_name_override="GridView.Item.Tips.Text",
)
if isinstance(item, MoreDetailItem):
self.more_item_right_tips = self._hover_label[item]
def _build_tips_at_center(self, item: AssetDetailItem) -> None:
# Hover background and text
self._hover_center_container[item] = ui.ZStack(visible=False)
with self._hover_center_container[item]:
ui.Rectangle(style_type_name_override="GridView.Item.Hover.Background")
self._hover_center_label[item] = ui.Label(
# TODO: use download link in tips ?
item.tips,
name=item.asset_type,
alignment=ui.Alignment.CENTER,
style_type_name_override="GridView.Item.Tips.Text",
)
if isinstance(item, MoreDetailItem):
self.more_item_center_tips = self._hover_center_label[item]
def _build_name_and_owner(self, item: AssetDetailItem) -> ui.Label:
text = self.get_label(item)
with ui.VStack(height=LABEL_HEIGHT):
label = ui.Label(
text or "",
word_wrap=True,
elided_text=True,
skip_draw_when_clipped=True,
alignment=ui.Alignment.LEFT,
style_type_name_override="GridView.Item",
)
if isinstance(item, AssetDetailItem):
with ui.HStack():
ui.Label(
"by " + item.asset_model["user"],
elided_text=True,
style_type_name_override="GridView.Item.User",
)
ui.Spacer()
else:
ui.Label("")
self.more_item_label = label
return label
def _build_vendor_image(self, item: AssetDetailItem):
vendor_image = self._get_vendor_image(item)
if not vendor_image:
return
self._vendor_container[item] = ui.Image(
vendor_image,
width=ASSET_PROVIDER_ICON_SIZE,
height=ASSET_PROVIDER_ICON_SIZE,
fill_policy=ui.FillPolicy.STRETCH,
style_type_name_override="GridView.Item.Vendor.Image",
)
def _build_asset_type(self, item: AssetDetailItem):
(type_image_url, type_image_size) = self._get_asset_type_image(item)
tips_size = 32 * self._asset_type_image_multiple
type_image_size *= self._asset_type_image_multiple
self._asset_type_container[item].clear()
with self._asset_type_container[item]:
ui.Spacer()
with ui.HStack(height=tips_size):
ui.Spacer()
with ui.ZStack(width=tips_size):
ui.Triangle(
alignment=ui.Alignment.RIGHT_TOP, style_type_name_override="GridView.Item.Tips.Background"
)
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
self._asset_type_image[item] = ui.Image(
type_image_url,
width=type_image_size,
height=type_image_size,
fill_policy=ui.FillPolicy.STRETCH,
mouse_pressed_fn=lambda x, y, btn, flag, item=item: self._on_type_image_pressed(item),
style_type_name_override="GridView.Item.Tips.Image",
)
def _get_asset_type_image(self, item: AssetDetailItem) -> Tuple[str, int]:
"""Get item tips image url and text"""
if isinstance(item, AssetDetailItem):
if item.asset_type == AssetType.EXTERNAL_LINK:
return (f"{ICON_PATH}/External_link_green.svg", 16)
elif item.asset_type == AssetType.DOWNLOAD:
return (f"{ICON_PATH}/Download_dark.svg", 20)
elif item.asset_type == AssetType.NORMAL:
return (f"{ICON_PATH}/finger_drag_dark.svg", 24)
else:
return ("", 0)
else:
return ("", 0)
def _get_vendor_image(self, item: AssetDetailItem) -> str:
"""Get item vendor image url"""
if isinstance(item, AssetDetailItem):
vendor_name = item.asset_model["vendor"]
return self._model.providers[vendor_name]["icon"]
else:
return ""
def _download_fusion_asset(self, fusion: AssetFusion) -> None:
self.select_fusion_download_folder(fusion)
def select_fusion_download_folder(self, fusion: AssetFusion):
self._action_item = fusion.asset
self._action_fusion = fusion
if self._pick_folder_dialog is None:
self._pick_folder_dialog = self._create_filepicker(
"Select Directory to Download Asset", click_apply_fn=self._on_fusion_folder_picked, dir_only=True
)
self._pick_folder_dialog.show()
def _create_filepicker(
self,
title: str,
filters: list = ["All Files (*)"],
click_apply_fn: Callable = None,
error_fn: Callable = None,
dir_only: bool = False,
) -> FilePickerDialog:
async def on_click_handler(
filename: str, dirname: str, dialog: FilePickerDialog, click_fn: Callable, dir_only: bool
):
fullpath = None
if dir_only:
fullpath = dirname
else:
if dirname:
fullpath = f"{dirname}/{filename}"
elif filename:
fullpath = filename
if click_fn:
click_fn(fullpath)
dialog.hide()
dialog = FilePickerDialog(
title,
allow_multi_selection=False,
apply_button_label="Select",
click_apply_handler=lambda filename, dirname: asyncio.ensure_future(
on_click_handler(filename, dirname, dialog, click_apply_fn, dir_only)
),
click_cancel_handler=lambda filename, dirname: dialog.hide(),
item_filter_options=filters,
error_handler=error_fn,
)
dialog.hide()
return dialog
def _on_fusion_folder_picked(self, url: Optional[str]) -> None:
fusion = self._action_fusion
if url is not None:
self._pick_folder_dialog.set_current_directory(url)
asyncio.ensure_future(
self._model.download_fusion_async(
fusion,
fusion.asset.asset_model,
url,
callback=partial(self._on_fusion_asset_downloaded, fusion.asset),
on_progress_fn=partial(self._on_fusion_download_progress, fusion.asset),
on_prepared_fn=lambda: self._on_fusion_asset_prepared(fusion.asset)
)
)
if self._download_progress_bar.get(fusion.asset):
self._download_progress_bar[fusion.asset].visible = True
if fusion.asset in self._hover_center_label:
self._hover_label[fusion.asset].text = "Preparing"
if fusion.asset in self._hover_label:
self._hover_center_label[fusion.asset].text = "Preparing"
def _on_fusion_asset_prepared(self, item: AssetDetailItem):
if item in self._hover_center_label:
self._hover_label[item].text = "Downloading"
if item in self._hover_label:
self._hover_center_label[item].text = "Downloading"
def _on_fusion_download_progress(self, item: AssetDetailItem, progress: float) -> None:
if item in self._download_progress_bar:
self._download_progress_bar[item].progress = progress
def _on_fusion_asset_downloaded(self, item: AssetDetailItem, results: Dict):
self._add_to_my_assets(results["url"])
if self._download_progress_bar.get(item):
self._download_progress_bar[item].visible = False
if results.get("status") != omni.client.Result.OK:
return
async def delayed_item_changed(model: AssetStoreModel, item: AssetDetailItem):
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
# TODO Do I need item changed
self.item_changed(model, item)
url = results.get("url")
if url:
asyncio.ensure_future(delayed_item_changed(self._model, item))
if item in self._hover_center_label:
self._hover_label[item].text = ASSET_TIPS[AssetType.DOWNLOAD]
if item in self._hover_label:
self._hover_center_label[item].text = ASSET_TIPS[AssetType.DOWNLOAD]
async def _download_thumbnail(self, item: AssetDetailItem, dest_url: str):
"""Copies the thumbnail for the given asset to the .thumbs subdir."""
if not (item and dest_url):
return
thumbnail = item.asset_model["thumbnail"]
thumbnail_ext = os.path.splitext(thumbnail)[-1]
if not thumbnail_ext:
return
filename = os.path.basename(dest_url) + thumbnail_ext
thumbnail_url = f"{os.path.dirname(dest_url)}/.thumbs/256x256/{filename}"
thumbnail_url = thumbnail_url.replace(".jpeg", ".png")
await omni.client.copy_async(thumbnail, thumbnail_url, behavior=omni.client.CopyBehavior.OVERWRITE)
# Add downloaded to My Assets after thumbnails downloaded to make sure it display well
self._add_to_my_assets(dest_url)
def _navigate(self, url: str):
try:
import omni.kit.window.content_browser
content_window = omni.kit.window.content_browser.get_content_window()
content_window.navigate_to(url)
content_window._window._window.focus()
except ImportError:
pass
def _on_type_image_pressed(self, item: AssetDetailItem) -> None:
if item.asset_type == AssetType.EXTERNAL_LINK:
webbrowser.open(item.asset_model["product_url"])
def _get_asset_type_image_multiple(self, thumbnail_size):
if thumbnail_size > 384:
return 3
elif thumbnail_size > 192:
return 2
else:
return 1
def _add_to_my_assets(self, url: str) -> None:
# Add download folder to My Assets
for provider, setting in self._model.providers.items():
if provider == "My Assets":
url = url.replace("\\", "/")
downloaded_folder = url[: url.rfind("/")]
my_assets_folders = self._settings.get(SETTING_MY_ASSET_FOLDERS)
# Check if download folder already in My Assets
if my_assets_folders:
for folder in my_assets_folders:
if downloaded_folder.startswith(folder):
# folder already in my assets, require to refresh folder
self._settings.set(SETTING_MY_ASSET_FOLDER_CHANGED, folder)
return
my_assets_folders.append(downloaded_folder)
else:
my_assets_folders = [downloaded_folder]
# Add download folder to My Assets
self._settings.set(SETTING_MY_ASSET_FOLDERS, my_assets_folders)
break
| 25,416 | Python | 41.01157 | 118 | 0.584828 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/models/asset_store_client.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.
#
# Forked from AssetStore AssetStoreClient
import asyncio
from typing import List, Optional, Dict, Tuple
import carb.settings
from omni.services.client import AsyncClient
from omni.services.core import main
from artec.services.browser.asset import AssetModel
class AssetStoreClient:
"""
Represent client to asset store service.
Args:
url: Asset service url
"""
def __init__(self, url: str):
self._url = url
self._assets: List[AssetModel] = []
api_version = carb.settings.get_settings_interface().get("exts/artec.services.browser.asset/api_version")
self._client = AsyncClient(f"{self._url}/{api_version}", app=main.get_app())
def destroy(self):
asyncio.ensure_future(self._stop())
def list(self, category: str, search_words: Optional[List[str]] = None) -> List[AssetModel]:
return asyncio.get_event_loop().run_until_complete(self._list_async(category, search_words=search_words))
async def list_categories_async(self):
categories = await self._client.artec_assets.categories.get()
return categories
async def list_providers_async(self) -> Dict[str, str]:
return await self._client.artec_assets.providers.get()
async def config_provider_async(self, provider: str) -> None:
return await self._client.artec_assets.config.post(vendor=provider)
async def _list_async(
self,
category: Optional[str],
search_words: Optional[List[str]] = None,
sort=["name", "asc"],
page_size=100,
page_number=1,
providers=None,
) -> Tuple[List[AssetModel], bool]:
assets = []
search_args = {
"page": {"size": page_size, "number": page_number},
"keywords": search_words,
"sort": sort,
"vendors": providers,
}
if category:
search_args["filter"] = {"categories": [category]}
to_continue = False
result = await self._client.artec_assets.search.post(**search_args)
for store in result:
assets.extend(result[store][0])
if result[store][1]:
to_continue = True
return (assets, to_continue)
async def _stop(self):
await self._client.stop_async()
self._client = None
| 2,753 | Python | 32.180723 | 113 | 0.648747 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/models/asset_fusion.py | from dataclasses import dataclass
from .asset_detail_item import AssetDetailItem
@dataclass(frozen=True)
class AssetFusion:
asset: AssetDetailItem
name: str
url: str
thumbnail_url: str
| 203 | Python | 17.545453 | 46 | 0.753695 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/models/__init__.py | from .asset_store_model import AssetStoreModel
from .asset_detail_item import AssetDetailItem, AssetType, MoreDetailItem, SearchingDetailItem
from .main_navigation_item import MainNavigationItem
from .asset_fusion import AssetFusion | 232 | Python | 57.249986 | 94 | 0.862069 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/models/common_categories.py | COMMON_CATEGORIES = {
}
| 24 | Python | 7.333331 | 21 | 0.666667 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/models/asset_detail_item.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.
#
# Forked from AssetStore AssetType, AssetDetailItem, MoreDetailItem, SearchingDetailItem
import re
import omni.client
from artec.services.browser.asset import AssetModel
from omni.kit.browser.core import DetailItem
from artec.services.browser.asset import get_instance as get_asset_services
from ..style import ICON_PATH
from ..download_helper import DownloadHelper
class AssetType:
# External link in product url
EXTERNAL_LINK = "ExternalLink"
# Asset in usdz or zip, to be downloaded and unzip if zip
DOWNLOAD = "Download"
# Normal, user could drag it into viewport
NORMAL = "Normal"
UNKNOWN = "Unknown"
ASSET_TIPS = {
AssetType.EXTERNAL_LINK: "DOUBLE CLICK FOR\nEXTERNAL LINK", # Artec Cloud provides external links
AssetType.DOWNLOAD: "DOUBLE CLICK TO\nDOWNLOAD", # Default action for download type is to open
AssetType.NORMAL: "DRAG INTO\nVIEWPORT",
AssetType.UNKNOWN: "",
}
class AssetDetailItem(DetailItem):
def __init__(self, asset_model: AssetModel):
self._local_url = DownloadHelper().get_download_url(asset_model)
super().__init__(
asset_model["name"],
self._local_url if self._local_url else asset_model["download_url"],
thumbnail=asset_model["thumbnail"]
)
self.uid = asset_model["identifier"]
self.user = asset_model["user"]
self.asset_model = asset_model
self._get_type()
@property
def tips(self) -> str:
return ASSET_TIPS[self.asset_type]
def _get_type(self):
download_url = self.asset_model["download_url"].split("?")[0]
if self._local_url:
self.asset_type = AssetType.NORMAL
elif download_url:
if self._is_local_path(download_url):
# For local assets, drag and drop into viewport
self.asset_type = AssetType.NORMAL
elif (
download_url.lower().endswith("usdz")
or download_url.lower().endswith("zip")
or download_url.lower().endswith("download")
):
self.asset_type = AssetType.DOWNLOAD
else:
self.asset_type = AssetType.NORMAL
elif self.asset_model["product_url"]:
self.asset_type = AssetType.EXTERNAL_LINK
else:
self.asset_type = AssetType.UNKNOWN
def authorized(self) -> bool:
asset_services = get_asset_services()
if asset_services:
asset_store = asset_services.get_store(self.asset_model.get("vendor"))
if asset_store:
return asset_store.authorized()
return False
def _is_local_path(self, path: str) -> bool:
"""Returns True if given path is a local path"""
broken_url = omni.client.break_url(path)
if broken_url.scheme == "file":
return True
elif broken_url.scheme in ["omniverse", "http", "https"]:
return False
# Return True if root directory looks like beginning of a Linux or Windows path
root_name = broken_url.path.split("/")[0]
return not root_name or re.match(r"[A-Za-z]:", root_name) is not None
class MoreDetailItem(DetailItem):
def __init__(self):
super().__init__("More", "", f"{ICON_PATH}/load_more.png")
# used to show tips
self.tips = "DOUBLE CLICK FOR\nMORE ASSETS"
self.asset_type = AssetType.NORMAL
class SearchingDetailItem(DetailItem):
def __init__(self):
super().__init__("Searching", "", f"{ICON_PATH}/search.png")
# used to show tips
self.tips = "Searching"
self.asset_type = AssetType.NORMAL
| 4,110 | Python | 34.136752 | 102 | 0.637713 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/models/asset_store_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# Forked from AssetStore AssetStoreModel
import traceback
import asyncio
import copy
import carb
import carb.dictionary
import carb.settings
import omni.usd
import omni.kit.app
import omni.client
from omni.kit.browser.core import AbstractBrowserModel, CollectionItem, CategoryItem, DetailItem
from typing import Dict, List, Optional, Union, Callable
from artec.services.browser.asset import AssetModel, ProviderModel, BaseAssetStore
from artec.services.browser.asset import get_instance as get_asset_services
from pxr import Tf
from .asset_store_client import AssetStoreClient
from .asset_detail_item import AssetDetailItem, MoreDetailItem, SearchingDetailItem
from .main_navigation_item import MainNavigationItem
from .asset_fusion import AssetFusion
from .common_categories import COMMON_CATEGORIES
SETTING_ROOT = "/exts/artec.asset.browser/"
SETTING_PROVIDER_ROOT = SETTING_ROOT + "provider"
SETTING_PAGE_SIZE = SETTING_ROOT + "pageSize"
SETTING_SINGLE_PROVIDER = SETTING_ROOT + "singleProvider"
CATEGORY_ANY = "All projects"
class AssetStoreModel(AbstractBrowserModel):
"""
Represents the browser model for asset store services.
"""
def __init__(self):
self.artec_cloud_provider_id = 'ArtecCloud'
super().__init__(always_realod_detail_items=True)
# Dummy collection item. Not displayed, but required for browser model
self._collection_item = CollectionItem("store", "")
# For browser UI, category items in category treeview
self._category_items: List[MainNavigationItem] = []
# Category url <=> Category item
self._cached_catetory_items: Dict[str, MainNavigationItem] = {}
# Category item <=> Detail items of this category item (without children category item)
self._cached_detail_items: Dict[MainNavigationItem, List[DetailItem]] = {}
# Store
store_url = carb.settings.get_settings().get(SETTING_PROVIDER_ROOT)
self._store_client = AssetStoreClient(store_url)
# Sort of detail items, default by name with ascending
self._sort_args = {"key": lambda item: item["name"], "reverse": False}
self.search_words: Optional[List[str]] = None
self.search_provider: Optional[str] = None
self._search_sort_args = ["name", "asc"]
# Searched asset models
self._assets: Optional[List[AssetModel]] = None
self._categories: Optional[Dict] = None
self.providers: Dict[str, ProviderModel] = {}
self._refresh_provider_sub: Dict[str, omni.kit.app.SettingChangeSubscription] = {}
self._enable_provider_sub: Dict[str, omni.kit.app.SettingChangeSubscription] = {}
self.on_refresh_provider_fn: Callable[[str], None] = None
self.on_enable_provider_fn: Callable[[str], None] = None
self._page_number = 1
self._more_assets = False
self._searching = False
asyncio.ensure_future(self.list_providers_async())
def destroy(self):
for provider in self._refresh_provider_sub:
self._refresh_provider_sub[provider] = None
for provider in self._refresh_provider_sub:
self._refresh_provider_sub[provider] = None
self._store_client.destroy()
def get_store(self, vendor: str) -> BaseAssetStore:
asset_services = get_asset_services()
if asset_services:
return asset_services.get_store(vendor)
return None
def artec_cloud_provider(self) -> BaseAssetStore:
return self.get_store(self.artec_cloud_provider_id)
def get_collection_items(self) -> List[CollectionItem]:
"""Override to get list of collection items"""
return [self._collection_item]
def get_category_items(self, item: CollectionItem) -> List[CategoryItem]:
"""Override to get list of category items"""
self._category_items = []
self._cached_catetory_items = {}
# Public categories
full_categories = copy.deepcopy(COMMON_CATEGORIES)
for provider, categories in self._categories.items():
if provider in self.providers:
if self.providers[provider]["private"]:
continue
for name in categories:
if name in full_categories:
full_categories[name].extend(categories[name])
full_categories[name] = list(set(full_categories[name]))
else:
full_categories[name] = categories[name]
def __create_provider_category_items(category_list, provider=None, root=None):
for name in category_list:
self._create_category_chain(name, provider, root=root)
if category_list[name]:
category_list[name].sort()
for sub in category_list[name]:
url = name + "/" + sub
# Create category item
self._create_category_chain(url, provider, root=root)
__create_provider_category_items(full_categories)
self._category_items.sort(key=lambda item: item.name)
# Private categories
for provider, categories in self._categories.items():
if provider in self.providers:
if self.providers[provider]["private"]:
root_category_item = self._create_category_item(provider, None, provider)
if self.providers[provider]["configurable"]:
root_category_item.configurable = True
self._category_items.insert(0, root_category_item)
__create_provider_category_items(categories, provider=provider, root=root_category_item)
# All
self._category_items.insert(0, self._create_category_item(CATEGORY_ANY, None, list(self.providers.keys())))
# Cloud projects
self.cloud_projects_category_item = self._create_category_item("cloud projects", None, self.artec_cloud_provider_id)
self._category_items.insert(2, self.cloud_projects_category_item)
# Add dummy category to cloud projects to make it expandable
self._dummy_category_item = CategoryItem("")
self.cloud_projects_category_item.children.append(self._dummy_category_item)
return self._category_items
def get_detail_items(self, item: CategoryItem) -> List[DetailItem]:
"""Override to get list of detail items"""
detail_items = []
if self._assets:
for asset in self._assets:
detail_items.append(self._create_detail_item(asset))
if self._more_assets:
detail_items.append(MoreDetailItem())
if self._searching:
detail_items.append(SearchingDetailItem())
return detail_items
def execute(self, item: Union[AssetDetailItem, CategoryItem]) -> None:
if isinstance(item, CategoryItem):
# TODO: Jump to selected category item in category tree view
pass
elif isinstance(item, AssetDetailItem):
# Create a Reference of the Props in the stage
stage = omni.usd.get_context().get_stage()
if not stage:
return
name = item.name_model.as_string.split(".")[0]
prim_path = omni.usd.get_stage_next_free_path(stage, "/" + Tf.MakeValidIdentifier(name), True)
omni.kit.commands.execute(
"CreateReferenceCommand", path_to=prim_path, asset_path=item.url, usd_context=omni.usd.get_context()
)
def change_sort_args(self, sort_field: str, sort_order: str) -> None:
"""Change sort args with new field and order"""
sort_key = "name"
if sort_field == "Date":
sort_key = "created_at"
self._search_sort_args = [sort_key]
if sort_order == "Descending":
self._search_sort_args.append("desc")
else:
self._search_sort_args.append("asc")
if sort_field == "Date":
sort_fn = lambda item: item["published_at"]
else:
# Default, always sort by name
sort_fn = lambda item: item["name"]
self._sort_args = {"key": sort_fn, "reverse": sort_order == "Descending"}
def get_sort_args(self) -> Dict:
"""
Get sort args to sort detail items.
"""
return self._sort_args
def config_provider(self, provider: str) -> None:
asyncio.ensure_future(self._store_client.config_provider_async(provider))
def _on_client_prepared(self, client: AssetStoreClient) -> None:
# Client prepared, notify to model updated and regenerate items
self._category_items = []
self._cached_catetory_items = {}
self._cached_detail_items = {}
self._item_changed(self._collection_item)
def _create_category_chain(
self, category_url: str, provider_name: Optional[str], root: MainNavigationItem = None
) -> MainNavigationItem:
"""Create catetory chain by url."""
if category_url in self._cached_catetory_items:
category_item = self._cached_catetory_items[category_url]
if provider_name:
category_item.add_provider(provider_name)
return category_item
pos = category_url.rfind("/")
# Create new category item
category_item = self._create_category_item(category_url[pos + 1:], category_url, provider_name)
if pos < 0:
# Root category
if root:
root.children.append(category_item)
else:
self._category_items.append(category_item)
elif pos >= 0:
parent_category_item = self._create_category_chain(category_url[:pos], provider_name, root=root)
parent_category_item.children.append(category_item)
return category_item
def _create_category_item(self, category_name: str, category_url: Optional[str],
provider_name: str) -> MainNavigationItem:
category_item = MainNavigationItem(category_name, category_url, provider_name)
self._cached_catetory_items[category_url] = category_item
return category_item
def _create_detail_item(self, asset_model: AssetModel) -> DetailItem:
return AssetDetailItem(asset_model)
def reset_assets(self):
self._assets = []
self._page_number = 1
self._more_assets = False
async def list_assets_async(
self, category_item: MainNavigationItem, callback: Callable[[None], None] = None, reset: bool = True
) -> bool:
if reset:
self.reset_assets()
self._more_assets = False
page_size = carb.settings.get_settings().get(SETTING_PAGE_SIZE)
single_provider = carb.settings.get_settings().get(SETTING_SINGLE_PROVIDER)
if category_item.providers:
# If category is private, alwasy search for matched provider but do not care provider filter
if self.search_provider:
if self.search_provider not in category_item.providers:
carb.log_warn(
f"'{category_item.name}' used for {category_item.providers} only, ignore filter '{self.search_provider}'!"
)
providers = category_item.providers
else:
providers = [self.search_provider]
else:
providers = category_item.providers
elif self.search_provider:
providers = [self.search_provider]
else:
providers = list(self.providers.keys())
if single_provider:
self._searching = True
queries: Dict[str, asyncio.Future] = {}
for provider in providers:
queries[provider] = asyncio.ensure_future(
self._list_assets_by_vendor_async(
category_item.url, page_size, [provider], callback, single_step=True
)
)
await asyncio.gather(*queries.values(), return_exceptions=True)
for provider, query in queries.items():
try:
if query.result():
self._more_assets = True
except Exception:
carb.log_warn(f"Failed to fetch results for provider {provider}. Reason:")
carb.log_warn(traceback.format_exc())
self._searching = False
if callback:
callback()
else:
self._more_assets = await self._list_assets_by_vendor_async(
category_item.url, page_size, providers, callback
)
self._page_number += 1
return self._more_assets
async def _list_assets_by_vendor_async(self, category_url, page_size, providers, callback, single_step=False):
carb.log_info(
f"Searching providers: {providers} with category: {category_url}, keywords: {self.search_words}, page: {self._page_number}"
)
(assets, more_assets) = await self._store_client._list_async(
category_url,
search_words=self.search_words,
sort=self._search_sort_args,
page_size=page_size,
page_number=self._page_number,
providers=providers,
)
if assets:
# Filter duplicated results
new_assets = []
for asset in assets:
if asset not in self._assets + new_assets:
new_assets.append(asset)
# Sort new results
new_assets.sort(**self._sort_args)
# Add as a sub-categories to cloud projects category
self._add_assets_to_cloud_projects_category(new_assets)
# Unpack cloud projects
assets_to_add = []
for asset in new_assets:
if asset.get("vendor") == self.artec_cloud_provider_id:
assets_to_add.extend(self._extract_fusions_from_artec_cloud_project(asset))
else:
assets_to_add.append(asset)
self._assets.extend(assets_to_add)
carb.log_info(f" {len(assets)} projects returned, {len(assets_to_add)} assets added, total {len(self._assets)}")
if not single_step and more_assets:
self._more_assets = True
if callback:
callback()
elif not single_step:
if callback:
callback()
return more_assets
def _add_assets_to_cloud_projects_category(self, assets):
for asset in assets:
if asset.get("vendor") != self.artec_cloud_provider_id:
continue
if any(child.name == asset.get("name") for child in self.cloud_projects_category_item.children):
continue
category_url = asset.get("product_url").split("/")[-1]
item = self._create_category_item(asset.get("name"), category_url,
self.artec_cloud_provider_id)
self.cloud_projects_category_item.children.append(item)
if (self._dummy_category_item in self.cloud_projects_category_item.children
and len(self.cloud_projects_category_item.children) > 1):
self.cloud_projects_category_item.children.remove(self._dummy_category_item)
def _extract_fusions_from_artec_cloud_project(self, project_asset):
asset_store = self.get_store(project_asset["vendor"])
fusion_assets = []
for fusion_data in project_asset.get("fusions", []):
thumbnail_url = fusion_data["preview_url"]
if asset_store is not None:
thumbnail_url = asset_store.url_with_token(thumbnail_url)
categories = project_asset.get("categories", []).copy()
slug = project_asset.get("product_url").split("/")[-1]
categories.append(slug)
fusion_assets.append(
{
"identifier": fusion_data["fusion_id"],
"name": fusion_data["name"],
"download_url": fusion_data["download_url"],
"thumbnail": thumbnail_url,
"vendor": project_asset["vendor"],
"user": project_asset["user"],
"categories": categories,
"fusions": [],
"product_url": project_asset["product_url"]
}
)
return fusion_assets
async def list_categories_async(self):
self._categories = await self._store_client.list_categories_async()
async def list_providers_async(self):
self.providers = await self._store_client.list_providers_async()
for provider, setting in self.providers.items():
if provider in self._refresh_provider_sub:
self._refresh_provider_sub[provider] = None
if provider in self._enable_provider_sub:
self._enable_provider_sub[provider] = None
if setting["refresh_setting"]:
self._refresh_provider_sub[provider] = omni.kit.app.SettingChangeSubscription(
setting["refresh_setting"],
lambda item, event_type, p=provider: self._on_refresh_provider(p, item, event_type),
)
if setting["enable_setting"]:
self._enable_provider_sub[provider] = omni.kit.app.SettingChangeSubscription(
setting["enable_setting"],
lambda item, event_type, p=provider: self._on_enable_provider(p, item, event_type),
)
def _on_refresh_provider(self, provider: str, item: carb.dictionary.Item, event_type) -> None:
if self.on_refresh_provider_fn:
self.on_refresh_provider_fn(provider, item, event_type)
def _on_enable_provider(self, provider: str, item: carb.dictionary.Item, event_type) -> None:
if self.on_enable_provider_fn:
self.on_enable_provider_fn(provider, item, event_type)
async def authenticate_async(self, vendor: str, username: str, password: str, callback: Callable[[], None] = None):
asset_store = self.get_store(vendor)
if not asset_store:
return False
await asset_store.authenticate(username, password)
if callback:
callback()
async def download_fusion_async(
self,
fusion: AssetFusion,
asset: Dict,
dest_url: str,
callback: Callable[[Dict], None] = None,
on_progress_fn: Callable[[float], None] = None,
on_prepared_fn: Optional[Callable[[float], None]] = None
):
asset_store = self.get_store(asset.get("vendor"))
if not asset_store:
return
asset_model = AssetModel(
identifier=asset.get("identifier", ""),
name=asset.get("name", ""),
version=asset.get("version", ""),
published_at=asset.get("publishedAt", ""),
categories=asset.get("categories", []),
tags=asset.get("tags", []),
vendor=asset.get("vendor", ""),
download_url=asset.get("download_url", ""),
product_url=asset.get("product_url", ""),
price=asset.get("price", 0.0),
thumbnail=asset.get("thumbnail", ""),
user=asset.get("user", ""),
fusions=asset.get("fusions", ""),
)
results = await asset_store.download(fusion, dest_url, on_progress_fn=on_progress_fn,
timeout=600, on_prepared_fn=on_prepared_fn)
if results.get("status") != omni.client.Result.OK:
carb.log_warn(f"Failed to download asset from {asset.get('vendor')}.")
return
if callback:
callback(results)
| 20,375 | Python | 40.080645 | 135 | 0.598086 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/models/main_navigation_item.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.
#
# Forked from AssetStore MainNavigationItem
from typing import List, Union
from omni.kit.browser.core import CategoryItem
class MainNavigationItem(CategoryItem):
def __init__(self, name: str, url: str, provider: Union[str, List[str], None]):
super().__init__(name)
self.url = url
self.thumbnail = None
self.configurable = False
self.providers: List[str] = []
if provider is None:
self.providers = []
elif isinstance(provider, str):
self.providers = [provider]
else:
self.providers = provider
def add_provider(self, provider):
if provider not in self.providers:
self.providers.append(provider)
| 1,153 | Python | 35.062499 | 83 | 0.69124 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/artec/asset/browser/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import artec.asset.browser
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = artec.asset.browser.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,674 | Python | 34.638297 | 142 | 0.682198 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2023-05-15
- Initial version of extension | 150 | Markdown | 20.571426 | 80 | 0.693333 |
ArtecGroup/omni-artec-asset-browser/exts/artec.asset.browser/docs/README.md | # Artec Cloud asset browser
Provides access to Artec Cloud models for Omniverse

| 123 | Markdown | 19.666663 | 51 | 0.747967 |
superboySB/SBDrone_deprecated/README.md | 从模型在环(MITL)、软件在环(SITL)、硬件在环(HITL)再到实测(REAL),搞一个对UAV的preception-aware velocity control,下面就让我们开始吧。
# 模型在环(Model-in-the-loop, MITL)仿真训练
## Install
找一台强大的服务器,安装nvidia最新驱动、nvidia docker,并通过如下的NGC container安装全部依赖
```sh
docker login nvcr.io
docker build --pull --network host -t sbdrone_image:v1 -f docker/simulation.dockerfile docker
docker run --name sbdrone --entrypoint /bin/bash \
-itd --privileged --gpus all -e "ACCEPT_EULA=Y" --network=host \
-v /tmp/.X11-unix:/tmp/.X11-unix:ro -v $HOME/.Xauthority:/root/.Xauthority -e DISPLAY=$DISPLAY \
-v /usr/share/vulkan/icd.d/nvidia_icd.json:/etc/vulkan/icd.d/nvidia_icd.json \
-v /usr/share/vulkan/implicit_layer.d/nvidia_layers.json:/etc/vulkan/implicit_layer.d/nvidia_layers.json \
-v ~/docker/isaac-sim/cache/ov:/root/.cache/ov:rw \
-v ~/docker/isaac-sim/cache/pip:/root/.cache/pip:rw \
-v ~/docker/isaac-sim/cache/glcache:/root/.cache/nvidia/GLCache:rw \
-v ~/docker/isaac-sim/cache/computecache:/root/.nv/ComputeCache:rw \
-v ~/docker/isaac-sim/logs:/root/.nvidia-omniverse/logs:rw \
-v ~/docker/isaac-sim/config:/root/.nvidia-omniverse/config:rw \
-v ~/docker/isaac-sim/data:/root/.local/share/ov/data:rw \
-v ~/docker/isaac-sim/documents:/root/Documents:rw \
-v ~/docker/isaac-sim/cache/kit:/isaac-sim/kit/cache/Kit:rw \
sbdrone_image:v1
docker exec -it sbdrone /bin/bash
```
以headless app方式启动,并且尝试使用Omniverse Streaming Client
```sh
git clone https://github.com/superboySB/SBDrone && cd SBDrone
ln -s /isaac-sim _isaac_sim && dos2unix ./dzp_is_sb.sh && bash ./dzp_is_sb.sh --install
# note: execute the command from where the `dzp_is_sb.sh` executable exists (e.g., for bash users)
echo -e "alias sbpy=$(pwd)/dzp_is_sb.sh" >> ${HOME}/.bashrc && source ~/.bashrc
```
# 软件在环(Software-in-the-loop, SITL)仿真训练
sbpy --python -c "print('HelloWorld.')"
sbpy --python /isaac-sim/standalone_examples/api/omni.isaac.core/add_cubes.py
ssh -L 8211:localhost:8211 -L 48010:localhost:48010 -p 17003 [email protected]
`source /opt/ros/foxy/setup.bash`
# 硬件在环(Hardware-in-the-loop, HITL)调试
考虑到[官方教程](https://www.youtube.com/watch?v=e3HUKGAWdx0)里面的WSL2限制太多,为了便于部署,PX4+RL都建议在远程server(172.16.15.188)的docker里运行,同时airsim在本地windows11开发机(172.16.13.104)里运行。
## Install
```sh
docker build --network host -t sbdrone_image:sitl-v1 .
docker run -itd --privileged -v /tmp/.X11-unix:/tmp/.X11-unix:ro -e DISPLAY=$DISPLAY --gpus all --user=user --env=PX4_SIM_HOST_ADDR=172.23.53.8 --network=host --name=sitl sbdrone_image:sitl-v1 /bin/bash
docker exec -it --user=user sbdrone /bin/bash
git clone https://github.com/superboySB/SBDrone && cd cd SBDrone && pip install -r requirements.txt && pip install -e .
```
为了测试后续ROS2的offboard功能,可以把我构建的docker container作为虚拟机,后续验证流程可以参考这个[教程](https://github.com/Jaeyoung-Lim/px4-offboard/blob/master/doc/ROS2_PX4_Offboard_Tutorial.md)。如果不想用两台机器,想用一台机器做,可以考虑将Dockerfile中的github-token补全,并且取消对UE、Airsim编译的注释,运行`docker build -t mypx4_image:full .`,预计会生成一个300GB左右的image,请留好空间。
## 消除碰撞体(以下是Non-interactive Unreal Engine Custom Environments的英文教程)
We provide the environment presented within the paper to allow others to validate our approach. However, to create a custom environment, we recomend you follow the following steps to prevent agent interaction.
### Remove ego-perspective rendering of other quadrotors
To make the quadrotor invisible in the scene, change the 'Hidden in Scene Capture' to True. This will make it invisible to other drones but the spectator actor can still see it. Go to details, then rendering, this will show the setting 'Actor Hidden In Game'.


### Remove Collision boxes from all agents within the environment
We need to specifically remove agent-agent interaction while also enabling environment interaction. Hence we need to define all components of the quadrotor blueprint 'BP_FlyingPawn' as 'Pawn' and ignore any overlaps that occour between this group. To do this, we modify the collision response within the agent blueprint.
There are five components to change within the 'BP_FlyingPawn' blueprint: BodyMesh, Prop3, Prop2, Prop1, Prop0. For all of these, go to collisions, then change the collision presents to custom. Thange the Object Type to 'Pawn' and then in 'Object Responses' change the Pawn to Ignore as shown bellow.

Now to remove collisions between 'Pawns', we need to ignore the event 'ActorBeginOverlap' which we can do using a Blueprint Event Graph. Add the following event graph to 'BP_FlyingPawn'.

Agents will interact with the environment without interacting with each other.
## 在Airsim里手动控制一台PX4无人机的测试
### 方法一:使用QGC
如果需要手动控制无人机(remote control),则在QGroundControl里面,必须手动设置通信链接,QGC的自动连接功能在多个机器的时候不起作用,如果在同一台机器有时候没有问题。具体做法是,添加一个14550的UDP监听,并且需要在可选的指定server处添加`172.16.13.104:18570`,并点击连接,如果有多台则需要连接多次,端口要累加。对应地,需要开启多个PX4实例,其它参数配置可以参考[官方教程](https://microsoft.github.io/AirSim/px4_sitl/),同样端口需要累加。
### 方法二:不使用QGC
在`settings.json`中对需要控制的无人机添加手柄id
```json
"RC": {
"RemoteControlID": 1
}
```
打开一个airsim的UE实例,再开启一个PX4实例。
```sh
bash /home/user/PX4-Autopilot/Tools/simulation/sitl_multiple_run.sh 1
```
## 测试强化学习
先打开UE实例,然后依次
```sh
bash /home/user/PX4-Autopilot/Tools/simulation/sitl_multiple_run.sh 5
python sbrl/Storage.py
python sbrl/
```
## TroubleShooting
### 1. 可以换一台网络好的机器直接拉镜像副本,解决docker拉不下来的问题
```sh
docker save > <image-name>.tar sbdrone_image:v1
docker load < <image-name>.tar
```
如果想分享,可以配置一个https://transfer.sh/,分块来存:
```sh
docker save sbdrone_image:v1 | split -b 5G -d - "sbdrone_image.tar.part."
cat sbdrone_image.tar.part.* | docker load
```
### 2. 关于"WSL2本地跑PX4+Windows跑AirSim+Windows跑QGC"的连接问题
如果不用docker,而是在WSL本地跑cmake装PX4来调试,连接问题也会很烦。首先解决PX4与airsim的连接问题,需要在windows的powershell里用`ipconfig`来找本机的WSL IPv4 Address,这需要设置到AirSim中`settings.json`的`LocalHostIp`属性,以及上述教程中所有`PX4_SIM_HOST_ADDR`中。之后每次跑PX4以前,甚至需要人为指定环境变量来找windows本机,例如:
```sh
export PX4_SIM_HOST_ADDR=172.18.240.1
```
其次,需要解决PX4与QGC的连接问题,在QGroundControl里面,需要添加一个14550的UDP监听,并且需要在可选的指定server处添加`<wsl-ip>:18570`,其中`wsl-ip`可以在WSL里面输入`ifconfig`查到外部ip地址(针对windows网络的eth0),每次重启WSL2这个ip都会刷新,形如:`172.18.243.55:18570`,最后的端口也不一定是`18570`,也要注意PX4版本(详见:`PX4-Autopilot/ROMFS/px4fmu_common/init.d-posix/px4-rc.mavlink`中的`udp_gcs_port_local`)。
### 3. px4编译过程中的自动依赖安装问题
在运行`make px4_sitl_default none_iris`的时候如果遇到警报,可以hit 'u',避免resolve manually,亲测会省心一点。如果半天卡在`Building for code coverage`,请检查网速是不是太慢。
## 4. 我想修改编译后的UE游戏的窗口等设置
https://blog.csdn.net/qq_33727884/article/details/89487292
# 实际(REAL)部署测试 | 6,558 | Markdown | 43.924657 | 320 | 0.764867 |
superboySB/SBDrone_deprecated/examples/1_px4_single_vehicle.py | #!/usr/bin/env python
"""
| File: 1_px4_single_vehicle.py
| Author: Marcelo Jacinto ([email protected])
| License: BSD-3-Clause. Copyright (c) 2023, Marcelo Jacinto. All rights reserved.
| Description: This files serves as an example on how to build an app that makes use of the Pegasus API to run a simulation with a single vehicle, controlled using the MAVLink control backend.
"""
# Imports to start Isaac Sim from this script
import carb
from omni.isaac.kit import SimulationApp
# Start Isaac Sim's simulation environment
# Note: this simulation app must be instantiated right after the SimulationApp import, otherwise the simulator will crash
# as this is the object that will load all the extensions and load the actual simulator.
simulation_app = SimulationApp({"headless": False})
# -----------------------------------
# The actual script should start here
# -----------------------------------
import omni.timeline
from omni.isaac.core.world import World
# Import the Pegasus API for simulating drones
from pegasus.simulator.params import ROBOTS, SIMULATION_ENVIRONMENTS
from pegasus.simulator.logic.state import State
from pegasus.simulator.logic.backends.mavlink_backend import MavlinkBackend, MavlinkBackendConfig
from pegasus.simulator.logic.vehicles.multirotor import Multirotor, MultirotorConfig
from pegasus.simulator.logic.interface.pegasus_interface import PegasusInterface
# Auxiliary scipy and numpy modules
from scipy.spatial.transform import Rotation
class PegasusApp:
"""
A Template class that serves as an example on how to build a simple Isaac Sim standalone App.
"""
def __init__(self):
"""
Method that initializes the PegasusApp and is used to setup the simulation environment.
"""
# Acquire the timeline that will be used to start/stop the simulation
self.timeline = omni.timeline.get_timeline_interface()
# Start the Pegasus Interface
self.pg = PegasusInterface()
# Acquire the World, .i.e, the singleton that controls that is a one stop shop for setting up physics,
# spawning asset primitives, etc.
self.pg._world = World(**self.pg._world_settings)
self.world = self.pg.world
# Launch one of the worlds provided by NVIDIA
self.pg.load_environment(SIMULATION_ENVIRONMENTS["Curved Gridroom"])
# Create the vehicle
# Try to spawn the selected robot in the world to the specified namespace
config_multirotor = MultirotorConfig()
# Create the multirotor configuration
mavlink_config = MavlinkBackendConfig({
"vehicle_id": 0,
"px4_autolaunch": True,
"px4_dir": "/home/marcelo/PX4-Autopilot",
"px4_vehicle_model": 'iris'
})
config_multirotor.backends = [MavlinkBackend(mavlink_config)]
Multirotor(
"/World/quadrotor",
ROBOTS['Iris'],
0,
[0.0, 0.0, 0.07],
Rotation.from_euler("XYZ", [0.0, 0.0, 0.0], degrees=True).as_quat(),
config=config_multirotor,
)
# Reset the simulation environment so that all articulations (aka robots) are initialized
self.world.reset()
# Auxiliar variable for the timeline callback example
self.stop_sim = False
def run(self):
"""
Method that implements the application main loop, where the physics steps are executed.
"""
# Start the simulation
self.timeline.play()
# The "infinite" loop
while simulation_app.is_running() and not self.stop_sim:
# Update the UI of the app and perform the physics step
self.world.step(render=True)
# Cleanup and stop
carb.log_warn("PegasusApp Simulation App is closing.")
self.timeline.stop()
simulation_app.close()
def main():
# Instantiate the template app
pg_app = PegasusApp()
# Run the application loop
pg_app.run()
if __name__ == "__main__":
main()
| 4,067 | Python | 34.68421 | 192 | 0.664372 |
superboySB/SBDrone_deprecated/examples/6_paper_results.py | #!/usr/bin/env python
"""
| File: python_control_backend.py
| Author: Marcelo Jacinto and Joao Pinto ([email protected], [email protected])
| License: BSD-3-Clause. Copyright (c) 2023, Marcelo Jacinto. All rights reserved.
| Description: This files serves as an example on how to use the control backends API to create a custom controller
for the vehicle from scratch and use it to perform a simulation, without using PX4 nor ROS. NOTE: to see the HDR
environment as shown in the video and paper, you must have opened ISAAC SIM at least once thorugh the OMNIVERSE APP,
otherwise, the path to the HDR environment is not recognized.
"""
# Imports to start Isaac Sim from this script
import carb
from omni.isaac.kit import SimulationApp
# Start Isaac Sim's simulation environment
# Note: this simulation app must be instantiated right after the SimulationApp import, otherwise the simulator will crash
# as this is the object that will load all the extensions and load the actual simulator.
simulation_app = SimulationApp({"headless": False})
# -----------------------------------
# The actual script should start here
# -----------------------------------
import omni.timeline
from omni.isaac.core.world import World
# Used for adding extra lights to the environment
import omni.isaac.core.utils.prims as prim_utils
# Import the Pegasus API for simulating drones
from pegasus.simulator.params import ROBOTS
from pegasus.simulator.logic.vehicles.multirotor import Multirotor, MultirotorConfig
from pegasus.simulator.logic.dynamics.linear_drag import LinearDrag
from pegasus.simulator.logic.interface.pegasus_interface import PegasusInterface
# Import the custom python control backend
from utils.nonlinear_controller import NonlinearController
# Auxiliary scipy and numpy modules
import numpy as np
from scipy.spatial.transform import Rotation
# Use os and pathlib for parsing the desired trajectory from a CSV file
import os
from pathlib import Path
from omni.isaac.debug_draw import _debug_draw
class PegasusApp:
"""
A Template class that serves as an example on how to build a simple Isaac Sim standalone App.
"""
def __init__(self):
"""
Method that initializes the PegasusApp and is used to setup the simulation environment.
"""
# Acquire the timeline that will be used to start/stop the simulation
self.timeline = omni.timeline.get_timeline_interface()
# Start the Pegasus Interface
self.pg = PegasusInterface()
# Acquire the World, .i.e, the singleton that controls that is a one stop shop for setting up physics,
# spawning asset primitives, etc.
self.pg._world_settings = {"physics_dt": 1.0 / 500.0, "stage_units_in_meters": 1.0, "rendering_dt": 1.0 / 60.0}
self.pg._world = World(**self.pg._world_settings)
self.world = self.pg.world
# Add a custom light with a high-definition HDR surround environment of an exhibition hall,
# instead of the typical ground plane
prim_utils.create_prim(
"/World/Light/DomeLight",
"DomeLight",
attributes={
"texture:file": "omniverse://localhost/NVIDIA/Assets/Skies/Indoor/ZetoCGcom_ExhibitionHall_Interior1.hdr",
"intensity": 1000.0
})
# Get the current directory used to read trajectories and save results
self.curr_dir = str(Path(os.path.dirname(os.path.realpath(__file__))).resolve())
# Create the vehicle 1
# Try to spawn the selected robot in the world to the specified namespace
config_multirotor1 = MultirotorConfig()
config_multirotor1.drag = LinearDrag([0.0, 0.0, 0.0])
# Use the nonlinear controller with the built-in exponential trajectory
config_multirotor1.backends = [NonlinearController(
trajectory_file=None,
results_file=self.curr_dir + "/results/statistics_1.npz")]
Multirotor(
"/World/quadrotor1",
ROBOTS['Iris'],
1,
[-5.0,0.00,1.00],
Rotation.from_euler("XYZ", [0.0, 0.0, 0.0], degrees=True).as_quat(),
config=config_multirotor1,
)
# Create the vehicle 2
#Try to spawn the selected robot in the world to the specified namespace
config_multirotor2 = MultirotorConfig()
# Use the nonlinear controller with the built-in exponential trajectory
config_multirotor2.backends = [NonlinearController(
trajectory_file=None,
results_file=self.curr_dir + "/results/statistics_2.npz",
reverse=True)]
Multirotor(
"/World/quadrotor2",
ROBOTS['Iris'],
2,
[-5.0,4.5,1.0],
Rotation.from_euler("XYZ", [0.0, 0.0, 0.0], degrees=True).as_quat(),
config=config_multirotor2,
)
# Set the camera to a nice position so that we can see the 2 drones almost touching each other
self.pg.set_viewport_camera([1.0, 5.15, 1.65], [0.0, -1.65, 3.3])
# Draw the lines of the desired trajectory in Isaac Sim with the same color as the output plots for the paper
gamma = np.arange(start=-5.0, stop=5.0, step=0.01)
num_samples = gamma.size
trajectory1 = [config_multirotor1.backends[0].pd(gamma[i], 0.6) for i in range(num_samples)]
trajectory2 = [config_multirotor2.backends[0].pd(gamma[i], 0.6, reverse=True) for i in range(num_samples)]
draw = _debug_draw.acquire_debug_draw_interface()
point_list_1 = [(trajectory1[i][0], trajectory1[i][1], trajectory1[i][2]) for i in range(num_samples)]
draw.draw_lines_spline(point_list_1, (31/255, 119/255, 180/255, 1), 5, False)
point_list_2 = [(trajectory2[i][0], trajectory2[i][1], trajectory2[i][2]) for i in range(num_samples)]
draw.draw_lines_spline(point_list_2, (255/255, 0, 0, 1), 5, False)
# Reset the world
self.world.reset()
def run(self):
"""
Method that implements the application main loop, where the physics steps are executed.
"""
# Start the simulation
self.timeline.play()
# The "infinite" loop
while simulation_app.is_running():
# Update the UI of the app and perform the physics step
self.world.step(render=True)
# Cleanup and stop
carb.log_warn("PegasusApp Simulation App is closing.")
self.timeline.stop()
simulation_app.close()
def main():
# Instantiate the template app
pg_app = PegasusApp()
# Run the application loop
pg_app.run()
if __name__ == "__main__":
main()
| 6,729 | Python | 38.588235 | 122 | 0.657601 |
superboySB/SBDrone_deprecated/examples/9_custom.py | #!/usr/bin/env python
"""
| File: 8_camera_vehicle.py
| License: BSD-3-Clause. Copyright (c) 2023, Marcelo Jacinto. All rights reserved.
| Description: This files serves as an example on how to build an app that makes use of the Pegasus API to run a simulation
with a single vehicle equipped with a camera, producing rgb and camera info ROS2 Humble topics.
"""
# Imports to start Isaac Sim from this script
import carb
from omni.isaac.kit import SimulationApp
# Start Isaac Sim's simulation environment
# Note: this simulation app must be instantiated right after the SimulationApp import, otherwise the simulator will crash
# as this is the object that will load all the extensions and load the actual simulator.
simulation_app = SimulationApp({"headless": False, "width": 640, "height": 480})
# -----------------------------------
# The actual script should start here
# -----------------------------------
import omni.timeline
from omni.isaac.core.world import World
from omni.isaac.core.utils.extensions import disable_extension, enable_extension
# Enable/disable ROS bridge extensions to keep only ROS2 Humble Bridge
disable_extension("omni.isaac.ros_bridge")
disable_extension("omni.isaac.ros2_bridge")
enable_extension("omni.isaac.ros2_bridge-humble")
# Import the Pegasus API for simulating drones
from pegasus.simulator.params import ROBOTS, SIMULATION_ENVIRONMENTS
from pegasus.simulator.logic.state import State
from pegasus.simulator.logic.backends.mavlink_backend import MavlinkBackend, MavlinkBackendConfig
from pegasus.simulator.logic.vehicles.multirotor import Multirotor, MultirotorConfig
from pegasus.simulator.logic.interface.pegasus_interface import PegasusInterface
from pegasus.simulator.logic.graphs import ROS2Camera, ROS2Tf, ROS2Odometry, ROS2Lidar
from pegasus.simulator.logic.sensors import Magnetometer, IMU, Barometer, Vision, Camera, Lidar
# Auxiliary scipy and numpy modules
from scipy.spatial.transform import Rotation
class PegasusApp:
"""
A Template class that serves as an example on how to build a simple Isaac Sim standalone App.
"""
def __init__(self):
"""
Method that initializes the PegasusApp and is used to setup the simulation environment.
"""
# Acquire the timeline that will be used to start/stop the simulation
self.timeline = omni.timeline.get_timeline_interface()
# Start the Pegasus Interface
self.pg = PegasusInterface()
# Acquire the World, .i.e, the singleton that controls that is a one stop shop for setting up physics,
# spawning asset primitives, etc.
self.pg._world = World(**self.pg._world_settings)
self.world = self.pg.world
# Launch one of the worlds provided by NVIDIA
self.pg.load_environment(SIMULATION_ENVIRONMENTS["Curved Gridroom"])
# Create the vehicle
# Try to spawn the selected robot in the world to the specified namespace
config_multirotor = MultirotorConfig()
# Create the multirotor configuration
mavlink_config = MavlinkBackendConfig({
"vehicle_id": 0,
"px4_autolaunch": True,
"px4_dir": "/home/fstec/Projects/PX4-Autopilot",
"px4_vehicle_model": 'iris_vision'
})
config_multirotor.backends = [MavlinkBackend(mavlink_config)]
# Sensors
camera_prim_path = "body/camera"
camera_config = {
"position": [0.1, 0.0, 0.0],
"orientation": Rotation.from_euler("XYZ", [0.0, 0.0, 0.0], degrees=True).as_quat(),
"focal_length": 16.0,
"overwrite_params": True
}
lidar_prim_path = "body/lidar"
lidar_config = {
"position": [-0.1, 0.0, 0.0],
"yaw_offset": 180.0,
"horizontal_fov": 27.0,
"vertical_fov": 27.0,
"min_range": 0.01,
"max_range": 5.0,
"draw_lines": True
}
config_multirotor.sensors = [
Magnetometer(), IMU(), Barometer(), Vision(),
Camera(camera_prim_path, camera_config),
Lidar(lidar_prim_path, lidar_config)]
# Graphs
config_multirotor.graphs = [
ROS2Tf(), ROS2Odometry(),
ROS2Camera(camera_prim_path, config={"types": ['rgb', 'camera_info', 'depth']}),
ROS2Lidar(lidar_prim_path)
]
Multirotor(
"/World/quadrotor",
ROBOTS['Iris'],
0,
[0.0, 0.0, 0.07],
Rotation.from_euler("XYZ", [0.0, 0.0, 0.0], degrees=True).as_quat(),
config=config_multirotor,
)
# Reset the simulation environment so that all articulations (aka robots) are initialized
self.world.reset()
# Auxiliar variable for the timeline callback example
self.stop_sim = False
def run(self):
"""
Method that implements the application main loop, where the physics steps are executed.
"""
# Start the simulation
self.timeline.play()
# The "infinite" loop
while simulation_app.is_running() and not self.stop_sim:
# Update the UI of the app and perform the physics step
self.world.step(render=True)
# Cleanup and stop
carb.log_warn("PegasusApp Simulation App is closing.")
self.timeline.stop()
simulation_app.close()
def main():
# Instantiate the template app
pg_app = PegasusApp()
# Run the application loop
pg_app.run()
if __name__ == "__main__":
main()
| 5,584 | Python | 35.743421 | 123 | 0.643087 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.