file_path
stringlengths
21
224
content
stringlengths
0
80.8M
NVIDIA-Omniverse/kit-extension-template-cpp/source/apps/exts.deps.generated.kit
######################################################################################################################## # This kit file is generated by "repo precache_exts" tool. # It is an app, that contains all extensions from the repo as dependencies. It is used to: # 1. lock all versions of their dependencies (reproducible builds). # 2. precache (download) all dependencies before building. # # This file is regenerated if: # 1. Any extension is added or removed from the repo. # 2. Any extension version is updated # 3. This file is removed. # # To update version lock the same `repo build -u` flag can be used. ######################################################################################################################## [settings.app.exts.folders] '++' = ["${app}/../exts", "${app}/../extscache/"] # All local extensions built in this repo: [dependencies] "omni.example.cpp.actions" = {} "omni.example.cpp.commands" = {} "omni.example.cpp.hello_world" = {} "omni.example.cpp.omnigraph_node" = {} "omni.example.cpp.pybind" = {} "omni.example.cpp.tasking" = {} "omni.example.cpp.ui_widget" = {} "omni.example.cpp.usd" = {} "omni.example.cpp.usd_physics" = {} "omni.example.cpp.usdrt" = {} "omni.example.python.hello_world" = {} "omni.example.python.ui" = {} "omni.example.python.usdrt" = {} "omni.example.python.usdrt_mesh" = {} ######################################################################################################################## # BEGIN GENERATED PART (Remove from 'BEGIN' to 'END' to regenerate) ######################################################################################################################## # Kit SDK Version: 105.1.0+release.51.a7407fb5.tc # Version lock for all dependencies: [settings.app.exts] enabled = [ ] ######################################################################################################################## # END GENERATED PART ########################################################################################################################
NVIDIA-Omniverse/kit-extension-template-cpp/source/apps/omni.app.example.extension_browser.kit
# An application is really just an extension that depends on other extensions. [package] title = "Example Application: Extension Browser" description = "An example application that runs kit with the minimal set of extensions required to use the extension browser." keywords = ["app"] # Makes this browsable in the UI under the "experience" filter. [dependencies] "omni.kit.uiapp" = {} "omni.kit.window.extensions" = {} # Add new extensions here if you want them enabled automatically when this app is run. # Otherwise, you can search for them in the extensions window and enable/disable them. [settings] app.exts.folders.'++' = ["${app}/../exts"] # Make extensions from this repo available to kit. app.menu.legacy_mode = false # So the extension window shows up app.windowtitle = "Example Application: Extension Browser" app.windowwidth = 1700 app.windowheight = 900
NVIDIA-Omniverse/kit-extension-template-cpp/source/apps/omni.app.kit.dev.kit
[package] title = "Kit Dev App With Example Extensions" description = "The default kit dev app with extensions from this repo made available." version = "1.0.0" keywords = ["app"] [dependencies] "omni.app.dev" = {} [settings.app.exts] folders.'++' = ["${app}/../exts"] # Make extensions from this repo available. [[test]] enabled = false
NVIDIA-Omniverse/kit-extension-template-cpp/source/apps/omni.app.example.viewport.kit
# An application is really just an extension that depends on other extensions [package] title = "Example Application: Viewport" description = "An example application that runs kit with the minimal set of extensions required to use the viewport." keywords = ["app"] # Makes this browsable in the UI under the "experience" filter. # Add new extensions here if you want them enabled automatically when this app is run. # Otherwise, you can search for them in the extensions window and enable/disable them. [dependencies] "omni.kit.uiapp" = {} "omni.kit.viewport.bundle" = {} "omni.kit.viewport.rtx" = {} "omni.kit.window.extensions" = {} "omni.kit.window.file" = {} "omni.kit.window.toolbar" = {} [settings] app.content.emptyStageOnStart = true app.exts.folders.'++' = ["${app}/../exts"] # Make extensions from this repo available. app.window.title = "Example Application: Viewport" app.window.width = 1700 app.window.height = 900
NVIDIA-Omniverse/kit-extension-sample-ui-scene/link_app.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) cd "$SCRIPT_DIR" exec "tools/packman/python.sh" tools/scripts/link_app.py $@
NVIDIA-Omniverse/kit-extension-sample-ui-scene/link_app.bat
@echo off call "%~dp0tools\packman\python.bat" %~dp0tools\scripts\link_app.py %* if %errorlevel% neq 0 ( goto Error ) :Success exit /b 0 :Error exit /b %errorlevel%
NVIDIA-Omniverse/kit-extension-sample-ui-scene/README.md
# omni.ui.scene Kit Extension Samples ## [Object Info (omni.example.ui_scene.object_info)](exts/omni.example.ui_scene.object_info) [![Object Info](exts/omni.example.ui_scene.object_info/data/preview.png)](exts/omni.example.ui_scene.object_info) ### About This extension uses the omni.ui.scene API to add simple graphics and labels in the viewport above your selected prim. The labels provide the prim path of the selected prim and the prim path of its assigned material. ### [README](exts/omni.example.ui_scene.object_info) See the [README for this extension](exts/omni.example.ui_scene.object_info) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## [Widget Info (omni.example.ui_scene.widget_info)](exts/omni.example.ui_scene.object_info) [![Widget Info](exts/omni.example.ui_scene.widget_info/data/preview.png)](exts/omni.example.ui_scene.widget_info) ### About This extension uses the omni.ui.scene API to add a widget in the viewport, just above your selected prim. The widget provides the prim path of your selection and a scale slider. ### [README](exts/omni.example.ui_scene.widget_info) See the [README for this extension](exts/omni.example.ui_scene.widget_info) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## [Light Manipulator (omni.example.ui_scene.light_manipulator)](exts/omni.example.ui_scene.light_manipulator) [![Light Manipulator](exts/omni.example.ui_scene.light_manipulator/data/preview.png)](exts/omni.example.ui_scene.light_manipulator) ### About This extension add a custom manipulator for RectLights that allows you to control the width, height, and intensity of RectLights by clicking and dragging in the viewport. ### [README](exts/omni.example.ui_scene.light_manipulator) See the [README for this extension](exts/omni.example.ui_scene.light_manipulator) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_scene.light_manipulator/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_scene.light_manipulator/tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## [Slider Manipulator (omni.example.ui_scene.slider_manipulator)](exts/omni.example.ui_scene.slider_manipulator) [![Light Manipulator](exts/omni.example.ui_scene.slider_manipulator/data/preview.png)](exts/omni.example.ui_scene.slider_manipulator) ### About This extension add a custom slider manipulator above you selected prim that controls the scale of the prim when you click and drag the slider. ### [README](exts/omni.example.ui_scene.slider_manipulator) See the [README for this extension](exts/omni.example.ui_scene.slider_manipulator) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md) that walks you through how to use omni.ui.scene to build this extension. # Adding These Extensions To add these extensions to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene?branch=main&dir=exts` ## Linking with an Omniverse app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app code ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3" ``` Running this command adds a symlink to Omniverse Code. This makes intellisense work and lets you easily run the app from the terminal. ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
NVIDIA-Omniverse/kit-extension-sample-ui-scene/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!")
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/python.sh
#!/bin/bash # Copyright 2019-2020 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. set -e PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi source "$PACKMAN_CMD" init export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}" export PYTHONNOUSERSITE=1 # workaround for our python not shipping with certs if [[ -z ${SSL_CERT_DIR:-} ]]; then export SSL_CERT_DIR=/etc/ssl/certs/ fi "${PM_PYTHON}" -u "$@"
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/python.bat
:: Copyright 2019-2020 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. @echo off setlocal call "%~dp0\packman" init set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%" set PYTHONNOUSERSITE=1 "%PM_PYTHON%" -u %*
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/packman.cmd
:: Reset errorlevel status (don't inherit from caller) [xxxxxxxxxxx] @call :ECHO_AND_RESET_ERROR :: You can remove the call below if you do your own manual configuration of the dev machines call "%~dp0\bootstrap\configure.bat" if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Everything below is mandatory if not defined PM_PYTHON goto :PYTHON_ENV_ERROR if not defined PM_MODULE goto :MODULE_ENV_ERROR :: Generate temporary path for variable file for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile ^ -File "%~dp0bootstrap\generate_temp_file_name.ps1"') do set PM_VAR_PATH=%%a if %1.==. ( set PM_VAR_PATH_ARG= ) else ( set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%" ) "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG% if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Marshall environment variables into the current environment if they have been generated and remove temporary file if exist "%PM_VAR_PATH%" ( for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) if exist "%PM_VAR_PATH%" ( del /F "%PM_VAR_PATH%" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) set PM_VAR_PATH= goto :eof :: Subroutines below :PYTHON_ENV_ERROR @echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat. exit /b 1 :MODULE_ENV_ERROR @echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat. exit /b 1 :VAR_ERROR @echo Error while processing and setting environment variables! exit /b 1 :ECHO_AND_RESET_ERROR @echo off if /I "%PM_VERBOSITY%"=="debug" ( @echo on ) exit /b 0
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/bootstrap/generate_temp_file_name.ps1
<# 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. #> $out = [System.IO.Path]::GetTempFileName() Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAK+Ewup1N0/mdf # 1l4R58rxyumHgZvTmEhrYTb2Zf0zd6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1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6LdnYJp38eMs3fqTTvjhyDw # HffXrwdqWy5/fgW3o3qJXqa5o7hLxYIoWSULOCpJRGdt+w7XKPAbZqHrN9elAhWJ # vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V # mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo # PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof # wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU # SIG # End signature block
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/bootstrap/configure.bat
:: 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. set PM_PACKMAN_VERSION=6.33.2 :: Specify where packman command is rooted set PM_INSTALL_PATH=%~dp0.. :: The external root may already be configured and we should do minimal work in that case if defined PM_PACKAGES_ROOT goto ENSURE_DIR :: If the folder isn't set we assume that the best place for it is on the drive that we are currently :: running from set PM_DRIVE=%CD:~0,2% set PM_PACKAGES_ROOT=%PM_DRIVE%\packman-repo :: We use *setx* here so that the variable is persisted in the user environment echo Setting user environment variable PM_PACKAGES_ROOT to %PM_PACKAGES_ROOT% setx PM_PACKAGES_ROOT %PM_PACKAGES_ROOT% if %errorlevel% neq 0 ( goto ERROR ) :: The above doesn't work properly from a build step in VisualStudio because a separate process is :: spawned for it so it will be lost for subsequent compilation steps - VisualStudio must :: be launched from a new process. We catch this odd-ball case here: if defined PM_DISABLE_VS_WARNING goto ENSURE_DIR if not defined VSLANG goto ENSURE_DIR echo The above is a once-per-computer operation. Unfortunately VisualStudio cannot pick up environment change echo unless *VisualStudio is RELAUNCHED*. echo If you are launching VisualStudio from command line or command line utility make sure echo you have a fresh launch environment (relaunch the command line or utility). echo If you are using 'linkPath' and referring to packages via local folder links you can safely ignore this warning. echo You can disable this warning by setting the environment variable PM_DISABLE_VS_WARNING. echo. :: Check for the directory that we need. Note that mkdir will create any directories :: that may be needed in the path :ENSURE_DIR if not exist "%PM_PACKAGES_ROOT%" ( echo Creating directory %PM_PACKAGES_ROOT% mkdir "%PM_PACKAGES_ROOT%" ) if %errorlevel% neq 0 ( goto ERROR_MKDIR_PACKAGES_ROOT ) :: The Python interpreter may already be externally configured if defined PM_PYTHON_EXT ( set PM_PYTHON=%PM_PYTHON_EXT% goto PACKMAN ) set PM_PYTHON_VERSION=3.7.9-windows-x86_64 set PM_PYTHON_BASE_DIR=%PM_PACKAGES_ROOT%\python set PM_PYTHON_DIR=%PM_PYTHON_BASE_DIR%\%PM_PYTHON_VERSION% set PM_PYTHON=%PM_PYTHON_DIR%\python.exe if exist "%PM_PYTHON%" goto PACKMAN if not exist "%PM_PYTHON_BASE_DIR%" call :CREATE_PYTHON_BASE_DIR set PM_PYTHON_PACKAGE=python@%PM_PYTHON_VERSION%.cab for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME%.zip call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_PYTHON_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching python from CDN !!! goto ERROR ) for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_folder.ps1" -parentPath "%PM_PYTHON_BASE_DIR%"') do set TEMP_FOLDER_NAME=%%a echo Unpacking Python interpreter ... "%SystemRoot%\system32\expand.exe" -F:* "%TARGET%" "%TEMP_FOLDER_NAME%" 1> nul del "%TARGET%" :: Failure during extraction to temp folder name, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error unpacking python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :: If python has now been installed by a concurrent process we need to clean up and then continue if exist "%PM_PYTHON%" ( call :CLEAN_UP_TEMP_FOLDER goto PACKMAN ) else ( if exist "%PM_PYTHON_DIR%" ( rd /s /q "%PM_PYTHON_DIR%" > nul ) ) :: Perform atomic rename rename "%TEMP_FOLDER_NAME%" "%PM_PYTHON_VERSION%" 1> nul :: Failure during move, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error renaming python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :PACKMAN :: The packman module may already be externally configured if defined PM_MODULE_DIR_EXT ( set PM_MODULE_DIR=%PM_MODULE_DIR_EXT% ) else ( set PM_MODULE_DIR=%PM_PACKAGES_ROOT%\packman-common\%PM_PACKMAN_VERSION% ) set PM_MODULE=%PM_MODULE_DIR%\packman.py if exist "%PM_MODULE%" goto ENSURE_7ZA set PM_MODULE_PACKAGE=packman-common@%PM_PACKMAN_VERSION%.zip for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME% call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_MODULE_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching packman from CDN !!! goto ERROR ) echo Unpacking ... "%PM_PYTHON%" -S -s -u -E "%~dp0\install_package.py" "%TARGET%" "%PM_MODULE_DIR%" if %errorlevel% neq 0 ( echo !!! Error unpacking packman !!! goto ERROR ) del "%TARGET%" :ENSURE_7ZA set PM_7Za_VERSION=16.02.4 set PM_7Za_PATH=%PM_PACKAGES_ROOT%\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END set PM_7Za_PATH=%PM_PACKAGES_ROOT%\chk\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" pull "%PM_MODULE_DIR%\deps.packman.xml" if %errorlevel% neq 0 ( echo !!! Error fetching packman dependencies !!! goto ERROR ) goto END :ERROR_MKDIR_PACKAGES_ROOT echo Failed to automatically create packman packages repo at %PM_PACKAGES_ROOT%. echo Please set a location explicitly that packman has permission to write to, by issuing: echo. echo setx PM_PACKAGES_ROOT {path-you-choose-for-storing-packman-packages-locally} echo. echo Then launch a new command console for the changes to take effect and run packman command again. exit /B %errorlevel% :ERROR echo !!! Failure while configuring local machine :( !!! exit /B %errorlevel% :CLEAN_UP_TEMP_FOLDER rd /S /Q "%TEMP_FOLDER_NAME%" exit /B :CREATE_PYTHON_BASE_DIR :: We ignore errors and clean error state - if two processes create the directory one will fail which is fine md "%PM_PYTHON_BASE_DIR%" > nul 2>&1 exit /B 0 :END
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/bootstrap/fetch_file_from_packman_bootstrap.cmd
:: 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. :: You need to specify <package-name> <target-path> as input to this command @setlocal @set PACKAGE_NAME=%1 @set TARGET_PATH=%2 @echo Fetching %PACKAGE_NAME% ... @powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0download_file_from_url.ps1" ^ -source "http://bootstrap.packman.nvidia.com/%PACKAGE_NAME%" -output %TARGET_PATH% :: A bug in powershell prevents the errorlevel code from being set when using the -File execution option :: We must therefore do our own failure analysis, basically make sure the file exists and is larger than 0 bytes: @if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED @if %~z2==0 goto ERROR_DOWNLOAD_FAILED @endlocal @exit /b 0 :ERROR_DOWNLOAD_FAILED @echo Failed to download file from S3 @echo Most likely because endpoint cannot be reached or file %PACKAGE_NAME% doesn't exist @endlocal @exit /b 1
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/bootstrap/download_file_from_url.ps1
<# 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. #> param( [Parameter(Mandatory=$true)][string]$source=$null, [string]$output="out.exe" ) $filename = $output $triesLeft = 3 do { $triesLeft -= 1 try { Write-Host "Downloading from bootstrap.packman.nvidia.com ..." $wc = New-Object net.webclient $wc.Downloadfile($source, $fileName) $triesLeft = 0 } catch { Write-Host "Error downloading $source!" Write-Host $_.Exception|format-list -force } } while ($triesLeft -gt 0)
NVIDIA-Omniverse/kit-extension-sample-ui-scene/tools/packman/bootstrap/generate_temp_folder.ps1
<# 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. #> param( [Parameter(Mandatory=$true)][string]$parentPath=$null ) [string] $name = [System.Guid]::NewGuid() $out = Join-Path $parentPath $name New-Item -ItemType Directory -Path ($out) | Out-Null Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgE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MBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCDvFxQ6lYLr8vB+9czUl19rjCw1pWhhUXw/SqOmvIa/VDANBgkqhkiG # 9w0BAQEFAASCAQB9ox2UrcUXQsBI4Uycnhl4AMpvhVXJME62tygFMppW1l7QftDy # LvfPKRYm2YUioak/APxAS6geRKpeMkLvXuQS/Jlv0kY3BjxkeG0eVjvyjF4SvXbZ # 3JCk9m7wLNE+xqOo0ICjYlIJJgRLudjWkC5Skpb1NpPS8DOaIYwRV+AWaSOUPd9P # O5yVcnbl7OpK3EAEtwDrybCVBMPn2MGhAXybIHnth3+MFp1b6Blhz3WlReQyarjq # 1f+zaFB79rg6JswXoOTJhwICBP3hO2Ua3dMAswbfl+QNXF+igKLJPYnaeSVhBbm6 # VCu2io27t4ixqvoD0RuPObNX/P3oVA38afiM # SIG # End signature block
NVIDIA-Omniverse/kit-extension-sample-ui-scene/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])
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md
![](./Images/logo.png) # How to make a Slider Manipulator In this guide you will learn how to draw a 3D slider in the viewport that overlays on the top of the bounding box of the selected prim. This slider will control the scale of the prim with a custom manipulator, model, and gesture. When the slider is changed, the manipulator processes the custom gesture that changes the data in the model, which changes the data directly in the USD stage. ![](./Images/sliderPreview.png) # Learning Objectives - Create an extension - Import omni.ui and USD - Set up Model and Manipulator - Create Gestures - Create a working scale slider # Prerequisites To help understand the concepts used in this guide, it is recommended that you complete the following: - [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial) - [Spawning Prims Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims) - [Display Object Info Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/tree/main/exts/omni.example.ui_scene.object_info) :exclamation: <span style="color:red"><b>WARNING:</b> Check that Viewport Utility Extension is turned ON in the Extensions Manager: </span> ![](./Images/viewportUtilOn.PNG) # Step 1: Create the extension In this section, you will create a new extension in Omniverse Code. ## Step 1.1: Create new extension template In Omniverse Code navigate to the `Extensions` tab and create a new extension by clicking the ➕ icon in the upper left corner and select `New Extension Template Project`. ![icon](./Images/icon_create.png "Plus Icon") ![new template](./Images/new_template.png "New Extension Template") <br> A new extension template window and Visual Studio Code will open after you have selected the folder location, folder name, and extension ID. ## Step 1.2: Naming your extension In the extension manager, you may have noticed that each extension has a title and description: ![](./Images/extensionManager_example.PNG) You can change this in the `extension.toml` file by navigating to `VS Code` and editing the file there. It is important that you give your extension a detailed title and summary for the end user to understand what your extension will accomplish or display. Here is how to change it for this guide: ```python # The title and description fields are primarily for displaying extension info in UI title = "UI Scene Slider Manipulator" description="Interactive example of the slider manipulator with omni.ui.scene" ``` ## Step 2: Model module In this step you will be creating the `slider_model.py` module where you will be tracking the current selected prim, listening to stage events, and getting the position directly from USD. This module will be made up of many lines so be sure to review the <b>":memo:Code Checkpoint"</b> for updated code of the module at various steps. ### Step 2.1: Import omni.ui and USD After creating `slider_model.py` in the same folder as `extension.py`, import `scene` from `omni.ui` and the necessary USD modules, as follows: ```python from omni.ui import scene as sc from pxr import Tf from pxr import Gf from pxr import Usd from pxr import UsdGeom import omni.usd ``` ### Step 2.2: `SliderModel` and `PositionItem` Classes Next, let's set up your `SliderModel` and `PositionItem` classes. `SliderModel` tracks the position and scale of the selected prim and `PositionItem` stores the position value. ```python from omni.ui import scene as sc from pxr import Tf from pxr import Gf from pxr import Usd from pxr import UsdGeom import omni.usd # NEW class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because you take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() self.position = SliderModel.PositionItem() # END NEW ``` ## Step 2.3: Current Selection and Tracking Selection In this section, you will be setting the variables for the current selection and tracking the selected prim, where you will also set parameters for the stage event later on. ```python ... class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because you take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() self.position = SliderModel.PositionItem() # NEW # Current selection self.current_path = "" self.stage_listener = None self.usd_context = omni.usd.get_context() self.stage: Usd.Stage = self.usd_context.get_stage() # Track selection self.selection = self.usd_context.get_selection() self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Slider Selection Update" ) # END NEW ``` >:memo: Code Checkpoint <details> <summary> Click here for the updated <b>SliderModel</b> </summary> ```python from omni.ui import scene as sc from pxr import Tf from pxr import Gf from pxr import Usd from pxr import UsdGeom import omni.usd class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because you take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() self.position = SliderModel.PositionItem() # Current selection self.current_path = "" self.stage_listener = None self.usd_context = omni.usd.get_context() self.stage: Usd.Stage = self.usd_context.get_stage() # Track selection self.selection = self.usd_context.get_selection() self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Slider Selection Update" ) ``` </details> ## Step 2.4: Define `on_stage_event()` With your selection variables set, you now define the `on_stage_event()` call back to get the selected prim and its position on selection changes. You will start the new function for these below module previous code: ```python ... def on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_paths = self.selection.get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, you don't need to update anything if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return prim = self.stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): return self.current_path = prim_paths[0] # Add a Tf.Notice listener to update the position if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage) # Position is changed self._item_changed(self.position) ``` >:memo: Code Checkpoint <details> <summary> Click here for the updated <b>SliderModel</b> </summary> ```python from omni.ui import scene as sc from pxr import Tf from pxr import Gf from pxr import Usd from pxr import UsdGeom import omni.usd class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because you take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() self.position = SliderModel.PositionItem() # Current selection self.current_path = "" self.stage_listener = None self.usd_context = omni.usd.get_context() self.stage: Usd.Stage = self.usd_context.get_stage() # Track selection self.selection = self.usd_context.get_selection() self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Slider Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_paths = self.selection.get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, you don't need to update anything if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return prim = self.stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): return self.current_path = prim_paths[0] # Add a Tf.Notice listener to update the position if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage) # Position is changed self._item_changed(self.position) ``` </details> <br> ## Step 2.5: `Tf.Notice` callback In the previous step, you registered a callback to be called when objects in the stage change. [Click here for more information on Tf.Notice.](https://graphics.pixar.com/usd/dev/api/page_tf__notification.html) Now, you will define the callback function. You want to update the stored position of the selected prim. You can add that as follows: ```python ... def _notice_changed(self, notice, stage): """Called by Tf.Notice""" for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) ``` ## Step 2.6: Set the Position Identifier and return Position Let's define the identifier for position like so: ```python ... def get_item(self, identifier): if identifier == "position": return self.position ``` And now, you will set item to return the position and get the value from the item: ```python ... def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] ``` >:memo: Code Checkpoint <details> <summary> Click here for the updated <b>SliderModel</b> </summary> ```python from omni.ui import scene as sc from pxr import Tf from pxr import Gf from pxr import Usd from pxr import UsdGeom import omni.usd class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because you take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() self.position = SliderModel.PositionItem() # Current selection self.current_path = "" self.stage_listener = None self.usd_context = omni.usd.get_context() self.stage: Usd.Stage = self.usd_context.get_stage() # Track selection self.selection = self.usd_context.get_selection() self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Slider Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_paths = self.selection.get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, you don't need to update anything if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return prim = self.stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): return self.current_path = prim_paths[0] # Add a Tf.Notice listener to update the position if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage) # Position is changed self._item_changed(self.position) def _notice_changed(self, notice, stage): """Called by Tf.Notice""" for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] ``` </details> ### Step 2.7: Position from USD In this last section of `slider_model.py`, you will be defining `get_position` to compute position directly from USD, like so: ```python ... def get_position(self): """Returns position of currently selected object""" if not self.current_path: return [0, 0, 0] # Get position directly from USD prim = self.stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5 y_Pos = (bboxMax[1] + 10) z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5 position = [x_Pos, y_Pos, z_Pos] return position ``` >:memo: Code Checkpoint <details> <summary> Click here for the full <b>slider_model.py</b> </summary> ```python from omni.ui import scene as sc from pxr import Tf from pxr import Gf from pxr import Usd from pxr import UsdGeom import omni.usd class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because you take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() self.position = SliderModel.PositionItem() # Current selection self.current_path = "" self.stage_listener = None self.usd_context = omni.usd.get_context() self.stage: Usd.Stage = self.usd_context.get_stage() # Track selection self.selection = self.usd_context.get_selection() self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Slider Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_paths = self.selection.get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, you don't need to update anything if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return prim = self.stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): return self.current_path = prim_paths[0] # Add a Tf.Notice listener to update the position if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage) # Position is changed self._item_changed(self.position) def _notice_changed(self, notice, stage): """Called by Tf.Notice""" for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] def get_position(self): """Returns position of currently selected object""" if not self.current_path: return [0, 0, 0] # Get position directly from USD prim = self.stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5 y_Pos = (bboxMax[1] + 10) z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5 position = [x_Pos, y_Pos, z_Pos] return position ``` </details> ## Step 3: Manipulator Module In this step, you will be creating `slider_manipulator.py` in the same folder as `slider_model.py`. The Manipulator class will define `on_build()` as well as create the `Label` and regenerate the model. ### Step 3.1: Import omni.ui After creating `slider_manipulator.py`, import `omni.ui` as follows: ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui ``` ### Step 3.2: Create `SliderManipulator` class Now, you will begin the `SliderManipulator` class and define the `__init__()`: ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) ``` ### Step 3.3: Define `on_build()` and create the `Label` `on_build()` is called when the model is changed and it will rebuild the slider. You will also create the `Label` for the slider and position it more towards the top of the screen. ```python ... def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return value = 0.0 position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) ``` ### Step 3.4: Regenerate the Manipulator Finally, let's define `on_model_updated()` to regenerate the manipulator: ```python ... def on_model_updated(self, item): # Regenerate the manipulator self.invalidate() ``` >:memo: Code Checkpoint <details> <summary>Click here for the full <b>slider_manipulator.py</b> </summary> ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return value = 0.0 position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) def on_model_updated(self, item): # Regenerate the manipulator self.invalidate() ``` </details> <br> <br> ## Step 4: Registry Module In this step, you will create `slider_registry.py` in the same location as the `slider_manipulator.py`. You will use `slider_registry.py` to have the number display on the screen when the prim is selected. ### Step 4.1: Import from Model and Manipulator After creating `slider_registry.py`, import from the `SliderModel` and `SliderManipulator`, as well as `import typing` for type hinting, like so: ```python from .slider_model import SliderModel from .slider_manipulator import SliderManipulator from typing import Any from typing import Dict from typing import Optional ``` ### Step 4.2: Disable Selection in Viewport Legacy Your first class will address disabling the selection in viewport legacy but you may encounter a bug that will not set your focused window to `True`. As a result, you will operate all `Viewport` instances for a given usd_context instead: ```python ... class ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact the focused window! # And there's no good solution to this when multiple Viewport-1 instances are open; so you just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass ``` ### Step 4.3: `SliderChangedGesture` Class Under your previously defined `ViewportLegacyDisableSelection` class, you will define `SliderChangedGesture` class. In this class you will start with `__init__()` and then define `on_began()`, which will disable the selection rect when the user drags the slider: ```python class SliderChangedGesture(SliderManipulator.SliderChangedGesture): """User part. Called when slider is changed.""" def __init__(self, **kwargs): super().__init__(**kwargs) def on_began(self): # When the user drags the slider, you don't want to see the selection rect self.__disable_selection = ViewportLegacyDisableSelection() ``` Next in this class, you will define `on_changed()`, which will be called when the user moves the slider. This will update the mesh as the scale of the model is changed. You will also define `on_ended()` to re-enable the selection rect when the slider is not being dragged. ```python def on_changed(self): """Called when the user moved the slider""" if not hasattr(self.gesture_payload, "slider_value"): return # The current slider value is in the payload. slider_value = self.gesture_payload.slider_value # Change the model. Slider watches it and it will update the mesh. self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value]) def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None ``` >:memo: Code Checkpoint <details> <summary>Click here for <b>slider_registry.py</b> up to this point</summary> ```python from .slider_model import SliderModel from .slider_manipulator import SliderManipulator from typing import Any from typing import Dict from typing import Optional class ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact the focused window! # And there's no good solution to this when multiple Viewport-1 instances are open; so you just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass class SliderChangedGesture(SliderManipulator.SliderChangedGesture): """User part. Called when slider is changed.""" def __init__(self, **kwargs): super().__init__(**kwargs) def on_began(self): # When the user drags the slider, you don't want to see the selection rect self.__disable_selection = ViewportLegacyDisableSelection() def on_changed(self): """Called when the user moved the slider""" if not hasattr(self.gesture_payload, "slider_value"): return # The current slider value is in the payload. slider_value = self.gesture_payload.slider_value # Change the model. Slider watches it and it will update the mesh. self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value]) def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None ``` </details> ### Step 4.4: `SliderRegistry` Class Now create `SliderRegistry` class after your previous functions. This class is created by `omni.kit.viewport.registry` or `omni.kit.manipulator.viewport` per viewport and will keep the manipulator and some other properties that are needed in the viewport. You will set the `SliderRegistry` class after the class you made in the previous step. Included in this class are the `__init__()` methods for your manipulator and some getters and setters: ```python ... class SliderRegistry: """ Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per viewport. Keeps the manipulator and some properties that are needed to the viewport. """ def __init__(self, description: Optional[Dict[str, Any]] = None): self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture()) def destroy(self): if self.__slider_manipulator: self.__slider_manipulator.destroy() self.__slider_manipulator = None # PrimTransformManipulator & TransformManipulator don't have their own visibility @property def visible(self): return True @visible.setter def visible(self, value): pass @property def categories(self): return ("manipulator",) @property def name(self): return "Example Slider Manipulator" ``` >:memo: Code Checkpoint <details> <summary>Click here for the full <b>slider_registry.py</b> </summary> ```python from .slider_model import SliderModel from .slider_manipulator import SliderManipulator from typing import Any from typing import Dict from typing import Optional class ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact the focused window! # And there's no good solution to this when mutliple Viewport-1 instances are open; so you just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass class SliderChangedGesture(SliderManipulator.SliderChangedGesture): """User part. Called when slider is changed.""" def __init__(self, **kwargs): super().__init__(**kwargs) def on_began(self): # When the user drags the slider, you don't want to see the selection rect self.__disable_selection = ViewportLegacyDisableSelection() def on_changed(self): """Called when the user moved the slider""" if not hasattr(self.gesture_payload, "slider_value"): return # The current slider value is in the payload. slider_value = self.gesture_payload.slider_value # Change the model. Slider watches it and it will update the mesh. self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value]) def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None class SliderRegistry: """ Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per viewport. Keeps the manipulator and some properties that are needed to the viewport. """ def __init__(self, description: Optional[Dict[str, Any]] = None): self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture()) def destroy(self): if self.__slider_manipulator: self.__slider_manipulator.destroy() self.__slider_manipulator = None # PrimTransformManipulator & TransformManipulator don't have their own visibility @property def visible(self): return True @visible.setter def visible(self, value): pass @property def categories(self): return ("manipulator",) @property def name(self): return "Example Slider Manipulator" ``` </details> <br> <br> ## Step 5: Update `extension.py` You still have the default code in `extension.py` so now you will update the code to reflect the the modules you made. You can locate the `extension.py` in the `exts` folder hierarchy where you created `slider_model.py` and `slider_manipulator.py`. ### Step 5.1: New `extension.py` Imports Let's begin by updating the imports at the top of `extension.py` to include `ManipulatorFactory`, `RegisterScene`, and `SliderRegistry` so that you can use them later on: ```python import omni.ext # NEW from omni.kit.manipulator.viewport import ManipulatorFactory from omni.kit.viewport.registry import RegisterScene from .slider_registry import SliderRegistry # END NEW ``` ### Step 5.2: References in on_startup In this step, you will remove the default code in `on_startup` and replace it with a reference to the `slider_registry` and `slider_factory`, like so: ```python ... class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): # NEW self.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider") self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry) # END NEW ``` ### Step 5.3: Update on_shutdown Now, you need to properly shutdown the extension. Let's remove the print statement and replace it with: ```python ... def on_shutdown(self): # NEW ManipulatorFactory.destroy_manipulator(self.slider_factory) self.slider_factory = None self.slider_registry.destroy() self.slider_registry = None # END NEW ``` >:memo: Code Checkpoint <details> <summary>Click here for the full <b>extension.py</b></summary> ```python import omni.ext from omni.kit.manipulator.viewport import ManipulatorFactory from omni.kit.viewport.registry import RegisterScene from .slider_registry import SliderRegistry class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): self.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider") self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry) def on_shutdown(self): ManipulatorFactory.destroy_manipulator(self.slider_factory) self.slider_factory = None self.slider_registry.destroy() self.slider_registry = None ``` </details> This is what you should see at this point in the viewport: ![](./Images/step5EndView.png) ## Step 6: Creating the Slider Widget Now that you have all of the variables and necessary properties referenced, let's start to create the slider widget. You will begin by creating the geometry needed for the widget, like the line, and then you will add a circle to the line. ### Step 6.1: Geometry Properties You are going to begin by adding new geometry to `slider_manipulator.py`. You will set the geometry properties in the `__init__()` like so: ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) # NEW # Geometry properties self.width = 100 self.thickness = 5 self._radius = 5 self._radius_hovered = 7 # END NEW ``` ### Step 6.2: Create the line Next, you will create a line above the selected prim. Let's add this to `on_build()`: ```python ... def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return value = 0.0 position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # NEW # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * 1 - self._radius if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # END NEW # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) ``` This should be the result in your viewport: ![](./Images/step6Result.png) ### Step 6.3: Create the circle You are still working in `slider_manipulator.py` and now you will be adding the circle on the line for the slider. This will also be added to `on_build()` like so: ```python ... def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return value = 0.0 position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * 1 - self.radius if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # NEW # Circle circle_position = -self.width * 0.5 + self.width * 1 with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)): radius = self._radius sc.Arc(radius, axis=2, color=cl.gray) # END NEW ... ``` Now, your line in your viewport should look like this: ![](./Images/step6CircleResult.png) <details> <summary>Click here for the full <b>slider_manipulatory.py</b></summary> ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) # Geometry properties self.width = 100 self.thickness = 5 self.radius = 5 self.radius_hovered = 7 def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return value = 0.0 position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * 1 - self._radius if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # Circle circle_position = -self.width * 0.5 + self.width * 1 with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)): radius = self._radius sc.Arc(radius, axis=2, color=cl.gray) # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) def on_model_updated(self, item): # Regenerate the manipulator self.invalidate() ``` </details> <br> ## Step 7: Set up the Model For this step, you will need to set up `SliderModel` to hold the information you need for the size of the selected prim. You will later use this information to connect it to the Manipulator. ### Step 7.1: Import Omniverse Command Library First, let's start by importing the Omniverse Command Library in `slider_model.py` ```python from omni.ui import scene as sc from pxr import Tf from pxr import Gf from pxr import Usd from pxr import UsdGeom import omni.usd # NEW IMPORT import omni.kit.commands # END NEW ``` ### Step 7.2: ValueItem Class Next, you will add a new Manipulator Item class, which you will name `ValueItem`, like so: ```python ... class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because you take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] # NEW MANIPULATOR ITEM class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value""" def __init__(self, value=0): super().__init__() self.value = [value] # END NEW ... ``` You will use this new class to create the variables for the min and max of the scale: ```python ... class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value""" def __init__(self, value=0): super().__init__() self.value = [value] def __init__(self) -> None: super().__init__() # NEW self.scale = SliderModel.ValueItem() self.min = SliderModel.ValueItem() self.max = SliderModel.ValueItem(1) # END NEW self.position = SliderModel.PositionItem() ... ``` ### Step 7.3: Set Scale to Stage With the new variables for the scale, populate them in `on_stage_event()` like so: ```python ... def on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_paths = self.selection.get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, you don't need to update anything if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return prim = self.stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): return self.current_path = prim_paths[0] # NEW (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim) scale = old_scale[0] _min = scale * 0.1 _max = scale * 2.0 self.set_floats(self.min, [_min]) self.set_floats(self.max, [_max]) self.set_floats(self.scale, [scale]) # END NEW # Add a Tf.Notice listener to update the position if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage) # Position is changed self._item_changed(self.position) ... ``` >:memo: Code Checkpoint <details> <summary>Click here for the updated <b>slider_model.py</b> at this point </summary> ```python from omni.ui import scene as sc from pxr import Tf from pxr import Gf from pxr import Usd from pxr import UsdGeom import omni.usd import omni.kit.commands class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because you take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value""" def __init__(self, value=0): super().__init__() self.value = [value] def __init__(self) -> None: super().__init__() self.scale = SliderModel.ValueItem() self.min = SliderModel.ValueItem() self.max = SliderModel.ValueItem(1) self.position = SliderModel.PositionItem() # Current selection self.current_path = "" self.stage_listener = None self.usd_context = omni.usd.get_context() self.stage: Usd.Stage = self.usd_context.get_stage() # Track selection self.selection = self.usd_context.get_selection() self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Slider Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_paths = self.selection.get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, you don't need to update anything if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return prim = self.stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): return self.current_path = prim_paths[0] (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim) scale = old_scale[0] _min = scale * 0.1 _max = scale * 2.0 self.set_floats(self.min, [_min]) self.set_floats(self.max, [_max]) self.set_floats(self.scale, [scale]) # Add a Tf.Notice listener to update the position if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage) # Position is changed self._item_changed(self.position) def _notice_changed(self, notice, stage): """Called by Tf.Notice""" for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] def get_position(self): """Returns position of currently selected object""" if not self.current_path: return [0, 0, 0] # Get position directly from USD prim = self.stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5 y_Pos = (bboxMax[1] + 10) z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5 position = [x_Pos, y_Pos, z_Pos] return position ``` </details> ### Step 7.4: Define Identifiers Just as you defined the identifier for position, you must do the same for value, min, and max. You will add these to `get_item`: ```python ... def get_item(self, identifier): if identifier == "position": return self.position # NEW if identifier == "value": return self.scale if identifier == "min": return self.min if identifier == "max": return self.max # END NEW ... ``` ### Step 7.5: Set Floats Previously, you called `set_floats()`, now define it after `get_item()`. In this function, you will set the scale when setting the value, set directly to the item, and update the manipulator: ```python def set_floats(self, item, value): if not self.current_path: return if not value or not item or item.value == value: return if item == self.scale: # Set the scale when setting the value. value[0] = min(max(value[0], self.min.value[0]), self.max.value[0]) (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT( self.stage.GetPrimAtPath(self.current_path) ) omni.kit.commands.execute( "TransformPrimSRTCommand", path=self.current_path, new_translation=old_translation, new_rotation_euler=old_rotation_euler, new_scale=Gf.Vec3d(value[0], value[0], value[0]), ) # Set directly to the item item.value = value # This makes the manipulator updated self._item_changed(item) ``` <details> <summary>Click here for the full <b>slider_model.py</b> </summary> ```python from omni.ui import scene as sc from pxr import Tf from pxr import Gf from pxr import Usd from pxr import UsdGeom import omni.usd import omni.kit.commands class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because you take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value""" def __init__(self, value=0): super().__init__() self.value = [value] def __init__(self) -> None: super().__init__() self.scale = SliderModel.ValueItem() self.min = SliderModel.ValueItem() self.max = SliderModel.ValueItem(1) self.position = SliderModel.PositionItem() # Current selection self.current_path = "" self.stage_listener = None self.usd_context = omni.usd.get_context() self.stage: Usd.Stage = self.usd_context.get_stage() # Track selection self.selection = self.usd_context.get_selection() self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Slider Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_paths = self.selection.get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, you don't need to update anything if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return prim = self.stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): return self.current_path = prim_paths[0] (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim) scale = old_scale[0] _min = scale * 0.1 _max = scale * 2.0 self.set_floats(self.min, [_min]) self.set_floats(self.max, [_max]) self.set_floats(self.scale, [scale]) # Add a Tf.Notice listener to update the position if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage) # Position is changed self._item_changed(self.position) def _notice_changed(self, notice, stage): """Called by Tf.Notice""" for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position if identifier == "value": return self.scale if identifier == "min": return self.min if identifier == "max": return self.max def set_floats(self, item, value): if not self.current_path: return if not value or not item or item.value == value: return if item == self.scale: # Set the scale when setting the value. value[0] = min(max(value[0], self.min.value[0]), self.max.value[0]) (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT( self.stage.GetPrimAtPath(self.current_path) ) omni.kit.commands.execute( "TransformPrimSRTCommand", path=self.current_path, new_translation=old_translation, new_rotation_euler=old_rotation_euler, new_scale=Gf.Vec3d(value[0], value[0], value[0]), ) # Set directly to the item item.value = value # This makes the manipulator updated self._item_changed(item) def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] def get_position(self): """Returns position of currently selected object""" if not self.current_path: return [0, 0, 0] # Get position directly from USD prim = self.stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5 y_Pos = (bboxMax[1] + 10) z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5 position = [x_Pos, y_Pos, z_Pos] return position ``` </details> ## Step 8: Add Gestures For your final step, you will be updating `slider_manipulator.py` to add the gestures needed to connect what you programmed in the Model. This will include checking that the gesture is not prevented during drag, calling the gesture, restructure the geometry properties, and update the Line and Circle. ### Step 8.1: `SliderDragGesturePayload` Class Begin by creating a new class that the user will access to get the current value of the slider, like so: ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): # NEW class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload): """ Public payload. The user will access it to get the current value of the slider. """ def __init__(self, base): super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance) self.slider_value = 0 ## END NEW ... ``` ### Step 8.2 `SliderChangedGesture` Class Next, you will create another new class that the user will reimplement to process the manipulator's callbacks, in addition to a new `__init__()`: ```python ... class SliderManipulator(sc.Manipulator): class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload): """ Public payload. The user will access it to get the current value of the slider. """ def __init__(self, base): super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance) self.slider_value = 0 # NEW class SliderChangedGesture(sc.ManipulatorGesture): """ Public Gesture. The user will reimplement it to process the manipulator's callbacks. """ def __init__(self, **kwargs): super().__init__(**kwargs) # END NEW def __init__(self, **kwargs): super().__init__(**kwargs) self.width = 100 self.thickness = 5 self._radius = 5 self._radius_hovered = 7 ... ``` Nested inside of the `SliderChangedGesture` class, define `process()` directly after the `__init__()` definition of this class: ```python ... class SliderChangedGesture(sc.ManipulatorGesture): """ Public Gesture. The user will reimplement it to process the manipulator's callbacks. """ def __init__(self, **kwargs): super().__init__(**kwargs) # NEW def process(self): # Redirection to methods if self.state == sc.GestureState.BEGAN: self.on_began() elif self.state == sc.GestureState.CHANGED: self.on_changed() elif self.state == sc.GestureState.ENDED: self.on_ended() # END NEW def __init__(self, **kwargs): super().__init__(**kwargs) self.width = 100 self.thickness = 5 self._radius = 5 self._radius_hovered = 7 ``` >:memo:Code Checkpoint <details> <summary>Click here for the updated <b>slider_manipulator.py</b> at this point </summary> ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload): """ Public payload. The user will access it to get the current value of the slider. """ def __init__(self, base): super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance) self.slider_value = 0 class SliderChangedGesture(sc.ManipulatorGesture): """ Public Gesture. The user will reimplement it to process the manipulator's callbacks. """ def __init__(self, **kwargs): super().__init__(**kwargs) def process(self): # Redirection to methods if self.state == sc.GestureState.BEGAN: self.on_began() elif self.state == sc.GestureState.CHANGED: self.on_changed() elif self.state == sc.GestureState.ENDED: self.on_ended() def __init__(self, **kwargs): super().__init__(**kwargs) self.width = 100 self.thickness = 5 self._radius = 5 self._radius_hovered = 7 def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return value = 0.0 position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * 1 - self._radius if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # Circle circle_position = -self.width * 0.5 + self.width * 1 with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)): radius = self._radius sc.Arc(radius, axis=2, color=cl.gray) # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) def on_model_updated(self, item): # Regenerate the manipulator self.invalidate() ``` </details> Now, you need to define a few of the Public API functions after the `process` function: ```python def process(self): # Redirection to methods if self.state == sc.GestureState.BEGAN: self.on_began() elif self.state == sc.GestureState.CHANGED: self.on_changed() elif self.state == sc.GestureState.ENDED: self.on_ended() # NEW # Public API: def on_began(self): pass def on_changed(self): pass def on_ended(self): pass # END NEW ``` ### Step 8.3 `_ArcGesturePrioritize` Class You will be adding an `_ArcGesture` class in the next step that needs the manager `_ArcGesturePrioritize` to make it the priority gesture. You will add the manager first to make sure the drag of the slider is not prevented during drag. You will slot this new class after your Public API functions: ```python # Public API: def on_began(self): pass def on_changed(self): pass def on_ended(self): pass # NEW class _ArcGesturePrioritize(sc.GestureManager): """ Manager makes _ArcGesture the priority gesture """ def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if isinstance(preventer, SliderManipulator._ArcGesture): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True # END NEW ``` ### Step 8.4: `_ArcGesture` Class Now, create the class `_ArcGesture` where you will set the new slider value and redirect to `SliderChangedGesture` class you made previously. This new class will be after the `ArcGesturePrioritize` manager class. ```python class _ArcGesturePrioritize(sc.GestureManager): """ Manager makes _ArcGesture the priority gesture """ def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if isinstance(preventer, SliderManipulator._ArcGesture): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True # NEW class _ArcGesture(sc.DragGesture): """ Internal gesture that sets the new slider value and redirects to public SliderChangedGesture. """ def __init__(self, manipulator): super().__init__(manager=SliderManipulator._ArcGesturePrioritize()) self._manipulator = manipulator def __repr__(self): return f"<_ArcGesture at {hex(id(self))}>" def process(self): if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]: # Form new gesture_payload object new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload) # Save the new slider position in the gesture_payload object object_ray_point = self._manipulator.transform_space( sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point ) center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position")) slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5 _min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0] _max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0] new_gesture_payload.slider_value = _min + slider_value * (_max - _min) # Call the public gesture self._manipulator._process_gesture( SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload ) # Base process of the gesture super().process() # END NEW ``` >:memo:Code Checkpoint <details> <summary>Click here for the updated <b>slider_manipulator.py</b> at this point </summary> ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload): """ Public payload. The user will access it to get the current value of the slider. """ def __init__(self, base): super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance) self.slider_value = 0 class SliderChangedGesture(sc.ManipulatorGesture): """ Public Gesture. The user will reimplement it to process the manipulator's callbacks. """ def __init__(self, **kwargs): super().__init__(**kwargs) def process(self): # Redirection to methods if self.state == sc.GestureState.BEGAN: self.on_began() elif self.state == sc.GestureState.CHANGED: self.on_changed() elif self.state == sc.GestureState.ENDED: self.on_ended() # Public API: def on_began(self): pass def on_changed(self): pass def on_ended(self): pass class _ArcGesturePrioritize(sc.GestureManager): """ Manager makes _ArcGesture the priority gesture """ def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if isinstance(preventer, SliderManipulator._ArcGesture): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True class _ArcGesture(sc.DragGesture): """ Internal gesture that sets the new slider value and redirects to public SliderChangedGesture. """ def __init__(self, manipulator): super().__init__(manager=SliderManipulator._ArcGesturePrioritize()) self._manipulator = manipulator def __repr__(self): return f"<_ArcGesture at {hex(id(self))}>" def process(self): if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]: # Form new gesture_payload object new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload) # Save the new slider position in the gesture_payload object object_ray_point = self._manipulator.transform_space( sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point ) center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position")) slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5 _min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0] _max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0] new_gesture_payload.slider_value = _min + slider_value * (_max - _min) # Call the public gesture self._manipulator._process_gesture( SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload ) # Base process of the gesture super().process() def __init__(self, **kwargs): super().__init__(**kwargs) self.width = 100 self.thickness = 5 self._radius = 5 self._radius_hovered = 7 def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return value = 0.0 position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * 1 - self._radius if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # Circle circle_position = -self.width * 0.5 + self.width * 1 with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)): radius = self._radius sc.Arc(radius, axis=2, color=cl.gray) # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) def on_model_updated(self, item): # Regenerate the manipulator self.invalidate() ``` </details> ### Step 8.5: Restructure Geometry Parameters For this step, you will be adding to `__init__()` that nests your Geometry properties, such as `width`,`thickness`,`radius`, and `radius_hovered`. >:bulb: Tip: If you are having trouble locating the geometry properties, be reminded that this `__init__()` is after the new classes you added in the previous steps. You should find it under "_ArcGesture" Start by defining `set_radius()` for the circle so that you can change it on hover later, and also set the parameters for arc_gesture to make sure it's active when the object is recreated: ```python def __init__(self, **kwargs): super().__init__(**kwargs) # Geometry properties self._width = 100 self._thickness = 5 self._radius = 5 self._radius_hovered = 7 # NEW def set_radius(circle, radius): circle.radius = radius # You don't recreate the gesture to make sure it's active when the # underlying object is recreated self._arc_gesture = self._ArcGesture(self) # END NEW ``` ### Step 8.6: Add Hover Gestures Now that you have set the geometry properties for when you hover over them, create the `HoverGesture` instance. You will set this within an `if` statement under the parameters for `self._arc_gesture`: ```python # You don't recreate the gesture to make sure it's active when the # underlying object is recreated self._arc_gesture = self._ArcGesture(self) # NEW if hasattr(sc, "HoverGesture"): self._hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_radius(sender, self._radius_hovered), on_ended_fn=lambda sender: set_radius(sender, self._radius), ) else: self._hover_gesture = None # END NEW ``` ## Step 8.7: UI Getters and Setters Before moving on, you need to add a few Python decorators for the UI, such as `@property`,`@width.setter` and `@height.setter`. These can be added after the `HoverGesture` statement from the step above: ```python def destroy(self): pass @property def width(self): return self._width @width.setter def width(self, value): self._width = value # Regenerate the mesh self.invalidate() @property def thickness(self): return self._thickness @thickness.setter def thickness(self, value): self._thickness = value # Regenerate the mesh self.invalidate() ``` >:memo: Code Checkpoint <details> <summary>Click here for the updated <b>slider_manipulator.py</b> at this point</summary> ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload): """ Public payload. The user will access it to get the current value of the slider. """ def __init__(self, base): super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance) self.slider_value = 0 class SliderChangedGesture(sc.ManipulatorGesture): """ Public Gesture. The user will reimplement it to process the manipulator's callbacks. """ def __init__(self, **kwargs): super().__init__(**kwargs) def process(self): # Redirection to methods if self.state == sc.GestureState.BEGAN: self.on_began() elif self.state == sc.GestureState.CHANGED: self.on_changed() elif self.state == sc.GestureState.ENDED: self.on_ended() # Public API: def on_began(self): pass def on_changed(self): pass def on_ended(self): pass class _ArcGesturePrioritize(sc.GestureManager): """ Manager makes _ArcGesture the priority gesture """ def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if isinstance(preventer, SliderManipulator._ArcGesture): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True class _ArcGesture(sc.DragGesture): """ Internal gesture that sets the new slider value and redirects to public SliderChangedGesture. """ def __init__(self, manipulator): super().__init__(manager=SliderManipulator._ArcGesturePrioritize()) self._manipulator = manipulator def __repr__(self): return f"<_ArcGesture at {hex(id(self))}>" def process(self): if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]: # Form new gesture_payload object new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload) # Save the new slider position in the gesture_payload object object_ray_point = self._manipulator.transform_space( sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point ) center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position")) slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5 _min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0] _max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0] new_gesture_payload.slider_value = _min + slider_value * (_max - _min) # Call the public gesture self._manipulator._process_gesture( SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload ) # Base process of the gesture super().process() def __init__(self, **kwargs): super().__init__(**kwargs) self.width = 100 self.thickness = 5 self._radius = 5 self._radius_hovered = 7 def set_radius(circle, radius): circle.radius = radius # You don't recreate the gesture to make sure it's active when the # underlying object is recreated self._arc_gesture = self._ArcGesture(self) if hasattr(sc, "HoverGesture"): self._hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_radius(sender, self._radius_hovered), on_ended_fn=lambda sender: set_radius(sender, self._radius), ) else: self._hover_gesture = None def destroy(self): pass @property def width(self): return self._width @width.setter def width(self, value): self._width = value # Regenerate the mesh self.invalidate() @property def thickness(self): return self._thickness @thickness.setter def thickness(self, value): self._thickness = value # Regenerate the mesh self.invalidate() def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return value = 0.0 position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * 1 - self._radius if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # Circle circle_position = -self.width * 0.5 + self.width * 1 with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)): radius = self._radius sc.Arc(radius, axis=2, color=cl.gray) # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) def on_model_updated(self, item): # Regenerate the manipulator self.invalidate() ``` </details> ### Step 8.8: Update `on_build()` For your final step in the Manipulator module, you will update `on_build()` to update the min and max values of the model, update the line and circle, and update the label. Start with replacing the `value` variable you had before with a new set of variables for `_min`,`_max`, new `value`, and `value_normalized`. ```python def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return ### REPLACE #### value = 0.0 ### WITH #### _min = self.model.get_as_floats(self.model.get_item("min"))[0] _max = self.model.get_as_floats(self.model.get_item("max"))[0] value = float(self.model.get_as_floats(self.model.get_item("value"))[0]) value_normalized = (value - _min) / (_max - _min) value_normalized = max(min(value_normalized, 1.0), 0.0) # END NEW position = self.model.get_as_floats(self.model.get_item("position")) ``` Now, you will add a new line to the slider so that you have a line for when the slider is moved to the left and to the right. Locate just below your previously set parameters the `Left Line` you created in `Step 6.2`. Before you add the new line, replace the `1` in `line_to` with your new parameter `value_normalized`. Then add the `Right Line` below the `Left Line`, as so: ```python with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * value_normalized - self._radius # REPLACED THE 1 WITH value_normalized if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # NEW: same as left line but flipped # Right line line_from = -self.width * 0.5 + self.width * value_normalized + self._radius line_to = self.width * 0.5 if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # END NEW ``` Next, update the circle to add the `hover_gesture`. This will increase the circle in size when hovered over. Also change the `1` value like you did for `Line` to `value_normalized` and also add the gesture to `sc.Arc`: ```python # Circle # NEW : Changed 1 value to value_normalized circle_position = -self.width * 0.5 + self.width * value_normalized with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)): radius = self._radius # NEW: Added Gesture when hovering over the circle it will increase in size gestures = [self._arc_gesture] if self._hover_gesture: gestures.append(self._hover_gesture) if self._hover_gesture.state == sc.GestureState.CHANGED: radius = self._radius_hovered sc.Arc(radius, axis=2, color=cl.gray, gestures=gestures) # END NEW ``` Last of all, update the `Label` below your circle to add more space between the slider and the label: ```python with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): # NEW: Added more space between the slider and the label # Move it to the top with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)): # END NEW with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) ``` >:memo: Code Checkpoint <details> <summary>Click here for the full <b>slider_manipulator.py</b></summary> ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload): """ Public payload. The user will access it to get the current value of the slider. """ def __init__(self, base): super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance) self.slider_value = 0 class SliderChangedGesture(sc.ManipulatorGesture): """ Public Gesture. The user will reimplement it to process the manipulator's callbacks. """ def __init__(self, **kwargs): super().__init__(**kwargs) def process(self): # Redirection to methods if self.state == sc.GestureState.BEGAN: self.on_began() elif self.state == sc.GestureState.CHANGED: self.on_changed() elif self.state == sc.GestureState.ENDED: self.on_ended() # Public API: def on_began(self): pass def on_changed(self): pass def on_ended(self): pass class _ArcGesturePrioritize(sc.GestureManager): """ Manager makes _ArcGesture the priority gesture """ def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if isinstance(preventer, SliderManipulator._ArcGesture): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True class _ArcGesture(sc.DragGesture): """ Internal gesture that sets the new slider value and redirects to public SliderChangedGesture. """ def __init__(self, manipulator): super().__init__(manager=SliderManipulator._ArcGesturePrioritize()) self._manipulator = manipulator def __repr__(self): return f"<_ArcGesture at {hex(id(self))}>" def process(self): if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]: # Form new gesture_payload object new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload) # Save the new slider position in the gesture_payload object object_ray_point = self._manipulator.transform_space( sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point ) center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position")) slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5 _min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0] _max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0] new_gesture_payload.slider_value = _min + slider_value * (_max - _min) # Call the public gesture self._manipulator._process_gesture( SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload ) # Base process of the gesture super().process() def __init__(self, **kwargs): super().__init__(**kwargs) self.width = 100 self.thickness = 5 self._radius = 5 self._radius_hovered = 7 def set_radius(circle, radius): circle.radius = radius # You don't recreate the gesture to make sure it's active when the # underlying object is recreated self._arc_gesture = self._ArcGesture(self) if hasattr(sc, "HoverGesture"): self._hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_radius(sender, self._radius_hovered), on_ended_fn=lambda sender: set_radius(sender, self._radius), ) else: self._hover_gesture = None def destroy(self): pass @property def width(self): return self._width @width.setter def width(self, value): self._width = value # Regenerate the mesh self.invalidate() @property def thickness(self): return self._thickness @thickness.setter def thickness(self, value): self._thickness = value # Regenerate the mesh self.invalidate() def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If you don't have a selection then just return if self.model.get_item("name") == "": return _min = self.model.get_as_floats(self.model.get_item("min"))[0] _max = self.model.get_as_floats(self.model.get_item("max"))[0] value = float(self.model.get_as_floats(self.model.get_item("value"))[0]) value_normalized = (value - _min) / (_max - _min) value_normalized = max(min(value_normalized, 1.0), 0.0) position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * value_normalized - self._radius # REPLACED THE 1 WITH value_normalized if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # NEW: same as left line but flipped # Right line line_from = -self.width * 0.5 + self.width * value_normalized + self._radius line_to = self.width * 0.5 if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # Circle circle_position = -self.width * 0.5 + self.width * value_normalized with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)): radius = self._radius gestures = [self._arc_gesture] if self._hover_gesture: gestures.append(self._hover_gesture) if self._hover_gesture.state == sc.GestureState.CHANGED: radius = self._radius_hovered sc.Arc(radius, axis=2, color=cl.gray) # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): # NEW: Added more space between the slider and the label # Move it to the top with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)): # END NEW with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) def on_model_updated(self, item): # Regenerate the manipulator self.invalidate() ``` </details> <br> <br> >:exclamation: If you are running into any errors in the Console, disable `Autoload` in the `Extension Manager` and restart Omniverse Code. ### Step 8.9: Completion Congratulations! You have completed the guide `How to make a Slider Manipulator` and now have a working scale slider!
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_manipulator.py
from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload): """ Public payload. The user will access it to get the current value of the slider. """ def __init__(self, base): super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance) self.slider_value = 0 class SliderChangedGesture(sc.ManipulatorGesture): """ Public Gesture. The user will reimplement it to process the manipulator's callbacks. """ def __init__(self, **kwargs): super().__init__(**kwargs) def process(self): # Redirection to methods if self.state == sc.GestureState.BEGAN: self.on_began() elif self.state == sc.GestureState.CHANGED: self.on_changed() elif self.state == sc.GestureState.ENDED: self.on_ended() # Public API: def on_began(self): pass def on_changed(self): pass def on_ended(self): pass class _ArcGesturePrioritize(sc.GestureManager): """ Manager makes _ArcGesture the priority gesture """ def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if isinstance(preventer, SliderManipulator._ArcGesture): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True class _ArcGesture(sc.DragGesture): """ Internal gesture that sets the new slider value and redirects to public SliderChangedGesture. """ def __init__(self, manipulator): super().__init__(manager=SliderManipulator._ArcGesturePrioritize()) self._manipulator = manipulator def __repr__(self): return f"<_ArcGesture at {hex(id(self))}>" def process(self): if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]: # Form new gesture_payload object new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload) # Save the new slider position in the gesture_payload object object_ray_point = self._manipulator.transform_space( sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point ) center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position")) slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5 _min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0] _max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0] new_gesture_payload.slider_value = _min + slider_value * (_max - _min) # Call the public gesture self._manipulator._process_gesture( SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload ) # Base process of the gesture super().process() def __init__(self, **kwargs): super().__init__(**kwargs) self.width = 100 self.thickness = 5 self._radius = 5 self._radius_hovered = 7 def set_radius(circle, radius): circle.radius = radius # We don't recreate the gesture to make sure it's active when the # underlying object is recreated self._arc_gesture = self._ArcGesture(self) if hasattr(sc, "HoverGesture"): self._hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_radius(sender, self._radius_hovered), on_ended_fn=lambda sender: set_radius(sender, self._radius), ) else: self._hover_gesture = None def destroy(self): pass @property def width(self): return self._width @width.setter def width(self, value): self._width = value # Regenerate the mesh self.invalidate() @property def thickness(self): return self._thickness @thickness.setter def thickness(self, value): self._thickness = value # Regenerate the mesh self.invalidate() def on_build(self): """Called when the model is changed and rebuilds the whole slider""" if not self.model: return # If we don't have a selection then just return if self.model.get_item("name") == "": return _min = self.model.get_as_floats(self.model.get_item("min"))[0] _max = self.model.get_as_floats(self.model.get_item("max"))[0] value = float(self.model.get_as_floats(self.model.get_item("value"))[0]) value_normalized = (value - _min) / (_max - _min) value_normalized = max(min(value_normalized, 1.0), 0.0) position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * value_normalized - self._radius if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # NEW: same as left line but flipped # Right line line_from = -self.width * 0.5 + self.width * value_normalized + self._radius line_to = self.width * 0.5 if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # Circle circle_position = -self.width * 0.5 + self.width * value_normalized with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)): radius = self._radius # NEW: Added Gesture when hovering over the circle it will increase in size gestures = [self._arc_gesture] if self._hover_gesture: gestures.append(self._hover_gesture) if self._hover_gesture.state == sc.GestureState.CHANGED: radius = self._radius_hovered sc.Arc(radius, axis=2, color=cl.gray, gestures=gestures) # END NEW # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): # NEW: Added more space between the slider and the label # Move it to the top with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)): # END NEW with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) def on_model_updated(self, item): # Regenerate the manipulator self.invalidate()
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_registry.py
from .slider_model import SliderModel from .slider_manipulator import SliderManipulator from typing import Any from typing import Dict from typing import Optional class ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact the focused window! # And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass class SliderChangedGesture(SliderManipulator.SliderChangedGesture): """User part. Called when slider is changed.""" def __init__(self, **kwargs): super().__init__(**kwargs) def on_began(self): # When the user drags the slider, we don't want to see the selection rect self.__disable_selection = ViewportLegacyDisableSelection() def on_changed(self): """Called when the user moved the slider""" if not hasattr(self.gesture_payload, "slider_value"): return # The current slider value is in the payload. slider_value = self.gesture_payload.slider_value # Change the model. Slider watches it and it will update the mesh. self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value]) def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None class SliderRegistry: """ Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per viewport. Keeps the manipulator and some properties that are needed to the viewport. """ def __init__(self, description: Optional[Dict[str, Any]] = None): self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture()) def destroy(self): if self.__slider_manipulator: self.__slider_manipulator.destroy() self.__slider_manipulator = None # PrimTransformManipulator & TransformManipulator don't have their own visibility @property def visible(self): return True @visible.setter def visible(self, value): pass @property def categories(self): return ("manipulator",) @property def name(self): return "Example Slider Manipulator"
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/extension.py
import omni.ext from omni.kit.manipulator.viewport import ManipulatorFactory from omni.kit.viewport.registry import RegisterScene from .slider_registry import SliderRegistry class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): self.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider") self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry) def on_shutdown(self): ManipulatorFactory.destroy_manipulator(self.slider_factory) self.slider_factory = None self.slider_registry.destroy() self.slider_registry = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_model.py
from omni.ui import scene as sc from pxr import Tf from pxr import Usd from pxr import UsdGeom import omni.usd import omni.kit.commands from pxr import Gf class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because we take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value""" def __init__(self, value=0): super().__init__() self.value = [value] def __init__(self) -> None: super().__init__() self.scale = SliderModel.ValueItem() self.min = SliderModel.ValueItem() self.max = SliderModel.ValueItem(1) self.position = SliderModel.PositionItem() # Current selection self.current_path = "" self.stage_listener = None self.usd_context = omni.usd.get_context() self.stage: Usd.Stage = self.usd_context.get_stage() # Track selection self.selection = self.usd_context.get_selection() self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Slider Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_paths = self.selection.get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, we don't need to update anything if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return prim = self.stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): return self.current_path = prim_paths[0] (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim) scale = old_scale[0] _min = scale * 0.1 _max = scale * 2.0 self.set_floats(self.min, [_min]) self.set_floats(self.max, [_max]) self.set_floats(self.scale, [scale]) # Add a Tf.Notice listener to update the position if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage) # Position is changed self._item_changed(self.position) def _notice_changed(self, notice, stage): """Called by Tf.Notice""" for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position if identifier == "value": return self.scale if identifier == "min": return self.min if identifier == "max": return self.max def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] def set_floats(self, item, value): if not self.current_path: return if not value or not item or item.value == value: return if item == self.scale: # Set the scale when setting the value. value[0] = min(max(value[0], self.min.value[0]), self.max.value[0]) (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT( self.stage.GetPrimAtPath(self.current_path) ) omni.kit.commands.execute( "TransformPrimSRTCommand", path=self.current_path, new_translation=old_translation, new_rotation_euler=old_rotation_euler, new_scale=Gf.Vec3d(value[0], value[0], value[0]), ) # Set directly to the item item.value = value # This makes the manipulator updated self._item_changed(item) def get_position(self): """Returns position of currently selected object""" if not self.current_path: return [0, 0, 0] # Get position directly from USD prim = self.stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5 y_Pos = (bboxMax[1] + 10) z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5 position = [x_Pos, y_Pos, z_Pos] return position
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/config/extension.toml
[package] version = "1.2.1" authors = ["Victor Yudin <[email protected]>"] title = "Omni.UI Scene Slider Example" description="The interactive example of the slider manipulator with omni.ui.scene" readme = "docs/README.md" repository="https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene" category = "Documentation" keywords = ["ui", "example", "scene", "docs", "documentation", "slider"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.kit.manipulator.viewport" = {} "omni.kit.viewport.registry" = {} "omni.ui.scene" = {} "omni.usd" = {} [[python.module]] name = "omni.example.ui_scene.slider_manipulator"
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/slider_manipulator.py
## Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["SliderManipulator"] from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class SliderManipulator(sc.Manipulator): class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload): """ Public payload. The user will access it to get the current value of the slider. """ def __init__(self, base): super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance) self.slider_value = 0 class SliderChangedGesture(sc.ManipulatorGesture): """ Public Gesture. The user will reimplement it to process the manipulator's callbacks. """ def __init__(self, **kwargs): super().__init__(**kwargs) def process(self): # Redirection to methods if self.state == sc.GestureState.BEGAN: self.on_began() elif self.state == sc.GestureState.CHANGED: self.on_changed() elif self.state == sc.GestureState.ENDED: self.on_ended() # Public API: def on_began(self): pass def on_changed(self): pass def on_ended(self): pass class _ArcGesturePrioritize(sc.GestureManager): """ Manager makes _ArcGesture the priority gesture """ def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if isinstance(preventer, SliderManipulator._ArcGesture): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True class _ArcGesture(sc.DragGesture): """ Internal gesture that sets the new slider value and redirects to public SliderChangedGesture. """ def __init__(self, manipulator): super().__init__(manager=SliderManipulator._ArcGesturePrioritize()) self._manipulator = manipulator def __repr__(self): return f"<_ArcGesture at {hex(id(self))}>" def process(self): if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]: # Form new gesture_payload object new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload) # Save the new slider position in the gesture_payload object object_ray_point = self._manipulator.transform_space( sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point ) center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position")) slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5 _min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0] _max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0] new_gesture_payload.slider_value = _min + slider_value * (_max - _min) # Call the public gesture self._manipulator._process_gesture( SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload ) # Base process of the gesture super().process() def __init__(self, **kwargs): super().__init__(**kwargs) # Geometry properties self._width = 100 self._thickness = 5 self._radius = 5 self._radius_hovered = 7 def set_radius(circle, radius): circle.radius = radius # We don't recreate the gesture to make sure it's active when the # underlying object is recreated self._arc_gesture = self._ArcGesture(self) # Compatibility with old versions of ui.scene if hasattr(sc, "HoverGesture"): self._hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_radius(sender, self._radius_hovered), on_ended_fn=lambda sender: set_radius(sender, self._radius), ) else: self._hover_gesture = None def destroy(self): pass @property def width(self): return self._width @width.setter def width(self, value): self._width = value # Regenerate the mesh self.invalidate() @property def thickness(self): return self._thickness @thickness.setter def thickness(self, value): self._thickness = value # Regenerate the mesh self.invalidate() def on_build(self): """Called when the model is chenged and rebuilds the whole slider""" if not self.model: return _min = self.model.get_as_floats(self.model.get_item("min"))[0] _max = self.model.get_as_floats(self.model.get_item("max"))[0] value = float(self.model.get_as_floats(self.model.get_item("value"))[0]) value_normalized = (value - _min) / (_max - _min) value_normalized = max(min(value_normalized, 1.0), 0.0) position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Left line line_from = -self.width * 0.5 line_to = -self.width * 0.5 + self.width * value_normalized - self._radius if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # Right line line_from = -self.width * 0.5 + self.width * value_normalized + self._radius line_to = self.width * 0.5 if line_to > line_from: sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness) # Circle circle_position = -self.width * 0.5 + self.width * value_normalized with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)): radius = self._radius gestures = [self._arc_gesture] if self._hover_gesture: gestures.append(self._hover_gesture) if self._hover_gesture.state == sc.GestureState.CHANGED: radius = self._radius_hovered sc.Arc(radius, axis=2, color=cl.gray, gestures=gestures) # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): # Move it to the top with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)): with sc.Transform(scale_to=sc.Space.SCREEN): # Move it 5 points more to the top in the screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)): sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM) def on_model_updated(self, item): # Regenerate the mesh self.invalidate()
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/slider_registry.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["SliderRegistry"] from .slider_manipulator import SliderManipulator from .slider_model import SliderModel from typing import Any from typing import Dict from typing import Optional class ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact is the focused window! # And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass class SliderChangedGesture(SliderManipulator.SliderChangedGesture): """User part. Called when slider is changed.""" def __init__(self, **kwargs): super().__init__(**kwargs) def on_began(self): # When the user drags the slider, we don't want to see the selection # rect. In Viewport Next, it works well automatically because the # selection rect is a manipulator with its gesture, and we add the # slider manipulator to the same SceneView. # In Viewport Legacy, the selection rect is not a manipulator. Thus it's # not disabled automatically, and we need to disable it with the code. self.__disable_selection = ViewportLegacyDisableSelection() def on_changed(self): """Called when the user moved the slider""" if not hasattr(self.gesture_payload, "slider_value"): return # The current slider value is in the payload. slider_value = self.gesture_payload.slider_value # Change the model. Slider watches it and it will update the mesh. self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value]) def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None class SliderRegistry: """ Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per viewport. Keeps the manipulator and some properties that are needed to the viewport. """ def __init__(self, description: Optional[Dict[str, Any]] = None): self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture()) def destroy(self): if self.__slider_manipulator: self.__slider_manipulator.destroy() self.__slider_manipulator = None # PrimTransformManipulator & TransformManipulator don't have their own visibility @property def visible(self): return True @visible.setter def visible(self, value): pass @property def categories(self): return ("manipulator",) @property def name(self): return "Example Slider Manipulator"
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["SliderExtension"] from .slider_extension import SliderExtension
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/slider_extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["SliderExtension"] from .slider_registry import SliderRegistry from omni.kit.manipulator.viewport import ManipulatorFactory from omni.kit.viewport.registry import RegisterScene import omni.ext class SliderExtension(omni.ext.IExt): """The entry point to the extension""" def on_startup(self, ext_id): # Viewport Next: omni.kit.viewport.window self._slider_registry = RegisterScene(SliderRegistry, "omni.example.ui_scene.slider_manipulator") # Viewport Legacy: omni.kit.window.viewport self._slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry) def on_shutdown(self): ManipulatorFactory.destroy_manipulator(self._slider_factory) self._slider_factory = None self._slider_registry.destroy() self._slider_registry = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/omni/example/ui_scene/slider_manipulator/slider_model.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["SliderModel"] from omni.ui import scene as sc from pxr import Gf from pxr import UsdGeom from pxr import Usd import omni.usd import omni.kit.commands class SliderModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and scale of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because we take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value""" def __init__(self, value=0): super().__init__() self.value = [value] def __init__(self): super().__init__() self.scale = SliderModel.ValueItem() self.min = SliderModel.ValueItem() self.max = SliderModel.ValueItem(1) self.position = SliderModel.PositionItem() # The distance from the bounding box to the position the model returns self._offset = 10 # Current selection self._current_path = "" usd_context = omni.usd.get_context() self._stage: Usd.Stage = None # Track selection self._selection = usd_context.get_selection() self._events = usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="Slider Selection Update" ) def get_item(self, identifier): if identifier == "value": return self.scale if identifier == "position": return self.position if identifier == "min": return self.min if identifier == "max": return self.max def get_as_floats(self, item): if item == self.position: # Requesting position return self._get_position() if item: # Get the value directly from the item return item.value return [] def set_floats(self, item, value): if not self._current_path: return if not value or not item or item.value == value: return if item == self.scale: # Set the scale when setting the value. value[0] = min(max(value[0], self.min.value[0]), self.max.value[0]) (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT( self._stage.GetPrimAtPath(self._current_path) ) omni.kit.commands.execute( "TransformPrimSRTCommand", path=self._current_path, new_translation=old_translation, new_rotation_euler=old_rotation_euler, new_scale=Gf.Vec3d(value[0], value[0], value[0]), ) # Set directly to the item item.value = value # This makes the manipulator updated self._item_changed(item) def _get_stage(self): if not self._stage: usd_context = omni.usd.get_context() self._stage: Usd.Stage = usd_context.get_stage() return self._stage def _on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_kit_selection_changed() def _on_kit_selection_changed(self): prim_paths = self._selection.get_selected_prim_paths() if not prim_paths: return prim = self._get_stage().GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): return self._current_path = prim_paths[0] (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim) scale = old_scale[0] _min = scale * 0.1 _max = scale * 2.0 self.set_floats(self.min, [_min]) self.set_floats(self.max, [_max]) self.set_floats(self.scale, [scale]) # Position is changed self._item_changed(self.position) def _get_position(self): """Returns position of currently selected object""" if not self._current_path: return [0, 1e38, 0] # Get position directly from USD prim = self._get_stage().GetPrimAtPath(self._current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + self._offset, (bboxMin[2] + bboxMax[2]) * 0.5] return position
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/docs/CHANGELOG.md
# Changelog omni.example.ui_scene.slider_manipulator ## [1.2.1] - 2022-06-17 ### Added - Documentation ## [1.2.0] - 2022-06-01 ### Changed - Full refactoring ## [1.1.1] - 2021-12-22 ### Changed - Fixes for tests on 103.0+release.679.1bc9fadb ## [1.1.0] - 2021-12-06 ### Changed - Using the model-based SceneView ### Added - Support for HoverGesture ## [1.0.1] - 2021-11-25 ### Changed - Default aspect ratio to match Kit Viewport - Renamed Intersection to GesturePayload (need omni.ui.scene 1.1.0) ## [1.0.0] - 2021-11-19 ### Added - The initial documentation
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/docs/README.md
# Slider Manipulator (omni.example.ui_scene.slider_manipulator) ![](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/raw/main/exts/omni.example.ui_scene.slider_manipulator/data/preview.png) ## Overview We provide the End-to-End example that draws a 3D slider in the viewport overlay on the top of the bounding box of the selected imageable. The slider controls the scale of the prim. It has a custom manipulator, model, and gesture. When the slider's value is changed, the manipulator processes the custom gesture that changes the data in the model, which changes the data directly in the USD stage. ​The viewport overlay is synchronized with the viewport using `Tf.Notice` that watches the USD Camera. ### Manipulator The manipulator is a very basic implementation of the slider in 3D space. The main feature of the manipulator is that it redraws and recreates all the children once the model is changed. It makes the code straightforward. It takes the position and the slider value from the model, and when the user changes the slider position, it processes a custom gesture. It doesn't write to the model directly to let the user decide what to do with the new data and how the manipulator should react to the modification. For example, if the user wants to implement the snapping to the round value, it would be handy to do it in the custom gesture. ### Model The model contains the following named items: - `value` - the current value of the slider - `min` - the minimum value of the slider - `max` - the maximum value of the slider - `position` - the position of the slider in 3D space The model demonstrates two main strategies working with the data. The first strategy is that the model is the bridge between the manipulator and the data, and it doesn't keep and doesn't duplicate the data. When the manipulator requests the position from the model, the model computes the position using USD API and returns it to the manipulator. The first strategy is that the model can be a container of the data. For example, the model pre-computes min and max values and passes them to the manipulator once the selection is changed. ## [Tutorial](../Tutorial/slider_Manipulator_Tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. In the tutorial you will learn how to create an extension from the Extension Manager in Omniverse Code, set up your files, and use Omniverse's Library. Additionally, the tutorial has a `Final Scripts` folder to use as a reference as you go along. ​[Get started with the tutorial here.](../Tutorial/slider_Manipulator_Tutorial.md) ## Usage Once the extension is enabled in the `Extension Manager`, go to your `Viewport` and right-click to create a primitive - such as a cube, sphere, cylinder, etc. Then, left-click/select the primitive to view and manipulate the slider. ​
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/docs/index.rst
omni.example.ui_scene.slider_manipulator ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/tutorial/tutorial.md
![](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.light_manipulator/tutorial/images/logo.png?raw=true) # Create a Reusable Light Panel with the Drag and Hover Gestures [`Gestures`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Gestures.html) are a powerful way to allow you to create scenes with interactive objects. In this hands-on tutorial you will create a light panel where users can alter the size and intensity of the light by dragging its edges. ## Learning Objectives In this tutorial, you will learn how to: * Extend the [`Manipulator`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Manipulator.html) class to create a light panel with a basic model based UI. * Use [`Gestures`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Gestures.html) to customize and extend an object's UI. ## Prerequisites It is recommended to understand the concepts in the following tutorials before proceeding: * [How to make an extension that spawns primitives](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) * [Learn how to add extensions to the Omniverse Extension Manager](https://github.com/NVIDIA-Omniverse/kit-extension-template). > **_NOTE:_** You must use Omniverse Code version `2022.1.2` or newer. ## Step 1: Download the Starter Project Clone the `tutorial-start` branch of the `kit-extension-sample-ui-scene` repository to get the assets for this tutorial: https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene This tutorial will focus on the `light_manipulator.py` file found in the `/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator` directory. To learn more about the other files in the repository check out the [How to make an extension that spawns primitives](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md). ## Step 2: Familiarize Yourself with `on_build()` of the `LightManipulator` Class This tutorial will be focusing on the `LightManipulator` class, which is created by extending the [`Manipulator`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Manipulator.html) class. By doing this, it enables you to create an interactive rectangular light, a `LightPanel`, as shown in the image below: ![](../data/preview.png) `LightManipulator` overrides [`on_build()`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Manipulator.on_build) from `Manipulator` and is where you will be adding the custom code. It should initially look like this: ```python def on_build(self): """Called when the model is changed and rebuilds the whole slider""" model = self.model if not model: return # if we don't have selection then just return prim_path_item = model.prim_path prim_path = prim_path_item.value if prim_path_item else None if not prim_path: return #TODO: Add Step 3 self.__root_xf = sc.Transform(model.get_as_floats(model.transform)) with self.__root_xf: self._x_xform = sc.Transform() with self._x_xform: self._shape_xform = sc.Transform() # Build the shape's transform self._build_shape() with self._shape_xform: #TODO: Add Step 4.1 #TODO: Add Step 4.2 #TODO: Add Step 5.1 #TODO: Add Step 6.1 #TODO: Add Step 6.2 #TODO: Add Step 7.1 #TODO: Add Step 7.2 pass ``` When a `Manipulator` needs updating `on_build()` is called and uses a [`Model`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Manipulator.html#model), as defined in [`light_model.py`](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_model.py). This `self.model` has a number of useful functions such as getting and setting the `height`, `width` and `intensity` of the light. [`get_as_floats()`](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/18a3cb7f657c1c87be88810bc5544d2ab1efe673/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_model.py#L137) and [`set_floats()`](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/18a3cb7f657c1c87be88810bc5544d2ab1efe673/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_model.py#L153) allow you to retrieve or alter all of these values all at once. If `self.model` is not set the function ends since there isn't anything to manipulate. Similarly, there must also be a `RectLight` available in `prim_path`. ## Step 3: Setting Line Style of the `LightPanel` To show the user the `LightPanel` is resizable, and which edge of its rectangle is being hovered over, set the style and thickness of its edges: Copy the following code under the `# Add Step 3` comment in `on_build()`. This will not render anything in Omniverse yet, but will provide a setup for later. ```python # Style settings, as kwargs thickness = 1 hover_thickness = 3 color = cl.yellow shape_style = {"thickness": thickness, "color": color} def set_thickness(sender, shapes, thickness): for shape in shapes: shape.thickness = thickness ``` Here you created `set_thickness()` for the `HoverGesture` to use as a callback for adjusting the size of the edge that's being hovered over. **CHALLENGE (optional):** Want to make the style your own? Try changing the `thickness`, `hover_thickness` and `color` variables to your liking. It may be worth revisiting this code and adjusting it over the course of this tutorial. ## Step 4: Building the Manipulator Transform To make it easier for the user to scale the LightPanel, give it a [`Transform`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Transform). A Translation `Transform` is created with the following code: > **_NOTE:_** Do not copy this code ```python self.__root_xf = sc.Transform(model.get_as_floats(model.transform)) with self.__root_xf: self._x_xform = sc.Transform() with self._x_xform: self._shape_xform = sc.Transform() # Build the shape's transform self._build_shape() ``` This code will start from the top down, store the root `Transform` of the `Model` in `self.__root_xf`. Then, the code creates `self._x_xform`, a `Transform` for translation and it also creates a `Transform` for the shape, `self._shape_xform`: ### Step 4.1: Set the Scale Add this code to `# Add Step 4.1` in `on_build()`: ```python def _build_shape(self): if not self.model: return if self.model.width and self.model.height and self.model.intensity: x = self.model.get_as_floats(self.model.width) y = self.model.get_as_floats(self.model.height) # this INTENSITY_SCALE is too make the transform a reasonable length with large intensity number z = self.model.get_as_floats(self.model.intensity) / INTENSITY_SCALE self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1] ``` Finally, `_build_shape()` sets the scale on the `_shape_xform` using the vector `[x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1]` where x is width, y is the height, and z is the light intensity. This list is being used as a [scale matrix](https://en.wikipedia.org/wiki/Scaling_(geometry)#Using_homogeneous_coordinates). ### Step 4.2: Build the Geometry Now that the transform has been created you need to render the rectangle's geometry. Copy the below code block under the `# Add Step 4.2` comment in `on_build()`. Be sure to check the alignment of the python code and feel free to view the [completed function](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_manipulator.py) as a hint. ```python # Build the shape geometry as unit-sized h = 0.5 z = -1.0 # the rectangle shape1 = sc.Line((-h, h, 0), (h, h, 0), **shape_style) shape2 = sc.Line((-h, -h, 0), (h, -h, 0), **shape_style) shape3 = sc.Line((h, h, 0), (h, -h, 0), **shape_style) shape4 = sc.Line((-h, h, 0), (-h, -h, 0), **shape_style) ``` There should now be a rectangle viewable in Omniverse. ## Step 5: Handling Gestures [Gestures](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Gestures.html) handle callback data from user input. [There are many kinds of Gestures in Omniverse, listed here](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni-ui-scene-module). This tutorial focuses on the [Hover](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.HoverGesture) and [Drag](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.DragGesture) Gestures. ### Step 5.1: Add the `HoverGesture` for the `RectLight` Copy the below code block under the `# Add Step 5.1` comment `on_build()`. Again, make sure that this code aligns with the comment. ```python # add gesture to the lines of the rectangle to update width or height of the light vertical_hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_thickness(sender, [shape1, shape2], hover_thickness), on_ended_fn=lambda sender: set_thickness(sender, [shape1, shape2], thickness), ) shape1.gestures = [_DragGesture(self, [1], [1]), vertical_hover_gesture] shape2.gestures = [_DragGesture(self, [1], [-1]), vertical_hover_gesture] horizontal_hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_thickness(sender, [shape3, shape4], hover_thickness), on_ended_fn=lambda sender: set_thickness(sender, [shape3, shape4], thickness), ) shape3.gestures = [_DragGesture(self, [0], [1]), horizontal_hover_gesture] shape4.gestures = [_DragGesture(self, [0], [-1]), horizontal_hover_gesture] ``` To change the thickness of the edges of your `RectLight` while the user hovers over them, set the `on_began_fn()` (beginning of the hover) and `on_ended_fn()` (ending of the hover) to use `set_thickness()` defined in [Step 3: Setting Line Style of the LightPanel](#step-3-setting-line-style-of-the-lightpanel) Since the rectangle will grow and shrink about its center, you will highlight both of the affected edges to reflect this mirrored behavior. For instance, if you're changing the vertical height of the rectangle, both the top and bottom edges will be highlighted like so: ![](../data/height_s.png) ### Step 5.2: Analyzing the `DragGesture` The `DragGesture` will do a number of different things to your light panel depending on which edge is dragged. You'll extend the base [DragGesture]([Drag](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.DragGesture)) class into `_DragGesture`. Take a look at a key part of the [`on_began()`](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/18a3cb7f657c1c87be88810bc5544d2ab1efe673/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_manipulator.py#L91) function: > **_NOTE:_** Do not copy this code ```python if 0 in self.orientations: self.width_item = self.model.width self._manipulator.model.set_item_value(self.width_item, self.model.get_as_floats(self.width_item)) if 1 in self.orientations: self.height_item = self.model.height self._manipulator.model.set_item_value(self.height_item, self.model.get_as_floats(self.height_item)) if 2 in self.orientations or self.is_global: self.intensity_item = self.model.intensity self._manipulator.model.set_item_value(self.intensity_item, self.model.get_as_floats(self.intensity_item)) ``` When defining the `Gesture`, you pass in an `Orientation` to let it know whether it's for width, height, or intensity. Then, you will alter the respective variable. Finally, to build the `Gesture`, call it like so: ```python _DragGesture(manipulator, orientation, flag) ``` Where `flag` indicates the negative or positive edge (i.e. the left horizontal edge vs. the right horizontal edge). ## Step 6: Adding Intensity While you have learned how to manipulate the light's height and width, it would be useful if users could also define the intensity of the light using the `DragGesture`. To make it clear to the user that they are using the panel's local z-axis to modify its intensity, you can use arrows like this: ![](../data/preview_s.png) ### Step 6.1: Create Custom Arrows Add this code to `# Add Step 6.1` in `on_build()` ```python # create z-axis to indicate the intensity z1 = sc.Line((h, h, 0), (h, h, z), **shape_style) z2 = sc.Line((-h, -h, 0), (-h, -h, z), **shape_style) z3 = sc.Line((h, -h, 0), (h, -h, z), **shape_style) z4 = sc.Line((-h, h, 0), (-h, h, z), **shape_style) def make_arrow(translate): vert_count = len(ARROW_VI) with sc.Transform( transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2]) * sc.Matrix44.get_rotation_matrix(0, -180, 0, True) ): return sc.PolygonMesh(ARROW_P, [color] * vert_count, ARROW_VC, ARROW_VI, visible=False) # arrows on the z-axis arrow_1 = make_arrow((h, h, z)) arrow_2 = make_arrow((-h, -h, z)) arrow_3 = make_arrow((h, -h, z)) arrow_4 = make_arrow((-h, h, z)) # the line underneath the arrow which is where the gesture applies z1_arrow = sc.Line((h, h, z), (h, h, z - ARROW_HEIGHT), **shape_style) z2_arrow = sc.Line((-h, -h, z), (-h, -h, z - ARROW_HEIGHT), **shape_style) z3_arrow = sc.Line((h, -h, z), (h, -h, z - ARROW_HEIGHT), **shape_style) z4_arrow = sc.Line((-h, h, z), (-h, h, z - ARROW_HEIGHT), **shape_style) ``` The arrow's mesh has already been defined at the top of `light_manipulator.py` with the variables `ARROW_P`, `ARROW_VI`, and `ARROW_VC`. `make_arrow()` makes use of these variables to draw the arrows. While this draws the arrows, you still need to add the HoverGesture to show them... ### Step 6.2: Adding the `HoverGesture` to the Arrows Add this code to `# Add Step 6.2` in `on_build()` ```python def set_visible(sender, shapes, thickness, arrows, visible): set_thickness(sender, shapes, thickness) for arrow in arrows: arrow.visible = visible thickness_group = [z1, z1_arrow, z2, z2_arrow, z3, z3_arrow, z4, z4_arrow] visible_group = [arrow_1, arrow_2, arrow_3, arrow_4] visible_arrow_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_visible(sender, thickness_group, hover_thickness, visible_group, True), on_ended_fn=lambda sender: set_visible(sender, thickness_group, thickness, visible_group, True), ) gestures = [_DragGesture(self, [2], [-1]), visible_arrow_gesture] z1_arrow.gestures = gestures z2_arrow.gestures = gestures z3_arrow.gestures = gestures z4_arrow.gestures = gestures ``` This code creates a function, `set_visible()`, that alters both the visibility of the arrows and the thickness of the edge lines as part of your `HoverGesture`. Then, adds the `DragGestures` in order to change the light intensity while dragging an arrow. **CHALLENGE (Optional):** Right now, the arrows are always visible regardless if the cursor is hovering over them or not. Can you alter the code so that the arrows only appear when hovering? Only one line needs to be changed. Click the below for a hint. <details> <summary>Solution</summary> In <code>on_ended_fn</code>, the <code>visible</code> parameter (the last argument of the function) should be set to <code>False</code>. </details> ### Step 7: Scaling Everything All the critical features of the extension have been implemented so far: * The ability to change the width and height of a light panel * The ability to change the intensity of a light panel. In many 3D apps, there is often a shortcut to scale all of the dimensions of an object at once. Add a few small rectangles to the corners of the `LightPanel` to allow users to scale width and height at the same time. ![](../data/preview.png) ### Step 7.1: Add Scaling Rectangles Add this code to `# Add Step 7.1` in `on_build()` ```python # create 4 rectangles at the corner, and add gesture to update width, height and intensity at the same time s = 0.03 def make_corner_rect(translate): with sc.Transform(transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])): return sc.Rectangle(s, s, color=0x0) r1 = make_corner_rect((h - 0.5 * s, -h + 0.5 * s, 0)) r2 = make_corner_rect((h - 0.5 * s, h - 0.5 * s, 0)) r3 = make_corner_rect((-h + 0.5 * s, h - 0.5 * s, 0)) r4 = make_corner_rect((-h + 0.5 * s, -h + 0.5 * s, 0)) ``` This defines the function `make_corner_rec()` to draw a [`rectangle`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Rectangle). ### Step 7.2: Highlight All of the Edges at Once Add this code to `# Add Step 7.2` in `on_build()` ```python def set_color_and_visible(sender, shapes, thickness, arrows, visible, rects, color): set_visible(sender, shapes, thickness, arrows, visible) for rect in rects: rect.color = color highlight_group = [shape1, shape2, shape3, shape4] + thickness_group color_group = [r1, r2, r3, r4] hight_all_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_color_and_visible(sender, highlight_group, hover_thickness, visible_group, True, color_group, color), on_ended_fn=lambda sender: set_color_and_visible(sender, highlight_group, thickness, visible_group, False, color_group, 0x0), ) r1.gestures = [_DragGesture(self, [0, 1], [1, -1]), hight_all_gesture] r2.gestures = [_DragGesture(self, [0, 1], [1, 1]), hight_all_gesture] r3.gestures = [_DragGesture(self, [0, 1], [-1, 1]), hight_all_gesture] r4.gestures = [_DragGesture(self, [0, 1], [-1, -1]), hight_all_gesture] ``` You've defined `set_color_and_visible()` in order to highlight all the edges at once with your `HoverGesture`. Then, the code passes in multiple orientations (`[0, 1]`) to the `_DragGesture` to indicate you're altering the width and height at the same time. ## Step 8: Congratulations!! Great job getting through this tutorial. Interested in improving your skills further? [Please consider checking out the Reticle Extension Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-reticle/blob/main/tutorial/tutorial.md). ![](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.light_manipulator/tutorial/images/logo.png?raw=true)
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/config/extension.toml
[package] version = "1.1.1" authors = ["NVIDIA"] title = "Omni.UI Scene Sample For Manipulating Select Light" description = "This example show an 3D manipulator for a selected light" readme = "docs/README.md" repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene" category = "Documentation" keywords = ["ui", "example", "scene", "docs", "documentation", "light"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.ui.scene" = { } "omni.usd" = { } "omni.kit.viewport.utility" = { } "omni.kit.commands" = { } [[python.module]] name = "omni.example.ui_scene.light_manipulator" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/app/viewport/forceHideFps=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.hydra.pxr", "omni.kit.test_helpers_gfx", "omni.kit.viewport.utility", "omni.kit.window.viewport" ]
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["LightManipulatorExtension"] import carb import omni.ext from omni.kit.viewport.utility import get_active_viewport_window from .viewport_scene import ViewportScene class LightManipulatorExtension(omni.ext.IExt): def __init__(self): self._viewport_scene = None def on_startup(self, ext_id): # Get the active (which at startup is the default Viewport) viewport_window = get_active_viewport_window() # Issue an error if there is no Viewport if not viewport_window: carb.log_error(f"No Viewport Window to add {ext_id} scene to") return # Build out the scene self._viewport_scene = ViewportScene(viewport_window, ext_id) def on_shutdown(self): if self._viewport_scene: self._viewport_scene.destroy() self._viewport_scene = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/viewport_scene.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportScene"] from omni.ui import scene as sc from .light_model import LightModel from .light_manipulator import LightManipulator class ViewportScene: """The light Manipulator, placed into a Viewport""" def __init__(self, viewport_window, ext_id: str): self._scene_view = None self._viewport_window = viewport_window # Create a unique frame for our SceneView with self._viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: LightManipulator(model=LightModel()) # Register the SceneView with the Viewport to get projection and view updates self._viewport_window.viewport_api.add_scene_view(self._scene_view) def __del__(self): self.destroy() def destroy(self): if self._scene_view: # Empty the SceneView of any elements it may have self._scene_view.scene.clear() # Be a good citizen, and un-register the SceneView from Viewport updates if self._viewport_window: self._viewport_window.viewport_api.remove_scene_view(self._scene_view) # Remove our references to these objects self._viewport_window = None self._scene_view = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import * from .light_manipulator import LightManipulator from .light_model import LightModel
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_model.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["LightModel"] import carb from omni.ui import scene as sc import omni.usd from pxr import Usd, UsdGeom, UsdLux, Tf, Gf def _flatten_matrix(matrix: Gf.Matrix4d): m0, m1, m2, m3 = matrix[0], matrix[1], matrix[2], matrix[3] return [ m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3], ] class LightModel(sc.AbstractManipulatorModel): """ User part. The model tracks the attributes of the selected light. """ class MatrixItem(sc.AbstractManipulatorItem): """ The Model Item represents the tranformation. It doesn't contain anything because we take the tranformation directly from USD when requesting. """ identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] def __init__(self): super().__init__() self.value = self.identity.copy() class FloatItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value about some attibute""" def __init__(self, value=0.0): super().__init__() self.value = value class StringItem(sc.AbstractManipulatorItem): """The Model Item contains a single string value about some attibute""" def __init__(self, value=""): super().__init__() self.value = value def __init__(self): super().__init__() self.prim_path = LightModel.StringItem() self.transform = LightModel.MatrixItem() self.intensity = LightModel.FloatItem() self.width = LightModel.FloatItem() self.height = LightModel.FloatItem() # Save the UsdContext name (we currently only work with single Context) self._usd_context_name = "" # Current selection self._light = None self._stage_listener = None # Track selection change self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="Light Manipulator Selection Change" ) def __del__(self): self._invalidate_object() @property def _usd_context(self) -> Usd.Stage: # Get the UsdContext we are attached to return omni.usd.get_context(self._usd_context_name) @property def _current_path(self): return self.prim_path.value @property def _time(self): return Usd.TimeCode.Default() def _notice_changed(self, notice, stage): """Called by Tf.Notice. When USD data changes, we update the ui""" light_path = self.prim_path.value if not light_path: return changed_items = set() for p in notice.GetChangedInfoOnlyPaths(): prim_path = p.GetPrimPath().pathString if prim_path != light_path: # Update on any parent transformation changes too if light_path.startswith(prim_path): if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name): changed_items.add(self.transform) continue if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name): changed_items.add(self.transform) elif self.width and p.name == "width": changed_items.add(self.width) elif self.height and p.name == "height": changed_items.add(self.height) elif self.intensity and p.name == "intensity": changed_items.add(self.intensity) for item in changed_items: self._item_changed(item) def get_as_floats(self, item): """get the item value directly from USD""" if item == self.transform: return self._get_transform(self._time) if item == self.intensity: return self._get_intensity(self._time) if item == self.width: return self._get_width(self._time) if item == self.height: return self._get_height(self._time) if item: # Get the value directly from the item return item.value return None def set_floats_commands(self, item, value): """set the item value to USD using commands, this is useful because it supports undo/redo""" if not self._current_path: return if not value or not item: return # we get the previous value from the model instead of USD if item == self.height: prev_value = self.height.value if prev_value == value: return height_attr = self._light.GetHeightAttr() omni.kit.commands.execute('ChangeProperty', prop_path=height_attr.GetPath(), value=value, prev=prev_value) elif item == self.width: prev_value = self.width.value if prev_value == value: return width_attr = self._light.GetWidthAttr() omni.kit.commands.execute('ChangeProperty', prop_path=width_attr.GetPath(), value=value, prev=prev_value) elif item == self.intensity: prev_value = self.intensity.value if prev_value == value: return intensity_attr = self._light.GetIntensityAttr() omni.kit.commands.execute('ChangeProperty', prop_path=intensity_attr.GetPath(), value=value, prev=prev_value) # This makes the manipulator updated self._item_changed(item) def set_item_value(self, item, value): """ This is used to set the model value instead of the usd. This is used to record previous value for omni.kit.commands """ item.value = value def set_floats(self, item, value): """set the item value directly to USD. This is useful when we want to update the usd but not record it in commands""" if not self._current_path: return if not value or not item: return pre_value = self.get_as_floats(item) # no need to update if the updated value is the same if pre_value == value: return if item == self.height: self._set_height(self._time, value) elif item == self.width: self._set_width(self._time, value) elif item == self.intensity: self._set_intensity(self._time, value) def _on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_kit_selection_changed() def _invalidate_object(self, settings): # Revoke the Tf.Notice listener, we don't need to update anything if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None # Reset original Viewport gizmo line width settings.set("/persistent/app/viewport/gizmo/lineWidth", 0) # Clear any cached UsdLux.Light object self._light = None # Set the prim_path to empty self.prim_path.value = "" self._item_changed(self.prim_path) def _on_kit_selection_changed(self): # selection change, reset it for now self._light = None # Turn off any native selected light drawing settings = carb.settings.get_settings() settings.set("/persistent/app/viewport/gizmo/lineWidth", 0) usd_context = self._usd_context if not usd_context: return self._invalidate_object(settings) stage = usd_context.get_stage() if not stage: return self._invalidate_object(settings) prim_paths = usd_context.get_selection().get_selected_prim_paths() if usd_context else None if not prim_paths: return self._invalidate_object(settings) prim = stage.GetPrimAtPath(prim_paths[0]) if prim and prim.IsA(UsdLux.RectLight): self._light = UsdLux.RectLight(prim) if not self._light: return self._invalidate_object(settings) selected_path = self._light.GetPrim().GetPath().pathString if selected_path != self.prim_path.value: self.prim_path.value = selected_path self._item_changed(self.prim_path) # Add a Tf.Notice listener to update the light attributes if not self._stage_listener: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage) def _get_transform(self, time: Usd.TimeCode): """Returns world transform of currently selected object""" if not self._light: return LightModel.MatrixItem.identity.copy() # Compute matrix from world-transform in USD world_xform = self._light.ComputeLocalToWorldTransform(time) # Flatten Gf.Matrix4d to list return _flatten_matrix(world_xform) def _get_intensity(self, time: Usd.TimeCode): """Returns intensity of currently selected light""" if not self._light: return 0.0 # Get intensity directly from USD return self._light.GetIntensityAttr().Get(time) def _set_intensity(self, time: Usd.TimeCode, value): """set intensity of currently selected light""" if not self._light: return # set height dirctly to USD self._light.GetIntensityAttr().Set(value, time=time) def _get_width(self, time: Usd.TimeCode): """Returns width of currently selected light""" if not self._light: return 0.0 # Get radius directly from USD return self._light.GetWidthAttr().Get(time) def _set_width(self, time: Usd.TimeCode, value): """set width of currently selected light""" if not self._light: return # set height dirctly to USD self._light.GetWidthAttr().Set(value, time=time) def _get_height(self, time: Usd.TimeCode): """Returns height of currently selected light""" if not self._light: return 0.0 # Get height directly from USD return self._light.GetHeightAttr().Get(time) def _set_height(self, time: Usd.TimeCode, value): """set height of currently selected light""" if not self._light: return # set height dirctly to USD self._light.GetHeightAttr().Set(value, time=time)
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_manipulator.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["LightManipulator"] from omni.ui import scene as sc from omni.ui import color as cl import omni.kit import omni.kit.commands INTENSITY_SCALE = 500.0 ARROW_WIDTH = 0.015 ARROW_HEIGHT = 0.1 ARROW_P = [ [ARROW_WIDTH, ARROW_WIDTH, 0], [-ARROW_WIDTH, ARROW_WIDTH, 0], [0, 0, ARROW_HEIGHT], # [ARROW_WIDTH, -ARROW_WIDTH, 0], [-ARROW_WIDTH, -ARROW_WIDTH, 0], [0, 0, ARROW_HEIGHT], # [ARROW_WIDTH, ARROW_WIDTH, 0], [ARROW_WIDTH, -ARROW_WIDTH, 0], [0, 0, ARROW_HEIGHT], # [-ARROW_WIDTH, ARROW_WIDTH, 0], [-ARROW_WIDTH, -ARROW_WIDTH, 0], [0, 0, ARROW_HEIGHT], # [ARROW_WIDTH, ARROW_WIDTH, 0], [-ARROW_WIDTH, ARROW_WIDTH, 0], [-ARROW_WIDTH, -ARROW_WIDTH, 0], [ARROW_WIDTH, -ARROW_WIDTH, 0], ] ARROW_VC = [3, 3, 3, 3, 4] ARROW_VI = [i for i in range(sum(ARROW_VC))] class _ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact is the focused window! # And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass class _DragGesture(sc.DragGesture): """"Gesture to disable rectangle selection in the viewport legacy""" def __init__(self, manipulator, orientation, flag): super().__init__() self._manipulator = manipulator # record this _previous_ray_point to get the mouse moved vector self._previous_ray_point = None # this defines the orientation of the move, 0 means x, 1 means y, 2 means z. It's a list so that we can move a selection self.orientations = orientation # global flag to indicate if the manipulator changes all the width, height and intensity, rectangle manipulator # in the example self.is_global = len(self.orientations) > 1 # this defines the negative or positive of the move. E.g. when we move the positive x line to the right, it # enlarges the width, and when we move the negative line to the left, it also enlarges the width # 1 means positive and -1 means negative. It's a list so that we can reflect list orientation self.flag = flag def on_began(self): # When the user drags the slider, we don't want to see the selection # rect. In Viewport Next, it works well automatically because the # selection rect is a manipulator with its gesture, and we add the # slider manipulator to the same SceneView. # In Viewport Legacy, the selection rect is not a manipulator. Thus it's # not disabled automatically, and we need to disable it with the code. self.__disable_selection = _ViewportLegacyDisableSelection() # initialize the self._previous_ray_point self._previous_ray_point = self.gesture_payload.ray_closest_point # record the previous value for the model self.model = self._manipulator.model if 0 in self.orientations: self.width_item = self.model.width self._manipulator.model.set_item_value(self.width_item, self.model.get_as_floats(self.width_item)) if 1 in self.orientations: self.height_item = self.model.height self._manipulator.model.set_item_value(self.height_item, self.model.get_as_floats(self.height_item)) if 2 in self.orientations or self.is_global: self.intensity_item = self.model.intensity self._manipulator.model.set_item_value(self.intensity_item, self.model.get_as_floats(self.intensity_item)) def on_changed(self): object_ray_point = self.gesture_payload.ray_closest_point # calculate the ray moved vector moved = [a - b for a, b in zip(object_ray_point, self._previous_ray_point)] # transfer moved from world to object space, [0] to make it a normal, not point moved = self._manipulator._x_xform.transform_space(sc.Space.WORLD, sc.Space.OBJECT, moved + [0]) # 2.0 because `_shape_xform.transform` is a scale matrix and it means # the width of the rectangle is twice the scale matrix. moved_x = moved[0] * 2.0 * self.flag[0] moved_y = moved[1] * 2.0 * (self.flag[1] if self.is_global else self.flag[0]) moved_z = moved[2] * self.flag[0] # update the self._previous_ray_point self._previous_ray_point = object_ray_point # since self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] # when we want to update the manipulator, we are actually updating self._manipulator._shape_xform.transform[0] # for width and self._manipulator._shape_xform.transform[5] for height and # self._manipulator._shape_xform.transform[10] for intensity width = self._manipulator._shape_xform.transform[0] height = self._manipulator._shape_xform.transform[5] intensity = self._manipulator._shape_xform.transform[10] self.width_new = width + moved_x self.height_new = height + moved_y # update the USD as well as update the ui if 0 in self.orientations: # update the data in the model self.model.set_floats(self.width_item, self.width_new) self._manipulator._shape_xform.transform[0] = self.width_new if 1 in self.orientations: # update the data in the model self.model.set_floats(self.height_item, self.height_new) self._manipulator._shape_xform.transform[5] = self.height_new if 2 in self.orientations: self._manipulator._shape_xform.transform[10] += moved_z self.intensity_new = self._manipulator._shape_xform.transform[10] * INTENSITY_SCALE self.model.set_floats(self.intensity_item, self.intensity_new) if self.is_global: # need to update the intensity in a different way intensity_new = intensity * width * height / (self.width_new * self.height_new) self._manipulator._shape_xform.transform[10] = intensity_new self.intensity_new = intensity_new * INTENSITY_SCALE self.model.set_floats(self.intensity_item, self.intensity_new) def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None if self.is_global: # start group command omni.kit.undo.begin_group() if 0 in self.orientations: self.model.set_floats_commands(self.width_item, self.width_new) if 1 in self.orientations: self.model.set_floats_commands(self.height_item, self.height_new) if 2 in self.orientations or self.is_global: self.model.set_floats_commands(self.intensity_item, self.intensity_new) if self.is_global: # end group command omni.kit.undo.end_group() class LightManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) self._shape_xform = None def __del__(self): self.model = None def _build_shape(self): if not self.model: return if self.model.width and self.model.height and self.model.intensity: x = self.model.get_as_floats(self.model.width) y = self.model.get_as_floats(self.model.height) # this INTENSITY_SCALE is too make the transform a reasonable length with large intensity number z = self.model.get_as_floats(self.model.intensity) / INTENSITY_SCALE self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1] def on_build(self): """Called when the model is changed and rebuilds the whole slider""" model = self.model if not model: return # if we don't have selection then just return prim_path_item = model.prim_path prim_path = prim_path_item.value if prim_path_item else None if not prim_path: return # Style settings, as kwargs thickness = 1 hover_thickness = 3 color = cl.yellow shape_style = {"thickness": thickness, "color": color} def set_thickness(sender, shapes, thickness): for shape in shapes: shape.thickness = thickness self.__root_xf = sc.Transform(model.get_as_floats(model.transform)) with self.__root_xf: self._x_xform = sc.Transform() with self._x_xform: self._shape_xform = sc.Transform() # Build the shape's transform self._build_shape() with self._shape_xform: # Build the shape geomtery as unit-sized h = 0.5 z = -1.0 # the rectangle shape1 = sc.Line((-h, h, 0), (h, h, 0), **shape_style) shape2 = sc.Line((-h, -h, 0), (h, -h, 0), **shape_style) shape3 = sc.Line((h, h, 0), (h, -h, 0), **shape_style) shape4 = sc.Line((-h, h, 0), (-h, -h, 0), **shape_style) # add gesture to the lines of the rectangle to update width or height of the light vertical_hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_thickness(sender, [shape1, shape2], hover_thickness), on_ended_fn=lambda sender: set_thickness(sender, [shape1, shape2], thickness), ) shape1.gestures = [_DragGesture(self, [1], [1]), vertical_hover_gesture] shape2.gestures = [_DragGesture(self, [1], [-1]), vertical_hover_gesture] horizontal_hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_thickness(sender, [shape3, shape4], hover_thickness), on_ended_fn=lambda sender: set_thickness(sender, [shape3, shape4], thickness), ) shape3.gestures = [_DragGesture(self, [0], [1]), horizontal_hover_gesture] shape4.gestures = [_DragGesture(self, [0], [-1]), horizontal_hover_gesture] # create z-axis to indicate the intensity z1 = sc.Line((h, h, 0), (h, h, z), **shape_style) z2 = sc.Line((-h, -h, 0), (-h, -h, z), **shape_style) z3 = sc.Line((h, -h, 0), (h, -h, z), **shape_style) z4 = sc.Line((-h, h, 0), (-h, h, z), **shape_style) def make_arrow(translate): vert_count = len(ARROW_VI) with sc.Transform( transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2]) * sc.Matrix44.get_rotation_matrix(0, -180, 0, True) ): return sc.PolygonMesh(ARROW_P, [color] * vert_count, ARROW_VC, ARROW_VI, visible=False) # arrows on the z-axis arrow_1 = make_arrow((h, h, z)) arrow_2 = make_arrow((-h, -h, z)) arrow_3 = make_arrow((h, -h, z)) arrow_4 = make_arrow((-h, h, z)) # the line underneath the arrow which is where the gesture applies z1_arrow = sc.Line((h, h, z), (h, h, z - ARROW_HEIGHT), **shape_style) z2_arrow = sc.Line((-h, -h, z), (-h, -h, z - ARROW_HEIGHT), **shape_style) z3_arrow = sc.Line((h, -h, z), (h, -h, z - ARROW_HEIGHT), **shape_style) z4_arrow = sc.Line((-h, h, z), (-h, h, z - ARROW_HEIGHT), **shape_style) def set_visible(sender, shapes, thickness, arrows, visible): set_thickness(sender, shapes, thickness) for arrow in arrows: arrow.visible = visible thickness_group = [z1, z1_arrow, z2, z2_arrow, z3, z3_arrow, z4, z4_arrow] visible_group = [arrow_1, arrow_2, arrow_3, arrow_4] visible_arrow_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_visible(sender, thickness_group, hover_thickness, visible_group, True), on_ended_fn=lambda sender: set_visible(sender, thickness_group, thickness, visible_group, False), ) gestures = [_DragGesture(self, [2], [-1]), visible_arrow_gesture] z1_arrow.gestures = gestures z2_arrow.gestures = gestures z3_arrow.gestures = gestures z4_arrow.gestures = gestures # create 4 rectangles at the corner, and add gesture to update width, height and intensity at the same time s = 0.03 def make_corner_rect(translate): with sc.Transform(transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])): return sc.Rectangle(s, s, color=0x0) r1 = make_corner_rect((h - 0.5 * s, -h + 0.5 * s, 0)) r2 = make_corner_rect((h - 0.5 * s, h - 0.5 * s, 0)) r3 = make_corner_rect((-h + 0.5 * s, h - 0.5 * s, 0)) r4 = make_corner_rect((-h + 0.5 * s, -h + 0.5 * s, 0)) def set_color_and_visible(sender, shapes, thickness, arrows, visible, rects, color): set_visible(sender, shapes, thickness, arrows, visible) for rect in rects: rect.color = color highlight_group = [shape1, shape2, shape3, shape4] + thickness_group color_group = [r1, r2, r3, r4] hight_all_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_color_and_visible(sender, highlight_group, hover_thickness, visible_group, True, color_group, color), on_ended_fn=lambda sender: set_color_and_visible(sender, highlight_group, thickness, visible_group, False, color_group, 0x0), ) r1.gestures = [_DragGesture(self, [0, 1], [1, -1]), hight_all_gesture] r2.gestures = [_DragGesture(self, [0, 1], [1, 1]), hight_all_gesture] r3.gestures = [_DragGesture(self, [0, 1], [-1, 1]), hight_all_gesture] r4.gestures = [_DragGesture(self, [0, 1], [-1, -1]), hight_all_gesture] def on_model_updated(self, item): # Regenerate the mesh if not self.model: return if item == self.model.transform: # If transform changed, update the root transform self.__root_xf.transform = self.model.get_as_floats(item) elif item == self.model.prim_path: # If prim_path or width or height or intensity changed, redraw everything self.invalidate() elif item == self.model.width or item == self.model.height or item == self.model.intensity: # Interpret None as changing multiple light shape settings self._build_shape()
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/tests/test_manipulator.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import carb import omni.kit import omni.kit.app import omni.kit.test from omni.example.ui_scene.light_manipulator import LightManipulator, LightModel import omni.usd from omni.ui import scene as sc from pxr import UsdLux, UsdGeom from omni.kit.viewport.utility import next_viewport_frame_async from omni.kit.viewport.utility.tests import setup_vieport_test_window CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.example.ui_scene.light_manipulator}/data")) OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()) class TestLightManipulator(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def setup_viewport(self, resolution_x: int = 800, resolution_y: int = 600): await self.create_test_area(resolution_x, resolution_y) return await setup_vieport_test_window(resolution_x, resolution_y) async def test_manipulator_transform(self): viewport_window = await self.setup_viewport() viewport = viewport_window.viewport_api await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() # Wait until the Viewport has delivered some frames await next_viewport_frame_async(viewport, 2) with viewport_window.get_frame(0): # Create a default SceneView (it has a default camera-model) scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with scene_view.scene: LightManipulator(model=LightModel()) omni.kit.commands.execute( "CreatePrim", prim_path="/RectLight", prim_type="RectLight", select_new_prim=True, attributes={}, ) rect_light = UsdLux.RectLight(stage.GetPrimAtPath("/RectLight")) # change light attribute rect_light.GetHeightAttr().Set(100) rect_light.GetWidthAttr().Set(200) rect_light.GetIntensityAttr().Set(10000) # rotate the light to have a better angle rect_light_x = UsdGeom.Xformable(rect_light) rect_light_x.ClearXformOpOrder() rect_light_x.AddRotateXOp().Set(30) rect_light_x.AddRotateYOp().Set(45) for _ in range(10): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir)
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/tests/__init__.py
from .test_manipulator import TestLightManipulator
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/docs/CHANGELOG.md
# Changelog omni.example.ui_scene.light_manipulator ## [1.1.1] - 2022-6-21 ### Added - Documentation ## [1.1.0] - 2022-6-06 ### Changed - Removed other lights except RectLight - Added gesture to the RectLight so that users can drag the manipulator to change the width, height and intensity - The drag gesture can be just on the width (x-axis line) or height (y-axis line) or intensity (z-axis line) or all of them when drag the corner rectangles - Added test for the extension ## [1.0.0] - 2022-5-26 ### Added - The initial version
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/docs/README.md
# Light Manipulator (omni.example.ui_scene.light_manipulator) ## Overview We provide an End-to-End example of a light manipulator extension, which adds manipulators to RectLight. There are 6 types of lights in Omniverse, shown in the image below. Here is the link of how to add a light: https://www.youtube.com/watch?v=c7qyI8pZvF4. In this example, we only create manipulators to RectLight. ![](../data/lights.png) It contains the LightModel which stores the light attribute values. Focused on "width", "height" and "intensity" in this example. It also plays the role of communication with the USD data, reading and writing updated attributes from and to USD. LightManipulator defines 4 types of manipulators which separately control the light's width, height, intensity and all of the three. ## [Tutorial](../tutorial/tutorial.md) Follow this [step-by-step guide](../tutorial/tutorial.md) to learn how this extension was created. ## Manipulator The manipulator contains a rectangle and 4 lines perpendicular to the rectangle face. The manipulator is generated in a unit size, and the update of the look is through the parent transform of the manipulator. - When you hover over the rectangle's width or height of the manipulator, you will see the line representation of the width or height highlighted and you can drag and move the manipulator. When you drag and move the height or width of the rectangle of the manipulator, you will see the width or height attributes of the RectLight in the property window are updated. ![](../data/width_s.png) ![](../data/height_s.png) - When you hover over on the tip of any line perpendicular to the rectangle face, you will see the 4 lines will be highlighted and the arrow on the tip will reveal. When you drag and move the arrow, you will see the intensity attribute of the RectLight is updated. ![](../data/intensity_s.png) - When you hover over to the corner of the rectangle (slightly inside the rectangle), you will see the entire manipulator is highlighted, and there will be 4 small rectangles revealed at the corner of the rectangle. When you drag and move the small rectangle, you will see all of the width, height and intensity attributes of the RectLight are updated. ![](../data/preview_s.png) - When you change the attributes (Width, height and intensity) of the RectLight in the property window, you will see the manipulator appearance updates. ![](../data/attribute_s.png) ## Gesture The example defined a customized `_DragGesture` for the manipulator. This is how the gesture is implemented: - `on_began`: the start attributes data is restored into the model, so that we have a record of previous values later for running `omni.kit.commands`. - `on_changed`: update the attributes into the model, and the model will directly write the value to the USD without keeping it since we want to see the real-time updating of attribute value in the property window - `on_ended`: update the attributes into the model, and the model will call `omni.kit.commands` to change the property since we want to support the undo/redo for the dragging. The previous value from `on_began` is used here. ## Model The model contains the following named items: - width - the width attribute of the RectLight - height - the height attribute of the RectLight - intensity - the intensity attribute of the RectLight - prim_path - the USD prim path of the RectLight. - transform - the transform of the RectLight. The model is the bridge between the manipulator and the attributes data. The manipulator subscribes to the model change to update the look. All the attributes values are directly coming from USD data. We use `Tf.Notice` to watch the rectLight and update the model. The model itself doesn't keep and doesn't duplicate the USD data, except the previous value when a gesture starts. - When the model's `width`, `height` or `intensity` changes, the manipulator's parent transform is updated. - The model's `prim_path` is subscribed to `omni.usd.StageEventType.SELECTION_CHANGED`, so when the selection of RectLight is changed, the entire manipulator is redrawn. - When the model's `transform` is changed, the root transform of the manipulator is updated. For width, height and intensity, the model demonstrates two strategies working with the data. It keeps the attribute data during the manipulating, so that the manipulator has the only one truth of data from the model. When the manipulator requests the attributes from the model, the model computes the position using USD API and returns it to the manipulator. ## Overlaying with the viewport We use `sc.Manipulator` to draw the manipulator in 3D view. To show it in the viewport, we overlay `sc.SceneView` with our `sc.Manipulator` on top of the viewport window. ```python from omni.kit.viewport.utility import get_active_viewport_window viewport_window = get_active_viewport_window() # Create a unique frame for our SceneView with viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: LightManipulator(model=LightModel()) ``` To synchronize the projection and view matrices, `omni.kit.viewport.utility` has the method `add_scene_view`, which replaces the camera model, and the manipulator visually looks like it's in the main viewport. ```python # Register the SceneView with the Viewport to get projection and view updates viewport_window.viewport_api.add_scene_view(self._scene_view) ```
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/docs/index.rst
omni.example.ui_scene.light_manipulator ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md
# How to make an extension to display Object Info The object info extension displays the selected prim’s Path and Type. This guide is great for first time extension builders. > NOTE: Visual Studio Code is the preferred IDE, hence forth we will be referring to it throughout this guide. # Learning Objectives In this tutorial you learn how to: - Create an extension in Omniverse Code - Use the omni.ui.scene API - Display object info in the viewport - Translate from World space to Local space # Prerequisites We recommend that you complete these tutorials before moving forward: - [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial) - [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims) > :exclamation: <span style="color:red"><b> WARNING: Check that Viewport Utility Extension is turned ON in the extension manager: </b></span> <br> ![](./Images/viewportUtilOn.PNG) # Step 1: Create an Extension > **Note:** This is a review, if you know how to create an extension, feel free to skip this step. For this guide, we will briefly go over how to create an extension. If you have not completed [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) we recommend you pause here and complete that before moving forward. ## Step 1.1: Create the extension template In Omniverse Code navigate to the `Extensions` tab and create a new extension by clicking the ➕ icon in the upper left corner and select `New Extension Template Project`. <br> ![](./Images/ext_tab.png) <br> <icon> | <new template> :-------------------------:|:-------------------------: ![icon](./Images/icon_create.png "Plus Icon") | ![new template](./Images/new_template.png "New Extension Template") <br> A new extension template window and Visual Studio Code will open after you have selected the folder location, folder name, and extension ID. ## Step 1.2: Naming your extension Before beginning to code, navigate into `VS Code` and change how the extension is viewed in the **Extension Manager**. It's important to give your extension a title and description for the end user to understand the extension's purpose. <br> Inside of the `config` folder, locate the `extension.toml` file: ![](./Images/step1.2_naming_ext_tomlFile.PNG) <br> > **Note:** `extension.toml` is located inside of the `exts` folder you created for your extension. <br> ![](./Images/fileStructTOML.PNG) <br> Inside of this file, there is a title and description for how the extension will look in the **Extension Manager**. Change the title and description for the object info extension. Here is an example of how it looks in `VS code` and how it looks in the **Extension Manager**: ![title and description](./Images/step1.2_naming_ext_uiTitle_uiDescrip.PNG) <br> ![new ui](./Images/step1.2_naming_ext_ui_update.PNG) # Step 2: Get the active viewport In this section, you import `omni.kit.viewport.utility` into `extension.py`. Then, you use it to store the active viewport. Finally, you will print the name of the active viewport to the console. ## Step 2.1: Navigate to `extension.py` Navigate to `extension.py`: ![](./Images/fileStruct.PNG) This module contains boilerplate code for building a new extension: ![extension.py module](./Images/step2.extension_script.PNG) ## Step 2.2: Import the `omni.kit.viewport.utility` Import the viewport utility: ```python import omni.ext import omni.ui as ui # NEW: Import function to get the active viewport from omni.kit.viewport.utility import get_active_viewport_window ``` Now that you've imported the viewport utility library, begin adding to the `MyExtension` class. ## Step 2.3: Get the activate viewport window In `on_startup()` set the `viewport_window` variable to the active viewport: ```python class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[company.hello.world] MyExtension startup") # NEW: Get the active Viewport viewport_window = get_active_viewport_window() self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): ui.Label("Some Label") def on_click(): print("clicked!") ui.Button("Click Me", clicked_fn=lambda: on_click()) ... ``` At startup the active window is the default Viewport. ## Step 2.4: Print the active viewport In `on_click()`, print the active viewport: ```python def on_click(): print(viewport_window) ``` Here, `on_click()` is acting as a convenience method that ensures you stored the active viewport ## Step 2.5: Review your changes Navigate to Omniverse Code, click the **Click Me** button inside of *My Window*, and locate "Viewport" in the *Console*. ![](./Images/viewport%20displayed%20on%20click.PNG "Viewport on Click Me") Here you see the result of the print statement you added in the last step. > **Tip:** If you encounter an error in your console, please refer to the [Viewport Utility tip in Prerequisites](#prerequisites) <br> ## Step 2.6: Create `object_info_model.py` In this new module, you will create the necessary information for the object information to be called, such as the selected prim and tracking when the selection changes. Create a file in the same file location as `extension.py` and name it `object_info_model.py`. <br> # Step 3: `object_info_model.py` Code > **Note:** Work in the `object_info_model.py` module for this section. <br> The objective of this step is to get the basic information that the `Manipulator` and `Viewport` will need to display on the selected prim. ## Step 3.1: Import scene from `omni.ui` As with `extension.py`, import `scene` from `omni.ui` to utilize scene related utilities. Also import `omni.usd`. ```python from omni.ui import scene as sc import omni.usd ``` ## Step 3.2: Begin setting up variables Next, create a new class and begin setting variables. Create the `ObjInfoModel` below the imports: ```python from omni.ui import scene as sc import omni.usd class ObjInfoModel(sc.AbstractManipulatorModel): """ The model tracks the position and info of the selected object. """ ``` ## Step 3.3: Initialize `ObjInfoModel` Use `__init__()` inside this class to initialize the object and events. In `__init__()`, set the variable for the current selected prim: ```python from omni.ui import scene as sc import omni.usd class ObjInfoModel(sc.AbstractManipulatorModel): """ The model tracks the position and info of the selected object. """ def __init__(self) -> None: super().__init__() # Current selected prim self.prim = None self.position = [0, 0, 0] ``` ## Step 3.4: Use UsdContext to listen for selection changes Finally, get the `UsdContext` ([see here for more information on UsdContext](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.usd/docs/index.html#omni.usd.UsdContext)) to track when the selection changes and create a stage event callback function to be used later on: ```python from omni.ui import scene as sc import omni.usd class ObjInfoModel(sc.AbstractManipulatorModel): """ The model tracks the position and info of the selected object. """ def __init__(self) -> None: super().__init__() # Current selected prim self.prim = None self.position = [0, 0, 0] # Save the UsdContext name (we currently only work with a single Context) self.usd_context = omni.usd.get_context() # Track selection changes self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Object Info Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream. We only care about selection changes.""" print("A stage event has occurred") def destroy(self): self.events = None self.stage_event_delegate.unsubscribe() ``` <br> It's important to include `destroy()` in the model class. You want to unsubscribed from events when the model is destroyed. <br> ## Step 4: Work on the object model > **Note:** Work in `extension.py` for this section. Now that you have created `object_info_model.py`, you need to do a few things in `extension.py` use the object model, such as import the model class, create an instance when the extension startsup, and then destroy the model when the extension is shutdown. ## Step 4.1: Import ObjInfoModel Import ObjInfoModel into `extension.py` from `object_info_model.py`: ```python import omni.ext import omni.ui as ui from omni.kit.viewport.utility import get_active_viewport_window # NEW: import model class from .object_info_model import ObjInfoModel ... ``` ## Step 4.2: Create a variable for the object model Create a variable for object model in `__init()__` of the `MyExtension` Class: ```python class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. # NEW: Reference to the objModel when created so we can destroy it later def __init__(self) -> None: super().__init__() self.obj_model = None ... ``` ## Step 4.3: Manage the object model You should then create the object in `on_startup()` and destroy it later on in `on_shutdown()`: ```python def on_startup(self, ext_id): print("[omni.objInfo.tutorial] MyExtension startup") # Get the active Viewport (which at startup is the default Viewport) viewport_window = get_active_viewport_window() # NEW: create the object self.obj_model = ObjInfoModel() self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): ui.Label("Some Label") def on_click(): # Print to see that we did grab the active viewport print(viewport_window) ui.Button("Click Me", clicked_fn=lambda: on_click()) def on_shutdown(self): """Called when the extension is shutting down.""" print("[omni.objInfo.tutorial] MyExtension shutdown") # NEW: Destroy the model when created self.obj_model.destroy() ``` <details> <summary>Click here for the updated <b>extension.py</b> module </summary> ```python import omni.ext import omni.ui as ui from omni.kit.viewport.utility import get_active_viewport_window from .object_info_model import ObjInfoModel # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def __init__(self) -> None: super().__init__() self.obj_model = None def on_startup(self, ext_id): """Called when the extension is starting up. Args: ext_id: Extension ID provided by Kit. """ print("[omni.objInfo.tutorial] MyExtension startup") # Get the active Viewport (which at startup is the default Viewport) viewport_window = get_active_viewport_window() # create the object self.obj_model = ObjInfoModel() self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): ui.Label("Some Label") def on_click(): # Print to see that we did grab the active viewport print(viewport_window) ui.Button("Click Me", clicked_fn=lambda: on_click()) def on_shutdown(self): """Called when the extension is shutting down.""" print("[omni.objInfo.tutorial] MyExtension shutdown") # Destroy the model when created self.obj_model.destroy() ``` </details> <br> # Step 5: Get the selected prim's data At this point, there is nothing viewable in Omniverse Code as you the code is not doing anything yet when stage events occur. In this section, you will fill in the logic for the stage event callback to get the selected object's information. By the end of Step 5 you should be able to view the object info in the console. > **Note:** Work in `object_info_model.py` for this section. At this point, you have created the start of the `on_stage_event()` callback in `object_info_model.py` but there is nothing happening in the event. Replace what's in `on_stage_event()` with the variable for the prim path and where that path information is located: ```python def on_stage_event(self, event): """Called by stage_event_stream.""" # NEW prim_path = self.usd_context.get_selection().get_selected_prim_paths() if not prim_path: return stage = self.usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path[0]) self.prim = prim self.current_path = prim_path[0] print("prim: " + str(prim)) ... ``` You can check that this is working by navigating back to Omniverse Code and create a prim in the viewport. When the prim is created, it's path should display at the bottom. ![](./Images/path%20displayed.PNG) # Step 6: Object Path Name in Scene In this step you create another `__init__()` method in a new class to represent the position. This position will be taken directly from USD when requested. ## Step 6.1: Nest the `PositionItem` class Nest the new `PositionItem` class inside of the `ObjInfoModel` class as so: ```python class ObjInfoModel(sc.AbstractManipulatorModel): """ The model tracks the position and info of the selected object. """ # NEW: needed for when we call item changed class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because we take the position directly from USD when requesting. """ def __init__(self) -> None: super().__init__() self.value = [0, 0, 0] ... ``` ## Step 6.2: Set path and position Set the current path and update the position from `[0,0,0]` to store a `PositionItem`: ```python def __init__(self) -> None: super().__init__() # Current selected prim self.prim = None #NEW: set to current path. self.current_path = "" # NEW: update to hold position obj created self.position = ObjInfoModel.PositionItem() # Save the UsdContext name (we currently only work with a single Context) self.usd_context = omni.usd.get_context() # Track selection changes self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Object Info Selection Update" ) ... ``` ## Step 6.3: Check the stage After updating the position, check the stage when the selection of an object is changed. Do this with an `if` statement in `on_stage_event()`, like so: ```python def on_stage_event(self, event): # NEW: if statement to only check when selection changed if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_path = self.usd_context.get_selection().get_selected_prim_paths() if not prim_path: return stage = self.usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path[0]) self.prim = prim self.current_path = prim_path[0] # NEW: Update on item change # Position is changed because new selected object has a different position self._item_changed(self.position) ... ``` ## Step 6.4: Set identifiers Finally, create a new function underneath `on_stage_event()` to set the identifiers: ```python # NEW: function to get identifiers from the model def get_item(self, identifier): if identifier == "name": return self.current_path def destroy(self): self.events = None self.stage_event_delegate.unsubscribe() ``` <details> <summary>Click here for the updated <b>object_info_model.py</b> module </summary> ```python from omni.ui import scene as sc import omni.usd class ObjInfoModel(sc.AbstractManipulatorModel): """ The model tracks the position and info of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because we take the position directly from USD when requesting. """ def __init__(self) -> None: super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() # Current selected prim self.prim = None self.current_path = "" self.position = ObjInfoModel.PositionItem() self.usd_context = omni.usd.get_context() # Track selection changes self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Object Info Selection Update" ) def on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_path = self.usd_context.get_selection().get_selected_prim_paths() if not prim_path: return stage = self.usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path[0]) self.prim = prim self.current_path = prim_path[0] # Position is changed because new selected object has a different position self._item_changed(self.position) def get_item(self, identifier): if identifier == "name": return self.current_path def destroy(self): self.events = None self.stage_event_delegate.unsubscribe() ``` </details> <br> # Step 7: The Manipulator Class In this step you will create a new module for the manipulator class for the object info, which will be displayed in the viewport in another step ([see here for more information on the Manipulator Class in Omniverse](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Manipulator.html)).<br> ## Step 7.1: Create `object_info_manipulator.py` Similar to when you created `object_info_model.py`, create a new module in the same folder and name it `object_info_manipulator.py`. The objective of this module is to getf the object model's details, such as name and path, and display it in the viewport through using `on_build()`. This is important as it connects the nested data in `object_info_model.py`. ## Step 7.2: Import ui import from omni.ui: ```python from omni.ui import scene as sc import omni.ui as ui ``` ## Step 7.3: Create `ObjectInfoManipilator` Create the `ObjInfoManipulator` class: ```python ... class ObjInfoManipulator(sc.Manipulator): """Manipulator that displays the object path and material assignment with a leader line to the top of the object's bounding box. """ ``` ## Step 7.4 Populate `ObjInfoManipulator` Populate the `ObjInfoManipulator` class with `on_build()`: ```python ... def on_build(self): """Called when the model is changed and rebuilds the whole manipulator""" if not self.model: return # If we don't have a selection then just return if self.model.get_item("name") == "": return position = [0, 0, 0] sc.Label(f"Path: {self.model.get_item('name')}") ``` This method checks if there is a selection and creates a label for the path. ## Step 7.5 Invalidate the manipulator on model update Before moving on from `object_info_manipulator.py`, navigate to the end of the file and call `invalidate()`. ```python ... def on_model_updated(self, item): # Regenerate the manipulator self.invalidate() ``` This method purges old memory when the model is updated. <details> <summary>Click here for the full <b>object_info_manipulator.py</b> module </summary> ```python from omni.ui import scene as sc import omni.ui as ui class ObjInfoManipulator(sc.Manipulator): """Manipulator that displays the object path and material assignment with a leader line to the top of the object's bounding box. """ def on_build(self): """Called when the model is changed and rebuilds the whole manipulator""" if not self.model: return # If we don't have a selection then just return if self.model.get_item("name") == "": return position = [0, 0, 0] sc.Label(f"Path: {self.model.get_item('name')}") def on_model_updated(self, item): # Regenerate the manipulator self.invalidate() ``` </details> <br> # Step 8: Displaying information in the viewport In this step, you will create a new module that uses the gathered information from other modules and displays them in the active viewport. ## Step 8.1: Create new file Add this module to the same folder and name it `viewport_scene.py`. Import the `scene` from `omni.ui`, `ObjInfoModel`, and `ObjInfoManipulator`: ```python from omni.ui import scene as sc import omni.ui as ui from .object_info_manipulator import ObjInfoManipulator from .object_info_model import ObjInfoModel ``` ## Step 8.2 Create new class Create the `ViewportSceneInfo` class and define the `__init__()`: ```python ... class ViewportSceneInfo(): """The Object Info Manipulator, placed into a Viewport""" def __init__(self, viewport_window, ext_id) -> None: self.scene_view = None self.viewport_window = viewport_window ``` ## Step 8.3 Display object information To display the information, set the default SceneView. Then add the manipulator into the SceneView's scene and register it with the Viewport: ```python ... class ViewportSceneInfo(): """The Object Info Manipulator, placed into a Viewport""" def __init__(self, viewport_window, ext_id) -> None: self.scene_view = None self.viewport_window = viewport_window # NEW: Create a unique frame for our SceneView with self.viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self.scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self.scene_view.scene: ObjInfoManipulator(model=ObjInfoModel()) # Register the SceneView with the Viewport to get projection and view updates self.viewport_window.viewport_api.add_scene_view(self.scene_view) ``` ## Step 8.4: Clean up scene and viewport memory Before closing out on `viewport_scene.py` don't forget to call `destroy()` to clear the scene and un-register our unique SceneView from the Viewport. ```python ... def __del__(self): self.destroy() def destroy(self): if self.scene_view: # Empty the SceneView of any elements it may have self.scene_view.scene.clear() # un-register the SceneView from Viewport updates if self.viewport_window: self.viewport_window.viewport_api.remove_scene_view(self.scene_view) # Remove our references to these objects self.viewport_window = None self.scene_view = None ``` <details> <summary>Click here for the full <b>viewport_scene.py</b> module </summary> ```python from omni.ui import scene as sc import omni.ui as ui from .object_info_manipulator import ObjInfoManipulator from .object_info_model import ObjInfoModel class ViewportSceneInfo(): """The Object Info Manipulator, placed into a Viewport""" def __init__(self, viewport_window, ext_id) -> None: self.scene_view = None self.viewport_window = viewport_window # Create a unique frame for our SceneView with self.viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self.scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self.scene_view.scene: ObjInfoManipulator(model=ObjInfoModel()) # Register the SceneView with the Viewport to get projection and view updates self.viewport_window.viewport_api.add_scene_view(self.scene_view) def __del__(self): self.destroy() def destroy(self): if self.scene_view: # Empty the SceneView of any elements it may have self.scene_view.scene.clear() # un-register the SceneView from Viewport updates if self.viewport_window: self.viewport_window.viewport_api.remove_scene_view(self.scene_view) # Remove our references to these objects self.viewport_window = None self.scene_view = None ``` </details> <br> # Step 9: Cleaning up `extension.py` > **Note:** Work in `extension.py` for this section. Now that you've have established a Viewport, you need to clean up `extension.py` to reflect these changes. You will remove some of code from previous steps and ensure that the viewport is flushed out on shutdown. ## Step 9.1: Import class Import `ViewportSceneInfo`: ```python import omni.ext from omni.kit.viewport.utility import get_active_viewport_window # NEW: from .viewport_scene import ViewportSceneInfo ``` ## Step 9.2: Remove `ObjInfoModel` Remove the import from the `object_info_model` module as it will no longer be used: ```python # REMOVE from .object_info_model import ObjInfoModel ``` ## Step 9.3: Remove reference As you removed the import from `ObjInfoModel` import, remove its reference in the `__init__()` method and replace it with the `viewport_scene`: ```python class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def __init__(self) -> None: super().__init__() # NEW: removed reference to objmodelinfo and replaced with viewportscene self.viewport_scene = None ``` ## Step 9.4: Remove start up code Remove the start up code that constructs the `ObjInfoModel` object and the code following it that creates the extension window and **Click Me** button: ```python ... def on_startup(self, ext_id): # # # !REMOVE! # # # print("[omni.objInfo.tutorial] MyExtension startup") viewport_window = get_active_viewport_window() self.obj_model = ObjInfoModel() self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): ui.Label("Some Label") def on_click(): print(viewport_window) ui.Button("Click Me", clicked_fn=lambda: on_click()) # # # END # # # # # # !REPLACE WITH! # # # viewport_window = get_active_viewport_window() self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id) # # # END # # # ``` <details> <summary>Click to view final <b>on_startup</b> code</summary> ```python def on_startup(self, ext_id): viewport_window = get_active_viewport_window() self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id) ``` </details> <br> ## Step 9.5: Clean up viewport memory Finally, update `on_shutdown()` to clean up the viewport: ```python ... def on_shutdown(self): """Called when the extension is shutting down.""" # NEW: updated to destroy viewportscene if self.viewport_scene: self.viewport_scene.destroy() self.viewport_scene = None ``` <details> <summary>Click to view the updated <b>extension.py</b> </summary> ```python import omni.ext import omni.ui as ui from omni.kit.viewport.utility import get_active_viewport_window from .viewport_scene import ViewportSceneInfo class MyExtension(omni.ext.IExt): """Creates an extension which will display object info in 3D over any object in a UI Scene. """ # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def __init__(self) -> None: super().__init__() self.viewport_scene = None def on_startup(self, ext_id): viewport_window = get_active_viewport_window() self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id) def on_shutdown(self): """Called when the extension is shutting down.""" if self.viewport_scene: self.viewport_scene.destroy() self.viewport_scene = None ``` </details> <br> ## Congratulations! You should be able to create a prim in the viewport and view the Object Info at the world position `[0,0,0]`. ![](./Images/step3_end_viewport.PNG) >💡 Tip: If you are logging any errors in the Console in Omniverse Code after updating `extention.py` try refreshing the application. <br> # Step 10: Displaying Object Info in Local Space At this stage, the Object Info is displaying in the viewport but it is displayed at the origin. This means that regardless of where your object is located in the World, the info will always be displayed at [0,0,0]. In the next few steps you will convert this into Local Space. By the end of step 4 the Object Info should follow the object. ## Step 10.1: Import USD > **Note:** Work in `object_info_model.py` for this section. In this step and the following steps, we will be doing a little bit of math. Before we jump into that though, let's import what we need to make this work into `object_info_model.py`. We will be importing primarily what we need from USD and we will place these imports at the top of the file: ```python # NEW IMPORTS from pxr import Usd from pxr import UsdGeom from omni.ui import scene as sc import omni.usd ``` ## Step 10.2: Add identifier Add a new identifier for the position in `get_item()`: ```python ... def get_item(self, identifier): if identifier == "name": return self.current_path # NEW: new identifier elif identifier == "position": return self.position ``` ## Step 10.3: Add `get_as_floats()` After adding to `get_item()`, create a new function to get the position of the prim. Call this function `get_as_floats()`: ```python ... # NEW: new function to get position of prim def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] ``` This function requests the position and value from the item. ## Step 10.4: Define `get_position()`: Although you created this new function to get the position, you've yet to define the position. The position will be defined in a new function based on the bounding box we will compute for the prim. Name the new function `get_position()` and get a reference to the stage: ```python ... # NEW: new function that defines the position based on the bounding box of the prim def get_position(self): stage = self.usd_context.get_stage() if not stage or self.current_path == "": return [0, 0, 0] ``` ## Step 10.5: Get the position Use `get_position()` to get the position directly form USD using the bounding box: ```python ... def get_position(self): stage = self.usd_context.get_stage() if not stage or self.current_path == "": return [0, 0, 0] # Get position directly from USD prim = stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() #bbox stands for bounding box bboxMax = range.GetMax() ``` ## Step 10.6: Find the top center Finally, find the top center of the bounding box. Additionally, add a small offset upward so that the information is not overlapping our prim. Append this code to `get_position()`: ```python ... def get_position(self): stage = self.usd_context.get_stage() if not stage or self.current_path == "": return [0, 0, 0] # Get position directly from USD prim = stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() #bbox stands for bounding box bboxMax = range.GetMax() # NEW # Find the top center of the bounding box and add a small offset upward. x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5 y_Pos = bboxMax[1] + 5 z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5 position = [x_Pos, y_Pos, z_Pos] return position ``` <details> <summary>Click here for the final <b>object_info_model.py</b> code for this step.</summary> ```python from pxr import Usd from pxr import UsdGeom from omni.ui import scene as sc import omni.usd class ObjInfoModel(sc.AbstractManipulatorModel): """ The model tracks the position and info of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because we take the position directly from USD when requesting. """ def __init__(self) -> None: super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() # Current selected prim self.prim = None self.current_path = "" self.position = ObjInfoModel.PositionItem() # Save the UsdContext name (we currently only work with a single Context) self.usd_context = omni.usd.get_context() # Track selection changes self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Object Info Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream. We only care about selection changes.""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_path = self.usd_context.get_selection().get_selected_prim_paths() if not prim_path: return stage = self.usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path[0]) self.prim = prim self.current_path = prim_path[0] # Position is changed because new selected object has a different position self._item_changed(self.position) def get_item(self, identifier): if identifier == "name": return self.current_path elif identifier == "position": return self.position def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] # defines the position based on the bounding box of the prim def get_position(self): stage = self.usd_context.get_stage() if not stage or self.current_path == "": return [0, 0, 0] # Get position directly from USD prim = stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() #bbox stands for bounding box bboxMax = range.GetMax() # Find the top center of the bounding box and add a small offset upward. x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5 y_Pos = bboxMax[1] + 5 z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5 position = [x_Pos, y_Pos, z_Pos] return position def destroy(self): self.events = None self.stage_event_delegate.unsubscribe() ``` </details> <br> # Step 11: Updating `ObjInfoManipulator` > **Note:** You are working in `object_info_manipulator.py` for this section. In this step, you need to update the position value and to position the Object Info at the object's origin and then offset it in the up-direction. You'll also want to make sure that it is scaled properly in the viewport. Fortunately, this does not require a big alteration to our existing code. You merely need to add onto the `on_build` function in the `object_info_manipulator.py` module: ```python ... def on_build(self): """Called when the model is changed and rebuilds the whole manipulator""" if not self.model: return # If we don't have a selection then just return if self.model.get_item("name") == "": return # NEW: update to position value and added transform functions to position the Label at the object's origin and +5 in the up direction # we also want to make sure it is scaled properly position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): with sc.Transform(scale_to=sc.Space.SCREEN): sc.Label(f"Path: {self.model.get_item('name')}") sc.Label(f"Path: {self.model.get_item('name')}") ... ``` # Step 12: Moving the Label with the prim In the viewport, the text does not follow our object despite positioning the label at the top center of the bounding box of the object. The text also remains in the viewport even when the object is no longer selected. This is because we are reacting to all stage events and not only when a prim is selected. In this final step we will be guiding you to cleaning up these issues. > **Note:** Work in `object_info_model.py` for this section ## 12.1: Import `Tf` Place one more import into `object_info_model.py` at the top of the file, as so: ```python # NEW from pxr import Tf from pxr import Usd from pxr import UsdGeom from omni.ui import scene as sc import omni.usd ``` You will use `Tf` to receive notifications of any selection changes. ### 12.2: Store the stage listener Add a new variable to store the stage listener under the second `__init__()` method: ```python ... def __init__(self) -> None: super().__init__() # Current selected prim self.prim = None self.current_path = "" # NEW: new variable self.stage_listener = None self.position = ObjInfoModel.PositionItem() ... ``` ### 12.3: Handle prim selection events Now, you need to add some code to `on_stage_event()`. You need to do a few things in this function, such as checking if the `prim_path` exists, turn off the manipulator if it does not, then check if the selected item is a `UsdGeom.Imageable` and remove the stage listener if not. Additionally, notice a change with the stage listener when the selection has changed. ```python ... def on_stage_event(self, event): """Called by stage_event_stream. We only care about selection changes.""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_path = self.usd_context.get_selection().get_selected_prim_paths() # NEW: if prim path doesn't exist we want to make sure nothing shows up because that means we do not have a prim selected if not prim_path: # This turns off the manipulator when everything is deselected self.current_path = "" self._item_changed(self.position) return stage = self.usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path[0]) # NEW: if the selected item is not a prim we need to revoke the stagelistener since we don't need to update anything if not prim.IsA(UsdGeom.Imageable): self.prim = None # Revoke the Tf.Notice listener, we don't need to update anything if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return # NEW: Register a notice when objects in the scene have changed if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage) ``` <details> <summary>Click here for the full <b>on_stage_event</b> function </summary> ```python def on_stage_event(self, event): """Called by stage_event_stream. We only care about selection changes.""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_path = self.usd_context.get_selection().get_selected_prim_paths() if not prim_path: self.current_path = "" self._item_changed(self.position) return stage = self.usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path[0]) if not prim.IsA(UsdGeom.Imageable): self.prim = None if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage) ``` </details> ## 12.4: Setup `notice_changed()` callback In the final step, create a new function that will be called when any objects change. It will loop through all changed prim paths until the selected one is found and get the latest position for the selected prim. After this, the path should follow the selected object.: ```python ... # NEW: function that will get called when objects change in the scene. We only care about our selected object so we loop through all notices that get passed along until we find ours def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None: """Called by Tf.Notice. Used when the current selected object changes in some way.""" for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) ... ``` <details> <summary>Click here for the final <b>object_info_model.py</b> code </summary> ```python from pxr import Tf from pxr import Usd from pxr import UsdGeom from omni.ui import scene as sc import omni.usd class ObjInfoModel(sc.AbstractManipulatorModel): """ The model tracks the position and info of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because we take the position directly from USD when requesting. """ def __init__(self) -> None: super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() # Current selected prim self.prim = None self.current_path = "" self.stage_listener = None self.position = ObjInfoModel.PositionItem() # Save the UsdContext name (we currently only work with a single Context) self.usd_context = omni.usd.get_context() # Track selection changes self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Object Info Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream. We only care about selection changes.""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_path = self.usd_context.get_selection().get_selected_prim_paths() if not prim_path: self.current_path = "" self._item_changed(self.position) return stage = self.usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path[0]) if not prim.IsA(UsdGeom.Imageable): self.prim = None if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage) self.prim = prim self.current_path = prim_path[0] # Position is changed because new selected object has a different position self._item_changed(self.position) def get_item(self, identifier): if identifier == "name": return self.current_path elif identifier == "position": return self.position def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] def get_position(self): """Returns position of currently selected object""" stage = self.usd_context.get_stage() if not stage or self.current_path == "": return [0, 0, 0] # Get position directly from USD prim = stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() # Find the top center of the bounding box and add a small offset upward. x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5 y_Pos = bboxMax[1] + 5 z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5 position = [x_Pos, y_Pos, z_Pos] return position # loop through all notices that get passed along until we find selected def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None: """Called by Tf.Notice. Used when the current selected object changes in some way.""" for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) def destroy(self): self.events = None self.stage_event_delegate.unsubscribe() ``` </details> # Congratulations! Your viewport should now display the object info above the selected object and move with the prim in the scene. You have successfully created the Object Info Extension! ![](./Images/objectinfo_finished.gif)
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/extension.py
import omni.ext import omni.ui as ui from omni.kit.viewport.utility import get_active_viewport_window from .viewport_scene import ViewportSceneInfo class MyExtension(omni.ext.IExt): """Creates an extension which will display object info in 3D over any object in a UI Scene. """ # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def __init__(self) -> None: super().__init__() self.viewport_scene = None def on_startup(self, ext_id): viewport_window = get_active_viewport_window() self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id) def on_shutdown(self): """Called when the extension is shutting down.""" if self.viewport_scene: self.viewport_scene.destroy() self.viewport_scene = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/viewport_scene.py
from omni.ui import scene as sc import omni.ui as ui from .object_info_manipulator import ObjInfoManipulator from .object_info_model import ObjInfoModel class ViewportSceneInfo(): def __init__(self, viewportWindow, ext_id) -> None: self.sceneView = None self.viewportWindow = viewportWindow with self.viewportWindow.get_frame(ext_id): self.sceneView = sc.SceneView() with self.sceneView.scene: ObjInfoManipulator(model=ObjInfoModel()) self.viewportWindow.viewport_api.add_scene_view(self.sceneView) def __del__(self): self.destroy() def destroy(self): if self.sceneView: self.sceneView.scene.clear() if self.viewportWindow: self.viewportWindow.viewport_api.remove_scene_view(self.sceneView) self.viewportWindow = None self.sceneView = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/object_info_model.py
from pxr import Tf from pxr import Usd from pxr import UsdGeom from omni.ui import scene as sc import omni.usd class ObjInfoModel(sc.AbstractManipulatorModel): """ The model tracks the position and info of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because we take the position directly from USD when requesting. """ def __init__(self) -> None: super().__init__() self.value = [0, 0, 0] def __init__(self) -> None: super().__init__() # Current selected prim self.prim = None self.current_path = "" self.stage_listener = None self.position = ObjInfoModel.PositionItem() # Save the UsdContext name (we currently only work with a single Context) self.usd_context = omni.usd.get_context() # Track selection changes self.events = self.usd_context.get_stage_event_stream() self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event, name="Object Info Selection Update" ) def on_stage_event(self, event): """Called by stage_event_stream. We only care about selection changes.""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): prim_path = self.usd_context.get_selection().get_selected_prim_paths() if not prim_path: self.current_path = "" self._item_changed(self.position) return stage = self.usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path[0]) if not prim.IsA(UsdGeom.Imageable): self.prim = None if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage) self.prim = prim self.current_path = prim_path[0] # Position is changed because new selected object has a different position self._item_changed(self.position) def get_item(self, identifier): if identifier == "name": return self.current_path elif identifier == "position": return self.position def get_as_floats(self, item): if item == self.position: # Requesting position return self.get_position() if item: # Get the value directly from the item return item.value return [] def get_position(self): """Returns position of currently selected object""" stage = self.usd_context.get_stage() if not stage or self.current_path == "": return [0, 0, 0] # Get position directly from USD prim = stage.GetPrimAtPath(self.current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() # Find the top center of the bounding box and add a small offset upward. x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5 y_Pos = bboxMax[1] + 5 z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5 position = [x_Pos, y_Pos, z_Pos] return position # loop through all notices that get passed along until we find selected def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None: """Called by Tf.Notice. Used when the current selected object changes in some way.""" for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) def destroy(self): self.events = None self.stage_event_delegate.unsubscribe()
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/object_info_manipulator.py
from omni.ui import scene as sc import omni.ui as ui class ObjInfoManipulator(sc.Manipulator): def on_build(self): """Called when the model is changed and rebuilds the whole manipulator""" if not self.model: return # If we don't have a selection then just return if self.model.get_item("name") == "": return # NEW: update to position value and added transform functions to position the Label at the object's origin and +5 in the up direction # we also want to make sure it is scaled properly position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): with sc.Transform(scale_to=sc.Space.SCREEN): # END NEW sc.Label(f"Path: {self.model.get_item('name')}") sc.Label(f"Path: {self.model.get_item('name')}") def on_model_updated(self, item): # Regenerate the manipulator self.invalidate()
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/config/extension.toml
[package] version = "1.0.0" authors = ["NVIDIA"] title = "Omni UI Scene Object Info Example" description = "This example shows a 3D info popover-type tool tip scene object" readme = "docs/README.md" repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene" category = "Documentation" keywords = ["ui", "example", "scene", "docs", "documentation", "popover"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.ui.scene" = { } "omni.usd" = { } "omni.kit.viewport.utility" = { } [[python.module]] name = "omni.example.ui_scene.object_info" [[test]] args = ["--/renderer/enabled=pxr", "--/renderer/active=pxr", "--no-window"] dependencies = ["omni.hydra.pxr", "omni.kit.window.viewport"]
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ObjectInfoExtension"] import carb import omni.ext from omni.kit.viewport.utility import get_active_viewport_window from .viewport_scene import ViewportScene class ObjectInfoExtension(omni.ext.IExt): """Creates an extension which will display object info in 3D over any object in a UI Scene. """ def __init__(self): self._viewport_scene = None def on_startup(self, ext_id: str) -> None: """Called when the extension is starting up. Args: ext_id: Extension ID provided by Kit. """ # Get the active Viewport (which at startup is the default Viewport) viewport_window = get_active_viewport_window() # Issue an error if there is no Viewport if not viewport_window: carb.log_error(f"No Viewport Window to add {ext_id} scene to") return # Build out the scene self._viewport_scene = ViewportScene(viewport_window, ext_id) def on_shutdown(self) -> None: """Called when the extension is shutting down.""" if self._viewport_scene: self._viewport_scene.destroy() self._viewport_scene = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/viewport_scene.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportScene"] from omni.ui import scene as sc import omni.ui as ui from .object_info_manipulator import ObjectInfoManipulator from .object_info_model import ObjectInfoModel class ViewportScene(): """The Object Info Manipulator, placed into a Viewport""" def __init__(self, viewport_window: ui.Window, ext_id: str) -> None: self._scene_view = None self._viewport_window = viewport_window # Create a unique frame for our SceneView with self._viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: ObjectInfoManipulator(model=ObjectInfoModel()) # Register the SceneView with the Viewport to get projection and view updates self._viewport_window.viewport_api.add_scene_view(self._scene_view) def __del__(self): self.destroy() def destroy(self): if self._scene_view: # Empty the SceneView of any elements it may have self._scene_view.scene.clear() # Be a good citizen, and un-register the SceneView from Viewport updates if self._viewport_window: self._viewport_window.viewport_api.remove_scene_view(self._scene_view) # Remove our references to these objects self._viewport_window = None self._scene_view = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import *
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/object_info_model.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ObjectInfoModel"] from pxr import Tf from pxr import Usd from pxr import UsdGeom from pxr import UsdShade from omni.ui import scene as sc import omni.usd # The distance to raise above the top of the object's bounding box TOP_OFFSET = 5 class ObjectInfoModel(sc.AbstractManipulatorModel): """ The model tracks the position and info of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because we take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] def __init__(self): super().__init__() # Current selected prim and material self._prim = None self._current_path = "" self._material_name = "" self._stage_listener = None self.position = ObjectInfoModel.PositionItem() # Save the UsdContext name (we currently only work with a single Context) usd_context = self._get_context() # Track selection changes self._events = usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="Object Info Selection Update" ) def _get_context(self) -> Usd.Stage: # Get the UsdContext we are attached to return omni.usd.get_context() def _notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None: """Called by Tf.Notice. Used when the current selected object changes in some way.""" for p in notice.GetChangedInfoOnlyPaths(): if self._current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position if identifier == "name": return self._current_path if identifier == "material": return self._material_name def get_as_floats(self, item): if item == self.position: # Requesting position return self._get_position() if item: # Get the value directly from the item return item.value return [] def _on_stage_event(self, event): """Called by stage_event_stream. We only care about selection changes.""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_kit_selection_changed() def _on_kit_selection_changed(self): """Called when a selection has changed.""" # selection change, reset it for now self._current_path = "" usd_context = self._get_context() stage = usd_context.get_stage() if not stage: return prim_paths = usd_context.get_selection().get_selected_prim_paths() if not prim_paths: # This turns off the manipulator when everything is deselected self._item_changed(self.position) return prim = stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): self._prim = None # Revoke the Tf.Notice listener, we don't need to update anything if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None return if not self._stage_listener: # This handles camera movement self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage) material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() if material: self._material_name = str(material.GetPath()) else: self._material_name = "N/A" self._prim = prim self._current_path = prim_paths[0] # Position is changed because new selected object has a different position self._item_changed(self.position) def _get_position(self): """Returns position of currently selected object""" stage = self._get_context().get_stage() if not stage or not self._current_path: return [0, 0, 0] # Get position directly from USD prim = stage.GetPrimAtPath(self._current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() # Find the top center of the bounding box and add a small offset upward. position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + TOP_OFFSET, (bboxMin[2] + bboxMax[2]) * 0.5] return position
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/object_info_manipulator.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["ObjectInfoManipulator"] from omni.ui import color as cl from omni.ui import scene as sc import omni.ui as ui LEADER_LINE_CIRCLE_RADIUS = 2 LEADER_LINE_THICKNESS = 2 LEADER_LINE_SEGMENT_LENGTH = 20 VERTICAL_MULT = 1.5 HORIZ_TEXT_OFFSET = 5 LINE1_OFFSET = 3 LINE2_OFFSET = 0 class ObjectInfoManipulator(sc.Manipulator): """Manipulator that displays the object path and material assignment with a leader line to the top of the object's bounding box. """ def on_build(self): """Called when the model is changed and rebuilds the whole manipulator""" if not self.model: return # If we don't have a selection then just return if self.model.get_item("name") == "": return position = self.model.get_as_floats(self.model.get_item("position")) # Move everything to where the object is with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Rotate everything to face the camera with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): # Leader lines with a small circle on the end sc.Arc(LEADER_LINE_CIRCLE_RADIUS, axis=2, color=cl.yellow) sc.Line([0, 0, 0], [0, LEADER_LINE_SEGMENT_LENGTH, 0], color=cl.yellow, thickness=LEADER_LINE_THICKNESS) sc.Line([0, LEADER_LINE_SEGMENT_LENGTH, 0], [LEADER_LINE_SEGMENT_LENGTH, LEADER_LINE_SEGMENT_LENGTH * VERTICAL_MULT, 0], color=cl.yellow, thickness=LEADER_LINE_THICKNESS) # Shift text to the end of the leader line with some offset with sc.Transform(transform=sc.Matrix44.get_translation_matrix( LEADER_LINE_SEGMENT_LENGTH + HORIZ_TEXT_OFFSET, LEADER_LINE_SEGMENT_LENGTH * VERTICAL_MULT, 0)): with sc.Transform(scale_to=sc.Space.SCREEN): # Offset each Label vertically in screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, LINE1_OFFSET, 0)): sc.Label(f"Path: {self.model.get_item('name')}", alignment=ui.Alignment.LEFT_BOTTOM) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, LINE2_OFFSET, 0)): sc.Label(f"Material: {self.model.get_item('material')}", alignment=ui.Alignment.LEFT_TOP) def on_model_updated(self, item): # Regenerate the manipulator self.invalidate()
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/docs/CHANGELOG.md
# Changelog omni.example.ui_scene.object_info ## [1.0.0] - 2022-5-1 ### Added - The initial version
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/docs/README.md
# Object Info (omni.example.ui_scene.object_info) ![](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/raw/main/exts/omni.example.ui_scene.object_info/Tutorial/Images/objectinfo_finished.gif) ​ ## Overview This Extension displays the selected prim's Path and Type. ​ ## [Tutorial](../Tutorial/object_info.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 an extension from the Extension Manager in Omniverse Code, set up your files, and use Omniverse's Library. Additionally, the tutorial has a `Final Scripts` folder to use as a reference as you go along. ​[Get started with the tutorial here.](../Tutorial/object_info.tutorial.md) ## Usage Once the extension is enabled in the *Extension Manager*, go to your *Viewport* and right-click to create a prim - such as a cube, sphere, cyclinder, etc. Then, left-click/select it to view the Object Info. ​
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/docs/index.rst
omni.example.ui_scene.object_info ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md
# How to make a Object Info Widget Extension This guide will provide you with a starting point for displaying Object Info and nesting these modules into a Widget. A Widget is a useful utility in `Omniverse Kit` that can be used to add features such as buttons and sliders. # Learning Objectives In this guide you will learn how to: - Create a Widget Extension - Use Omniverse UI Framework - Create a label - (optional) Create a toggle button feature - (optional) Create a slider # Prerequisites It is recommended that you have completed the following: - [Extension Enviroment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial) - [How to make an extension to display Object Info](../../omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md) # Step 1: Create a Widget Module In this series of steps, you will be setting up your Extension to create a module needed for a widget. ## Step 1.1: Clone Slider Tutorial Branch Clone the `slider-tutorial-start` branch of the `kit-extension-sample-ui-scene` [github respositiory](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene) to get the assets needed for this hands-on lab. ## Step 1.2: Add Extension Path to Extension Manager Open the `Extensions Manager` in `Omniverse Code` Select gear icon to display `Extension Search Paths`. Use the <span style="color:green">green</span> :heavy_plus_sign: to add the path to `exts/slider-tutorial-start` from the cloned directory. ![](./Images/add_ext.PNG) :memo: Check that the `UI Scene Object Info` Extension is enabled in the `Extensions Manager` and working by creating a new primitive in the `Viewport` and selecting it, the object's path and info should be displayed above the object. ## Step 1.3 Open VS Code with Shortcut Open `VS Code` directly from the `Extension Manager` ![](./Images/openVS.PNG) :bulb:If you would like to know more about how to create the modules for displaying Object Info, [check out the guide here.](../../omni.example.ui_scene.object_info/Tutorial/object_info.tutorial.md) ## Step 1.4: Create the Module Create a new module called `object_info_widget.py` in the `exts` hierarchy that our other modules are located in. This will be our widget module. `object_info_widget.py` will be building off the Object Info modules provided for you. You will see these modules as `object_info_manipulator.py`, `object_info_model.py`, `viewport_scene.py`, and an updated `extension.py`. :memo: Visual Studio Code (VS Code) is our preferred IDE, hence forth referred to throughout this guide. ## Step 1.5: Set up Widget Class Inside of the `object_info_widget.py`, import `omni.ui` then create the `WidgetInfoManipulator` class to nest our functions. After, initialize our methods, as so: ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class WidgetInfoManipulator(sc.Manipulator): def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.destroy() def destroy(self): self._root = None self._name_label = None ``` This widget will house our widget info to make the information contrasted in the viewport and add other utilities later on. You will accomplish this by creating a box for the label with a background color. ## Step 1.6: Build the widget Let's define this as `on_build_widgets` and use the `Omniverse UI Framework` to create the label for this widget in a `ZStack`. [See here for more documentation on Omniverse UI Framework](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html). ```python ... def on_build_widgets(self): with ui.ZStack(): ``` Once you have established the UI layout, you can create the background for the widget using `ui.Rectangle` and set the border attributes and background color. You can then create the `ui.Label` and set its alignment, as so: ```python ... def on_build_widgets(self): with ui.ZStack(): ui.Rectangle(style={ "background_color": cl(0.2), "border_color": cl(0.7), "border_width": 2, "border_radius": 4, }) self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER) ``` ## Step 1.7: Create Manipulator Functions With a Manipulator, you need to define an `on_build` function. This function is called when the model is changed so that the widget is rebuilt. [You can find more information about the Manipulator here.](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/Manipulator.html) ```python ... self.on_model_updated(None) def on_build(self): """Called when the model is changed and rebuilds the whole slider""" self._root = sc.Transform(visible=False) with self._root: with sc.Transform(scale_to=sc.Space.SCREEN): with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)): self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED) self._widget.frame.set_build_fn(self.on_build_widgets) ``` Now define `on_model_updated()` that was called above. In this function you need to establish what happens if nothing is selected, when to update the prims, and when to update the prim name, as so: ```python ... def on_model_updated(self, _): # if you don't have selection then show nothing if not self.model or not self.model.get_item("name"): self._root.visible = False return # Update the shapes position = self.model.get_as_floats(self.model.get_item("position")) if self._root: self._root.transform = sc.Matrix44.get_translation_matrix(*position) self._root.visible = True # Update the shape name if self._name_label: self._name_label.text = f"Prim:{self.model.get_item('name')}" ``` <details> <summary>Click here for the end code of <b>widget_info_manipulator.py</b></summary> ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui class WidgetInfoManipulator(sc.Manipulator): def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.destroy() def destroy(self): self._root = None self._name_label = None def on_build_widgets(self): with ui.ZStack(): ui.Rectangle(style={ "background_color": cl(0.2), "border_color": cl(0.7), "border_width": 2, "border_radius": 4, }) self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER) self.on_model_updated(None) def on_build(self): """Called when the model is changed and rebuilds the whole slider""" self._root = sc.Transform(visible=False) with self._root: with sc.Transform(scale_to=sc.Space.SCREEN): with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)): self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED) self._widget.frame.set_build_fn(self.on_build_widgets) def on_model_updated(self, _): # if you don't have selection then show nothing if not self.model or not self.model.get_item("name"): self._root.visible = False return # Update the shapes position = self.model.get_as_floats(self.model.get_item("position")) if self._root: self._root.transform = sc.Matrix44.get_translation_matrix(*position) self._root.visible = True # Update the shape name if self._name_label: self._name_label.text = f"Prim:{self.model.get_item('name')}" ``` </details> # Step 2: Update Viewport and Extension Now that you have created a new module, it is important for us to bring this information into `viewport_scene.py` and update `extension.py` to reflect these new changes. ## Step 2.1: Import Widget Info Begin by updating `viewport_scene.py` and importing `WidgetInfoManipulator` at the top of the file with the other imports. ```python from omni.ui import scene as sc import omni.ui as ui from .object_info_manipulator import ObjInfoManipulator from .object_info_model import ObjInfoModel # NEW from .widget_info_manipulator import WidgetInfoManipulator # END NEW ``` ### Step 2.2: Add Display Widget Inside the `ViewportSceneInfo` class, you will add a `display_widget` parameter to `__init__()`: ```python ... class ViewportSceneInfo(): # NEW PARAMETER: display_widget def __init__(self, viewport_window, ext_id, display_widget) -> None: self.scene_view = None self.viewport_window = viewport_window ... ``` ### Step 2.3: Use `display_widget` Use `display_widget` to control whether to show `WidgetInfoManipulator` or `ObjInfoManipulator` as so: ```python ... class ViewportSceneInfo(): # NEW PARAMETER: display_widget def __init__(self, viewport_window, ext_id, display_widget) -> None: self.scene_view = None self.viewport_window = viewport_window with self.viewport_window.get_frame(ext_id): self.scene_view = sc.SceneView() with self.scene_view.scene: # NEW if display_widget: WidgetInfoManipulator(model=ObjInfoModel()) else: # END NEW ObjInfoManipulator(model=ObjInfoModel()) ... ``` <details> <summary>Click here for the updated <b>viewport_scene.py</b></summary> ```python from omni.ui import scene as sc import omni.ui as ui from .object_info_manipulator import ObjInfoManipulator from .object_info_model import ObjInfoModel from .widget_info_manipulator import WidgetInfoManipulator class ViewportSceneInfo(): def __init__(self, viewport_window, ext_id, display_widget) -> None: self.scene_view = None self.viewport_window = viewport_window with self.viewport_window.get_frame(ext_id): self.scene_view = sc.SceneView() with self.scene_view.scene: if display_widget: WidgetInfoManipulator(model=ObjInfoModel()) else: ObjInfoManipulator(model=ObjInfoModel()) self.viewport_window.viewport_api.add_scene_view(self.scene_view) def __del__(self): self.destroy() def destroy(self): if self.scene_view: self.scene_view.scene.clear() if self.viewport_window: self.viewport_window.viewport_api.remove_scene_view(self.scene_view) self.viewport_window = None self.scene_view = None ``` </details> <br> ## Step 3: Update `extension.py` Now that you have created the widget and passed it into the viewport, you need to call this in the `extension.py` module for it to function. ### Step 3.1: Edit the Class Name Start by changing the class name of `extension.py` from `MyExtension` to something more descriptive, like `ObjectInfoWidget`: ```python ... ## Replace ## class MyExtension(omni.ext.IExt): ## With ## class ObjectInfoWidget(omni.ext.IExt): ## END ## def __init__(self) -> None: super().__init__() self.viewportScene = None ``` ### Step 3.2: Pass the Parameter Pass the new parameter in `on_startup()` as follows: ```python ... def on_startup(self, ext_id): #Grab a reference to the viewport viewport_window = get_active_viewport_window() # NEW PARAMETER PASSED self.viewportScene = ViewportSceneInfo(viewport_window, ext_id, True) ... ``` <details> <summary>Click here for the updated <b>extension.py</b> module </summary> ```python import omni.ext import omni.ui as ui from omni.ui import scene as sc from omni.ui import color as cl from omni.kit.viewport.utility import get_active_viewport_window from .viewport_scene import ViewportSceneInfo class ObjectInfoWidget(omni.ext.IExt): def __init__(self) -> None: super().__init__() self.viewportScene = None def on_startup(self, ext_id): #Grab a reference to the viewport viewport_window = get_active_viewport_window() self.viewportScene = ViewportSceneInfo(viewport_window, ext_id, True) def on_shutdown(self): if self.viewportScene: self.viewportScene.destroy() self.viewportScene = None ``` </details> Excellent, You should now see these updates in Omniverse Code at this point. ![](./Images/step2_complete.gif) ## Step 4: Create a Toggle Button In this section you will create a button that enables us to turn the object info widget on and off in the viewport. This feature is built in `extension.py` and is an optional section. If you do not want the toggle button, feel free to skip this part. ## Step 4.1: Add the button to `extension.py` First define new properties in `extension.py` for `viewport_scene`,`widget_view`, and `ext_id`, as follows: ```python ... class ObjectInfoWidget(omni.ext.IExt): def __init__(self) -> None: super().__init__() # NEW VALUES self.viewport_scene = None self.widget_view_on = False self.ext_id = None # END NEW ``` ### Step 4.2 Update Startup Update `on_startup()` to create a new window for the button. ### Step 4.3 Passs `self.widget_view_on` into ViewportSceneInfo ```python ... def on_startup(self, ext_id): # NEW: Window with a label and button to toggle the widget / info self.window = ui.Window("Toggle Widget View", width=300, height=300) self.ext_id = ext_id with self.window.frame: with ui.HStack(height=0): ui.Label("Toggle Widget View", alignment=ui.Alignment.CENTER_TOP, style={"margin": 5}) ui.Button("Toggle Widget", clicked_fn=self.toggle_view) # END NEW #Grab a reference to the viewport viewport_window = get_active_viewport_window() # NEW: passed in our new value self.widget_view_on self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id, self.widget_view_on) ... ``` ### Step 4.4 Create the Toggle Define `toggle_view()`. This function will be bound to the button's clicked function, thus requiring an `if` statement to check when the button is on/off: ```python ... # NEW: New function that is binded to our button's clicked_fn def toggle_view(self): self.reset_viewport_scene() self.widget_view_on = not self.widget_view_on if self.widget_view_on: self._toggle_button.text = "Toggle Widget Info Off" else: self._toggle_button.text = "Toggle Widget Info On" viewport_window = get_active_viewport_window() self.viewport_scene = ViewportSceneInfo(viewport_window, self.ext_id, self.widget_view_on) # END NEW ... ``` ### Step 4.5: Create Reset Viewport Scene Function This button is used in more than one spot, therefore define `reset_viewport_scene()`. This function will purge our viewport scene when the button is reset. ```python ... # NEW: New function for resetting the viewport scene (since this will be used in more than one spot) def reset_viewport_scene(self): if self.viewport_scene: self.viewport_scene.destroy() self.viewport_scene = None # END NEW ... ``` ### Step 4.6: Reset Viewport Scene on Shutdown Update `on_shutdown` to remove the `viewport_scene` parameters you moved into the reset function and then call that function. ```python ... def on_shutdown(self): # NEW: Moved code block to a function and call it self.reset_viewport_scene() # END NEW ``` <br> <details> <summary>Click here for the updated <b>extension.py</b> module </summary> ```python import omni.ext import omni.ui as ui from omni.kit.viewport.utility import get_active_viewport_window from .viewport_scene import ViewportSceneInfo class ObjectInfoWidget(omni.ext.IExt): def __init__(self) -> None: super().__init__() self.viewport_scene = None self.widget_view_on = False self.ext_id = None def on_startup(self, ext_id): self.window = ui.Window("Toggle Widget View", width=300, height=300) self.ext_id = ext_id with self.window.frame: with ui.HStack(height=0): ui.Label("Toggle Widget View", alignment=ui.Alignment.CENTER_TOP, style={"margin": 5}) ui.Button("Toggle Widget", clicked_fn=self.toggle_view) #Grab a reference to the viewport viewport_window = get_active_viewport_window() self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id, self.widget_view_on) def toggle_view(self): self.reset_viewport_scene() self.widget_view_on = not self.widget_view_on if self.widget_view_on: self._toggle_button.text = "Toggle Widget Info Off" else: self._toggle_button.text = "Toggle Widget Info On" viewport_window = get_active_viewport_window() self.viewport_scene = ViewportSceneInfo(viewport_window, self.ext_id, self.widget_view_on) def reset_viewport_scene(self): if self.viewport_scene: self.viewport_scene.destroy() self.viewport_scene = None def on_shutdown(self): self.reset_viewport_scene() ``` </details> <br> Here is what you should see in the viewport at this point: <br> ![](./Images/togglewidget_window.gif) ## Step 5: Add a Slider In this step, you will be adding a slider to the widget. This slider will change the scale of the object. This is an optional step and may be skipped as it is just to showcase a simple addition of what a widget can do. For a more complex slider, [check out the guide to `Slider Manipulator` here.](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.slider_manipulator/Tutorial/slider_Manipulator_Tutorial.md) ### Step 5.1: Add to `widget_info_manipulator.py` Use `omni.ui` to build the framework for the slider in the function `on_build_widgets()`. This slider is an optional feature to the widget but is a great way to add utility. ```python ... def on_build_widgets(self): with ui.ZStack(): ui.Rectangle(style={ "background_color": cl(0.2), "border_color": cl(0.7), "border_width": 2, "border_radius": 4, }) # NEW: Adding the Slider to the widget in the scene with ui.VStack(style={"font_size": 24}): self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER) # setup some model, just for simple demonstration here self._slider_model = ui.SimpleFloatModel() ui.Spacer(height=5) with ui.HStack(): ui.Spacer(width=10) ui.Label("scale", height=0, width=0) ui.Spacer(width=5) ui.FloatSlider(self._slider_model) ui.Spacer(width=5) ui.Spacer(height=5) # END NEW self.on_model_updated(None) ... ``` ### Step 5.2: Update the Scale with a Slider Function Add a new function that will scale the model when the slider is dragged. Define this function after `on_model_updated` and name it `update_scale`. ```python ... def on_model_updated(self, _): # if you don't have selection then show nothing if not self.model or not self.model.get_item("name"): self._root.visible = False return # Update the shapes position = self.model.get_as_floats(self.model.get_item("position")) if self._root: self._root.transform = sc.Matrix44.get_translation_matrix(*position) self._root.visible = True # NEW # Update the slider def update_scale(prim_name, value): print(f"changing scale of {prim_name}, {value}") stage = self.model.usd_context.get_stage() prim = stage.GetPrimAtPath(self.model.current_path) scale = prim.GetAttribute("xformOp:scale") scale.Set(Gf.Vec3d(value, value, value)) if self._slider_model: self._slider_subscription = None self._slider_model.as_float = 1.0 self._slider_subscription = self._slider_model.subscribe_value_changed_fn( lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float) ) # END NEW ... ``` <details> <summary>Click here for the updated <b>widget_info_manipulator.py</b> module </summary> ```python from omni.ui import scene as sc from omni.ui import color as cl import omni.ui as ui from pxr import Gf class WidgetInfoManipulator(sc.Manipulator): def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.destroy() def destroy(self): self._root = None self._name_label = None self._slider_model = None def on_build_widgets(self): with ui.ZStack(): ui.Rectangle(style={ "background_color": cl(0.2), "border_color": cl(0.7), "border_width": 2, "border_radius": 4, }) with ui.VStack(): self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER) # setup some model, just for simple demonstration here self._slider_model = ui.SimpleFloatModel() ui.Spacer(height=5) with ui.HStack(): ui.Spacer(width=10) ui.Label("scale", height=0, width=0) ui.Spacer(width=5) ui.FloatSlider(self._slider_model) ui.Spacer(width=5) ui.Spacer(height=5) self.on_model_updated(None) def on_build(self): """Called when the model is changed and rebuilds the whole slider""" self._root = sc.Transform(visibile=False) with self._root: with sc.Transform(scale_to=sc.Space.SCREEN): with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)): self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED) self._widget.frame.set_build_fn(self.on_build_widgets) def on_model_updated(self, _): # if you don't have selection then show nothing if not self.model or not self.model.get_item("name"): self._root.visible = False return # Update the shapes position = self.model.get_as_floats(self.model.get_item("position")) if self._root: self._root.transform = sc.Matrix44.get_translation_matrix(*position) self._root.visible = True # Update the slider def update_scale(prim_name, value): print(f"changing scale of {prim_name}, {value}") stage = self.model.usd_context.get_stage() prim = stage.GetPrimAtPath(self.model.current_path) scale = prim.GetAttribute("xformOp:scale") scale.Set(Gf.Vec3d(value, value, value)) if self._slider_model: self._slider_subscription = None self._slider_model.as_float = 1.0 self._slider_subscription = self._slider_model.subscribe_value_changed_fn( lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float) ) # Update the shape name if self._name_label: self._name_label.text = f"Prim:{self.model.get_item('name')}" ``` </details> <br> Here is what is created in the viewport of Omniverse Code: <br> ![](./Images/sliderWorking.gif) # Congratulations! You have successfully created a Widget Info Extension!
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/config/extension.toml
[package] version = "1.0.1" authors = ["NVIDIA"] title = "Omni.UI Scene Object Info with Widget Example" description = "This example show an 3d info pophover type tool tip scene object" readme = "docs/README.md" repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene" category = "Documentation" keywords = ["ui", "example", "scene", "docs", "documentation", "popover"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.kit.viewport.utility" = { } "omni.ui.scene" = { } "omni.usd" = { } [[python.module]] name = "omni.example.ui_scene.widget_info" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_manipulator.py
## Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["WidgetInfoManipulator"] from omni.ui import color as cl from omni.ui import scene as sc import omni.ui as ui class _ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact is the focused window! # And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass class _DragPrioritize(sc.GestureManager): """Refuses preventing _DragGesture.""" def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True class _DragGesture(sc.DragGesture): """"Gesture to disable rectangle selection in the viewport legacy""" def __init__(self): super().__init__(manager=_DragPrioritize()) def on_began(self): # When the user drags the slider, we don't want to see the selection # rect. In Viewport Next, it works well automatically because the # selection rect is a manipulator with its gesture, and we add the # slider manipulator to the same SceneView. # In Viewport Legacy, the selection rect is not a manipulator. Thus it's # not disabled automatically, and we need to disable it with the code. self.__disable_selection = _ViewportLegacyDisableSelection() def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None class WidgetInfoManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) self.destroy() self._radius = 2 self._distance_to_top = 5 self._thickness = 2 self._radius_hovered = 20 def destroy(self): self._root = None self._slider_subscription = None self._slider_model = None self._name_label = None def _on_build_widgets(self): with ui.ZStack(): ui.Rectangle( style={ "background_color": cl(0.2), "border_color": cl(0.7), "border_width": 2, "border_radius": 4, } ) with ui.VStack(style={"font_size": 24}): ui.Spacer(height=4) with ui.ZStack(style={"margin": 1}, height=30): ui.Rectangle( style={ "background_color": cl(0.0), } ) ui.Line(style={"color": cl(0.7), "border_width": 2}, alignment=ui.Alignment.BOTTOM) ui.Label("Hello world, I am a scene.Widget!", height=0, alignment=ui.Alignment.CENTER) ui.Spacer(height=4) self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER) # setup some model, just for simple demonstration here self._slider_model = ui.SimpleFloatModel() ui.Spacer(height=10) with ui.HStack(): ui.Spacer(width=10) ui.Label("scale", height=0, width=0) ui.Spacer(width=5) ui.FloatSlider(self._slider_model) ui.Spacer(width=10) ui.Spacer(height=4) ui.Spacer() self.on_model_updated(None) # Additional gesture that prevents Viewport Legacy selection self._widget.gestures += [_DragGesture()] def on_build(self): """Called when the model is chenged and rebuilds the whole slider""" self._root = sc.Transform(visible=False) with self._root: with sc.Transform(scale_to=sc.Space.SCREEN): with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)): # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED) self._widget.frame.set_build_fn(self._on_build_widgets) def on_model_updated(self, _): # if we don't have selection then show nothing if not self.model or not self.model.get_item("name"): self._root.visible = False return # Update the shapes position = self.model.get_as_floats(self.model.get_item("position")) self._root.transform = sc.Matrix44.get_translation_matrix(*position) self._root.visible = True # Update the slider def update_scale(prim_name, value): print(f"changing scale of {prim_name}, {value}") if self._slider_model: self._slider_subscription = None self._slider_model.as_float = 1.0 self._slider_subscription = self._slider_model.subscribe_value_changed_fn( lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float) ) # Update the shape name if self._name_label: self._name_label.text = f"Prim:{self.model.get_item('name')}"
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WidgetInfoExtension"] from .widget_info_scene import WidgetInfoScene from omni.kit.viewport.utility import get_active_viewport_window import carb import omni.ext class WidgetInfoExtension(omni.ext.IExt): """The entry point to the extension""" def on_startup(self, ext_id): # Get the active (which at startup is the default Viewport) viewport_window = get_active_viewport_window() # Issue an error if there is no Viewport if not viewport_window: carb.log_warn(f"No Viewport Window to add {ext_id} scene to") self._widget_info_viewport = None return # Build out the scene self._widget_info_viewport = WidgetInfoScene(viewport_window, ext_id) def on_shutdown(self): if self._widget_info_viewport: self._widget_info_viewport.destroy() self._widget_info_viewport = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WidgetInfoExtension"] from .widget_info_extension import WidgetInfoExtension
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_scene.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WidgetInfoScene"] import omni.ui as ui from omni.ui import scene as sc from .widget_info_model import WidgetInfoModel from .widget_info_manipulator import WidgetInfoManipulator class WidgetInfoScene(): """The Object Info Manupulator, placed into a Viewport""" def __init__(self, viewport_window, ext_id: str): self._scene_view = None self._viewport_window = viewport_window # Create a unique frame for our SceneView with self._viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: WidgetInfoManipulator(model=WidgetInfoModel()) # Register the SceneView with the Viewport to get projection and view updates self._viewport_window.viewport_api.add_scene_view(self._scene_view) def __del__(self): self.destroy() def destroy(self): if self._scene_view: # Empty the SceneView of any elements it may have self._scene_view.scene.clear() # Be a good citizen, and un-register the SceneView from Viewport updates if self._viewport_window: self._viewport_window.viewport_api.remove_scene_view(self._scene_view) # Remove our references to these objects self._viewport_window = None self._scene_view = None
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_model.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WidgetInfoModel"] from omni.ui import scene as sc from pxr import Gf from pxr import UsdGeom from pxr import Usd from pxr import UsdShade from pxr import Tf from pxr import UsdLux import omni.usd import omni.kit.commands class WidgetInfoModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and info of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because we take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value about some attibute""" def __init__(self, value=0): super().__init__() self.value = [value] def __init__(self): super().__init__() self.material_name = "" self.position = WidgetInfoModel.PositionItem() # The distance from the bounding box to the position the model returns self._offset = 0 # Current selection self._prim = None self._current_path = "" self._stage_listener = None # Save the UsdContext name (we currently only work with single Context) self._usd_context_name = '' usd_context = self._get_context() # Track selection self._events = usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="Object Info Selection Update" ) def _get_context(self) -> Usd.Stage: # Get the UsdContext we are attached to return omni.usd.get_context(self._usd_context_name) def _notice_changed(self, notice, stage): """Called by Tf.Notice""" for p in notice.GetChangedInfoOnlyPaths(): if self._current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position if identifier == "name": return self._current_path if identifier == "material": return self.material_name def get_as_floats(self, item): if item == self.position: # Requesting position return self._get_position() if item: # Get the value directly from the item return item.value return [] def set_floats(self, item, value): if not self._current_path: return if not value or not item or item.value == value: return # Set directly to the item item.value = value # This makes the manipulator updated self._item_changed(item) def _on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_kit_selection_changed() def _on_kit_selection_changed(self): # selection change, reset it for now self._current_path = "" usd_context = self._get_context() stage = usd_context.get_stage() if not stage: return prim_paths = usd_context.get_selection().get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, we don't need to update anything if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None return prim = stage.GetPrimAtPath(prim_paths[0]) if prim.IsA(UsdLux.Light): print("Light") self.material_name = "I am a Light" elif prim.IsA(UsdGeom.Imageable): material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() if material: self.material_name = str(material.GetPath()) else: self.material_name = "N/A" else: self._prim = None return self._prim = prim self._current_path = prim_paths[0] # Add a Tf.Notice listener to update the position if not self._stage_listener: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage) (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim) # Position is changed self._item_changed(self.position) def _get_position(self): """Returns position of currently selected object""" stage = self._get_context().get_stage() if not stage or not self._current_path: return [0, 0, 0] # Get position directly from USD prim = stage.GetPrimAtPath(self._current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + self._offset, (bboxMin[2] + bboxMax[2]) * 0.5] return position
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/tests/test_info.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["TestInfo"] from omni.example.ui_scene.widget_info.widget_info_manipulator import WidgetInfoManipulator from omni.ui import scene as sc from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import omni.kit.app import omni.kit.test EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests") class WidgetInfoTestModelItem(sc.AbstractManipulatorItem): pass class WidgetInfoTestModel(sc.AbstractManipulatorModel): def __init__(self): super().__init__() self.position = WidgetInfoTestModelItem() def get_item(self, identifier): if identifier == "position": return self.position if identifier == "name": return "Name" if identifier == "material": return "Material" def get_as_floats(self, item): if item == self.position: return [0, 0, 0] class TestInfo(OmniUiTest): async def test_general(self): """Testing general look of the item""" window = await self.create_test_window(width=256, height=256) with window.frame: # Camera matrices projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, -2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, 0) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: # The manipulator model = WidgetInfoTestModel() WidgetInfoManipulator(model=model) await omni.kit.app.get_app().next_update_async() model._item_changed(None) for _ in range(10): await omni.kit.app.get_app().next_update_async() await self.finalize_test(threshold=100, golden_img_dir=TEST_DATA_PATH, golden_img_name="general.png")
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/tests/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .test_info import TestInfo
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/docs/CHANGELOG.md
# Changelog omni.ui.scene.object_info ## [1.0.1] - 2022-06-01 ### Changed - It doesn't recreate sc.Widget to avoid crash ## [1.0.0] - 2022-5-1 ### Added - The initial version
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/docs/README.md
# Widget Info (omni.example.ui_scene.widget_info) ![](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/raw/main/exts/omni.example.ui_scene.widget_info/data/preview.png) ​ ## Overview In the example, we show how to leverage `ui.scene.Widget` item to create a `ui.Widget` that is in 3D space. The Widget can have any type of `omni.ui` element, including being interactive, as shown with the slider. ​ ## [Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. In the tutorial you will learn how to build from existing modules to create a Widget. A Widget is a useful utility in `Omniverse Kit` that can be used to add features such as buttons and sliders. ​[Get started with the tutorial here.](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md) ## Usage Once the extension is enabled in the `Extension Manager`, go to your `Viewport` and right-click to create a primitive - such as a cube, sphere, cyclinder, etc. Then, left-click/select the primitive to view the Object Info. The Path and Type of the Object will be displayed inside of a Widget. ​ ## The extension showcases view concepts Similarly to the other `ui.scene` example it shows you how to set up the viewport scene in `viewport_scene.py`. Then there is the Manipulator object that manages the presentation of the item `widget_info_manipulator.py`. Finally, the `widget_info_model.py` contains the model that connects the world with the manipulator. ## Overlaying with the viewport We use `sc.Manipulator` with `sc.Widget` to draw `omni.ui` widgets in 3D view. To show it in the viewport, we overlay `sc.SceneView` with our `sc.Manipulator` on top of the viewport window. ```python from omni.kit.viewport.utility import get_active_viewport_window viewport_window = get_active_viewport_window() # Create a unique frame for our SceneView with viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: WidgetInfoManipulator(model=WidgetInfoModel()) ``` To synchronize the projection and view matrices, `omni.kit.viewport.utility` has the method `add_scene_view`, which replaces the camera model, and the manipulator visually looks like it's in the main viewport. ```python # Register the SceneView with the Viewport to get projection and view updates viewport_window.viewport_api.add_scene_view(self._scene_view) ```
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/docs/index.rst
omni.example.ui_scene.widget_info ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
NVIDIA-Omniverse/IsaacSim-Automator/CONTRUBUTING.md
# Isaac Automation OSS Contribution Rules - [Development Tips](#development-tips) - [Updating Pre-Built VM Images](#updating-pre-built-vm-images) - [Azure](#azure) - [Issue Tracking](#issue-tracking) - [Coding Guidelines](#coding-guidelines) - [Formatting and Linting](#formatting-and-linting) - [General](#general) - [Pull Requests](#pull-requests) - [Signing Your Work](#signing-your-work) ## Development Tips ### Updating Pre-Built VM Images Pre-built VM images are created using [Packer](https://www.packer.io/) and can be used to accelerate deployment of the app instances by skipping the time-consuming installation and configuration steps. To use pre-built images, add `--from-image` flag to the `deploy-*` commands. ```sh #### AWS Refer to [../src/packer/aws/README.md](src/packer/aws/README.md) for pre-requisites. Then: ```sh packer build -force /app/src/packer/aws/isaac ... ``` #### Azure Refer to [../src/packer/azure/README.md](src/packer/azure/README.md) for pre-requisites. Then: ```sh packer build -force /app/src/packer/azure/isaac ... ``` ## Issue Tracking - All enhancement, bugfix, or change requests must begin with the creation of a [Isaac Automation Issue Request](https://github.com/nvidia/Isaac-Automation/issues). - The issue request must be reviewed by Isaac Automation engineers and approved prior to code review. ## Coding Guidelines Please follow the existing conventions in the relevant file, submodule, module, and project when you add new code or when you extend/fix existing functionality. ### Formatting and Linting - Make sure your editor is using the included `.editorconfig` file for indentation, line endings, etc. - Use the following formatters and linting tools for the respective languages: - Python: [black](<https://github.com/psf/black>), [isort](<https://github.com/pycqa/isort/>), [flake8](https://github.com/pycqa/flake8) - Terraform: [terraform fmt](<https://www.terraform.io/docs/commands/fmt.html>) - Ansible: [ansible-lint](<https://github.com/ansible/ansible-lint>) - Packer: [packer fmt](<https://www.packer.io/docs/commands/fmt.html>) Project includes settings and recommended extensions for [Visual Studio Code](https://code.visualstudio.com/) which make it easier following the formatting linting and guidelines. ### General - Avoid introducing unnecessary complexity into existing code so that maintainability and readability are preserved. - Try to keep pull requests (PRs) as concise as possible: - Avoid committing commented-out code. - Wherever possible, each PR should address a single concern. If there are several otherwise-unrelated things that should be fixed to reach a desired endpoint, our recommendation is to open several PRs and indicate the dependencies in the description. The more complex the changes are in a single PR, the more time it will take to review those changes. - Write commit titles using imperative mood and [these rules](https://chris.beams.io/posts/git-commit/), and reference the Issue number corresponding to the PR. Following is the recommended format for commit texts: ```text #<Issue Number> - <Commit Title> <Commit Body> ``` - All OSS components must contain accompanying documentation (READMEs) describing the functionality, dependencies, and known issues. - Accompanying tests are highly desireable and recommended. If the test is not possible or not feasible to implement, please provide a sample usage information. - Make sure that you can contribute your work to open source (no license and/or patent conflict is introduced by your code). You will need to [`sign`](#signing-your-work) your commit. - Thanks in advance for your patience as we review your contributions; we do appreciate them! ## Pull Requests Developer workflow for code contributions is as follows: 1. Developers must first [fork](https://help.github.com/en/articles/fork-a-repo) the [upstream](https://github.com/nvidia/Isaac-Automation) Isaac Automation OSS repository. 1. Git clone the forked repository and push changes to the personal fork. ```bash git clone https://github.com/YOUR_USERNAME/YOUR_FORK.git Isaac-Automation # Checkout the targeted branch and commit changes # Push the commits to a branch on the fork (remote). git push -u origin <local-branch>:<remote-branch> ``` 1. Once the code changes are staged on the fork and ready for review, a [Pull Request](https://help.github.com/en/articles/about-pull-requests) (PR) can be [requested](https://help.github.com/en/articles/creating-a-pull-request) to merge the changes from a branch of the fork into a selected branch of upstream. ## Signing Your Work - We require that all contributors "sign-off" on their commits. This certifies that the contribution is your original work, or you have rights to submit it under the same license, or a compatible license. - Any contribution which contains commits that are not Signed-Off will not be accepted. - To sign off on a commit you simply use the `--signoff` (or `-s`) option when committing your changes: ```bash git commit -s -m "Add cool feature." ``` This will append the following to your commit message: ```text Signed-off-by: Your Name <[email protected]> ``` - Full text of the DCO: ```text Developer Certificate of Origin Version 1.1 Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 1 Letterman Drive Suite D4700 San Francisco, CA, 94129 Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ```
NVIDIA-Omniverse/IsaacSim-Automator/README.md
# Isaac Sim Automator - [Installation](#installation) - [Installing Docker](#installing-docker) - [Obtaining NGC API Key](#obtaining-ngc-api-key) - [Building the Container](#building-the-container) - [Usage](#usage) - [Tip: Running the Automator Commands](#tip-running-the-automator-commands) - [Deploying Isaac Sim](#deploying-isaac-sim) - [AWS](#aws) - [GCP](#gcp) - [Azure](#azure) - [Alibaba Cloud](#alibaba-cloud) - [Connecting to Deployed Instances](#connecting-to-deployed-instances) - [Running Applications](#running-applications) - [Isaac Sim](#isaac-sim) - [Shell in Isaac Sim Container](#shell-in-isaac-sim-container) - [Omniverse Isaac Gym Environments](#omniverse-isaac-gym-environments) - [Isaac Orbit](#isaac-orbit) - [Mapped Folders](#mapped-folders) - [Pausing and Resuming](#pausing-and-resuming) - [Uploading Data](#uploading-data) - [Downloading Data](#downloading-data) - [Repairing](#repairing) - [Destroying](#destroying) This tool automates deployment of [Isaac Sim](https://developer.nvidia.com/isaac-sim) to public clouds. ## Installation ### Installing Docker `docker` should be present on your system. Visit <https://docs.docker.com/engine/install/> for installation instructions. ### Obtaining NGC API Key **NGC API Key** allows you to download docker images from <https://ngc.nvidia.com/>. Please prepare one or obtain it at <https://ngc.nvidia.com/setup/api-key>. ### Building the Container Please enter the following command in the project root directory to build the container: ```sh ./build ``` This will build the Isaac Sim Automator container and tag it as `isa`. ## Usage ### Tip: Running the Automator Commands There are two ways to run the automator commands: 1. First enter the automator container and then run the command inside the container: ```sh # enter the automator container ./run # inside container: ./someconnad ``` 2. Simply prepend the command with `./run` like so: ```sh ./run ./somecommand <parameters> ``` for example: ```sh ./run ./deploy-aws ./run ./destroy my-deployment ``` ### Deploying Isaac Sim #### AWS <details> <a name="#aws-permissions"></a> <summary>Enabling Access Permissions</summary> You need _AmazonEC2FullAccess_ permissions enabled for your AWS user. You can enable those in [Identity and Access Management (IAM) Section](https://console.aws.amazon.com/iamv2/home#/home) in AWS console like so: 1. Go to <https://console.aws.amazon.com/iamv2/home#/home> 2. Click "Access Management" \> "Users" in the left menu 3. Search for your user name 4. Under "Permissions" tab click "Add permissions" 5. Choose "Attach existing policies directly" 6. Search for _AmazonEC2FullAccess_, check the box next to it, click "Next" 7. Click "Add permissions" </details> <details> <a name="#aws-access-creds"></a> <summary>Getting Access Credentials</summary> You will need _AWS Access Key_ and _AWS Secret Key_ for an existing account. You can obtain those in <a href="https://console.aws.amazon.com/iamv2/home#/home">Identity and Access Management (IAM) Section</a> in the AWS console. </details> If yoou have completed the above steps or already have your permissions and credentials set up, run the following command in the project root directory: ```sh # enter the automator container ./run # inside container: ./deploy-aws ``` Tip: Run `./deploy-aws --help` to see more options. #### GCP ```sh # enter the automator container ./run # inside container: ./deploy-gcp ``` Tip: Run `./deploy-gcp --help` to see more options. #### Azure If You Have Single Subscription: ```sh # enter the automator container ./run # inside container: ./deploy-azure ``` If You Have Multiple Subscriptions: ```sh # enter the automator container ./run # inside container: az login # login az account show --output table # list subscriptions az account set --subscription "<subscription_name>" ./deploy-azure --no-login ``` Tip: Run `./deploy-azure --help` to see more options. #### Alibaba Cloud <details> <a name="#alicloud-access-creds"></a> <summary>Getting Access Credentials</summary> You will need <i>Access Key</i> and <i>Secret Key</i> for an existing AliCloud account. You can obtain those in <a href="https://usercenter.console.aliyun.com/#/manage/ak">AccessKey Management</a> section in the Alibaba Cloud console. </details> Once you have prepared the access credentials, run the following command in the project root directory: ```sh # enter the automator container ./run # inside container: ./deploy-alicloud ``` Tip: Run `./deploy-alicloud --help` to see more options. GPU-accelerated instances with NVIDIA A100, A10 and T4 GPUs are supported. You can find the complete list of instance types, availability and pricing at <https://www.alibabacloud.com/help/en/ecs/user-guide/gpu-accelerated-compute-optimized-and-vgpu-accelerated-instance-families-1>. Please note that vGPU instances are not supported. ### Connecting to Deployed Instances Deployed Isaac Sim instances can be accessed via: - SSH - noVNC (browser-based VNC client) - NoMachine (remote desktop client) Look for the connection instructions at the end of the deploymnt command output. Additionally, this info is saved in `state/<deployment-name>/info.txt` file. You can view available arguments with `--help` switch for the start scripts, in most cases you wouldn't need to change the defaults. Tip: You can use `./connect <deployment-name>` helper command to connect to the deployed instance via ssh. ### Running Applications To use installed applications, connect to the deployed instance using noVNC or NoMachine. You can find the connection instructions at the end of the deployment command output. Additionally, this info is saved in `state/<deployment-name>/info.txt` file. #### Isaac Sim Isaac Sim will be automatically started when cloud VM is deployed. Alternatively you can click "Isaac Sim" icon on the desktop or run the following command in the terminal on the deployed instance or launch it from the terminal as follows: ```sh ~/Desktop/isaacsim.sh ``` #### Shell in Isaac Sim Container To get a shell inside Isaac Sim container, click "Isaac Sim Shell" icon on the desktop. Alternatively you can run the following command in the terminal on the deployed instance: ```sh ~/Desktop/isaacsim-shell.sh ``` #### Omniverse Isaac Gym Environments [Omniverse Isaac Gym Reinforcement Learning Environments for Isaac Sim](https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs) ("Omni Isaac Gym Envs") can be pre-installed on the deployed Isaac instances. To run Omniverse Isaac Gym Environments click "Omni Isaac Gym Envs" icon on the desktop or run the following command in the terminal: ```sh ~/Desktop/omni-isaac-gym-envs.sh ``` Default output directory (`/OmniIsaacGymEnvs/omniisaacgymenvs/runs`) in the OmniIsaacGymEnvs contaner will be linked to the default results directory (`/home/ubuntu/results`) on the deployed instance. You can download the contents of this directory to your local machine using `./download <deployment_name>` command. Tip: To install a specific git reference of OmniIsaacGymEnvs, provide valid reference from <https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs> as a value of `--oige` parameter to the deployment command. For example, to install `devel` branch on an AWS instance, run the following command: ```sh ./deploy-aws --oige devel ``` #### Isaac Orbit *Isaac Orbit is still experimental and intended for preview purposes only.* [Isaac Orbit](https://isaac-orbit.github.io/orbit/index.html) can be pre-installed on the deployed Isaac instances. To run Isaac Orbit click "Isaac Orbit" icon on the desktop or run the following command in the terminal: ```sh ~/Desktop/isaac-orbit.sh ``` Tip: To install a specific git reference of Isaac Orbit, provide valid git reference from <https://github.com/NVIDIA-Omniverse/Orbit> as a value of `--orbit` parameter to the deployment command. For example, to install `devel` branch on an AWS instance, run the following command: ```sh ./deploy-aws --orbit devel ``` ### Mapped Folders The following folders are mapped to the running Isaac Sim container by default (container paths may be different for specific applications): - `/home/ubuntu/uploads` (host) --> `/uploads` (container) - user data uploaded to the deployment with `./upload` command or automatically from local `uploads/` folder - `/home/ubuntu/results` (host) --> `/results` (container) - results of the applications run on the deployment, can be downloaded from the deployed machine with `./download` command - `/home/ubuntu/workspace` (host) --> `/workspace` (container) - workspace folder, can be used to exchange data between the host and the container. ### Pausing and Resuming You can stop and re-start instances to save on cloud costs. To do so, run the following commands: ```sh # enter the automator container ./run # inside container: ./stop <deployment-name> ./start <deployment-name> ``` ### Uploading Data You can upload user data from `uploads/` folder (in the project root) to the deployment by running the following command: ```sh # enter the automator container ./run # inside container: ./upload <deployment-name> ``` Data will be uploaded to `/home/ubuntu/uploads` directory by default to all deployed instances. You can change this by passing `--remote-dir` argument to the command. Run `./upload --help` to see more options. ### Downloading Data You can download user data to `results/` folder (in the project root) from deployed instances by running the following command: ```sh # enter the automator container ./run # inside container: ./download <deployment-name> ``` Data will be downloaded from `/home/ubuntu/results` directory by default. You can change this by passing `--remote-dir` argument to the command. Run `./download --help` to see more options. ### Repairing If for some reason the deployment cloud resouces or software configuration get corrupted, you can attempt to repair the deployment by running the following command: ```sh # run both terraform and ansible ./repair <deployment-name> # just run terraform to try fixing the cloud resources ./repair <deployment-name> --no-ansible # just run ansible to try fixing the software configuration ./repair <deployment-name> --no-terraform ``` ### Destroying To destroy a deployment, run the following command: ```sh # enter the automator container ./run # inside container: ./destroy <deployment-name> ``` You will be prompted to enter the deployment name to destroy. *Please note that information about the deployed cloud resources is stored in `state/` directory. Do not delete this directory ever.*
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/isaac.yml
# region copyright # 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. # endregion - name: Wait for the instance to become available hosts: isaac gather_facts: false tasks: - wait_for_connection: timeout=300 tags: # packer checks connectivity beforehand - skip_in_image - on_stop_start - name: Deploy Isaac Sim hosts: isaac gather_facts: true vars: in_china: False application_name: isaac prompt_ansi_color: 36 # cyan roles: - isaac handlers: - include: roles/rdesktop/handlers/main.yml - include: roles/system/handlers/main.yml
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/ovami.yml
# region copyright # 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. # endregion - name: Wait for the instance to become available hosts: ovami gather_facts: false tasks: - wait_for_connection: timeout=300 tags: # packer checks connectivity beforehand - skip_in_ovami - name: OV AMI hosts: ovami gather_facts: true vars: in_china: False application_name: ovami prompt_ansi_color: 34 # bright blue roles: - ovami handlers: - include: roles/rdesktop/handlers/main.yml - include: roles/system/handlers/main.yml
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/ngc.yml
# region copyright # 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. # endregion --- - name: Install packages apt: name={{ item }} state=latest update_cache=yes with_items: - unzip - name: Download and extract NGC client unarchive: src: https://ngc.nvidia.com/downloads/ngccli_cat_linux.zip dest: /opt remote_src: yes - name: Add ngc cli to PATH lineinfile: dest: "/etc/profile.d/ngc-cli.sh" line: export PATH="$PATH:/opt/ngc-cli" create: yes
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/nvidia-docker.yml
# region copyright # 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. # endregion --- - name: Add repository shell: "rm -f /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg && rm -f /etc/apt/sources.list.d/nvidia-container-toolkit.list && distribution=$(. /etc/os-release;echo $ID$VERSION_ID) && curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg && curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list | sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list" - name: Install nvidia-docker2 apt: name={{ item }} state=latest update_cache=yes with_items: - nvidia-docker2 - name: Restart docker service service: > name=docker state=restarted
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/nvidia-driver.azure.yml
# region copyright # 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. # endregion --- # @see https://learn.microsoft.com/en-us/azure/virtual-machines/linux/n-series-driver-setup#install-grid-drivers-on-nv-or-nvv3-series-vms - name: Azure / Prerequisites (APT) apt: name={{ item }} state=latest update_cache=yes install_recommends=no with_items: - build-essential - ubuntu-desktop - linux-azure # reqd by asible get_url - python3-pip # reqd by driver runfile - pkg-config - libglvnd-dev - name: Azure /Prerequisites (PIP) pip: # older version is needed by ansible get_url for some reason name: requests==2.20.1 executable: pip3 - name: Azure / Blacklist nouveau kernel_blacklist: name={{ item }} state=present with_items: - nouveau - lbs-nouveau - name: Azure / Fix 3818429 kernel_blacklist: name=hyperv_drm state=present - name: Azure / Check if reboot required stat: path: /var/run/reboot-required register: reboot_required_file - name: Azure / Reboot and wait reboot: post_reboot_delay: 5 connect_timeout: 3 reboot_timeout: 600 when: reboot_required_file.stat.exists == true # download driver, timeout 3 min, 5 retries # @see https://github.com/Azure/azhpc-extensions/blob/master/NvidiaGPU/resources.json#L275 - name: Azure / Download GRID driver get_url: url: https://go.microsoft.com/fwlink/?linkid=874272 dest: /tmp/nvidia_grid_azure_driver.run mode: "0755" timeout: 180 retries: 5 - name: Azure / Install GRID driver shell: "/tmp/nvidia_grid_azure_driver.run --run-nvidia-xconfig --disable-nouveau --no-questions --silent" - name: Azure / Enable persistent mode for the driver shell: nvidia-smi -pm ENABLED - name: Azure / Copy grid.conf copy: > src=/etc/nvidia/gridd.conf.template dest=/etc/nvidia/gridd.conf remote_src=true force=no - name: Azure / Update GRID config [1] lineinfile: path: /etc/nvidia/gridd.conf line: "{{ item }}" state: present with_items: - "IgnoreSP=FALSE" - "EnableUI=FALSE" - name: Azure / Update GRID config [2] lineinfile: path: /etc/nvidia/gridd.conf regexp: "^FeatureType=(.*)$" line: '# FeatureType=\1' state: present backrefs: yes
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/nvidia-driver.gcp.yml
# region copyright # 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. # endregion # @see https://cloud.google.com/compute/docs/gpus/install-grid-drivers - name: GCP / Prerequisites (APT) apt: name={{ item }} state=latest update_cache=yes install_recommends=no with_items: - build-essential - python3-pip # required by asible get_url - name: GCP / Prerequisites (PIP) pip: # older version is needed by ansible get_url for some reason name: requests==2.20.1 executable: pip3 # download driver - name: GCP / Download GRID driver get_url: url: "{{ gcp_driver_url }}" dest: /tmp/nvidia_driver.run mode: 0755 - name: GCP / Install GRID driver shell: "/tmp/nvidia_driver.run \ --x-module-path=/usr/lib/xorg/modules/drivers \ --run-nvidia-xconfig \ --disable-nouveau \ --no-questions \ --silent" - name: GCP / Enable persistent mode for the driver shell: nvidia-smi -pm ENABLED - name: GCP / Copy gridd.conf copy: > src=/etc/nvidia/gridd.conf.template dest=/etc/nvidia/gridd.conf remote_src=true force=no - name: GCP / Update GRID config [1] lineinfile: path: /etc/nvidia/gridd.conf line: "{{ item }}" state: present with_items: - "IgnoreSP=FALSE" - "EnableUI=TRUE" - name: GCP / Update GRID config [2] lineinfile: path: /etc/nvidia/gridd.conf regexp: "^FeatureType=(.*)$" line: 'FeatureType=\2' state: present backrefs: yes
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/main.yml
# region copyright # 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. # endregion --- # driver - name: Detect if the driver is already installed shell: lsmod | grep nvidia_drm | wc -l register: driver_installed - import_tasks: nvidia-driver.azure.yml when: driver_installed.stdout == "0" and cloud == "azure" - import_tasks: nvidia-driver.generic.yml when: driver_installed.stdout == "0" and (cloud == "aws" or cloud == "alicloud") - import_tasks: nvidia-driver.gcp.yml when: driver_installed.stdout == "0" and cloud == "gcp" # Disable ECC # Needs to be done after restoring from image or from scratch - name: Detect ECC status shell: nvidia-smi --query-gpu="ecc.mode.current" --format="csv,noheader" -i 0 register: ecc_status tags: on_stop_start - debug: msg: "ECC status: {{ ecc_status.stdout }}" # - name: Disable ECC shell: nvidia-smi --ecc-config=0 when: ecc_status.stdout == 'Enabled' tags: on_stop_start # - name: Reboot and wait reboot: post_reboot_delay=5 connect_timeout=3 reboot_timeout=600 when: ecc_status.stdout == 'Enabled' tags: on_stop_start # nvidia-docker2 - package_facts: manager=apt - import_tasks: nvidia-docker.yml when: '"nvidia-docker2" not in ansible_facts.packages'
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/tasks/nvidia-driver.generic.yml
# region copyright # 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. # endregion --- - name: NVIDIA GPU Driver / Add CUDA keyring apt: deb: https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-keyring_1.1-1_all.deb - name: NVIDIA GPU Driver / Blacklist the nouveau driver module kernel_blacklist: name=nouveau state=present - name: NVIDIA GPU Driver / Install pre-requisites apt: name={{ item }} state=latest update_cache=yes with_items: - xserver-xorg - "{{ generic_driver_apt_package }}" - name: NVIDIA GPU Driver / Enable persistent mode shell: nvidia-smi -pm ENABLED - name: NVIDIA GPU Driver / Check if reboot is needed stat: path: /var/run/reboot-required register: reboot_required_file - name: AWS / Reboot and wait reboot: post_reboot_delay: 5 connect_timeout: 3 reboot_timeout: 600 when: reboot_required_file.stat.exists == true
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/defaults/main.yml
# region copyright # 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. # endregion # driver package when installed from apt # nvidia-driver-470-server # nvidia-driver-510-server nvidia_driver_package:
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/nvidia/meta/main.yml
# region copyright # 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. # endregion --- galaxy_info: role_name: nvidia_runtime author: NVIDIA Corporation description: NVIDIA driver and docker standalone: false dependencies: - { role: system }
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/icon.yml
# region copyright # 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. # endregion - name: Make sure dirs exist file: path: "{{ item }}" state: directory owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0755 with_items: - /home/{{ ansible_user }}/Pictures - /home/{{ ansible_user }}/Desktop - name: Upload icon copy: src: "{{ item }}" dest: /home/{{ ansible_user }}/Pictures/isaacsim-{{ item }} owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0644 with_items: - icon.png - icon-shell.png - name: Create desktop icon copy: src: "{{ item }}" dest: /home/{{ ansible_user }}/Desktop/{{ item }} owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0644 with_items: - isaacsim.desktop - isaacsim-shell.desktop - name: Allow execution of desktop icon shell: gio set /home/{{ ansible_user }}/Desktop/{{ item }} metadata::trusted true become_user: "{{ ansible_user }}" with_items: - isaacsim.desktop - isaacsim-shell.desktop - name: Set permissions for desktop icon file: path: /home/{{ ansible_user }}/Desktop/{{ item }} mode: 0755 owner: "{{ ansible_user }}" group: "{{ ansible_user }}" with_items: - isaacsim.desktop - isaacsim-shell.desktop
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/wallpaper.yml
# region copyright # 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. # endregion - name: Make sure wallpaper dir exists file: path: /home/{{ ansible_user }}/Pictures state: directory owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0755 - name: Upload wallpaper copy: src: wallpaper.png dest: /home/{{ ansible_user }}/Pictures/wallpaper.png owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0644 - name: Set wallpaper shell: gsettings set org.gnome.desktop.background picture-uri file:///home/{{ ansible_user }}/Pictures/wallpaper.png become_user: "{{ ansible_user }}"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/orbit.yml
# region copyright # 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. # endregion - name: Create directory for Orbit file: path: "{{ orbit_dir }}" state: directory owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0755 - name: Upload Orbit setup files [1] template: src={{ item }} dest="{{ orbit_dir }}/{{ item }}" mode=755 owner=ubuntu group=ubuntu with_items: - orbit.dockerfile tags: __orbit_dockerfile - name: Upload Orbit setup files [2] template: src="{{ item }}" dest="/home/{{ ansible_user }}/Desktop" mode=755 owner=ubuntu group=ubuntu with_items: - orbit.sh - name: Desktop icon for Orbit copy: src: "{{ item }}" dest: "/home/{{ ansible_user }}/Desktop/{{ item }}" owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0644 with_items: - orbit.desktop - name: Allow execution of desktop icon for Orbit shell: gio set "/home/{{ ansible_user }}/Desktop/{{ item }}" metadata::trusted true become_user: "{{ ansible_user }}" with_items: - orbit.desktop - name: Set permissions for Orbit desktop icon file: path: "/home/{{ ansible_user }}/Desktop/{{ item }}" mode: 0755 owner: "{{ ansible_user }}" group: "{{ ansible_user }}" with_items: - orbit.desktop - name: Build Orbit shell: docker build -t orbit -f "{{ orbit_dir }}/orbit.dockerfile" "{{ orbit_dir }}" become_user: "{{ ansible_user }}" tags: - skip_in_ovami
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/isaac_app.yml
# region copyright # 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. # endregion - name: Create cache directory file: path: "{{ isaac_cache_dir }}" state: directory owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0777 - name: Launch scripts [1] file: path: /home/ubuntu/Desktop state: directory owner: ubuntu group: ubuntu - name: Launch scripts [2] template: src={{ item }} dest=/home/ubuntu/Desktop/{{ item }} mode=755 owner=ubuntu group=ubuntu with_items: - isaacsim.sh - isaacsim-shell.sh - name: Log into nvcr.io shell: until docker login -u "\$oauthtoken" --password "{{ ngc_api_key }}" nvcr.io; do sleep 10; done ignore_errors: true become_user: "{{ item }}" with_items: - root - ubuntu timeout: 60 # for each item when: ngc_api_key != "none" tags: - skip_in_ovami - name: Pull Isaac Sim image docker_image: name: "{{ isaac_image }}" repository: nvcr.io source: pull ignore_errors: true when: ngc_api_key != "none" tags: - skip_in_ovami - name: Log out from nvcr.io shell: docker logout nvcr.io become_user: "{{ item }}" with_items: - root - ubuntu when: ngc_api_key != "none" tags: - never - cleanup - name: Start Isaac Sim shell: | export DISPLAY=":0" gnome-terminal -- bash -c "./isaacsim.sh; exec bash" args: chdir: /home/{{ ansible_user }}/Desktop become_user: "{{ ansible_user }}" when: ngc_api_key != "none" tags: - skip_in_image - on_stop_start
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/omni_isaac_gym_envs.yml
# region copyright # 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. # endregion - name: Create directory for OmniIsaacGymEnvs file: path: "{{ omni_isaac_gym_envs_dir }}" state: directory owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0755 - name: Upload OmniIsaacGymEnvs setup files [1] template: src={{ item }} dest="{{ omni_isaac_gym_envs_dir }}/{{ item }}" mode=755 owner=ubuntu group=ubuntu with_items: - omni-isaac-gym-envs.dockerfile - name: Upload OmniIsaacGymEnvs setup files [2] template: src="{{ item }}" dest="/home/{{ ansible_user }}/Desktop" mode=755 owner=ubuntu group=ubuntu with_items: - omni-isaac-gym-envs.sh - name: Desktop icon for OmniIsaacGymEnvs copy: src: "{{ item }}" dest: "/home/{{ ansible_user }}/Desktop/{{ item }}" owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0644 with_items: - omni-isaac-gym-envs.desktop - name: Allow execution of desktop icon for OmniIsaacGymEnvs shell: gio set "/home/{{ ansible_user }}/Desktop/{{ item }}" metadata::trusted true become_user: "{{ ansible_user }}" with_items: - omni-isaac-gym-envs.desktop - name: Set permissions for OmniIsaacGymEnvs desktop icon file: path: "/home/{{ ansible_user }}/Desktop/{{ item }}" mode: 0755 owner: "{{ ansible_user }}" group: "{{ ansible_user }}" with_items: - omni-isaac-gym-envs.desktop - name: Build OmniIsaacGymEnvs shell: docker build -t omni-isaac-gym-envs -f "{{ omni_isaac_gym_envs_dir }}/omni-isaac-gym-envs.dockerfile" "{{ omni_isaac_gym_envs_dir }}" become_user: "{{ ansible_user }}" tags: - skip_in_ovami
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/tasks/main.yml
# region copyright # 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. # endregion - name: Prerequisites apt: name: "{{ item }}" state: latest with_items: - libvulkan-dev - name: Wallpaper import_tasks: wallpaper.yml - name: Desktop Icon import_tasks: icon.yml - name: Isaac App import_tasks: isaac_app.yml # https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs - name: Omni Isaac Gym Envs import_tasks: omni_isaac_gym_envs.yml when: omni_isaac_gym_envs_git_checkpoint != 'no' # https://isaac-orbit.github.io/orbit/index.html - name: Orbit import_tasks: orbit.yml when: orbit_git_checkpoint != 'no' tags: __orbit - name: Restart NX server meta: noop notify: nx_restart
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/defaults/main.yml
# region copyright # 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. # endregion deployment_name: isaac_image: isaac_cache_dir: /home/{{ ansible_user }}/isaac # OmniIsaacGymEnvs omni_isaac_gym_envs_dir: /opt/omni-isaac-gym-envs omni_isaac_gym_envs_git_checkpoint: main # Orbit orbit_dir: /opt/orbit orbit_git_checkpoint: devel # "none" skips login/pull ngc_api_key: # directory to output results to results_dir: /home/{{ ansible_user }}/results workspace_dir: /home/{{ ansible_user }}/results uploads_dir: /home/{{ ansible_user }}/uploads omniverse_user: omniverse_password: nucleus_uri:
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/templates/isaacsim.sh
#!/bin/bash # default parameter values # isaac sim startup command CMD="/isaac-sim/kit/kit \ /isaac-sim/apps/omni.isaac.sim.kit \ --ext-folder /isaac-sim/apps \ --allow-root" DISPLAY=":0" CONTAINER_NAME="isaacsim" OUT_DIR="{{ results_dir }}" UPLOADS_DIR="{{ uploads_dir }}" WORKSPACE_DIR="{{ workspace_dir }}" OMNI_USER="{{ omniverse_user }}" OMNI_PASS="{{ omniverse_password }}" DOCKER_IMAGE="{{ isaac_image }}" CACHE_DIR="{{ isaac_cache_dir }}" NUCLEUS_SERVER_NAME="{{ nucleus_uri }}" # detect vulkan location if [ -f /usr/share/vulkan/icd.d/nvidia_icd.json ] then VULKAN_DIR="/usr/share/vulkan" elif [ -f /etc/vulkan/icd.d/nvidia_icd.json ] then VULKAN_DIR="/etc/vulkan" else echo "ERROR: Could not detect Vulkan installation directory" exit 1 fi # find .Xauthority XAUTHORITY_LOCATION=$(systemctl --user show-environment | grep XAUTHORITY | cut -c 12-) # process named arguments while [ $# -gt 0 ]; do case "$1" in --help|-h) echo "Usage: `basename $0` \\" echo " [--command=..] \\" echo " [--out_dir=..] \\" echo " [--omni_user=..] \\" echo " [--omni_pass=..] \\" echo " [--docker_image=..] \\" echo " [--container_name=..] \\" echo " [--nucleus_server=..]" echo echo "Defaults: " echo " --command='${CMD}'" echo " --out_dir='${OUT_DIR}'" echo " --omni_user='${OMNI_USER}'" echo " --omni_pass='${OMNI_PASS}'" echo " --docker_image='${DOCKER_IMAGE}'" echo " --container_name='${CONTAINER_NAME}'" echo " --nucleus_server='${NUCLEUS_SERVER_NAME}'" exit ;; --debug) set -x ;; --nucleus=*|--nucleus_server=*|--nucleus_server_name=*|--nucleus_url=*|--nucleus_ip=*) NUCLEUS_SERVER_NAME="${1#*=}" ;; --user=*|--username=*|--omni_user=*) OMNI_USER="${1#*=}" ;; --pass=*|--password=*|--omni_pass=*) OMNI_PASS="${1#*=}" ;; --image=*|--docker_image=*) DOCKER_IMAGE="${1#*=}" ;; --out=*|--output=*|--out_dir=*|--output_dir=*) OUT_DIR="${1#*=}" ;; --uploads_dir=*) UPLOADS_DIR="${1#*=}" ;; --workspace_dir=*) WORKSPACE_DIR="${1#*=}" ;; --display=*) DISPLAY="${1#*=}" ;; --cmd=*|--command=*) CMD="${1#*=}" ;; --container-name=*|--name=*) CONTAINER_NAME="${1#*=}" ;; esac shift done # create cache dir if it doesn't exist, assign permissions [ ! -d "${CACHE_DIR}" ] && mkdir -pv "${CACHE_DIR}" [ -d "${CACHE_DIR}" ] && chmod 0777 "${CACHE_DIR}" mkdir -pv "${CACHE_DIR}/ov" "${CACHE_DIR}/pip" "${CACHE_DIR}/glcache" "${CACHE_DIR}/computecache" "${CACHE_DIR}/logs" "${CACHE_DIR}/config" "${CACHE_DIR}/data" "${CACHE_DIR}/documents" 2>/dev/null # create output/uploads/workspace dirs if it doesn't exist for d in "${OUT_DIR}" "${UPLOADS_DIR}" "${WORKSPACE_DIR}"; do [ ! -d "${d}" ] && mkdir -pv "${d}" done # kill any existing container docker kill $CONTAINER_NAME 2>/dev/null docker run \ --network=host -it --rm --gpus all \ \ --env "ACCEPT_EULA=Y" \ --env OMNI_USER="$OMNI_USER" \ --env OMNI_PASS="$OMNI_PASS" \ \ -v "${VULKAN_DIR}/icd.d/nvidia_icd.json":/etc/vulkan/icd.d/nvidia_icd.json \ -v "${VULKAN_DIR}/implicit_layer.d/nvidia_layers.json":/etc/vulkan/implicit_layer.d/nvidia_layers.json \ -v /usr/share/glvnd/egl_vendor.d/10_nvidia.json:/usr/share/glvnd/egl_vendor.d/10_nvidia.json \ \ -v "${CACHE_DIR}/ov":/root/.cache/ov:rw \ -v "${CACHE_DIR}/pip":/root/.cache/pip:rw \ -v "${CACHE_DIR}/glcache":/root/.cache/nvidia/GLCache:rw \ -v "${CACHE_DIR}/computecache":/root/.nv/ComputeCache:rw \ -v "${CACHE_DIR}/logs":/root/.nvidia-omniverse/logs:rw \ -v "${CACHE_DIR}/config":/root/.nvidia-omniverse/config:rw \ -v "${CACHE_DIR}/data":/root/.local/share/ov/data:rw \ -v "${CACHE_DIR}/docs":/root/Documents:rw \ \ -v "${OUT_DIR}":/results \ -v "${UPLOADS_DIR}":/uploads \ -v "${WORKSPACE_DIR}":/workspace \ \ -v "/tmp/.X11-unix:/tmp/.X11-unix" \ -v "${XAUTHORITY_LOCATION}:/root/.Xauthority" \ -v /etc/xdg:/etc/xdg \ --env XDG_CONFIG_DIRS \ --env DISPLAY \ \ --name $CONTAINER_NAME \ --entrypoint "/bin/sh" \ $DOCKER_IMAGE \ -c "$CMD"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/templates/omni-isaac-gym-envs.sh
#!/bin/bash # build and launch https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs # build docker image for OmniIsaacGymEnvs docker build -t omni-isaac-gym-envs -f "{{ omni_isaac_gym_envs_dir }}/omni-isaac-gym-envs.dockerfile" "{{ omni_isaac_gym_envs_dir }}" clear /home/{{ ansible_user }}/Desktop/isaacsim.sh --docker_image="omni-isaac-gym-envs" --cmd="bash"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/templates/isaacsim-shell.sh
#!/bin/bash # launch shell inside isaacsim contaner MY_DIR=$(realpath $(dirname ${BASH_SOURCE})) ${MY_DIR}/isaacsim.sh --cmd="bash"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/templates/orbit.sh
#!/bin/bash # build and launch https://github.com/NVIDIA-Omniverse/Orbit # build docker image for Orbit docker build -t orbit -f "{{ orbit_dir }}/orbit.dockerfile" "{{ orbit_dir }}" clear /home/{{ ansible_user }}/Desktop/isaacsim.sh --docker_image="orbit" --cmd="bash"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/isaac/meta/main.yml
# region copyright # 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. # endregion --- galaxy_info: role_name: isaac author: NVIDIA Corporation description: Isaac Sim installation standalone: false dependencies: - { role: system } - { role: docker } - { role: nvidia } - { role: rdesktop }
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/nice_dcv.yml
# region copyright # 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. # endregion # install nice dcv # @see https://docs.aws.amazon.com/dcv/latest/adminguide/setting-up-installing-linux-prereq.html # @see https://docs.aws.amazon.com/dcv/latest/adminguide/setting-up-installing-linux-server.html # prerequisites - name: Install prerequisites for NICE DCV apt: name: "{{ item }}" state: latest with_items: - rpm # needed for rpm_key ansible module - mesa-utils # import GPG key - name: Import GPG key for NICE DCV rpm_key: key: https://d1uj6qtbmh3dt5.cloudfront.net/NICE-GPG-KEY state: present # download nice dcv - name: Download NICE DCV get_url: url: https://d1uj6qtbmh3dt5.cloudfront.net/nice-dcv-ubuntu{{ ansible_distribution_version | replace('.', '') }}-{{ ansible_machine }}.tgz dest: /tmp/nice-dcv.tgz mode: 0644 # download and unzip nice dcv - name: Unarchive NICE DCV unarchive: src: /tmp/nice-dcv.tgz remote_src: yes dest: /tmp extra_opts: [--strip-components=1] # find .deb for nice dcv installer - name: Find .deb for NICE DCV Server installer find: paths: /tmp patterns: "nice-dcv-server*.deb" register: nice_dcv_deb # install nice dcv .deb file - name: Install NICE DCV Server apt: deb: "{{ nice_dcv_deb.files[0].path }}" state: present # find .deb for nice xdcv - name: Find .deb for NICE XDCV find: paths: /tmp patterns: "nice-xdcv*.deb" register: nice_xdcv_deb # install nice xdcv - name: Install NICE XDCV apt: deb: "{{ nice_xdcv_deb.files[0].path }}" state: present # print nice_dcv_unarchive - name: Print nice_dcv_unarchive debug: msg: "{{ nice_dcv_deb.files[0].path }}" # add the dcv user to the video group - name: Add "dcv" user to "video" group user: name: dcv groups: video append: yes # find nice-dcv-gl .deb file - name: Find .deb for NICE DCV GL find: paths: /tmp patterns: "nice-dcv-gl*.deb" register: nice_dcv_gl_deb # print nice_dcv_gl_deb - name: Print nice_dcv_gl_deb debug: msg: "{{ nice_dcv_gl_deb.files[0].path }}" # install nice-dcv-gl from .deb file - name: Install NICE DCV GL apt: deb: "{{ nice_dcv_gl_deb.files[0].path }}" state: present # post-install steps # @see https://docs.aws.amazon.com/dcv/latest/adminguide/setting-up-installing-linux-checks.html # configure dcvgladmin - name: Post-install confgiuration of NICE DCV GL shell: | systemctl isolate multi-user.target dcvgladmin disable dcvgladmin enable systemctl isolate graphical.target # configure dcvserver - name: Configure NICE DCV Server ini_file: section: "{{ item.section }}" path: /etc/dcv/dcv.conf option: "{{ item.key }}" value: "{{ item.value }}" no_extra_spaces: true with_items: - { section: "security", key: "authentication", value: "{{ dcv_authentication_method }}", } - { section: "session-management", key: "create-session", value: "true" } - { section: "session-management/automatic-console-session", key: "owner", value: "{{ ansible_user }}", } - { section: "display", key: "default-layout", value: "[{'w':<1920>, 'h':<1200>, 'x':<0>,'y':<0>}]", } # start dcvserver, reboot - name: Start/Restart/Enable NICE DCV Server systemd: name: dcvserver state: restarted enabled: yes - name: Reboot reboot: post_reboot_delay=5 connect_timeout=3 reboot_timeout=600
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/vscode.yml
# region copyright # 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. # endregion # @see https://code.visualstudio.com/docs/setup/linux - name: Prerequisites for VS Code apt: name: "{{ item }}" state: latest with_items: - wget - gpg - apt-transport-https - name: Install VSC sources shell: | wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg install -D -o root -g root -m 644 packages.microsoft.gpg /etc/apt/keyrings/packages.microsoft.gpg sh -c 'echo "deb [arch=amd64,arm64,armhf signed-by=/etc/apt/keyrings/packages.microsoft.gpg] https://packages.microsoft.com/repos/code stable main" > /etc/apt/sources.list.d/vscode.list' args: creates: /etc/apt/sources.list.d/vscode.list - name: Install VS Code apt: name: code update_cache: yes state: latest - name: Add desktop icon copy: src: /usr/share/applications/code.desktop remote_src: yes dest: /home/{{ ansible_user }}/Desktop/code.desktop mode: 0644 - name: Allow execution of VSC desktop icon shell: gio set /home/{{ ansible_user }}/Desktop/{{ item }} metadata::trusted true become_user: "{{ ansible_user }}" with_items: - code.desktop - name: Set permissions for VSC desktop icon file: path: /home/{{ ansible_user }}/Desktop/{{ item }} mode: 0755 owner: "{{ ansible_user }}" group: "{{ ansible_user }}" with_items: - code.desktop
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/wallpaper.yml
# region copyright # 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. # endregion - name: Make sure wallpaper dir exists file: path: /home/{{ ansible_user }}/Pictures state: directory owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0755 - name: Upload wallpaper copy: src: ov-wallpaper.jpeg dest: /home/{{ ansible_user }}/Pictures/ owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0644 - name: Set wallpaper shell: gsettings set org.gnome.desktop.background picture-uri file:///home/{{ ansible_user }}/Pictures/ov-wallpaper.jpeg become_user: "{{ ansible_user }}"
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/cloud_init.yml
# region copyright # 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. # endregion - name: Preserve user password when starting from image lineinfile: path: /etc/cloud/cloud.cfg regexp: ".*lock_passwd:.*" line: " lock_passwd: False" state: present
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/ov_launcher.yml
# region copyright # 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. # endregion - name: Make sure dirs exist file: path: "{{ item }}" state: directory owner: "{{ ansible_user }}" group: "{{ ansible_user }}" mode: 0755 with_items: - /home/{{ ansible_user }}/Pictures - /home/{{ ansible_user }}/Desktop - name: Upload OV Icon copy: src: "{{ item }}" dest: "/home/{{ ansible_user }}/Pictures/{{ item }}" mode: 0644 with_items: - ov-icon.png - name: Download OV Launcher get_url: url: https://install.launcher.omniverse.nvidia.com/installers/omniverse-launcher-linux.AppImage dest: "/home/{{ ansible_user }}/Omniverse.AppImage" mode: 0755 become_user: "{{ ansible_user }}" - name: Create desktop icon copy: content: | [Desktop Entry] Name=Omniverse Launcher Comment=Omniverse Launcher Exec=/home/{{ ansible_user }}/Omniverse.AppImage Icon=/home/{{ ansible_user }}/Pictures/ov-icon.png Terminal=false Type=Application Categories=Utility; dest: /home/{{ ansible_user }}/Desktop/ovl.desktop mode: 0644 - name: Allow execution of OVL desktop icon shell: gio set /home/{{ ansible_user }}/Desktop/{{ item }} metadata::trusted true become_user: "{{ ansible_user }}" with_items: - ovl.desktop - name: Set permissions for OVL desktop icon file: path: /home/{{ ansible_user }}/Desktop/{{ item }} mode: 0755 owner: "{{ ansible_user }}" group: "{{ ansible_user }}" with_items: - ovl.desktop
NVIDIA-Omniverse/IsaacSim-Automator/src/ansible/roles/ovami/tasks/main.yml
# region copyright # 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. # endregion # this role is meant to be executed while creating # the OV AMI, so no skip tags are present # for NV-use only, don't try to make too much sense of it - name: Prerequisites apt: name: "{{ item }}" state: latest with_items: - libvulkan-dev - firefox - xdg-utils - name: NICE DCV import_tasks: nice_dcv.yml - name: OV Launcher import_tasks: ov_launcher.yml - name: Install VS Code import_tasks: vscode.yml - name: Set wallpaper import_tasks: wallpaper.yml - name: Configure cloud-init import_tasks: cloud_init.yml