file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
profK/Worldwizards-Export-Tools/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
profK/Worldwizards-Export-Tools/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 shutil import sys import tempfile import zipfile __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,844
Python
33.166666
108
0.703362
profK/Worldwizards-Export-Tools/exts/worldwizards.export.tools/worldwizards/export/tools/extension.py
from asyncio import Future, Task import traceback import carb import omni.ext import omni.ui as ui from .ww_omniverse_utils import * import os import shutil from omni import usd from pxr import Usd,UsdShade # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print("[worldwizards.export.tools] some_public_function was called with x: ", x) return x ** x def get_kind(prim:Usd.Prim): kindAPI = Usd.ModelAPI(prim) return kindAPI.GetKind() def recurse_list_components(prim:Usd.Prim, components:list): if (get_kind(prim)=="component"): print("Found component "+str(prim.GetPath())) components.append(prim.GetPath()) else: for child in prim.GetChildren(): recurse_list_components(child,components) def recurse_list_material_paths(prim:Usd.Prim, materials:list): print("recurse_list_material_paths "+str(prim.GetPath())+ " type "+prim.GetTypeName()) if (prim.GetTypeName()=="Mesh"): materialAPI:UsdShade.MaterialBindingAPI = \ UsdShade.MaterialBindingAPI(prim) material: UsdShade.Material = materialAPI.ComputeBoundMaterial()[0] if not material is None: #print("material "+str(material.GetPath())) materials.append(material) for child in prim.GetChildren(): recurse_list_material_paths(child,materials) # 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 WorldwizardsExportToolsExtension(ExtensionFramework): # 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): # add to menu self._menu_path = f"Tileset/Export All Components" self._window = None self._menu = omni.kit.ui.get_editor_menu().add_item(self._menu_path, self._export_components, True) return super().on_startup(ext_id) def on_stage_opened(self, event: carb.events.IEvent): return super().on_stage_opened(event) def _export_components(self, event, *args): print("INFO:Export components called") task:Task = \ asyncio.create_task(self._export_components_async(event, *args)) async def _export_components_async(self, event, *args): try: filepath:str = get_current_stage().GetRootLayer().realPath if filepath is None: print("Could not find root layer path "+filepath) return; materials_path:str = os.path.join(os.path.dirname(filepath),"Materials") if not os.path.exists(materials_path): print("Could not find materials file "+materials_path) return; #copy materials to output root new_root = await get_directory_async("/") if new_root is None: print("User canceled output ") return; new_materials_path = os.path.join(new_root,"Materials") if os.path.exists(new_materials_path): shutil.rmtree(new_materials_path) shutil.copytree(materials_path,new_materials_path) root:Usd.Prim = get_current_stage().GetPseudoRoot() component_paths:list = [] recurse_list_components(root,component_paths) print("INFO: Components in tree:"+str(component_paths)) for path in component_paths: component:Usd.Prim = get_current_stage().GetPrimAtPath(path) self.export_component(component,new_root) print("INFO: Exported "+str(len(component_paths))+" components to "+new_root) except Exception: print(traceback.format_exc()) return def export_component(self,prim:Usd.Prim, outDir:str): print("INFO: Exporting component "+str(prim.GetPath())) if not (get_kind(prim)=="component"): print("Not a component "+str(prim.GetPath())) return #localize materials material_list = [] recurse_list_material_paths(prim,material_list) print(str(prim.GetPath())+" has materials "+str(material_list)) for material_prim in material_list: self._localize_material(prim,material_prim) #create directory componentPath:str = prim.GetPath() componentDir:str = os.path.join(outDir,str(componentPath)) print("component dir "+componentDir) if not os.path.exists(componentDir): os.makedirs(componentDir) '''#export prim self.export_prim(componentPath) #export materials self.export_materials(componentPath,componentDir) #export textures self.export_textures(componentPath,componentDir) #export meshes self.export_meshes(componentPath,componentDir) ''' def _localize_material(self,prim:Usd.Prim, material_prim:UsdShade.Material): material_path:str = str(material_prim.GetPath()) prim_path:str = str(prim.GetPath()) print("copying material from"+prim_path+" to "+material_path) material_name:str = material_path.split("/")[-1] new_material_path: str = prim_path +"/Looks/"+material_name if not material_path == new_material_path: stage = get_current_stage() usd.duplicate_prim(stage,material_path, new_material_path) new_material_prim:UsdShade.Material = \ UsdShade.Material(stage.GetPrimAtPath(new_material_path)) materialApi:UsdShade.MaterialBindingAPI = \ UsdShade.MaterialBindingAPI(prim) materialApi.Bind(new_material_prim) def export_prim(self, path): prim:Usd.Prim = get_current_stage().GetPrimAtPath(path)
6,211
Python
41.258503
119
0.631782
profK/Worldwizards-Export-Tools/exts/worldwizards.export.tools/worldwizards/export/tools/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
profK/Worldwizards-Export-Tools/exts/worldwizards.export.tools/worldwizards/export/tools/ww_omniverse_utils.py
from pxr import Usd, Sdf, UsdGeom, Tf from omni import usd import os import omni import carb from omni.kit.window.file_exporter import get_file_exporter import asyncio def get_ext_root_path(extname:str): #print("Get root of ext "+extname) manager = omni.kit.app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module(extname) path = manager.get_extension_path(ext_id) #print("path is "+path) return path def get_current_stage() -> Usd.Stage: return usd.get_context().get_stage() def add_layer_reference(ref_path:str, file_path:str, visible:bool = True) -> Usd.PrimAllPrimsPredicate: stage:Usd.Stage stage = get_current_stage() # You can use standard python list.insert to add the subLayer to any position in the list refPrim:Usd.Prim = stage.DefinePrim(ref_path) references: Usd.References = refPrim.GetReferences() references.AddReference( assetPath=file_path ) #print("visible= "+str(visible)) set_prim_visibility(refPrim,visible) return refPrim def set_prim_visibility(prim:Usd.Prim,visible:bool = True): imageable = UsdGeom.Imageable(prim) #print("Setting visibility of "+prim.GetName()+" to "+str(visible)) if not visible: imageable.MakeInvisible() else: imageable.MakeVisible() async def get_directory_async(root:str) -> str : file_exporter = get_file_exporter() dir_name=None def cb(filename, dirname, extension, selections): nonlocal dir_name dir_name= dirname file_exporter.show_window( title="Save components to ...", export_button_label="Choose", filename_url="root", # The callback function called after the user has selected an export location. export_handler= cb ) while dir_name is None: await asyncio.sleep(0.1) print("selected dir "+dir_name) return dir_name class ExtensionFramework(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("[extension.framework] extension framework startup") self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._stage = get_current_stage() # none first time self._events = self._usd_context.get_stage_event_stream() self._ext_Id = ext_id self._stage_event_sub = \ omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="WWStageEventSub") #register selection listener def on_shutdown(self): print("[extension.framework] extension framework shutdown") def _on_stage_event(self, event:carb.events.IEvent): #No switch statenment in p3.7 :frown: self._stage = get_current_stage() if event.type == int(omni.usd.StageEventType.OPENED) : Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_notice_changed, self._stage) self.on_stage_opened(event) elif event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def on_stage_opened(self, event:carb.events.IEvent): print("Stage opened") def _on_selection_changed(self): print("Selection Changed") selections = self._selection.get_selected_prim_paths() return self.on_selection_changed(selections) def on_selection_changed(self,currently_selected: list): print("current selections: "+str(currently_selected)) def _on_notice_changed(self, notice, stage): print("Notice changed")
3,793
Python
34.129629
119
0.663854
profK/Worldwizards-Export-Tools/exts/worldwizards.export.tools/worldwizards/export/tools/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
profK/Worldwizards-Export-Tools/exts/worldwizards.export.tools/worldwizards/export/tools/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import worldwizards.export.tools # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = worldwizards.export.tools.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,686
Python
34.893616
142
0.68446
profK/Worldwizards-Export-Tools/exts/worldwizards.export.tools/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "worldwizards export tools" description="A simple python extension example to use as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.mdl.usd_converter" = {} # Main python module this extension provides, it will be publicly available as "import worldwizards.export.tools". [[python.module]] name = "worldwizards.export.tools" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,631
TOML
32.306122
118
0.746168
profK/Worldwizards-Export-Tools/exts/worldwizards.export.tools/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
profK/Worldwizards-Export-Tools/exts/worldwizards.export.tools/docs/README.md
# Python Extension Example [worldwizards.export.tools] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
184
Markdown
35.999993
126
0.793478
profK/Worldwizards-Export-Tools/exts/worldwizards.export.tools/docs/index.rst
worldwizards.export.tools ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"worldwizards.export.tools" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
351
reStructuredText
15.761904
43
0.632479
terryaic/omniverse_text3d/README.md
# omniverse_text3d is a extension of omniverse to generate 3d text with blender. How to use? Just copy the directoy to the extension folder of your omniverse app, for example, $CreateAppPath$\kit\exts. then, at your omniverse app, Windows->extensions, search for "text3d", and you will find it, enable it. requirements: omniverse blender NOTES: before you generate text, please change the blender installed path first at the extension window. if you want to use your own fonts, you can simple copy your font files to this location: $omniverse_text3d\cn\appincloud\text3d\scripts\fonts, and then re-enable the extension
623
Markdown
46.999996
212
0.791332
terryaic/omniverse_text3d/cn/appincloud/text3d/__init__.py
from .scripts.extension import *
33
Python
15.999992
32
0.787879
terryaic/omniverse_text3d/cn/appincloud/text3d/scripts/extension.py
import os import asyncio import carb import carb.settings from omni.kit.widget.settings import create_setting_widget, SettingType import omni.kit.app import omni.ext import omni.ui from pxr import UsdGeom, UsdShade, Vt, Gf, Sdf, Usd WINDOW_NAME = "Make 3D Text" EXTENSION_NAME = "Make 3D Text" PY_PATH = os.path.dirname(os.path.realpath(__file__)) BLENDER_PATH = "cn.appincloud.text3d.blender_path" class Extension(omni.ext.IExt): def __init__(self): self.num = 0 self.enabled = True self.filepath = "tmptext.usd" self.extrude = 1.5 self.fontsize = 20 self.bevelDepth = 0 self.text = "hello" self.singleMesh = True self._settings = carb.settings.get_settings() self._settings.set_default_string(BLENDER_PATH, "") self.load_fonts() def load_fonts(self): #self.fontfamily = "SourceHanSansCN.otf" #self.fonts = ["SourceHanSansCN.otf", "SourceHanSerifCN.otf"] self.fonts = [] fontpath = os.path.join(PY_PATH, "fonts") for root, dir, files in os.walk(fontpath): for file in files: self.fonts.append(file) self.fontfamily = self.fonts[0] def on_startup(self, ext_id): self._window = omni.ui.Window(EXTENSION_NAME, width=600, height=800, menu_path=f"{EXTENSION_NAME}") self._window.deferred_dock_in("Property") self._window.frame.set_build_fn(self._ui_rebuild) self._ui_rebuild() def on_shutdown(self): pass async def generate_text(self): blender_path = self.get_blender_path() import subprocess try: cmd = "%s -b -P %s/make3d.py %s %s %d %f %f %s %s" % (blender_path, PY_PATH, self.text, PY_PATH + "/fonts/" + self.fontfamily, self.fontsize, self.extrude, self.bevelDepth, self.singleMesh, self.filepath) carb.log_info(f"cmd:{cmd}") #p = subprocess.Popen(cmd, shell=False) args = [blender_path, "-b", "-P", os.path.join(PY_PATH, "make3d.py"), self.text, \ os.path.join(PY_PATH, "fonts", self.fontfamily), str(self.fontsize), str(self.extrude), str(self.bevelDepth), str(self.singleMesh), self.filepath] p = subprocess.Popen(args, shell=False) p.wait() except Exception as e: print(e) stage1 = omni.usd.get_context().get_stage() selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths() defaultPrimPath = str(stage1.GetDefaultPrim().GetPath()) if len(selected_paths) > 0: path = selected_paths[0] else: path = defaultPrimPath stage2 = Usd.Stage.Open(self.filepath) selecteds = stage2.Traverse() carb.log_info(f"{selecteds}") for obj in selecteds: if obj.GetTypeName() == 'Xform': pass elif obj.GetTypeName() == "Mesh": newObj = stage1.DefinePrim(f"{path}/Text_{self.num}", "Mesh") self.copy_mesh(obj, newObj) self.num += 1 def copy_mesh(self, obj, newObj): attributes = obj.GetAttributes() for attribute in attributes: attributeValue = attribute.Get() if attributeValue is not None: newAttribute = newObj.CreateAttribute(attribute.GetName(),attribute.GetTypeName(), False) newAttribute.Set(attributeValue) mesh = UsdGeom.Mesh(obj) newMesh = UsdGeom.Mesh(newObj) newMesh.SetNormalsInterpolation(mesh.GetNormalsInterpolation()) def fontsize_changed(self, text_model): self.fontsize = text_model.get_value_as_int() carb.log_info(f"fontsize changed:{self.fontsize}") def extrude_changed(self, text_model): self.extrude = text_model.get_value_as_float() carb.log_info(f"extrude changed:{self.extrude}") def beveldepth_changed(self, text_model): self.bevelDepth = text_model.get_value_as_float() carb.log_info(f"extrude changed:{self.bevelDepth}") def text_changed(self, text_model): self.text = text_model.get_value_as_string() carb.log_info(f"text changed:{self.text}") def combo_changed(self, combo_model, item): all_options = [ combo_model.get_item_value_model(child).as_string for child in combo_model.get_item_children() ] current_index = combo_model.get_item_value_model().as_int self.fontfamily = all_options[current_index] carb.log_info(f"font changed to: {self.fontfamily}") def singleMesh_changed(self, model): self.singleMesh = model.get_value_as_bool() carb.log_info(f"singleMesh changed:{self.singleMesh}") def _ui_rebuild(self): self._scroll_frame = omni.ui.ScrollingFrame() with self._window.frame: with self._scroll_frame: with omni.ui.VStack(spacing=2): # intro with omni.ui.CollapsableFrame(title="Description", height=10): with omni.ui.VStack(style={"margin": 5}): omni.ui.Label( "This extension will generate 3d text with blender, please change the following path to your blender installed path", word_wrap=True, ) with omni.ui.HStack(height=20): omni.ui.Label("blender installed path", word_wrap=True, width=omni.ui.Percent(35)) create_setting_widget(BLENDER_PATH, SettingType.STRING, width=omni.ui.Percent(55)) blender_button = omni.ui.Button("...", height=5, style={"padding": 12, "font_size": 20}) blender_button.set_clicked_fn(self._on_file_select_click) with omni.ui.HStack(height=20): omni.ui.Label("text", word_wrap=True, width=omni.ui.Percent(35)) text = omni.ui.StringField(height=10, style={"padding": 5, "font_size": 20}).model text.add_value_changed_fn(self.text_changed) text.set_value(self.text) with omni.ui.HStack(height=20): omni.ui.Label("font", word_wrap=True, width=omni.ui.Percent(35)) fontFamily = omni.ui.ComboBox(0, *self.fonts, height=10, name="font family").model fontFamily.add_item_changed_fn(self.combo_changed) with omni.ui.HStack(height=20): omni.ui.Label("font-size", word_wrap=True, width=omni.ui.Percent(35)) fontsize = omni.ui.IntField(height=10, style={"padding": 5, "font_size": 20}).model fontsize.add_value_changed_fn(self.fontsize_changed) fontsize.set_value(self.fontsize) with omni.ui.HStack(height=20): omni.ui.Label("extrude", word_wrap=True, width=omni.ui.Percent(35)) extrude = omni.ui.FloatField(height=10, style={"padding": 5, "font_size": 20}).model extrude.add_value_changed_fn(self.extrude_changed) extrude.set_value(self.extrude) with omni.ui.HStack(height=20): omni.ui.Label("bevel depth", word_wrap=True, width=omni.ui.Percent(35)) bevel = omni.ui.FloatField(height=10, style={"padding": 5, "font_size": 20}).model bevel.add_value_changed_fn(self.beveldepth_changed) bevel.set_value(self.bevelDepth) with omni.ui.HStack(height=20): omni.ui.Label("as a single mesh", word_wrap=True, width=omni.ui.Percent(35)) singleMesh = omni.ui.CheckBox(height=10, style={"padding": 5, "font_size": 20}).model singleMesh.add_value_changed_fn(self.singleMesh_changed) singleMesh.set_value(self.singleMesh) with omni.ui.HStack(height=20): button = omni.ui.Button("Generate 3D Text", height=5, style={"padding": 12, "font_size": 20}) button.set_clicked_fn(lambda: asyncio.ensure_future(self.generate_text())) def get_blender_path(self): s = self._settings.get(BLENDER_PATH) return s def _on_filepicker_cancel(self, *args): self._filepicker.hide() def _on_filter_item(self, item): return True async def _on_selection(self, filename, dirname): path = os.path.join(dirname,filename) if os.path.isfile(path): pass else: path = os.path.join(path, "blender") self._settings.set(BLENDER_PATH, path) self._filepicker.hide() self._window.frame.rebuild() def _on_file_select_click(self): self._filepicker = omni.kit.window.filepicker.FilePickerDialog( f"{EXTENSION_NAME}/Select Blender installed path", click_apply_handler=lambda f, d: asyncio.ensure_future(self._on_selection(f, d)), click_cancel_handler= self._on_filepicker_cancel, item_filter_options= ["*"], item_filter_fn=self._on_filter_item, )
9,427
Python
46.857868
216
0.57452
terryaic/omniverse_text3d/cn/appincloud/text3d/scripts/make3d.py
#import argparse import bpy import math from math import pi import sys def str2bool(str): return True if str.lower() == 'true' else False def parse_args(): """parsing and configuration""" desc = "3dtexts..." parser = argparse.ArgumentParser(description=desc) parser.add_argument('-b', "--background", help="run at background", action="store_true") parser.add_argument('-P', type=str, default='') parser.add_argument('--text', type=str, default='hello', help='') parser.add_argument('--fontFamily', type=str, default='FreeSerif.ttf', help='') parser.add_argument('--extrude', type=float, default=0.2, help='') parser.add_argument('--fontSize', type=int, default=3, help='font size') parser.add_argument('--asSingleMesh', type=str2bool, default=True, help='as single mesh') return parser.parse_args() #config=parse_args() print("runing make3d") print(sys.argv) def removeObjects( scn ): for ob in scn.objects: if (ob.type == 'FONT') or (ob.type == 'MESH'): bpy.context.collection.objects.unlink( ob ) scn = bpy.context.scene removeObjects( scn ) #fnt = bpy.data.fonts.load('/home/terry/auto/fontfiles/GenJyuuGothic-Bold.ttf') DEFAULT_FONT = "/usr/share/fonts/truetype/freefont/FreeSerif.ttf" #fnt = bpy.data.fonts.load(DEFAULT_FONT) def text3d(text, fntFamily, fntSize, extrude, bevelDepth, asSingleMesh=True): fnt = bpy.data.fonts.load(fntFamily) if asSingleMesh: makeobj(text, fnt, 'Text1', 0, fntSize, extrude, bevelDepth) else: i = 0 for t in text: name = "Text%d" % i makeobj(t, fnt, name, i, fntSize, extrude, bevelDepth) i+=1 def makeobj(text, fnt, name = "Text1", offset = 0, size = 3, extrude = 0.2, bevelDepth = 0): # Create and name TextCurve object bpy.ops.object.text_add( location=(offset,0,0), rotation=(0,0,0)) ob = bpy.context.object ob.name = name # TextCurve attributes ob.data.body = text ob.data.font = fnt ob.data.size = size # Inherited Curve attributes ob.data.extrude = extrude ob.data.bevel_depth = bevelDepth bpy.ops.object.convert(target='MESH', keep_original=False) bpy.ops.object.mode_set(mode='EDIT') bpy.ops.uv.smart_project() bpy.ops.object.mode_set(mode='OBJECT') n = 4 text = sys.argv[n] fontFamily = sys.argv[n+1] fontSize = int(sys.argv[n+2]) extrude = float(sys.argv[n+3]) bevelDepth = float(sys.argv[n+4]) asSingleMesh = str2bool(sys.argv[n+5]) filepath = sys.argv[n+6] text3d(text, fontFamily, fontSize, extrude, bevelDepth, asSingleMesh) #text3d(config.text, config.fontFamily, config.fontSize, config.extrude, config.asSingleMesh) #bpy.ops.export_scene.fbx(filepath="text.fbx") bpy.ops.wm.usd_export(filepath=filepath)
2,680
Python
31.301204
93
0.696269
terryaic/omniverse_text3d/config/extension.toml
[package] version = "0.1.2" title = "Make 3D Text" [dependencies] "omni.kit.mainwindow" = {} [[python.module]] name = "cn.appincloud.text3d"
143
TOML
13.399999
29
0.664336
dariengit/kit-app-template/NOTES.md
## Build ```bash cd ~/omniverse/kit-app-template ./build.sh ``` ## Run App ```bash cd ~/omniverse/kit-app-template ./_build/linux-x86_64/release/my_company.my_app.sh ``` - user.config.json path ```bash ls ~/.local/share/ov/data/Kit/my_company.my_app/2023.0/user.config.json ``` ## Run headless ```bash cd ~/omniverse/kit-app-template/_build/linux-x86_64/release ./kit/kit ./apps/my_company.my_app.kit \ --enable omni.services.streaming.manager \ --enable omni.kit.livestream.native \ --no-window \ --allow-root ./kit/kit ./apps/my_company.my_app.kit \ --enable omni.services.streaming.manager \ --enable omni.kit.livestream.native \ --enable omni.kit.streamsdk.plugins \ --no-window \ --allow-root \ --/app/livestream/logLevel=debug ./kit/kit ./apps/omni.isaac.sim.headless.native.kit \ --no-window \ --allow-root \ --/app/livestream/logLevel=debug ``` ## OK ```bash cd ~/omniverse/kit-app-template/_build/linux-x86_64/release ./kit/kit ./apps/my_company.my_app.kit \ --enable omni.services.streaming.manager \ --enable omni.kit.livestream.native \ --no-window ``` ## How to create extension template ```bash cd ~/omniverse/kit-app-template ./repo.sh template new ```
1,236
Markdown
17.742424
71
0.669903
dariengit/kit-app-template/repo.toml
######################################################################################################################## # Repo tool base settings ######################################################################################################################## [repo] # Use the Kit Template repo configuration as a base. Only override things specific to the repo. import_configs = [ "${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml", "${root}/_repo/deps/repo_kit_tools/kit-template/repo-external-app.toml", ] # Repository Name name = "kit-app-template" ######################################################################################################################## # Extensions precacher ######################################################################################################################## [repo_precache_exts] # Apps to run and precache apps = [ "${root}/source/apps/omni.usd_explorer.kit", "${root}/source/apps/my_name.my_app.kit", ] registries = [ { name = "kit/default", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/shared" }, { name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" }, ]
1,265
TOML
37.363635
136
0.422925
dariengit/kit-app-template/README.md
## Build ```bash cd ~/omniverse/kit-app-template ./build.sh ``` ## Run as Desktop App ```bash cd ~/omniverse/kit-app-template ./_build/linux-x86_64/release/my_company.my_app.sh ``` ## Run as Headless App ```bash cd ~/omniverse/kit-app-template/_build/linux-x86_64/release ./kit/kit ./apps/my_company.my_app.kit \ --enable omni.services.streaming.manager \ --enable omni.kit.livestream.native \ --no-window \ --allow-root \ --/app/livestream/logLevel=debug ```
482
Markdown
16.249999
59
0.670124
dariengit/kit-app-template/tools/VERSION.md
2023.2.1
9
Markdown
3.999998
8
0.666667
dariengit/kit-app-template/tools/deps/repo-deps.packman.xml
<project toolsVersion="5.0"> <dependency name="repo_man" linkPath="../../_repo/deps/repo_man"> <package name="repo_man" version="1.50.6"/> </dependency> <dependency name="repo_build" linkPath="../../_repo/deps/repo_build"> <package name="repo_build" version="0.60.1"/> </dependency> <dependency name="repo_ci" linkPath="../../_repo/deps/repo_ci"> <package name="repo_ci" version="0.6.0" /> </dependency> <dependency name="repo_changelog" linkPath="../../_repo/deps/repo_changelog"> <package name="repo_changelog" version="0.3.13"/> </dependency> <dependency name="repo_docs" linkPath="../../_repo/deps/repo_docs"> <package name="repo_docs" version="0.39.2"/> </dependency> <dependency name="repo_kit_tools" linkPath="../../_repo/deps/repo_kit_tools"> <package name="repo_kit_tools" version="0.14.17"/> </dependency> <dependency name="repo_test" linkPath="../_repo/deps/repo_test"> <package name="repo_test" version="2.16.1" /> </dependency> <dependency name="repo_source" linkPath="../../_repo/deps/repo_source"> <package name="repo_source" version="0.4.3" /> </dependency> <dependency name="repo_package" linkPath="../../_repo/deps/repo_package"> <package name="repo_package" version="5.9.3" /> </dependency> <dependency name="repo_format" linkPath="../../_repo/deps/repo_format"> <package name="repo_format" version="2.8.0" /> </dependency> <dependency name="repo_kit_template" linkPath="../../_repo/deps/repo_kit_template"> <package name="repo_kit_template" version="0.1.9" /> </dependency> </project>
1,593
XML
43.277777
85
0.648462
dariengit/kit-app-template/tools/deps/kit-sdk.packman.xml
<project toolsVersion="5.0"> <dependency name="kit_sdk_${config}" linkPath="../../_build/${platform}/${config}/kit" tags="${config} non-redist"> <package name="kit-kernel" version="105.1.2+release.134727.de96b556.tc.${platform}.${config}"/> </dependency> </project>
274
XML
44.833326
117
0.664234
dariengit/kit-app-template/tools/deps/user.toml
[exts."omni.kit.registry.nucleus"] registries = [ { name = "kit/default", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/shared" }, { name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" }, ]
296
TOML
48.499992
136
0.675676
dariengit/kit-app-template/tools/deps/kit-sdk-deps.packman.xml
<project toolsVersion="5.0"> <!-- Only edit this file to pull kit depedencies. --> <!-- Put all extension-specific dependencies in `ext-deps.packman.xml`. --> <!-- This file contains shared Kit SDK dependencies used by most kit extensions. --> <!-- Import Kit SDK all-deps xml file to steal some deps from it: --> <import path="../../_build/${platform}/${config}/kit/dev/all-deps.packman.xml"> <filter include="pybind11" /> <filter include="fmt" /> <filter include="python" /> <filter include="carb_sdk_plugins" /> <filter include="winsdk" /> </import> <!-- Pull those deps of the same version as in Kit SDK. Override linkPath to point correctly, other properties can also be override, including version. --> <dependency name="carb_sdk_plugins" linkPath="../../_build/target-deps/carb_sdk_plugins" tags="non-redist" /> <dependency name="pybind11" linkPath="../../_build/target-deps/pybind11" /> <dependency name="fmt" linkPath="../../_build/target-deps/fmt" /> <dependency name="python" linkPath="../../_build/target-deps/python" /> <!-- Import host deps from Kit SDK to keep in sync --> <import path="../../_build/${platform}/${config}/kit/dev/deps/host-deps.packman.xml"> <filter include="premake" /> <filter include="msvc" /> <filter include="linbuild" /> </import> <dependency name="premake" linkPath="../../_build/host-deps/premake" /> <dependency name="msvc" linkPath="../../_build/host-deps/msvc" /> <dependency name="winsdk" linkPath="../../_build/host-deps/winsdk" /> <dependency name="linbuild" linkPath="../../_build/host-deps/linbuild" tags="non-redist"/> </project>
1,651
XML
49.060605
157
0.660206
dariengit/kit-app-template/tools/repoman/repoman.py
import os import sys import io import contextlib import packmanapi REPO_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..") REPO_DEPS_FILE = os.path.join(REPO_ROOT, "tools/deps/repo-deps.packman.xml") def bootstrap(): """ Bootstrap all omni.repo modules. Pull with packman from repo.packman.xml and add them all to python sys.path to enable importing. """ #with contextlib.redirect_stdout(io.StringIO()): deps = packmanapi.pull(REPO_DEPS_FILE) for dep_path in deps.values(): if dep_path not in sys.path: sys.path.append(dep_path) if __name__ == "__main__": bootstrap() import omni.repo.man omni.repo.man.main(REPO_ROOT)
709
Python
23.482758
100
0.662905
dariengit/kit-app-template/tools/packman/packmanconf.py
# Use this file to bootstrap packman into your Python environment (3.7.x). Simply # add the path by doing sys.insert to where packmanconf.py is located and then execute: # # >>> import packmanconf # >>> packmanconf.init() # # It will use the configured remote(s) and the version of packman in the same folder, # giving you full access to the packman API via the following module # # >> import packmanapi # >> dir(packmanapi) import os import platform import sys def init(): """Call this function to initialize the packman configuration. Calls to the packman API will work after successfully calling this function. Note: This function only needs to be called once during the execution of your program. Calling it repeatedly is harmless but wasteful. Compatibility with your Python interpreter is checked and upon failure the function will report what is required. Example: >>> import packmanconf >>> packmanconf.init() >>> import packmanapi >>> packmanapi.set_verbosity_level(packmanapi.VERBOSITY_HIGH) """ major = sys.version_info[0] minor = sys.version_info[1] if major != 3 or minor != 10: raise RuntimeError( f"This version of packman requires Python 3.10.x, but {major}.{minor} was provided" ) conf_dir = os.path.dirname(os.path.abspath(__file__)) os.environ["PM_INSTALL_PATH"] = conf_dir packages_root = get_packages_root(conf_dir) version = get_version(conf_dir) module_dir = get_module_dir(conf_dir, packages_root, version) sys.path.insert(1, module_dir) def get_packages_root(conf_dir: str) -> str: root = os.getenv("PM_PACKAGES_ROOT") if not root: platform_name = platform.system() if platform_name == "Windows": drive, _ = os.path.splitdrive(conf_dir) root = os.path.join(drive, "packman-repo") elif platform_name == "Darwin": # macOS root = os.path.join( os.path.expanduser("~"), "Library/Application Support/packman-cache" ) elif platform_name == "Linux": try: cache_root = os.environ["XDG_HOME_CACHE"] except KeyError: cache_root = os.path.join(os.path.expanduser("~"), ".cache") return os.path.join(cache_root, "packman") else: raise RuntimeError(f"Unsupported platform '{platform_name}'") # make sure the path exists: os.makedirs(root, exist_ok=True) return root def get_module_dir(conf_dir, packages_root: str, version: str) -> str: module_dir = os.path.join(packages_root, "packman-common", version) if not os.path.exists(module_dir): import tempfile tf = tempfile.NamedTemporaryFile(delete=False) target_name = tf.name tf.close() url = f"http://bootstrap.packman.nvidia.com/packman-common@{version}.zip" print(f"Downloading '{url}' ...") import urllib.request urllib.request.urlretrieve(url, target_name) from importlib.machinery import SourceFileLoader # import module from path provided script_path = os.path.join(conf_dir, "bootstrap", "install_package.py") ip = SourceFileLoader("install_package", script_path).load_module() print("Unpacking ...") ip.install_package(target_name, module_dir) os.unlink(tf.name) return module_dir def get_version(conf_dir: str): path = os.path.join(conf_dir, "packman") if not os.path.exists(path): # in dev repo fallback path += ".sh" with open(path, "rt", encoding="utf8") as launch_file: for line in launch_file.readlines(): if line.startswith("PM_PACKMAN_VERSION"): _, value = line.split("=") return value.strip() raise RuntimeError(f"Unable to find 'PM_PACKMAN_VERSION' in '{path}'")
3,931
Python
35.407407
95
0.632663
dariengit/kit-app-template/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
dariengit/kit-app-template/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 os import stat import time from typing import Any, Callable RENAME_RETRY_COUNT = 100 RENAME_RETRY_DELAY = 0.1 logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") def remove_directory_item(path): if os.path.islink(path) or os.path.isfile(path): try: os.remove(path) except PermissionError: # make sure we have access and try again: os.chmod(path, stat.S_IRWXU) os.remove(path) else: # try first to delete the dir because this will work for folder junctions, otherwise we would follow the junctions and cause destruction! clean_out_folder = False try: # make sure we have access preemptively - this is necessary because recursing into a directory without permissions # will only lead to heart ache os.chmod(path, stat.S_IRWXU) os.rmdir(path) except OSError: clean_out_folder = True if clean_out_folder: # we should make sure the directory is empty names = os.listdir(path) for name in names: fullname = os.path.join(path, name) remove_directory_item(fullname) # now try to again get rid of the folder - and not catch if it raises: os.rmdir(path) class StagingDirectory: def __init__(self, staging_path): self.staging_path = staging_path self.temp_folder_path = None os.makedirs(staging_path, exist_ok=True) def __enter__(self): self.temp_folder_path = tempfile.mkdtemp(prefix="ver-", dir=self.staging_path) return self def get_temp_folder_path(self): return self.temp_folder_path # this function renames the temp staging folder to folder_name, it is required that the parent path exists! def promote_and_rename(self, folder_name): abs_dst_folder_name = os.path.join(self.staging_path, folder_name) os.rename(self.temp_folder_path, abs_dst_folder_name) def __exit__(self, type, value, traceback): # Remove temp staging folder if it's still there (something went wrong): path = self.temp_folder_path if os.path.isdir(path): remove_directory_item(path) def rename_folder(staging_dir: StagingDirectory, folder_name: str): try: staging_dir.promote_and_rename(folder_name) except OSError as exc: # if we failed to rename because the folder now exists we can assume that another packman process # has managed to update the package before us - in all other cases we re-raise the exception abs_dst_folder_name = os.path.join(staging_dir.staging_path, folder_name) if os.path.exists(abs_dst_folder_name): logger.warning( f"Directory {abs_dst_folder_name} already present, package installation already completed" ) else: raise def call_with_retry( op_name: str, func: Callable, retry_count: int = 3, retry_delay: float = 20 ) -> Any: retries_left = retry_count while True: try: return func() except (OSError, IOError) as exc: logger.warning(f"Failure while executing {op_name} [{str(exc)}]") if retries_left: retry_str = "retry" if retries_left == 1 else "retries" logger.warning( f"Retrying after {retry_delay} seconds" f" ({retries_left} {retry_str} left) ..." ) time.sleep(retry_delay) else: logger.error("Maximum retries exceeded, giving up") raise retries_left -= 1 def rename_folder_with_retry(staging_dir: StagingDirectory, folder_name): dst_path = os.path.join(staging_dir.staging_path, folder_name) call_with_retry( f"rename {staging_dir.get_temp_folder_path()} -> {dst_path}", lambda: rename_folder(staging_dir, folder_name), RENAME_RETRY_COUNT, RENAME_RETRY_DELAY, ) def install_package(package_path, install_path): staging_path, version = os.path.split(install_path) with StagingDirectory(staging_path) as staging_dir: output_folder = staging_dir.get_temp_folder_path() with zipfile.ZipFile(package_path, allowZip64=True) as zip_file: zip_file.extractall(output_folder) # attempt the rename operation rename_folder_with_retry(staging_dir, version) print(f"Package successfully installed to {install_path}") if __name__ == "__main__": executable_paths = os.getenv("PATH") paths_list = executable_paths.split(os.path.pathsep) if executable_paths else [] target_path_np = os.path.normpath(sys.argv[2]) target_path_np_nc = os.path.normcase(target_path_np) for exec_path in paths_list: if os.path.normcase(os.path.normpath(exec_path)) == target_path_np_nc: raise RuntimeError(f"packman will not install to executable path '{exec_path}'") install_package(sys.argv[1], target_path_np)
5,776
Python
36.270968
145
0.645083
dariengit/kit-app-template/source/extensions/my_company.my_app.resources/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "0.1.0" # Lists people or organizations that are considered the "authors" of the package. authors = [""] # The title and description fields are primarly for displaying extension info in UI title = "Python Extension Example" description="The simplest python extension example. Use it as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository="" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" [dependencies] # none # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "my_company.my_app.resources" [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
1,494
TOML
30.80851
118
0.745649
dariengit/kit-app-template/source/extensions/my_company.my_app.resources/my_company/my_app/resources/python_ext.py
import omni.ext # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print(f"[my_company.my_app.resources] some_public_function was called with {x}") return x**x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class HelloPythonExtension(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("[my_company.my_app.resources] HelloPythonExtension startup") def on_shutdown(self): print("[my_company.my_app.resources] HelloPythonExtension shutdown")
964
Python
44.952379
119
0.741701
dariengit/kit-app-template/source/extensions/my_company.my_app.resources/my_company/my_app/resources/__init__.py
from .python_ext import *
26
Python
12.499994
25
0.730769
dariengit/kit-app-template/source/extensions/my_company.my_app.resources/my_company/my_app/resources/tests/test_hello.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.kit.test import my_company.my_app.resources # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCaseFailOnLogError): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = my_company.my_app.resources.some_public_function(4) self.assertEqual(result, 256)
970
Python
41.21739
142
0.737113
dariengit/kit-app-template/source/extensions/my_company.my_app.resources/my_company/my_app/resources/tests/__init__.py
from .test_hello import *
26
Python
12.499994
25
0.730769
dariengit/kit-app-template/source/extensions/my_company.my_app.resources/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). # [0.1.0] ### Added - Initial release
133
Markdown
15.749998
80
0.676692
dariengit/kit-app-template/source/extensions/my_company.my_app.resources/docs/README.md
# Python Extension Example [example.python_ext] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new ones.
171
Markdown
33.399993
120
0.777778
dariengit/kit-app-template/source/extensions/my_company.my_app.resources/docs/Overview.md
# Overview
10
Markdown
9.99999
10
0.8
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.32" # The title and description fields are primarily for displaying extension info in UI title = "Setup Extension for USD Explorer" description = "an extensions that Setup my App" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "https://gitlab-master.nvidia.com/omniverse/usd_explorer" # One of categories for UI. category = "setup" # Keywords for the extension keywords = ["kit", "app", "setup"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.quicklayout" = {} "omni.kit.window.title" = {} "omni.kit.browser.asset" = {} "omni.kit.window.console" = {} "omni.kit.window.content_browser" = {} "omni.kit.window.material" = {} "omni.kit.window.toolbar" = {version = "1.5.4", exact = true} "omni.kit.property.bundle" = {} "omni.kit.property.layer" = {} "omni.kit.viewport.navigation.usd_explorer.bundle" = {} "omni.kit.window.preferences" = {} # from omni.view.app.setup "omni.kit.viewport.menubar.camera" = { optional=true } "omni.kit.widget.layers" = { optional=true } "omni.kit.widgets.custom" = {} "omni.kit.window.file" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.usd_explorer.setup" [settings] app.layout.name = "viewport_only" app.application_mode = "review" exts."omni.kit.viewport.menubar.camera".expand = true # Expand the extra-camera settings by default exts."omni.kit.window.file".useNewFilePicker = true exts."omni.kit.tool.asset_importer".useNewFilePicker = true exts."omni.kit.tool.collect".useNewFilePicker = true exts."omni.kit.widget.layers".useNewFilePicker = true exts."omni.kit.renderer.core".imgui.enableMips = true exts."omni.kit.browser.material".enabled = false exts."omni.kit.window.material".load_after_startup = true exts."omni.kit.widget.cloud_share".require_access_code = false exts."omni.kit.mesh.raycast".bvhBuildOnFirstRequired = true # Avoids mesh raycast to initialize during stage open app.content.emptyStageOnStart = true app.viewport.createCameraModelRep = false # Disable creation of camera meshes in USD # USDRT app.usdrt.scene_delegate.enableProxyCubes = false app.usdrt.scene_delegate.geometryStreaming.enabled = true app.usdrt.scene_delegate.numFramesBetweenLoadBatches = 2 app.usdrt.scene_delegate.geometryStreaming.numberOfVerticesToLoadPerChunk = 600000 exts."omni.kit.viewport.navigation.camera_manipulator".defaultOperation = "" [[test]] dependencies = [ "omni.kit.core.tests", "omni.kit.ui_test", "omni.kit.mainwindow", "omni.kit.viewport.window", "omni.kit.viewport.utility", ] args = [ "--/app/file/ignoreUnsavedOnExit=true", # "--/renderer/enabled=pxr", # "--/renderer/active=pxr", "--/app/window/width=1280", "--/app/window/height=720", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/exts/omni.kit.viewport.window/startup/windowName=Viewport", "--reset-user", "--no-window", "--/app/fastShutdown=1" ]
3,294
TOML
33.322916
113
0.728597
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/menubar_helper.py
from pathlib import Path import carb import carb.settings import carb.tokens import omni.ui as ui from omni.ui import color as cl ICON_PATH = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/data/icons") VIEW_MENUBAR_STYLE = { "MenuBar.Window": {"background_color": 0xA0000000}, "MenuBar.Item.Background": { "background_color": 0, }, "Menu.Item.Background": { "background_color": 0, } } VIEWPORT_CAMERA_STYLE = { "Menu.Item.Icon::Expand": {"image_url": f"{ICON_PATH}/caret_s2_right_dark.svg", "color": cl.viewport_menubar_light}, "Menu.Item.Icon::Expand:checked": {"image_url": f"{ICON_PATH}/caret_s2_left_dark.svg"}, } class MenubarHelper: def __init__(self) -> None: self._settings = carb.settings.get_settings() # Set menubar background and style try: from omni.kit.viewport.menubar.core import DEFAULT_MENUBAR_NAME from omni.kit.viewport.menubar.core import get_instance as get_menubar_instance instance = get_menubar_instance() if not instance: # pragma: no cover return default_menubar = instance.get_menubar(DEFAULT_MENUBAR_NAME) default_menubar.background_visible = True default_menubar.style.update(VIEW_MENUBAR_STYLE) default_menubar.show_separator = True except ImportError: # pragma: no cover carb.log_warn("Viewport menubar not found!") try: import omni.kit.viewport.menubar.camera self._camera_menubar_instance = omni.kit.viewport.menubar.camera.get_instance() if not self._camera_menubar_instance: # pragma: no cover return # Change expand button icon self._camera_menubar_instance._camera_menu._style.update(VIEWPORT_CAMERA_STYLE) # New menu item for camera speed self._camera_menubar_instance.register_menu_item(self._create_camera_speed, order=100) # OM-76591 - Removing "Create from view" item - Bob self._camera_menubar_instance.deregister_menu_item(self._camera_menubar_instance._camera_menu._build_create_camera) except ImportError: carb.log_warn("Viewport menubar not found!") self._camera_menubar_instance = None except AttributeError: # pragma: no cover self._camera_menubar_instance = None # Hide default render and settings menubar self._settings.set("/persistent/exts/omni.kit.viewport.menubar.render/visible", False) self._settings.set("/persistent/exts/omni.kit.viewport.menubar.settings/visible", False) def destroy(self) -> None: if self._camera_menubar_instance: self._camera_menubar_instance.deregister_menu_item(self._create_camera_speed) def _create_camera_speed(self, _vc, _r: ui.Menu) -> None: from omni.kit.viewport.menubar.core import SettingModel, SliderMenuDelegate ui.MenuItem( "Speed", hide_on_click=False, delegate=SliderMenuDelegate( model=SettingModel("/persistent/app/viewport/camMoveVelocity", draggable=True), min=self._settings.get_as_float("/persistent/app/viewport/camVelocityMin") or 0.01, max=self._settings.get_as_float("/persistent/app/viewport/camVelocityMax"), tooltip="Set the Fly Mode navigation speed", width=0, reserve_status=True, ), )
3,517
Python
42.974999
127
0.642593
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/__init__.py
from .setup import *
21
Python
9.999995
20
0.714286
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/setup.py
import asyncio import weakref from functools import partial import os from pathlib import Path from typing import cast, Optional import omni.client import omni.ext import omni.kit.menu.utils import omni.kit.app import omni.kit.context_menu import omni.kit.ui import omni.usd from omni.kit.quicklayout import QuickLayout from omni.kit.menu.utils import MenuLayout from omni.kit.window.title import get_main_window_title from omni.kit.usd.layers import LayerUtils from omni.kit.viewport.menubar.core import get_instance as get_mb_inst, DEFAULT_MENUBAR_NAME from omni.kit.viewport.menubar.core.viewport_menu_model import ViewportMenuModel from omni.kit.viewport.utility import get_active_viewport, get_active_viewport_window, disable_selection import carb import carb.settings import carb.dictionary import carb.events import carb.tokens import carb.input import omni.kit.imgui as _imgui from pxr import Sdf, Usd from .navigation import Navigation from .menu_helper import MenuHelper from .menubar_helper import MenubarHelper from .stage_template import SunnySkyStage from .ui_state_manager import UIStateManager SETTINGS_PATH_FOCUSED = "/app/workspace/currentFocused" APPLICATION_MODE_PATH = "/app/application_mode" MODAL_TOOL_ACTIVE_PATH = "/app/tools/modal_tool_active" CURRENT_TOOL_PATH = "/app/viewport/currentTool" ROOT_WINDOW_NAME = "DockSpace" ICON_PATH = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/data/icons") SETTINGS_STARTUP_EXPAND_VIEWPORT = "/app/startup/expandViewport" VIEWPORT_CONTEXT_MENU_PATH = "/exts/omni.kit.window.viewport/showContextMenu" TELEPORT_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.teleport/visible" async def _load_layout_startup(layout_file: str, keep_windows_open: bool=False) -> None: try: # few frames delay to avoid the conflict with the layout of omni.kit.mainwindow for i in range(3): await omni.kit.app.get_app().next_update_async() # type: ignore QuickLayout.load_file(layout_file, keep_windows_open) # WOR: some layout don't happy collectly the first time await omni.kit.app.get_app().next_update_async() # type: ignore QuickLayout.load_file(layout_file, keep_windows_open) except Exception as exc: # pragma: no cover (Can't be tested because a non-existing layout file prints an log_error in QuickLayout and does not throw an exception) carb.log_warn(f"Failed to load layout {layout_file}: {exc}") async def _load_layout(layout_file: str, keep_windows_open:bool=False) -> None: try: # few frames delay to avoid the conflict with the layout of omni.kit.mainwindow for i in range(3): await omni.kit.app.get_app().next_update_async() # type: ignore QuickLayout.load_file(layout_file, keep_windows_open) except Exception as exc: # pragma: no cover (Can't be tested because a non-existing layout file prints an log_error in QuickLayout and does not throw an exception) carb.log_warn(f"Failed to load layout {layout_file}: {exc}") async def _clear_startup_scene_edits() -> None: try: for i in range(50): # This could possibly be a smaller value. I want to ensure this happens after RTX startup await omni.kit.app.get_app().next_update_async() # type: ignore omni.usd.get_context().set_pending_edit(False) except Exception as exc: # pragma: no cover carb.log_warn(f"Failed to clear stage edits on startup: {exc}") # This extension is mostly loading the Layout updating menu class SetupExtension(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. @property def _app(self): return omni.kit.app.get_app() @property def _settings(self): return carb.settings.get_settings() def on_startup(self, ext_id: str) -> None: self._ext_id = ext_id self._menubar_helper = MenubarHelper() self._menu_helper = MenuHelper() # using imgui directly to adjust some color and Variable imgui = _imgui.acquire_imgui() # match Create overides imgui.push_style_color(_imgui.StyleColor.ScrollbarGrab, carb.Float4(0.4, 0.4, 0.4, 1)) imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabHovered, carb.Float4(0.6, 0.6, 0.6, 1)) imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabActive, carb.Float4(0.8, 0.8, 0.8, 1)) # DockSplitterSize is the variable that drive the size of the Dock Split connection imgui.push_style_var_float(_imgui.StyleVar.DockSplitterSize, 2) # setup the Layout for your app self._layouts_path = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/layouts") layout_file = Path(self._layouts_path).joinpath(f"{self._settings.get('/app/layout/name')}.json") self.__setup_window_task = asyncio.ensure_future(_load_layout_startup(f"{layout_file}", True)) self.review_layout_path = str(Path(self._layouts_path) / "comment_layout.json") self.default_layout_path = str(Path(self._layouts_path) / "default.json") self.layout_user_path = str(Path(self._layouts_path) / "layout_user.json") # remove the user defined layout so that we always load the default layout when startup if os.path.exists(self.layout_user_path): os.remove(self.layout_user_path) # setup the menu and their layout self._current_layout_priority = 0 self._layout_menu_items = [] self._layout_file_menu() self._menu_layout = [] if self._settings.get_as_bool('/app/view/debug/menus'): self._layout_menu() # setup the Application Title window_title = get_main_window_title() if window_title: window_title.set_app_version(self._settings.get_as_string("/app/titleVersion")) # self._context_menu() self._register_my_menu() self._navigation = Navigation() self._navigation.on_startup(ext_id) self._application_mode_changed_sub = self._settings.subscribe_to_node_change_events( APPLICATION_MODE_PATH, weakref.proxy(self)._on_application_mode_changed ) self._set_viewport_menubar_visibility(False) self._test = asyncio.ensure_future(_clear_startup_scene_edits()) # OM-95865: Ensure teleport on by default. self._usd_context = omni.usd.get_context() self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_open_event, name="TeleportDefaultOn" ) if self._settings.get_as_bool(SETTINGS_STARTUP_EXPAND_VIEWPORT): self._set_viewport_fill_on() self._stage_templates = [SunnySkyStage()] disable_selection(get_active_viewport()) self._ui_state_manager = UIStateManager() self._setup_ui_state_changes() omni.kit.menu.utils.add_layout([ MenuLayout.Menu("Window", [ MenuLayout.Item("Viewport", source="Window/Viewport/Viewport 1"), MenuLayout.Item("Playlist", remove=True), MenuLayout.Item("Layout", remove=True), MenuLayout.Item("" if any(v in self._app.get_app_version() for v in ("alpha", "beta")) else "Extensions", remove=True), MenuLayout.Sort(exclude_items=["Extensions"], sort_submenus=True), ]) ]) def show_documentation(*x): import webbrowser webbrowser.open("http://docs.omniverse.nvidia.com/explorer") self._help_menu_items = [ omni.kit.menu.utils.MenuItemDescription(name="Documentation", onclick_fn=show_documentation, appear_after=[omni.kit.menu.utils.MenuItemOrder.FIRST]) ] omni.kit.menu.utils.add_menu_items(self._help_menu_items, name="Help") def _on_stage_open_event(self, event: carb.events.IEvent) -> None: if event.type == int(omni.usd.StageEventType.OPENED): app_mode = self._settings.get_as_string(APPLICATION_MODE_PATH).lower() # exit all tools self._settings.set(CURRENT_TOOL_PATH, "none") # OM-95865, OMFP-1993: Activate Teleport upon scene load ... # OMFP-2743: ... but only when in Review mode. if app_mode == "review": asyncio.ensure_future(self._stage_post_open_teleport_toggle()) # toggle RMB viewport context menu based on application mode value = False if app_mode == "review" else True self._settings.set(VIEWPORT_CONTEXT_MENU_PATH, value) # teleport is activated after loading a stage and app is in Review mode async def _stage_post_open_teleport_toggle(self) -> None: await self._app.next_update_async() if hasattr(self, "_usd_context") and self._usd_context is not None and not self._usd_context.is_new_stage(): self._settings.set("/exts/omni.kit.viewport.navigation.core/activeOperation", "teleport") def _set_viewport_fill_on(self) -> None: vp_window = get_active_viewport_window() vp_widget = vp_window.viewport_widget if vp_window else None if vp_widget: vp_widget.expand_viewport = True def _set_viewport_menubar_visibility(self, show: bool) -> None: mb_inst = get_mb_inst() if mb_inst and hasattr(mb_inst, "get_menubar"): main_menubar = mb_inst.get_menubar(DEFAULT_MENUBAR_NAME) if main_menubar.visible_model.as_bool != show: main_menubar.visible_model.set_value(show) ViewportMenuModel()._item_changed(None) # type: ignore def _on_application_mode_changed(self, item: carb.dictionary.Item, _typ: carb.settings.ChangeEventType) -> None: if self._settings.get_as_string(APPLICATION_MODE_PATH).lower() == "review": omni.usd.get_context().get_selection().clear_selected_prim_paths() disable_selection(get_active_viewport()) current_mode: str = cast(str, item.get_dict()) asyncio.ensure_future(self.defer_load_layout(current_mode)) async def defer_load_layout(self, current_mode: str) -> None: keep_windows = True # Focus Mode Toolbar self._settings.set_bool(SETTINGS_PATH_FOCUSED, True) # current_mode not in ("review", "layout")) # Turn off all tools and modal self._settings.set_string(CURRENT_TOOL_PATH, "none") self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, False) if current_mode == "review": # save the current layout for restoring later if switch back QuickLayout.save_file(self.layout_user_path) # we don't want to keep any windows except the ones which are visible in self.review_layout_path await _load_layout(self.review_layout_path, False) else: # current_mode == "layout": # check if there is any user modified layout, if yes use that one layout_filename = self.layout_user_path if os.path.exists(self.layout_user_path) else self.default_layout_path await _load_layout(layout_filename, keep_windows) self._set_viewport_menubar_visibility(current_mode == "layout") def _setup_ui_state_changes(self) -> None: windows_to_hide_on_modal = ["Measure", "Section", "Waypoints"] self._ui_state_manager.add_hide_on_modal(window_names=windows_to_hide_on_modal, restore=True) window_titles = ["Markups", "Waypoints"] for window in window_titles: setting_name = f'/exts/omni.usd_explorer.setup/{window}/visible' self._ui_state_manager.add_window_visibility_setting(window, setting_name) # toggle icon visibilites based on window visibility self._ui_state_manager.add_settings_copy_dependency( source_path="/exts/omni.usd_explorer.setup/Markups/visible", target_path="/exts/omni.kit.markup.core/show_icons", ) self._ui_state_manager.add_settings_copy_dependency( source_path="/exts/omni.usd_explorer.setup/Waypoints/visible", target_path="/exts/omni.kit.waypoint.core/show_icons", ) def _custom_quicklayout_menu(self) -> None: # we setup a simple ways to Load custom layout from the exts def add_layout_menu_entry(name, parameter, key): import inspect editor_menu = omni.kit.ui.get_editor_menu() layouts_path = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/layouts") menu_path = f"Layout/{name}" menu = editor_menu.add_item(menu_path, None, False, self._current_layout_priority) # type: ignore self._current_layout_priority = self._current_layout_priority + 1 if inspect.isfunction(parameter): # pragma: no cover (Never used, see commented out section below regarding quick save/load) menu_action = omni.kit.menu.utils.add_action_to_menu( menu_path, lambda *_: asyncio.ensure_future(parameter()), name, (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, key), ) else: menu_action = omni.kit.menu.utils.add_action_to_menu( menu_path, lambda *_: asyncio.ensure_future(_load_layout(f"{layouts_path}/{parameter}.json")), name, (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, key), ) self._layout_menu_items.append((menu, menu_action)) add_layout_menu_entry("Reset Layout", "default", carb.input.KeyboardInput.KEY_1) add_layout_menu_entry("Viewport Only", "viewport_only", carb.input.KeyboardInput.KEY_2) add_layout_menu_entry("Markup Editor", "markup_editor", carb.input.KeyboardInput.KEY_3) # add_layout_menu_entry("Waypoint Viewer", "waypoint_viewer", carb.input.KeyboardInput.KEY_4) # # you can enable Quick Save and Quick Load here # if False: # # create Quick Load & Quick Save # from omni.kit.quicklayout import QuickLayout # async def quick_save(): # QuickLayout.quick_save(None, None) # async def quick_load(): # QuickLayout.quick_load(None, None) # add_layout_menu_entry("Quick Save", quick_save, carb.input.KeyboardInput.KEY_7) # add_layout_menu_entry("Quick Load", quick_load, carb.input.KeyboardInput.KEY_8) def _register_my_menu(self) -> None: context_menu: Optional[omni.kit.context_menu.ContextMenuExtension] = omni.kit.context_menu.get_instance() if not context_menu: # pragma: no cover return def _layout_file_menu(self) -> None: self._menu_file_layout = [ MenuLayout.Menu( "File", [ MenuLayout.Item("New"), MenuLayout.Item("New From Stage Template"), MenuLayout.Item("Open"), MenuLayout.Item("Open Recent"), MenuLayout.Seperator(), MenuLayout.Item("Re-open with New Edit Layer"), MenuLayout.Seperator(), MenuLayout.Item("Share"), MenuLayout.Seperator(), MenuLayout.Item("Save"), MenuLayout.Item("Save As..."), MenuLayout.Item("Save With Options"), MenuLayout.Item("Save Selected"), MenuLayout.Item("Save Flattened As...", remove=True), MenuLayout.Seperator(), MenuLayout.Item("Collect As..."), MenuLayout.Item("Export"), MenuLayout.Seperator(), MenuLayout.Item("Import"), MenuLayout.Item("Add Reference"), MenuLayout.Item("Add Payload"), MenuLayout.Seperator(), MenuLayout.Item("Exit"), ] ) ] omni.kit.menu.utils.add_layout(self._menu_file_layout) def _layout_menu(self) -> None: self._menu_layout = [ MenuLayout.Menu( "Window", [ MenuLayout.SubMenu( "Animation", [ MenuLayout.Item("Timeline"), MenuLayout.Item("Sequencer"), MenuLayout.Item("Curve Editor"), MenuLayout.Item("Retargeting"), MenuLayout.Item("Animation Graph"), MenuLayout.Item("Animation Graph Samples"), ], ), MenuLayout.SubMenu( "Layout", [ MenuLayout.Item("Quick Save", remove=True), MenuLayout.Item("Quick Load", remove=True), ], ), MenuLayout.SubMenu( "Browsers", [ MenuLayout.Item("Content", source="Window/Content"), MenuLayout.Item("Materials"), MenuLayout.Item("Skies"), ], ), MenuLayout.SubMenu( "Rendering", [ MenuLayout.Item("Render Settings"), MenuLayout.Item("Movie Capture"), MenuLayout.Item("MDL Material Graph"), MenuLayout.Item("Tablet XR"), ], ), MenuLayout.SubMenu( "Simulation", [ MenuLayout.Group( "Flow", [ MenuLayout.Item("Presets", source="Window/Flow/Presets"), MenuLayout.Item("Monitor", source="Window/Flow/Monitor"), ], ), MenuLayout.Group( "Blast", [ MenuLayout.Item("Settings", source="Window/Blast/Settings"), MenuLayout.SubMenu( "Documentation", [ MenuLayout.Item("Kit UI", source="Window/Blast/Documentation/Kit UI"), MenuLayout.Item( "Programming", source="Window/Blast/Documentation/Programming" ), MenuLayout.Item( "USD Schemas", source="Window/Blast/Documentation/USD Schemas" ), ], ), ], ), MenuLayout.Item("Debug"), # MenuLayout.Item("Performance"), MenuLayout.Group( "Physics", [ MenuLayout.Item("Demo Scenes"), MenuLayout.Item("Settings", source="Window/Physics/Settings"), MenuLayout.Item("Debug"), MenuLayout.Item("Test Runner"), MenuLayout.Item("Character Controller"), MenuLayout.Item("OmniPVD"), MenuLayout.Item("Physics Helpers"), ], ), ], ), MenuLayout.SubMenu( "Utilities", [ MenuLayout.Item("Console"), MenuLayout.Item("Profiler"), MenuLayout.Item("USD Paths"), MenuLayout.Item("Statistics"), MenuLayout.Item("Activity Monitor"), ], ), # Remove 'Viewport 2' entry MenuLayout.SubMenu( "Viewport", [ MenuLayout.Item("Viewport 2", remove=True), ], ), MenuLayout.Sort(exclude_items=["Extensions"]), MenuLayout.Item("New Viewport Window", remove=True), ], ), # that is you enable the Quick Layout Menu MenuLayout.Menu( "Layout", [ MenuLayout.Item("Default", source="Reset Layout"), MenuLayout.Item("Viewport Only"), MenuLayout.Item("Markup Editor"), MenuLayout.Item("Waypoint Viewer"), MenuLayout.Seperator(), MenuLayout.Item("UI Toggle Visibility", source="Window/UI Toggle Visibility"), MenuLayout.Item("Fullscreen Mode", source="Window/Fullscreen Mode"), MenuLayout.Seperator(), MenuLayout.Item("Save Layout", source="Window/Layout/Save Layout..."), MenuLayout.Item("Load Layout", source="Window/Layout/Load Layout..."), # MenuLayout.Seperator(), # MenuLayout.Item("Quick Save", source="Window/Layout/Quick Save"), # MenuLayout.Item("Quick Load", source="Window/Layout/Quick Load"), ], ), MenuLayout.Menu("Tools", [MenuLayout.SubMenu("Animation", remove=True)]), ] omni.kit.menu.utils.add_layout(self._menu_layout) # type: ignore # if you want to support the Quick Layout Menu self._custom_quicklayout_menu() def on_shutdown(self): if self._menu_layout: omni.kit.menu.utils.remove_layout(self._menu_layout) # type: ignore self._menu_layout.clear() self._layout_menu_items.clear() self._navigation.on_shutdown() del self._navigation self._settings.unsubscribe_to_change_events(self._application_mode_changed_sub) del self._application_mode_changed_sub self._stage_event_sub = None # From View setup self._menubar_helper.destroy() if self._menu_helper and hasattr(self._menu_helper, "destroy"): self._menu_helper.destroy() self._menu_helper = None self._stage_templates = []
23,462
Python
45.005882
167
0.557753
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/navigation.py
import asyncio import carb import carb.settings import carb.tokens import carb.dictionary import omni.kit.app import omni.ext import omni.ui as ui import omni.kit.actions.core from omni.kit.viewport.navigation.core import ( NAVIGATION_TOOL_OPERATION_ACTIVE, ViewportNavigationTooltip, get_navigation_bar, ) __all__ = ["Navigation"] CURRENT_TOOL_PATH = "/app/viewport/currentTool" SETTING_NAVIGATION_ROOT = "/exts/omni.kit.tool.navigation/" NAVIGATION_BAR_VISIBLE_PATH = "/exts/omni.kit.viewport.navigation.core/isVisible" APPLICATION_MODE_PATH = "/app/application_mode" WALK_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.walk/visible" CAPTURE_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.capture/visible" MARKUP_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.markup/visible" MEASURE_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.measure/visible" SECTION_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.section/visible" TELEPORT_SEPARATOR_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.teleport/spvisible" WAYPOINT_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.waypoint/visible" VIEWPORT_CONTEXT_MENU_PATH = "/exts/omni.kit.window.viewport/showContextMenu" MENUBAR_APP_MODES_PATH = "/exts/omni.kit.usd_presenter.main.menubar/include_modify_mode" WELCOME_WINDOW_VISIBLE_PATH = "/exts/omni.kit.usd_presenter.window.welcome/visible" ACTIVE_OPERATION_PATH = "/exts/omni.kit.viewport.navigation.core/activeOperation" class Navigation: NAVIGATION_BAR_NAME = None # 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: str) -> None: sections = ext_id.split("-") self._ext_name = sections[0] self._settings = carb.settings.get_settings() self._navigation_bar = get_navigation_bar() self._tool_bar_button = None self._dict = carb.dictionary.get_dictionary() self._panel_visible = True self._navigation_bar.show() self._settings.set(CURRENT_TOOL_PATH, "navigation") self._settings.set(NAVIGATION_TOOL_OPERATION_ACTIVE, "teleport") self._viewport_welcome_window_visibility_changed_sub = self._settings.subscribe_to_node_change_events( WELCOME_WINDOW_VISIBLE_PATH, self._on_welcome_window_visibility_change ) # OMFP-1799 Set nav bar visibility defaults. These should remain fixed now. self._settings.set(WALK_VISIBLE_PATH, False) self._settings.set(MARKUP_VISIBLE_PATH, True) self._settings.set(WAYPOINT_VISIBLE_PATH, True) self._settings.set(TELEPORT_SEPARATOR_VISIBLE_PATH, True) self._settings.set(CAPTURE_VISIBLE_PATH, True) self._settings.set(MEASURE_VISIBLE_PATH, True) self._settings.set(SECTION_VISIBLE_PATH, True) self._application_mode_changed_sub = self._settings.subscribe_to_node_change_events( APPLICATION_MODE_PATH, self._on_application_mode_changed ) self._show_tooltips = False self._nav_bar_visibility_sub = self._settings.subscribe_to_node_change_events( NAVIGATION_BAR_VISIBLE_PATH, self._delay_reset_tooltip) _prev_navbar_vis = None _prev_tool = None _prev_operation = None def _on_welcome_window_visibility_change(self, item: carb.dictionary.Item, *_) -> None: if not isinstance(self._dict, (carb.dictionary.IDictionary, dict)): return welcome_window_vis = self._dict.get(item) # preserve the state of the navbar upon closing the Welcome window if the app is in Layout mode if self._settings.get_as_string(APPLICATION_MODE_PATH).lower() == "layout": # preserve the state of the navbar visibility if welcome_window_vis: self._prev_navbar_vis = self._settings.get_as_bool(NAVIGATION_BAR_VISIBLE_PATH) self._settings.set(NAVIGATION_BAR_VISIBLE_PATH, not(welcome_window_vis)) self._prev_tool = self._settings.get(CURRENT_TOOL_PATH) self._prev_operation = self._settings.get(ACTIVE_OPERATION_PATH) else: # restore the state of the navbar visibility if self._prev_navbar_vis is not None: self._settings.set(NAVIGATION_BAR_VISIBLE_PATH, self._prev_navbar_vis) self._prev_navbar_vis = None if self._prev_tool is not None: self._settings.set(CURRENT_TOOL_PATH, self._prev_tool) if self._prev_operation is not None: self._settings.set(ACTIVE_OPERATION_PATH, self._prev_operation) return else: if welcome_window_vis: self._settings.set(NAVIGATION_TOOL_OPERATION_ACTIVE, "none") else: self._settings.set(NAVIGATION_TOOL_OPERATION_ACTIVE, "teleport") self._settings.set(NAVIGATION_BAR_VISIBLE_PATH, not(welcome_window_vis)) def _on_application_mode_changed(self, item: carb.dictionary.Item, *_) -> None: if not isinstance(self._dict, (carb.dictionary.IDictionary, dict)): return current_mode = self._dict.get(item) self._test = asyncio.ensure_future(self._switch_by_mode(current_mode)) async def _switch_by_mode(self, current_mode: str) -> None: await omni.kit.app.get_app().next_update_async() state = True if current_mode == "review" else False self._settings.set(NAVIGATION_BAR_VISIBLE_PATH, state) self._settings.set(VIEWPORT_CONTEXT_MENU_PATH, not(state)) # toggle RMB viewport context menu self._delay_reset_tooltip(None) # OM-92161: Need to reset the tooltip when change the mode def _delay_reset_tooltip(self, *_) -> None: async def delay_set_tooltip() -> None: for _i in range(4): await omni.kit.app.get_app().next_update_async() # type: ignore ViewportNavigationTooltip.set_visible(self._show_tooltips) asyncio.ensure_future(delay_set_tooltip()) def _on_showtips_click(self, *_) -> None: self._show_tooltips = not self._show_tooltips ViewportNavigationTooltip.set_visible(self._show_tooltips) def on_shutdown(self) -> None: self._navigation_bar = None self._viewport_welcome_window_visibility_changed_sub = None self._settings.unsubscribe_to_change_events(self._application_mode_changed_sub) # type:ignore self._application_mode_changed_sub = None self._dict = None
6,679
Python
45.713286
119
0.676898
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/ui_state_manager.py
import carb.dictionary import carb.settings import omni.ui as ui from functools import partial from typing import Any, Dict, List, Tuple, Union MODAL_TOOL_ACTIVE_PATH = "/app/tools/modal_tool_active" class UIStateManager: def __init__(self) -> None: self._settings = carb.settings.acquire_settings_interface() self._modal_changed_sub = self._settings.subscribe_to_node_change_events( MODAL_TOOL_ACTIVE_PATH, self._on_modal_setting_changed ) self._hide_on_modal: List[Tuple[str,bool]] = [] self._modal_restore_window_states: Dict[str,bool] = {} self._settings_dependencies: Dict[Tuple(str,str), Dict[Any, Any]] = {} self._settings_changed_subs = {} self._window_settings = {} self._window_vis_changed_id = ui.Workspace.set_window_visibility_changed_callback(self._on_window_vis_changed) def destroy(self) -> None: if self._settings: if self._modal_changed_sub: self._settings.unsubscribe_to_change_events(self._modal_changed_sub) self._settings = None self._hide_on_modal = [] self._modal_restore_window_states = {} self._settings_dependencies = {} self._window_settings = {} if self._window_vis_changed_id: ui.Workspace.remove_window_visibility_changed_callback(self._window_vis_changed_id) self._window_vis_changed_id = None def __del__(self) -> None: self.destroy() def add_hide_on_modal(self, window_names: Union[str, List[str]], restore: bool) -> None: if isinstance(window_names, str): window_names = [window_names] for window_name in window_names: if window_name not in self._hide_on_modal: self._hide_on_modal.append((window_name, restore)) def remove_hide_on_modal(self, window_names: Union[str, List[str]]) -> None: if isinstance(window_names, str): window_names = [window_names] self._hide_on_modal = [item for item in self._hide_on_modal if item[0] not in window_names] def add_window_visibility_setting(self, window_name: str, setting_path: str) -> None: window = ui.Workspace.get_window(window_name) if window is not None: self._settings.set(setting_path, window.visible) else: # handle the case when the window is created later self._settings.set(setting_path, False) if window_name not in self._window_settings.keys(): self._window_settings[window_name] = [] self._window_settings[window_name].append(setting_path) def remove_window_visibility_setting(self, window_name: str, setting_path: str) -> None: if window_name in self._window_settings.keys(): setting_list = self._window_settings[window_name] if setting_path in setting_list: setting_list.remove(setting_path) if len(setting_list) == 0: del self._window_settings[window_name] def remove_all_window_visibility_settings(self, window_name: str) -> None: if window_name in self._window_settings.keys(): del self._window_settings[window_name] def add_settings_dependency(self, source_path: str, target_path: str, value_map: Dict[Any, Any]) -> None: key = (source_path, target_path) if key in self._settings_dependencies.keys(): carb.log_error(f'Settings dependency {source_path} -> {target_path} already exists. Ignoring.') return self._settings_dependencies[key] = value_map self._settings_changed_subs[key] = self._settings.subscribe_to_node_change_events( source_path, partial(self._on_settings_dependency_changed, source_path) ) def add_settings_copy_dependency(self, source_path: str, target_path: str) -> None: self.add_settings_dependency(source_path, target_path, None) def remove_settings_dependency(self, source_path: str, target_path: str) -> None: key = (source_path, target_path) if key in self._settings_dependencies.keys(): del self._settings_dependencies[key] if key in self._settings_changed_subs.keys(): sub = self._settings_changed_subs.pop(key) self._settings.unsubscribe_to_change_events(sub) def _on_settings_dependency_changed(self, path: str, item, event_type) -> None: value = self._settings.get(path) # setting does not exist if value is None: return target_settings = [source_target[1] for source_target in self._settings_dependencies.keys() if source_target[0] == path] for target_setting in target_settings: value_map = self._settings_dependencies[(path, target_setting)] # None means copy everything if value_map is None: self._settings.set(target_setting, value) elif value in value_map.keys(): self._settings.set(target_setting, value_map[value]) def _on_modal_setting_changed(self, item, event_type) -> None: modal = self._settings.get_as_bool(MODAL_TOOL_ACTIVE_PATH) if modal: self._hide_windows() else: self._restore_windows() def _hide_windows(self) -> None: for window_info in self._hide_on_modal: window_name, restore_later = window_info[0], window_info[1] window = ui.Workspace.get_window(window_name) if window is not None: if restore_later: self._modal_restore_window_states[window_name] = window.visible window.visible = False def _restore_windows(self) -> None: for window_info in self._hide_on_modal: window_name, restore_later = window_info[0], window_info[1] if restore_later: if window_name in self._modal_restore_window_states.keys(): old_visibility = self._modal_restore_window_states[window_name] if old_visibility is not None: window = ui.Workspace.get_window(window_name) if window is not None: window.visible = old_visibility self._modal_restore_window_states[window_name] = None def _on_window_vis_changed(self, title: str, state: bool) -> None: if title in self._window_settings.keys(): for setting in self._window_settings[title]: self._settings.set_bool(setting, state)
6,634
Python
44.136054
128
0.611999
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/stage_template.py
import carb import omni.ext import omni.kit.commands from omni.kit.stage_templates import register_template, unregister_template from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux class SunnySkyStage: def __init__(self): register_template("SunnySky", self.new_stage) def __del__(self): unregister_template("SunnySky") def new_stage(self, rootname, usd_context_name): # Create basic DistantLight usd_context = omni.usd.get_context(usd_context_name) stage = usd_context.get_stage() # get up axis up_axis = UsdGeom.GetStageUpAxis(stage) with Usd.EditContext(stage, stage.GetRootLayer()): # create Environment omni.kit.commands.execute( "CreatePrim", prim_path="/Environment", prim_type="Xform", select_new_prim=False, create_default_xform=True, context_name=usd_context_name ) texture_path = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/data/light_rigs/HDR/partly_cloudy.hdr") # create Sky omni.kit.commands.execute( "CreatePrim", prim_path="/Environment/Sky", prim_type="DomeLight", select_new_prim=False, attributes={ UsdLux.Tokens.inputsIntensity: 1000, UsdLux.Tokens.inputsTextureFile: texture_path, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.inputsSpecular: 1, UsdGeom.Tokens.visibility: "inherited", } if hasattr(UsdLux.Tokens, 'inputsIntensity') else \ { UsdLux.Tokens.intensity: 1000, UsdLux.Tokens.textureFile: texture_path, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong, UsdGeom.Tokens.visibility: "inherited", }, create_default_xform=True, context_name=usd_context_name ) prim = stage.GetPrimAtPath("/Environment/Sky") prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 1)) prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) if up_axis == "Y": prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(270, 0, 0)) else: prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 90)) prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]) # create DistantLight omni.kit.commands.execute( "CreatePrim", prim_path="/Environment/DistantLight", prim_type="DistantLight", select_new_prim=False, attributes={ UsdLux.Tokens.inputsAngle: 4.3, UsdLux.Tokens.inputsIntensity: 3000, UsdGeom.Tokens.visibility: "inherited", } if hasattr(UsdLux.Tokens, 'inputsIntensity') else \ { UsdLux.Tokens.angle: 4.3, UsdLux.Tokens.intensity: 3000, UsdGeom.Tokens.visibility: "inherited", }, create_default_xform=True, context_name=usd_context_name ) prim = stage.GetPrimAtPath("/Environment/DistantLight") prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 1)) prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) if up_axis == "Y": prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(310.6366313590111, -125.93251524567805, 0.8821359067542289)) else: prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(41.35092544555664, 0.517652153968811, -35.92928695678711)) prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
4,590
Python
48.902173
166
0.56732
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/menu_helper.py
import asyncio import carb.settings import omni.kit.app import omni.kit.commands import omni.kit.menu.utils import omni.renderer_capture from omni.kit.menu.utils import MenuLayout SETTINGS_APPLICATION_MODE_PATH = "/app/application_mode" class MenuHelper: def __init__(self) -> None: self._settings = carb.settings.get_settings() self._current_layout = None self._pending_layout = None self._changing_layout_task: asyncio.Task = None self._menu_layout_empty = [] self._menu_layout_modify = [] omni.kit.menu.utils.add_hook(self._menu_hook) self._app_mode_sub = self._settings.subscribe_to_node_change_events( SETTINGS_APPLICATION_MODE_PATH, self._on_application_mode_changed ) self._menu_hook() def destroy(self) -> None: omni.kit.menu.utils.remove_hook(self._menu_hook) if self._changing_layout_task and not self._changing_layout_task.done(): self._changing_layout_task.cancel() self._changing_layout_task = None if self._app_mode_sub: self._settings.unsubscribe_to_change_events(self._app_mode_sub) self._app_mode_sub = None self._app_ready_sub = None if self._current_layout: omni.kit.menu.utils.remove_layout(self._current_layout) self._current_layout = None def _menu_hook(self, *args, **kwargs) -> None: if self._settings.get_as_bool("/app/view/debug/menus"): return LAYOUT_EMPTY_ALLOWED_MENUS = set() LAYOUT_MODIFY_ALLOWED_MENUS = {"File", "Edit", "Window", "Tools", "Help"} # make NEW list object instead of clear original # the original list may be held by self._current_layout and omni.kit.menu.utils self._menu_layout_empty = [] self._menu_layout_modify = [] menu_instance = omni.kit.menu.utils.get_instance() if not menu_instance: # pragma: no cover return # Build new layouts using allowlists for key in menu_instance._menu_defs: if key.lower().endswith("widget"): continue if key not in LAYOUT_EMPTY_ALLOWED_MENUS: self._menu_layout_empty.append(MenuLayout.Menu(key, remove=True)) if key not in LAYOUT_MODIFY_ALLOWED_MENUS: self._menu_layout_modify.append(MenuLayout.Menu(key, remove=True)) # Remove 'Viewport 2' entry if key == "Window": for menu_item_1 in menu_instance._menu_defs[key]: for menu_item_2 in menu_item_1: if menu_item_2.name == "Viewport": menu_item_2.sub_menu = [mi for mi in menu_item_2.sub_menu if mi.name != "Viewport 2"] if self._changing_layout_task is None or self._changing_layout_task.done(): self._changing_layout_task = asyncio.ensure_future(self._delayed_change_layout()) def _on_application_mode_changed(self, *args) -> None: if self._changing_layout_task is None or self._changing_layout_task.done(): self._changing_layout_task = asyncio.ensure_future(self._delayed_change_layout()) async def _delayed_change_layout(self): mode = self._settings.get_as_string(SETTINGS_APPLICATION_MODE_PATH) if mode in ["present", "review"]: pending_layout = self._menu_layout_empty else: pending_layout = self._menu_layout_modify # Don't change layout inside of menu callback _on_application_mode_changed # omni.ui throws error if self._current_layout: # OMFP-2737: Do no rebuild menu (change menu layout) if layout is same # Here only check number of layout menu items and name of every of layout menu item same_layout = len(self._current_layout) == len(pending_layout) if same_layout: for index, item in enumerate(self._current_layout): if item.name != pending_layout[index].name: same_layout = False if same_layout: return omni.kit.menu.utils.remove_layout(self._current_layout) self._current_layout = None omni.kit.menu.utils.add_layout(pending_layout) # type: ignore self._current_layout = pending_layout.copy() self._changing_layout_task = None
4,434
Python
37.565217
113
0.608029
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/test_release_config.py
import carb.settings import carb.tokens import omni.kit.app import omni.kit.test class TestConfig(omni.kit.test.AsyncTestCase): async def test_l1_public_release_configuration(self): settings = carb.settings.get_settings() app_version = settings.get("/app/version") # This test covers a moment in time when we switch version to RC. # Following test cases must be satisfied. is_rc = "-rc." in app_version # title_format_string = settings.get("exts/omni.kit.window.modifier.titlebar/titleFormatString") # if is_rc: # Make sure the title format string doesn't use app version if app version contains rc # title_using_app_version = "/app/version" in title_format_string # self.assertFalse(is_rc and title_using_app_version, "check failed: title format string contains app version which contains 'rc'") # Make sure the title format string has "Beta" in it # title_has_beta = "Beta" in title_format_string # self.assertTrue(title_has_beta, "check failed: title format string does not have 'Beta ' in it") # if is_rc: # Make sure the title format string doesn't use app version if app version contains rc # title_using_app_version = "/app/version" in title_format_string # self.assertFalse(is_rc and title_using_app_version, "check failed: title format string contains app version which contains 'rc'") # Make sure the title format string has "Beta" in it # title_has_beta = "Beta" in title_format_string # self.assertTrue(title_has_beta, "check failed: title format string does not have 'Beta ' in it") # Make sure we set build to external when going into RC release mode # external = settings.get("/privacy/externalBuild") or False # self.assertEqual( # external, # is_rc, # "check failed: is this an RC build? %s Is /privacy/externalBuild set to true? %s" % (is_rc, external), # ) # if is_rc: # # Make sure we remove some extensions from public release # EXTENSIONS = [ # # "omni.kit.profiler.tracy", # "omni.kit.window.jira", # "omni.kit.testing.services", # "omni.kit.tests.usd_stress", # "omni.kit.tests.basic_validation", # # "omni.kit.extension.reports", # ] # manager = omni.kit.app.get_app().get_extension_manager() # ext_names = {e["name"] for e in manager.get_extensions()} # for ext in EXTENSIONS: # self.assertEqual( # ext in ext_names, # False, # f"looks like {ext} was not removed from public build", # ) async def test_l1_usd_explorer_and_usd_explorer_full_have_same_version(self): manager = omni.kit.app.get_app().get_extension_manager() EXTENSIONS = [ "omni.usd_explorer", "omni.usd_explorer.full", ] # need to find both extensions and they need the same version id usd_explorer_exts = [e for e in manager.get_extensions() if e.get("name", "") in EXTENSIONS] self.assertEqual(len(usd_explorer_exts), 2) self.assertEqual( usd_explorer_exts[0]["version"], usd_explorer_exts[1]["version"], "omni.usd_explorer.kit and omni.usd_explorer.full.kit have different versions", )
3,572
Python
43.662499
143
0.594905
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/test_state_manager.py
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb.settings import omni.kit.app import omni.ui as ui from omni.kit.test import AsyncTestCase from ..ui_state_manager import UIStateManager, MODAL_TOOL_ACTIVE_PATH class TestUIStateManager(AsyncTestCase): async def setUp(self): self._sm = UIStateManager() self._settings = carb.settings.get_settings() async def tearDown(self): self._sm = None async def test_destroy(self): self._sm.add_hide_on_modal('dummy', False) self._sm.add_settings_copy_dependency('a', 'b') self._sm.add_settings_dependency('c', 'd', {1: 2}) self._sm.add_window_visibility_setting('my_window', 'my_setting') self._sm.destroy() async def test_hide_on_modal(self): self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, False) self._sm.add_hide_on_modal('NO_RESTORE', False) self._sm.add_hide_on_modal(['A_RESTORE', 'B_RESTORE'], True) window_no_restore = ui.Window('NO_RESTORE') window_restore_1 = ui.Window('A_RESTORE') window_restore_2 = ui.Window('B_RESTORE') window_no_restore.visible = True window_restore_1.visible = True window_restore_2.visible = False await self._wait() self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, True) await self._wait() self.assertFalse(window_no_restore.visible) self.assertFalse(window_restore_1.visible) self.assertFalse(window_restore_2.visible) self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, False) await self._wait() self.assertFalse(window_no_restore.visible) self.assertTrue(window_restore_1.visible) self.assertFalse(window_restore_2.visible) self._sm.remove_hide_on_modal(window_restore_1.title) self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, True) await self._wait() self.assertTrue(window_restore_1.visible) self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, False) async def test_window_visibility_setting(self): window_name = 'Dummy' setting_path = '/apps/dummy' setting_path2 = '/apps/dummy2' window = ui.Window(window_name) window.visible = True await self._wait() self._sm.add_window_visibility_setting(window_name=window_name, setting_path=setting_path) self._sm.add_window_visibility_setting(window_name=window_name, setting_path=setting_path2) self.assertIsNotNone(self._settings.get(setting_path)) self.assertTrue(self._settings.get(setting_path)) self.assertTrue(self._settings.get(setting_path2)) window.visible = False self.assertFalse(self._settings.get(setting_path)) self.assertFalse(self._settings.get(setting_path2)) window.visible = True self.assertTrue(self._settings.get(setting_path)) self.assertTrue(self._settings.get(setting_path2)) self._sm.remove_window_visibility_setting(window_name=window_name, setting_path=setting_path) window.visible = False self.assertTrue(self._settings.get(setting_path)) self.assertFalse(self._settings.get(setting_path2)) self._sm.remove_all_window_visibility_settings(window_name=window_name) window.visible = True self.assertFalse(self._settings.get(setting_path2)) async def test_setting_dependency(self): setting_path_copy_from = '/app/copy_from' setting_path_copy_to = '/ext/copy_to' setting_path_map_from = '/ext/map_from' setting_path_map_to = '/something/map_to' self._sm.add_settings_copy_dependency(setting_path_copy_from, setting_path_copy_to) self._settings.set_string(setting_path_copy_from, 'hello_world') self.assertEqual(self._settings.get(setting_path_copy_from), self._settings.get(setting_path_copy_to)) # doesn't work the other way around self._settings.set_string(setting_path_copy_to, 'no_copy_back') self.assertEqual(self._settings.get(setting_path_copy_from), 'hello_world') self._sm.add_settings_dependency(setting_path_map_from, setting_path_map_to, {1: 2, 3: 4}) self._settings.set_int(setting_path_map_from, 1) self.assertEqual(self._settings.get(setting_path_map_to), 2) self._settings.set_int(setting_path_map_from, 3) self.assertEqual(self._settings.get(setting_path_map_to), 4) # not in the map self._settings.set_int(setting_path_map_from, 42) self.assertEqual(self._settings.get(setting_path_map_to), 4) self.assertEqual(self._settings.get(setting_path_copy_from), 'hello_world') self.assertEqual(self._settings.get(setting_path_copy_to), 'no_copy_back') self._sm.remove_settings_dependency(setting_path_copy_from, setting_path_copy_to) self._settings.set_string(setting_path_copy_from, 'this_is_not_copied') self.assertEqual(self._settings.get(setting_path_copy_to), 'no_copy_back') async def _wait(self, frames: int = 5): for _ in range(frames): await omni.kit.app.get_app().next_update_async()
5,552
Python
42.046511
110
0.67219
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/__init__.py
# run startup tests first from .test_app_startup import * # run all other tests after from .test_extensions import * from .test_release_config import * from .test import * from .test_state_manager import *
206
Python
24.874997
34
0.757282
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/test.py
import omni.kit.app from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test ext_id = 'omni.usd_explorer.setup' class TestSetupToolExtension(OmniUiTest): async def test_extension(self): manager = omni.kit.app.get_app().get_extension_manager() self.assertTrue(ext_id) self.assertTrue(manager.is_extension_enabled(ext_id)) app = omni.kit.app.get_app() for _ in range(500): await app.next_update_async() manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertTrue(not manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) async def test_menubar_helper_camera_dependency(self): manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled('omni.kit.viewport.menubar.camera', True) await ui_test.human_delay() manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) async def test_menu_helper(self): from ..menu_helper import MenuHelper menu_helper = MenuHelper() menu_helper.destroy() async def test_menubar_helper_menu(self): from ..menubar_helper import MenubarHelper menubar_helper = MenubarHelper() menubar_helper._create_camera_speed(None, None) menubar_helper.destroy() async def test_menu_helper_debug_setting(self): SETTINGS_VIEW_DEBUG_MENUS = '/app/view/debug/menus' import carb.settings settings = carb.settings.get_settings() manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) orig_value = settings.get(SETTINGS_VIEW_DEBUG_MENUS) settings.set_bool(SETTINGS_VIEW_DEBUG_MENUS, True) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) settings.set_bool(SETTINGS_VIEW_DEBUG_MENUS, orig_value) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) async def test_menu_helper_application_mode_change(self): from ..menu_helper import SETTINGS_APPLICATION_MODE_PATH import carb.settings settings = carb.settings.get_settings() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'modify') await ui_test.human_delay() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'welcome') await ui_test.human_delay() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'modify') await ui_test.human_delay() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'comment') await ui_test.human_delay() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'modify') await ui_test.human_delay() async def test_menu_helper_widget_menu(self): import omni.kit.menu.utils omni.kit.menu.utils.add_menu_items([], name='test widget') from ..menu_helper import MenuHelper menu_helper = MenuHelper() menu_helper.destroy() async def test_startup_expand_viewport(self): from ..setup import SETTINGS_STARTUP_EXPAND_VIEWPORT import carb.settings settings = carb.settings.get_settings() orig_value = settings.get(SETTINGS_STARTUP_EXPAND_VIEWPORT) settings.set_bool(SETTINGS_STARTUP_EXPAND_VIEWPORT, True) manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) settings.set_bool(SETTINGS_STARTUP_EXPAND_VIEWPORT, orig_value) manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) async def test_navigation_invalid_dict(self): from ..navigation import Navigation navigation = Navigation() navigation._show_tooltips = False navigation._dict = 42 navigation._on_application_mode_changed(None, None) navigation._on_showtips_click() async def test_navigation_current_tool_mode_change(self): from ..navigation import CURRENT_TOOL_PATH, APPLICATION_MODE_PATH import carb.settings settings = carb.settings.get_settings() settings.set_string(APPLICATION_MODE_PATH, 'modify') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'markup') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'navigation') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'markup') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'welcome') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'navigation') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'markup') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'navigation') await ui_test.human_delay() async def test_setup_clear_startup_scene_edits(self): from ..setup import _clear_startup_scene_edits await _clear_startup_scene_edits() import omni.usd self.assertFalse(omni.usd.get_context().has_pending_edit()) async def test_stage_template(self): import omni.kit.stage_templates omni.kit.stage_templates.new_stage(template='SunnySky')
6,826
Python
34.190721
79
0.665397
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/test_app_startup.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app from omni.kit.test import AsyncTestCase class TestAppStartup(AsyncTestCase): async def test_l1_app_startup_time(self): """Get startup time - send to nvdf""" for _ in range(60): await omni.kit.app.get_app().next_update_async() try: from omni.kit.core.tests import app_startup_time app_startup_time(self.id()) except: # noqa pass self.assertTrue(True) async def test_l1_app_startup_warning_count(self): """Get the count of warnings during startup - send to nvdf""" for _ in range(60): await omni.kit.app.get_app().next_update_async() try: from omni.kit.core.tests import app_startup_warning_count app_startup_warning_count(self.id()) except: # noqa pass self.assertTrue(True)
1,323
Python
32.948717
77
0.657596
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/test_extensions.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import sys import carb.settings import omni.kit.app import omni.kit.actions.core from omni.kit.core.tests import validate_extensions_load, validate_extensions_tests from omni.kit.test import AsyncTestCase from pxr import Usd, UsdGeom, Gf class TestUSDExplorerExtensions(AsyncTestCase): async def test_l1_extensions_have_tests(self): """Loop all enabled extensions to see if they have at least one (1) unittest""" await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # This list should be empty or near empty ideally EXCLUSION_LIST = [ # extensions from Kit "omni.mdl", "omni.ansel.init", # extensions from USD Explorer ] # These extensions only run tests on win32 for now if sys.platform != "win32": EXCLUSION_LIST.append("omni.hydra.scene_api") EXCLUSION_LIST.append("omni.rtx.tests") self.assertEqual(validate_extensions_tests(EXCLUSION_LIST), 0) async def test_l1_extensions_load(self): """Loop all enabled extensions to see if they loaded correctly""" self.assertEqual(validate_extensions_load(), 0) async def test_regression_omfp_2304(self): """Regression test for OMFP-2304""" loaded_omni_kit_collaboration_selection_outline = False manager = omni.kit.app.get_app().get_extension_manager() for ext in manager.get_extensions(): if ext["name"] == "omni.kit.collaboration.selection_outline": loaded_omni_kit_collaboration_selection_outline = True break self.assertTrue(loaded_omni_kit_collaboration_selection_outline) async def _wait(self, frames: int = 10): for _ in range(frames): await omni.kit.app.get_app().next_update_async() async def wait_stage_loading(self): while True: _, files_loaded, total_files = omni.usd.get_context().get_stage_loading_status() if files_loaded or total_files: await self._wait() continue break await self._wait(100) async def _get_1_1_1_rotation(self) -> Gf.Vec3d: """Loads a stage and returns the transformation of the (1,1,1) vector by the directional light's rotation""" await self._wait() omni.kit.actions.core.execute_action("omni.kit.window.file", "new") await self.wait_stage_loading() context = omni.usd.get_context() self.assertIsNotNone(context) stage = context.get_stage() self.assertIsNotNone(stage) prim_path = '/Environment/DistantLight' prim = stage.GetPrimAtPath(prim_path) self.assertTrue(prim.IsValid()) # Extract the prim's transformation matrix in world space xformAPI = UsdGeom.XformCache() transform_matrix_world = xformAPI.GetLocalToWorldTransform(prim) unit_point = Gf.Vec3d(1, 1, 1) transformed_point = transform_matrix_world.Transform(unit_point) return transformed_point async def test_regression_omfp_OMFP_3314(self): """Regression test for OMFP-3314""" settings = carb.settings.get_settings() UP_AXIS_PATH = "/persistent/app/stage/upAxis" settings.set("/persistent/app/newStage/defaultTemplate", "SunnySky") settings.set_string(UP_AXIS_PATH, "Z") point_z_up = await self._get_1_1_1_rotation() settings.set_string(UP_AXIS_PATH, "Y") point_y_up = await self._get_1_1_1_rotation() # with the default camera position: # in y-up: z points bottom left, x points bottom right, y points up # in z-up: x points bottom left, y points bottom right, z points up places = 4 self.assertAlmostEqual(point_y_up[2], point_z_up[0], places=places) self.assertAlmostEqual(point_y_up[0], point_z_up[1], places=places) self.assertAlmostEqual(point_y_up[1], point_z_up[2], places=places)
4,461
Python
40.314814
116
0.656355
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.32] - 2023-11-02 ### Changed - OMFP-3224: Added regression test - Added unit tests for state manager ## [1.0.31] - 2023-10-25 ### Changed - OMFP-3094: Restored Window/Viewport menu ## [1.0.30] - 2023-10-26 ### Changed - OMFP-2904: Show "Examples" by default in Layout mode ## [1.0.29] - 2023-10-25 ### Changed - OMFP-3224: Fix stage template light directions. ## [1.0.28] - 2023-10-23 ### Changed - OMFP-2654: Upgraded carb.imgui with omni.kit.imgui ## [1.0.27] - 2023-10-20 ### Changed - OMFP-2649: Missed the Layout item, it is now hidden as requested. ## [1.0.26] - 2023-10-20 ### Changed - Update embedded light rigs and textures ## [1.0.25] - 2023-10-19 ### Changed - Added regression test for OMFP-2304 ## [1.0.24] - 2023-10-19 ### Changed - OMFP-1981: always load the default layout when startup the app ## [1.0.23] - 2023-10-18 ### Changed - OMFP-2649: Hiding menu entries. ## [1.0.22] - 2023-10-18 ### Changed - Updated About dialog PNG to match the new application icon. ## [1.0.21] - 2023-10-18 ### Changed - OMFP-2737: Do no rebuild menu (change menu layout) if layout is same ## [1.0.20] - 2023-10-18 ### Changed - make windows invisible which are not desired to be in Review mode, OMFP-2252 activity progress window and OMFP-1981 scene optimizer window. - OMFP-1981: when user switch between modes, make sure the user defined layout in Layout mode is kept. ## [1.0.19] - 2023-10-17 ### Changed - OMFP-2547 - remove markup from modal list, markup window visibility is now handled in omni.kit.markup.core ## [1.0.18] - 2023-10-17 ### Changed - Fixed test ## [1.0.17] - 2023-10-16 ### Changed - Navigation bar visibility fixes ## [1.0.16] - 2023-10-13 ### Changed - Waypoint and markup visibilities are bound to their list windows ## [1.0.15] - 2023-10-12 ### Changed - OMFP-2417 - Rename 'comment' -> 'review' and 'modify' -> 'layout' ## [1.0.14] - 2023-10-12 ### Changed - Added more unit tests. ## [1.0.13] - 2023-10-11 ### Changed - OMFP-2328: Fix "Sunnysky" oriented incorrectly ## [1.0.12] - 2023-10-10 ### Changed - OMFP-2226 - Remove second Viewport menu item from layouts. ## [1.0.11] - 2023-10-11 ### Changed - Added UI state manager. ## [1.0.10] - 2023-10-10 ### Changed - Deactivate tools when app mode is changed. ## [1.0.9] - 2023-10-09 ### Changed - OMFP-2200 - Disabling the viewport expansion, this should keep us locked to a 16:9 aspect ratio. ## [1.0.8] - 2023-10-06 ### Changed - Added a new stage template and made it default ## [1.0.7] - 2023-10-06 ### Changed - Enable UI aware "expand_viewport" mode rather than lower-level fill_viewport mode ## [1.0.6] - 2023-10-05 ### Changed - Used allowlists for building main menu entries to guard against unexpected menus. ## [1.0.5] - 2023-10-05 ### Fixed - Regression in hiding viewport toolbar. ## [1.0.4] - 2023-10-04 ### Changed - Modify mode now shows selected menus on main menubar. ## [1.0.3] - 2023-10-04 - Hide Viewport top toolbar in Comment Mode ## [1.0.2] - 2023-10-03 - Navigation Toolbar hidden by default in Modify Mode ## [1.0.1] - 2023-09-27 - Renamed to omni.usd_explorer.setup ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
3,289
Markdown
23.37037
141
0.672545
dariengit/kit-app-template/source/extensions/omni.usd_explorer.setup/docs/README.md
# omni.usd_explorer.setup
25
Markdown
24.999975
25
0.8
dariengit/kit-app-template/source/extensions/omni.hello.world/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Simple UI Extension Template" description = "The simplest python extension example. Use it as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Path (relative to the root) of changelog changelog = "docs/CHANGELOG.md" # URL of the extension source repository. repository = "https://github.com/NVIDIA-Omniverse/kit-app-template" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.hello.world" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,200
TOML
26.295454
105
0.738333
dariengit/kit-app-template/source/extensions/omni.hello.world/omni/hello/world/extension.py
# Copyright 2019-2023 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ext import omni.ui as ui # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print(f"[omni.hello.world] some_public_function was called with {x}") return x ** x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class 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("[omni.hello.world] MyExtension startup") self._count = 0 self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_click(): self._count += 1 label.text = f"count: {self._count}" def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Add", clicked_fn=on_click) ui.Button("Reset", clicked_fn=on_reset) def on_shutdown(self): print("[omni.hello.world] MyExtension shutdown")
2,141
Python
36.578947
119
0.64269
dariengit/kit-app-template/source/extensions/omni.hello.world/omni/hello/world/__init__.py
# Copyright 2019-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. from .extension import *
609
Python
39.666664
74
0.770115
dariengit/kit-app-template/source/extensions/omni.hello.world/omni/hello/world/tests/__init__.py
# Copyright 2019-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. from .test_hello_world import *
617
Python
37.624998
74
0.768233
dariengit/kit-app-template/source/extensions/omni.hello.world/omni/hello/world/tests/test_hello_world.py
# Copyright 2019-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. # NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.hello.world # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = omni.hello.world.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
2,253
Python
35.950819
142
0.70395
dariengit/kit-app-template/source/extensions/omni.hello.world/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
dariengit/kit-app-template/source/extensions/omni.hello.world/docs/README.md
# Simple UI Extension Template The simplest python extension example. Use it as a starting point for your extensions.
119
Markdown
28.999993
86
0.806723
dariengit/kit-app-template/source/launcher/description.toml
name = "USD Explorer" # displayed application name shortName = "USD Explorer" # displayed application name in smaller card and library view version = "${version}" # version must be semantic kind = "app" # enum of "app", "connector", and "experience" for now latest = true # boolean for if this version is the latest version slug = "my_company.usd_explorer" # unique identifier for component, all lower case, persists between versions productArea = "My Company" # displayed before application name in launcher category = "Apps" # category of content channel = "beta" # 3 filter types [ "alpha", "beta", "release "] enterpriseStatus = false # set true if you want this package to show in enterprise launcher #values for filtering content, not implemented yet tags = [ "Manufacturing", "Product Design", "Scene Composition", "Visualization", "Rendering" ] #string array, each line is a new line, keep lines under 256 char and keep lines under 4 description = [ "My Company USD Explorer is an Omniverse app for Reviewing and Constructing large facilities such as factories, warehouses and more. It is built using NVIDIA Omniverse™ Kit. The Scene Description and in-memory model is based on Pixar's USD. Omniverse USD Composer takes advantage of the advanced workflows of USD like Layers, Variants, Instancing and much more.", "When connected to a Omniverse Nucleus server, worlds can be authored LIVE across multiple Omniverse applications, machines and users for advanced collaborative workflows." ] #array of links for more info on product [[links]] title = "Tutorials" url = "http://omniverse.nvidia.com/tutorials" [[links]] title = "Forums" url = "https://forums.developer.nvidia.com/c/omniverse/300" [developer] #name of developer name = 'My Company' # hyperlink on developer name (can be left as empty string) url = 'https://www.my-company.com/' [publisher] #name of publisher name = 'My Company' # hyperlink on publisher name (can be left as empty string) url = 'https://www.my-company.com/' [url] windows-x86_64 = 'windows-x86_64/package.zip' linux-x86_64 = 'linux-x86_64/package.zip'
2,246
TOML
43.939999
363
0.704809
dariengit/kit-app-template/source/launcher/requirements.toml
# Optional note that will be shown below system requirements. # Supports markdown. note = "Note: Omniverse is built to run on any RTX-powered machine. For ideal performance, we recommend using GeForce RTX™ 2080, Quadro RTX™ 5000, or higher. For latest drivers, visit [NVIDIA Driver Downloads](https://www.nvidia.com/Download/index.aspx). For Quadro, select 'Quadro New Feature Driver (QNF)." # System requirements specs. # Supports line breaks. [minimum] cpuNames = "Intel I7\nAMD Ryzen" cpuCores = "4" ram = "16 GB" storage = "512 GB SSD" vram = "6 GB" gpu = "Any RTX GPU" [recommended] cpuNames = "Intel I7\nAMD Ryzen" cpuCores = "8" ram = "32 GB" storage = "512 GB M.2 SSD" vram = "8 GB" gpu = "GeForce RTX 2080\nQuadro RTX 5000"
734
TOML
33.999998
308
0.723433
dariengit/kit-app-template/source/launcher/launcher.toml
## install and launch instructions by environment [defaults.windows-x86_64] url = "" entrypoint = "${productRoot}/omni.usd_explorer.bat" args = ["--/app/environment/name='launcher'"] [defaults.windows-x86_64.open] command = "${productRoot}/omni.usd_explorer.bat" args = ['--exec "open_stage.py ${file}"', "--/app/environment/name='launcher'"] [defaults.windows-x86_64.environment] [defaults.windows-x86_64.install] pre-install = "" pre-install-args = [] install = "${productRoot}/pull_kit_sdk.bat" install-args = [] post-install = "" # "${productRoot}/omni.usd_explorer.warmup.bat" post-install-args = ["--/app/environment/name='launcher_warmup'"] [defaults.windows-x86_64.uninstall] pre-uninstall = "" pre-uninstall-args = [] uninstall = "" uninstall-args = [] post-uninstall = "" post-uninstall-args = [] [defaults.linux-x86_64] url = "" entrypoint = "${productRoot}/omni.usd_explorer.sh" args = ["--/app/environment/name='launcher'"] [defaults.linux-x86_64.environment] [defaults.linux-x86_64.install] pre-install = "" pre-install-args = [] install = "${productRoot}/pull_kit_sdk.sh" install-args = [] post-install = "" # "${productRoot}/omni.usd_explorer.warmup.sh" post-install-args = ["--/app/environment/name='launcher_warmup'"] [defaults.linux-x86_64.uninstall] pre-uninstall = "" pre-uninstall-args = [] uninstall = "" uninstall-args = [] post-uninstall = "" post-uninstall-args = []
1,400
TOML
27.019999
79
0.696429
levi-kennedy/orbit.vlmrew/pyproject.toml
[build-system] requires = ["setuptools", "toml"] build-backend = "setuptools.build_meta" [tool.isort] atomic = true profile = "black" line_length = 120 py_version = 310 skip_glob = ["docs/*", "logs/*", "_orbit/*", "_isaac_sim/*"] group_by_package = true sections = [ "FUTURE", "STDLIB", "THIRDPARTY", "ORBITPARTY", "FIRSTPARTY", "LOCALFOLDER", ] extra_standard_library = [ "numpy", "h5py", "open3d", "torch", "tensordict", "bpy", "matplotlib", "gymnasium", "gym", "scipy", "hid", "yaml", "prettytable", "toml", "trimesh", "tqdm", ] known_thirdparty = [ "omni.isaac.core", "omni.replicator.isaac", "omni.replicator.core", "pxr", "omni.kit.*", "warp", "carb", ] known_orbitparty = [ "omni.isaac.orbit", "omni.isaac.orbit_tasks", "omni.isaac.orbit_assets" ] # Modify the following to include the package names of your first-party code known_firstparty = "orbit.ext_template" known_local_folder = "config" [tool.pyright] exclude = [ "**/__pycache__", "**/_isaac_sim", "**/_orbit", "**/docs", "**/logs", ".git", ".vscode", ] typeCheckingMode = "basic" pythonVersion = "3.10" pythonPlatform = "Linux" enableTypeIgnoreComments = true # This is required as the CI pre-commit does not download the module (i.e. numpy, torch, prettytable) # Therefore, we have to ignore missing imports reportMissingImports = "none" # This is required to ignore for type checks of modules with stubs missing. reportMissingModuleSource = "none" # -> most common: prettytable in mdp managers reportGeneralTypeIssues = "none" # -> raises 218 errors (usage of literal MISSING in dataclasses) reportOptionalMemberAccess = "warning" # -> raises 8 errors reportPrivateUsage = "warning"
1,823
TOML
20.458823
103
0.633022
levi-kennedy/orbit.vlmrew/setup.py
"""Installation script for the 'orbit.ext_template' python package.""" import os import toml from setuptools import setup # Obtain the extension data from the extension.toml file EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__)) # Read the extension.toml file EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml")) # Minimum dependencies required prior to installation INSTALL_REQUIRES = [ # NOTE: Add dependencies "psutil", ] # Installation operation setup( # TODO: Change your package naming # ----------------------------------------------------------------- name="orbit.ext_template", packages=["orbit.ext_template"], # ----------------------------------------------------------------- author=EXTENSION_TOML_DATA["package"]["author"], maintainer=EXTENSION_TOML_DATA["package"]["maintainer"], maintainer_email=EXTENSION_TOML_DATA["package"]["maintainer_email"], url=EXTENSION_TOML_DATA["package"]["repository"], version=EXTENSION_TOML_DATA["package"]["version"], description=EXTENSION_TOML_DATA["package"]["description"], keywords=EXTENSION_TOML_DATA["package"]["keywords"], install_requires=INSTALL_REQUIRES, license="BSD-3-Clause", include_package_data=True, python_requires=">=3.10", classifiers=[ "Natural Language :: English", "Programming Language :: Python :: 3.10", "Isaac Sim :: 2023.1.0-hotfix.1", "Isaac Sim :: 2023.1.1", ], zip_safe=False, )
1,524
Python
32.888888
89
0.622703
levi-kennedy/orbit.vlmrew/README.md
# Extension Template for Orbit [![IsaacSim](https://img.shields.io/badge/IsaacSim-2023.1.1-silver.svg)](https://docs.omniverse.nvidia.com/isaacsim/latest/overview.html) [![Orbit](https://img.shields.io/badge/Orbit-0.2.0-silver)](https://isaac-orbit.github.io/orbit/) [![Python](https://img.shields.io/badge/python-3.10-blue.svg)](https://docs.python.org/3/whatsnew/3.10.html) [![Linux platform](https://img.shields.io/badge/platform-linux--64-orange.svg)](https://releases.ubuntu.com/20.04/) [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://pre-commit.com/) [![License](https://img.shields.io/badge/license-MIT-yellow.svg)](https://opensource.org/license/mit) ## Overview This repository serves as a template for building projects or extensions based on Orbit. It allows you to develop in an isolated environment, outside of the core Orbit repository. Furthermore, this template serves three use cases: - **Python Package** Can be installed into Isaac Sim's Python environment, making it suitable for users who want to integrate their extension to `Orbit` as a python package. - **Project Template** Ensures access to `Isaac Sim` and `Orbit` functionalities, which can be used as a project template. - **Omniverse Extension** Can be used as an Omniverse extension, ideal for projects that leverage the Omniverse platform's graphical user interface. **Key Features:** - `Isolation` Work outside the core Orbit repository, ensuring that your development efforts remain self-contained. - `Flexibility` This template is set up to allow your code to be run as an extension in Omniverse. **Keywords:** extension, template, orbit ### License The source code is released under a [BSD 3-Clause license](https://opensource.org/licenses/BSD-3-Clause). **Author: The ORBIT Project Developers<br /> Affiliation: [The AI Institute](https://theaiinstitute.com/)<br /> Maintainer: Nico Burger, [email protected]** ## Setup Depending on the use case defined [above](#overview), follow the instructions to set up your extension template. Start with the [Basic Setup](#basic-setup), which is required for either use case. ### Basic Setup #### Dependencies This template depends on Isaac Sim and Orbit. For detailed instructions on how to install these dependencies, please refer to the [installation guide](https://isaac-orbit.github.io/orbit/source/setup/installation.html). - [Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/index.html) - [Orbit](https://isaac-orbit.github.io/orbit/) #### Configuration Decide on a name for your project or extension. This guide will refer to this name as `<your_extension_name>`. - Create a new repository based off this template [here](https://github.com/new?owner=isaac-orbit&template_name=orbit.ext_template&template_owner=isaac-orbit). Name your forked repository using the following convention: `"orbit.<your_extension_name>"`. - Clone your forked repository to a location **outside** the orbit repository. ```bash git clone <your_repository_url> ``` - To tailor this template to your needs, customize the settings in `config/extension.toml` and `setup.py` by completing the sections marked with TODO. - Rename your source folder. ```bash cd orbit.<your_extension_name> mv orbit/ext_template orbit/<your_extension_name> ``` - Define the following environment variable to specify the path to your Orbit installation: ```bash # Set the ORBIT_PATH environment variable to point to your Orbit installation directory export ORBIT_PATH=<your_orbit_path> ``` #### Set Python Interpreter Although using a virtual environment is optional, we recommend using `conda` (detailed instructions [here](https://isaac-orbit.github.io/orbit/source/setup/installation.html#setting-up-the-environment)). If you decide on using Isaac Sim's bundled Python, you can skip these steps. - If you haven't already: create and activate your `conda` environment, followed by installing extensions inside Orbit: ```bash # Create conda environment ${ORBIT_PATH}/orbit.sh --conda # Activate conda environment conda activate orbit # Install all Orbit extensions in orbit/source/extensions ${ORBIT_PATH}/orbit.sh --install ``` - Set your `conda` environment as the default interpreter in VSCode by opening the command palette (`Ctrl+Shift+P`), choosing `Python: Select Interpreter` and selecting your `conda` environment. Once you are in the virtual environment, you do not need to use `${ORBIT_PATH}/orbit.sh -p` to run python scripts. You can use the default python executable in your environment by running `python` or `python3`. However, for the rest of the documentation, we will assume that you are using `${ORBIT_PATH}/orbit.sh -p` to run python scripts. #### Set up IDE To setup the IDE, please follow these instructions: 1. Open the `orbit.<your_extension_template>` directory on Visual Studio Code IDE 2. Run VSCode Tasks, by pressing `Ctrl+Shift+P`, selecting `Tasks: Run Task` and running the `setup_python_env` in the drop down menu. When running this task, you will be prompted to add the absolute path to your Orbit installation. If everything executes correctly, it should create a file .python.env in the .vscode directory. The file contains the python paths to all the extensions provided by Isaac Sim and Omniverse. This helps in indexing all the python modules for intelligent suggestions while writing code. ### Setup as Python Package / Project Template From within this repository, install your extension as a Python package to the Isaac Sim Python executable. ```bash ${ORBIT_PATH}/orbit.sh -p -m pip install --upgrade pip ${ORBIT_PATH}/orbit.sh -p -m pip install -e . ``` ### Setup as Omniverse Extension To enable your extension, follow these steps: 1. **Add the search path of your repository** to the extension manager: - Navigate to the extension manager using `Window` -> `Extensions`. - Click on the **Hamburger Icon** (☰), then go to `Settings`. - In the `Extension Search Paths`, enter the path that goes up to your repository's location without actually including the repository's own directory. For example, if your repository is located at `/home/code/orbit.ext_template`, you should add `/home/code` as the search path. - If not already present, in the `Extension Search Paths`, enter the path that leads to your local Orbit directory. For example: `/home/orbit/source/extensions` - Click on the **Hamburger Icon** (☰), then click `Refresh`. 2. **Search and enable your extension**: - Find your extension under the `Third Party` category. - Toggle it to enable your extension. ## Usage ### Python Package Import your python package within `Isaac Sim` and `Orbit` using: ```python import orbit.<your_extension_name> ``` ### Project Template We provide an example for training and playing a policy for ANYmal on flat terrain. Install [RSL_RL](https://github.com/leggedrobotics/rsl_rl) outside of the orbit repository, e.g. `home/code/rsl_rl`. ```bash git clone https://github.com/leggedrobotics/rsl_rl.git cd rsl_rl ${ORBIT_PATH}/orbit.sh -p -m pip install -e . ``` Train a policy. ```bash cd <path_to_your_extension> ${ORBIT_PATH}/orbit.sh -p scripts/rsl_rl/train.py --task Template-Velocity-Flat-Anymal-D-v0 --num_envs 4096 --headless ``` Play the trained policy. ```bash ${ORBIT_PATH}/orbit.sh -p scripts/rsl_rl/play.py --task Template-Velocity-Flat-Anymal-D-Play-v0 --num_envs 16 ``` ### Omniverse Extension We provide an example UI extension that will load upon enabling your extension defined in `orbit/ext_template/ui_extension_example.py`. For more information on UI extensions, enable and check out the source code of the `omni.isaac.ui_template` extension and refer to the introduction on [Isaac Sim Workflows 1.2.3. GUI](https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html#gui). ## Pre-Commit Pre-committing involves using a framework to automate the process of enforcing code quality standards before code is actually committed to a version control system, like Git. This process involves setting up hooks that run automated checks, such as code formatting, linting (checking for programming errors, bugs, stylistic errors, and suspicious constructs), and running tests. If these checks pass, the commit is allowed; if not, the commit is blocked until the issues are resolved. This ensures that all code committed to the repository adheres to the defined quality standards, leading to a cleaner, more maintainable codebase. To do so, we use the [pre-commit](https://pre-commit.com/) module. Install the module using: ```bash pip install pre-commit ``` Run the pre-commit with: ```bash pre-commit run --all-files ``` ## Finalize You are all set and no longer need the template instructions - The `orbit/ext_template` and `scripts/rsl_rl` directories act as a reference template for your convenience. Delete them if no longer required. - When ready, use this `README.md` as a template and customize where appropriate. ## Docker / Cluster We are currently working on a docker and cluster setup for this template. In the meanwhile, please refer to the current setup provided in the Orbit [documentation](https://isaac-orbit.github.io/orbit/source/deployment/index.html). ## Troubleshooting ### Docker Container When running within a docker container, the following error has been encountered: `ModuleNotFoundError: No module named 'orbit'`. To mitigate, please comment out the docker specific environment definitions in `.vscode/launch.json` and run the following: ```bash echo -e "\nexport PYTHONPATH=\$PYTHONPATH:/workspace/orbit.<your_extension_name>" >> ~/.bashrc source ~/.bashrc ``` ## Bugs & Feature Requests Please report bugs and request features using the [Issue Tracker](https://github.com/isaac-orbit/orbit.ext_template/issues).
9,931
Markdown
46.295238
724
0.760145
levi-kennedy/orbit.vlmrew/scripts/rsl_rl/play.py
"""Script to play a checkpoint if an RL agent from RSL-RL.""" """Launch Isaac Sim Simulator first.""" import argparse from omni.isaac.orbit.app import AppLauncher # local imports import cli_args # isort: skip # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import os import torch from rsl_rl.runners import OnPolicyRunner import omni.isaac.orbit_tasks # noqa: F401 from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import ( RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper, export_policy_as_onnx, ) # Import extensions to set up environment tasks import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name> def main(): """Play with RSL-RL agent.""" # parse configuration env_cfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs) agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli) # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg) # wrap around environment for rsl-rl env = RslRlVecEnvWrapper(env) # specify directory for logging experiments log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Loading experiment from directory: {log_root_path}") resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # load previously trained model ppo_runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) ppo_runner.load(resume_path) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # obtain the trained policy for inference policy = ppo_runner.get_inference_policy(device=env.unwrapped.device) # export policy to onnx export_model_dir = os.path.join(os.path.dirname(resume_path), "exported") export_policy_as_onnx(ppo_runner.alg.actor_critic, export_model_dir, filename="policy.onnx") # reset environment obs, _ = env.get_observations() # simulate environment while simulation_app.is_running(): # run everything in inference mode with torch.inference_mode(): # agent stepping actions = policy(obs) # env stepping obs, _, _, _ = env.step(actions) # close the simulator env.close() if __name__ == "__main__": # run the main execution main() # close sim app simulation_app.close()
3,360
Python
32.949495
101
0.704762
levi-kennedy/orbit.vlmrew/scripts/rsl_rl/cli_args.py
from __future__ import annotations import argparse from typing import TYPE_CHECKING if TYPE_CHECKING: from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlOnPolicyRunnerCfg def add_rsl_rl_args(parser: argparse.ArgumentParser): """Add RSL-RL arguments to the parser. Args: parser: The parser to add the arguments to. """ # create a new argument group arg_group = parser.add_argument_group("rsl_rl", description="Arguments for RSL-RL agent.") # -- experiment arguments arg_group.add_argument( "--experiment_name", type=str, default=None, help="Name of the experiment folder where logs will be stored." ) arg_group.add_argument("--run_name", type=str, default=None, help="Run name suffix to the log directory.") # -- load arguments arg_group.add_argument("--resume", type=bool, default=None, help="Whether to resume from a checkpoint.") arg_group.add_argument("--load_run", type=str, default=None, help="Name of the run folder to resume from.") arg_group.add_argument("--checkpoint", type=str, default=None, help="Checkpoint file to resume from.") # -- logger arguments arg_group.add_argument( "--logger", type=str, default=None, choices={"wandb", "tensorboard", "neptune"}, help="Logger module to use." ) arg_group.add_argument( "--log_project_name", type=str, default=None, help="Name of the logging project when using wandb or neptune." ) def parse_rsl_rl_cfg(task_name: str, args_cli: argparse.Namespace) -> RslRlOnPolicyRunnerCfg: """Parse configuration for RSL-RL agent based on inputs. Args: task_name: The name of the environment. args_cli: The command line arguments. Returns: The parsed configuration for RSL-RL agent based on inputs. """ from omni.isaac.orbit_tasks.utils.parse_cfg import load_cfg_from_registry # load the default configuration rslrl_cfg: RslRlOnPolicyRunnerCfg = load_cfg_from_registry(task_name, "rsl_rl_cfg_entry_point") # override the default configuration with CLI arguments if args_cli.seed is not None: rslrl_cfg.seed = args_cli.seed if args_cli.resume is not None: rslrl_cfg.resume = args_cli.resume if args_cli.load_run is not None: rslrl_cfg.load_run = args_cli.load_run if args_cli.checkpoint is not None: rslrl_cfg.load_checkpoint = args_cli.checkpoint if args_cli.run_name is not None: rslrl_cfg.run_name = args_cli.run_name if args_cli.logger is not None: rslrl_cfg.logger = args_cli.logger # set the project name for wandb and neptune if rslrl_cfg.logger in {"wandb", "neptune"} and args_cli.log_project_name: rslrl_cfg.wandb_project = args_cli.log_project_name rslrl_cfg.neptune_project = args_cli.log_project_name return rslrl_cfg
2,858
Python
39.842857
117
0.686494
levi-kennedy/orbit.vlmrew/scripts/rsl_rl/train.py
"""Script to train RL agent with RSL-RL.""" """Launch Isaac Sim Simulator first.""" import argparse import os from omni.isaac.orbit.app import AppLauncher # local imports import cli_args # isort: skip # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import os import torch from datetime import datetime from rsl_rl.runners import OnPolicyRunner import omni.isaac.orbit_tasks # noqa: F401 from omni.isaac.orbit.envs import RLTaskEnvCfg from omni.isaac.orbit.utils.dict import print_dict from omni.isaac.orbit.utils.io import dump_pickle, dump_yaml from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper # Import extensions to set up environment tasks import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name> torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = False def main(): """Train with RSL-RL agent.""" # parse configuration env_cfg: RLTaskEnvCfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs) agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli) # specify directory for logging experiments log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Logging experiment in directory: {log_root_path}") # specify directory for logging runs: {time-stamp}_{run_name} log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if agent_cfg.run_name: log_dir += f"_{agent_cfg.run_name}" log_dir = os.path.join(log_root_path, log_dir) # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) # wrap for video recording if args_cli.video: video_kwargs = { "video_folder": os.path.join(log_dir, "videos"), "step_trigger": lambda step: step % args_cli.video_interval == 0, "video_length": args_cli.video_length, "disable_logger": True, } print("[INFO] Recording videos during training.") print_dict(video_kwargs, nesting=4) env = gym.wrappers.RecordVideo(env, **video_kwargs) # wrap around environment for rsl-rl env = RslRlVecEnvWrapper(env) # create runner from rsl-rl runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device) # write git state to logs runner.add_git_repo_to_log(__file__) # save resume path before creating a new log_dir if agent_cfg.resume: # get path to previous checkpoint resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # load previously trained model runner.load(resume_path) # set seed of the environment env.seed(agent_cfg.seed) # dump the configuration into log-directory dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg) dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg) dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg) dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg) # run training runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True) # close the simulator env.close() if __name__ == "__main__": # run the main execution main() # close sim app simulation_app.close()
4,801
Python
38.360655
117
0.70277
levi-kennedy/orbit.vlmrew/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.0" # Description category = "orbit" readme = "README.md" # TODO: Change your package specifications # ----------------------------------------------------------------- title = "Extension Template" author = "ORBIT Project Developers" maintainer = "Nico Burger" maintainer_email = "[email protected]" description="Extension Template for Orbit" repository = "https://github.com/isaac-orbit/orbit.ext_template.git" keywords = ["extension", "template", "orbit"] # ----------------------------------------------------------------- [dependencies] "omni.isaac.orbit" = {} "omni.isaac.orbit_assets" = {} "omni.isaac.orbit_tasks" = {} # NOTE: Add additional dependencies here [[python.module]] # TODO: Change your package name # ----------------------------------------------------------------- name = "orbit.ext_template" # -----------------------------------------------------------------
972
TOML
29.406249
68
0.52572
levi-kennedy/orbit.vlmrew/orbit/ext_template/__init__.py
""" Python module serving as a project/extension template. """ # Register Gym environments. from .tasks import * # Register UI extensions. from .ui_extension_example import *
177
Python
16.799998
54
0.745763
levi-kennedy/orbit.vlmrew/orbit/ext_template/ui_extension_example.py
import omni.ext import omni.ui as ui # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print("[orbit.ext_template] some_public_function was called with x: ", x) return x**x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class ExampleExtension(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("[orbit.ext_template] startup") self._count = 0 self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_click(): self._count += 1 label.text = f"count: {self._count}" def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Add", clicked_fn=on_click) ui.Button("Reset", clicked_fn=on_reset) def on_shutdown(self): print("[orbit.ext_template] shutdown")
1,527
Python
34.534883
119
0.599214
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/__init__.py
"""Package containing task implementations for various robotic environments.""" import os import toml # Conveniences to other module directories via relative paths ORBIT_TASKS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../")) """Path to the extension source directory.""" ORBIT_TASKS_METADATA = toml.load(os.path.join(ORBIT_TASKS_EXT_DIR, "config", "extension.toml")) """Extension metadata dictionary parsed from the extension.toml file.""" # Configure the module-level variables __version__ = ORBIT_TASKS_METADATA["package"]["version"] ## # Register Gym environments. ## from omni.isaac.orbit_tasks.utils import import_packages # The blacklist is used to prevent importing configs from sub-packages _BLACKLIST_PKGS = ["utils"] # Import all configs in this package import_packages(__name__, _BLACKLIST_PKGS)
845
Python
31.53846
95
0.745562
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/__init__.py
"""Locomotion environments for legged robots.""" from .velocity import * # noqa
82
Python
19.749995
48
0.719512
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/velocity_env_cfg.py
from __future__ import annotations import math from dataclasses import MISSING import omni.isaac.orbit.sim as sim_utils from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg from omni.isaac.orbit.envs import RLTaskEnvCfg from omni.isaac.orbit.managers import CurriculumTermCfg as CurrTerm from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm from omni.isaac.orbit.managers import RandomizationTermCfg as RandTerm from omni.isaac.orbit.managers import RewardTermCfg as RewTerm from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm from omni.isaac.orbit.scene import InteractiveSceneCfg from omni.isaac.orbit.sensors import ContactSensorCfg, RayCasterCfg, patterns from omni.isaac.orbit.terrains import TerrainImporterCfg from omni.isaac.orbit.utils import configclass from omni.isaac.orbit.utils.noise import AdditiveUniformNoiseCfg as Unoise import orbit.ext_template.tasks.locomotion.velocity.mdp as mdp ## # Pre-defined configs ## from omni.isaac.orbit.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip ## # Scene definition ## @configclass class MySceneCfg(InteractiveSceneCfg): """Configuration for the terrain scene with a legged robot.""" # ground terrain terrain = TerrainImporterCfg( prim_path="/World/ground", terrain_type="generator", terrain_generator=ROUGH_TERRAINS_CFG, max_init_terrain_level=5, collision_group=-1, physics_material=sim_utils.RigidBodyMaterialCfg( friction_combine_mode="multiply", restitution_combine_mode="multiply", static_friction=1.0, dynamic_friction=1.0, ), visual_material=sim_utils.MdlFileCfg( mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl", project_uvw=True, ), debug_vis=False, ) # robots robot: ArticulationCfg = MISSING # sensors height_scanner = RayCasterCfg( prim_path="{ENV_REGEX_NS}/Robot/base", offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)), attach_yaw_only=True, pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]), debug_vis=False, mesh_prim_paths=["/World/ground"], ) contact_forces = ContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True) # lights light = AssetBaseCfg( prim_path="/World/light", spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), ) sky_light = AssetBaseCfg( prim_path="/World/skyLight", spawn=sim_utils.DomeLightCfg(color=(0.13, 0.13, 0.13), intensity=1000.0), ) ## # MDP settings ## @configclass class CommandsCfg: """Command specifications for the MDP.""" base_velocity = mdp.UniformVelocityCommandCfg( asset_name="robot", resampling_time_range=(10.0, 10.0), rel_standing_envs=0.02, rel_heading_envs=1.0, heading_command=True, heading_control_stiffness=0.5, debug_vis=True, ranges=mdp.UniformVelocityCommandCfg.Ranges( lin_vel_x=(-1.0, 1.0), lin_vel_y=(-1.0, 1.0), ang_vel_z=(-1.0, 1.0), heading=(-math.pi, math.pi) ), ) @configclass class ActionsCfg: """Action specifications for the MDP.""" joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True) @configclass class ObservationsCfg: """Observation specifications for the MDP.""" @configclass class PolicyCfg(ObsGroup): """Observations for policy group.""" # observation terms (order preserved) base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.1, n_max=0.1)) base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.2, n_max=0.2)) projected_gravity = ObsTerm( func=mdp.projected_gravity, noise=Unoise(n_min=-0.05, n_max=0.05), ) velocity_commands = ObsTerm(func=mdp.generated_commands, params={"command_name": "base_velocity"}) joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5)) actions = ObsTerm(func=mdp.last_action) height_scan = ObsTerm( func=mdp.height_scan, params={"sensor_cfg": SceneEntityCfg("height_scanner")}, noise=Unoise(n_min=-0.1, n_max=0.1), clip=(-1.0, 1.0), ) def __post_init__(self): self.enable_corruption = True self.concatenate_terms = True # observation groups policy: PolicyCfg = PolicyCfg() @configclass class RandomizationCfg: """Configuration for randomization.""" # startup physics_material = RandTerm( func=mdp.randomize_rigid_body_material, mode="startup", params={ "asset_cfg": SceneEntityCfg("robot", body_names=".*"), "static_friction_range": (0.8, 0.8), "dynamic_friction_range": (0.6, 0.6), "restitution_range": (0.0, 0.0), "num_buckets": 64, }, ) add_base_mass = RandTerm( func=mdp.add_body_mass, mode="startup", params={"asset_cfg": SceneEntityCfg("robot", body_names="base"), "mass_range": (-5.0, 5.0)}, ) # reset base_external_force_torque = RandTerm( func=mdp.apply_external_force_torque, mode="reset", params={ "asset_cfg": SceneEntityCfg("robot", body_names="base"), "force_range": (0.0, 0.0), "torque_range": (-0.0, 0.0), }, ) reset_base = RandTerm( func=mdp.reset_root_state_uniform, mode="reset", params={ "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, "velocity_range": { "x": (-0.5, 0.5), "y": (-0.5, 0.5), "z": (-0.5, 0.5), "roll": (-0.5, 0.5), "pitch": (-0.5, 0.5), "yaw": (-0.5, 0.5), }, }, ) reset_robot_joints = RandTerm( func=mdp.reset_joints_by_scale, mode="reset", params={ "position_range": (0.5, 1.5), "velocity_range": (0.0, 0.0), }, ) # interval push_robot = RandTerm( func=mdp.push_by_setting_velocity, mode="interval", interval_range_s=(10.0, 15.0), params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}}, ) @configclass class RewardsCfg: """Reward terms for the MDP.""" # -- task track_lin_vel_xy_exp = RewTerm( func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) track_ang_vel_z_exp = RewTerm( func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) # -- penalties lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0) ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05) dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5) dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7) action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01) feet_air_time = RewTerm( func=mdp.feet_air_time, weight=0.125, params={ "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"), "command_name": "base_velocity", "threshold": 0.5, }, ) undesired_contacts = RewTerm( func=mdp.undesired_contacts, weight=-1.0, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0}, ) # -- optional penalties flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0) dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0) @configclass class TerminationsCfg: """Termination terms for the MDP.""" time_out = DoneTerm(func=mdp.time_out, time_out=True) base_contact = DoneTerm( func=mdp.illegal_contact, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0}, ) @configclass class CurriculumCfg: """Curriculum terms for the MDP.""" terrain_levels = CurrTerm(func=mdp.terrain_levels_vel) ## # Environment configuration ## @configclass class LocomotionVelocityRoughEnvCfg(RLTaskEnvCfg): """Configuration for the locomotion velocity-tracking environment.""" # Scene settings scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5) # Basic settings observations: ObservationsCfg = ObservationsCfg() actions: ActionsCfg = ActionsCfg() commands: CommandsCfg = CommandsCfg() # MDP settings rewards: RewardsCfg = RewardsCfg() terminations: TerminationsCfg = TerminationsCfg() randomization: RandomizationCfg = RandomizationCfg() curriculum: CurriculumCfg = CurriculumCfg() def __post_init__(self): """Post initialization.""" # general settings self.decimation = 4 self.episode_length_s = 20.0 # simulation settings self.sim.dt = 0.005 self.sim.disable_contact_processing = True self.sim.physics_material = self.scene.terrain.physics_material # update sensor update periods # we tick all the sensors based on the smallest update period (physics update period) if self.scene.height_scanner is not None: self.scene.height_scanner.update_period = self.decimation * self.sim.dt if self.scene.contact_forces is not None: self.scene.contact_forces.update_period = self.sim.dt # check if terrain levels curriculum is enabled - if so, enable curriculum for terrain generator # this generates terrains with increasing difficulty and is useful for training if getattr(self.curriculum, "terrain_levels", None) is not None: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = True else: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = False
10,526
Python
32.740385
118
0.625214
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/__init__.py
"""Locomotion environments with velocity-tracking commands. These environments are based on the `legged_gym` environments provided by Rudin et al. Reference: https://github.com/leggedrobotics/legged_gym """
213
Python
25.749997
86
0.779343
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/mdp/__init__.py
"""This sub-module contains the functions that are specific to the locomotion environments.""" from omni.isaac.orbit.envs.mdp import * # noqa: F401, F403 from .curriculums import * # noqa: F401, F403 from .rewards import * # noqa: F401, F403
247
Python
34.428567
94
0.728745
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/mdp/curriculums.py
"""Common functions that can be used to create curriculum for the learning environment. The functions can be passed to the :class:`omni.isaac.orbit.managers.CurriculumTermCfg` object to enable the curriculum introduced by the function. """ from __future__ import annotations import torch from collections.abc import Sequence from typing import TYPE_CHECKING from omni.isaac.orbit.assets import Articulation from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.terrains import TerrainImporter if TYPE_CHECKING: from omni.isaac.orbit.envs import RLTaskEnv def terrain_levels_vel( env: RLTaskEnv, env_ids: Sequence[int], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot") ) -> torch.Tensor: """Curriculum based on the distance the robot walked when commanded to move at a desired velocity. This term is used to increase the difficulty of the terrain when the robot walks far enough and decrease the difficulty when the robot walks less than half of the distance required by the commanded velocity. .. note:: It is only possible to use this term with the terrain type ``generator``. For further information on different terrain types, check the :class:`omni.isaac.orbit.terrains.TerrainImporter` class. Returns: The mean terrain level for the given environment ids. """ # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] terrain: TerrainImporter = env.scene.terrain command = env.command_manager.get_command("base_velocity") # compute the distance the robot walked distance = torch.norm(asset.data.root_pos_w[env_ids, :2] - env.scene.env_origins[env_ids, :2], dim=1) # robots that walked far enough progress to harder terrains move_up = distance > terrain.cfg.terrain_generator.size[0] / 2 # robots that walked less than half of their required distance go to simpler terrains move_down = distance < torch.norm(command[env_ids, :2], dim=1) * env.max_episode_length_s * 0.5 move_down *= ~move_up # update terrain levels terrain.update_env_origins(env_ids, move_up, move_down) # return the mean terrain level return torch.mean(terrain.terrain_levels.float())
2,253
Python
43.196078
112
0.742565
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/mdp/rewards.py
from __future__ import annotations import torch from typing import TYPE_CHECKING from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.sensors import ContactSensor if TYPE_CHECKING: from omni.isaac.orbit.envs import RLTaskEnv def feet_air_time(env: RLTaskEnv, command_name: str, sensor_cfg: SceneEntityCfg, threshold: float) -> torch.Tensor: """Reward long steps taken by the feet using L2-kernel. This function rewards the agent for taking steps that are longer than a threshold. This helps ensure that the robot lifts its feet off the ground and takes steps. The reward is computed as the sum of the time for which the feet are in the air. If the commands are small (i.e. the agent is not supposed to take a step), then the reward is zero. """ # extract the used quantities (to enable type-hinting) contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] # compute the reward first_contact = contact_sensor.compute_first_contact(env.step_dt)[:, sensor_cfg.body_ids] last_air_time = contact_sensor.data.last_air_time[:, sensor_cfg.body_ids] reward = torch.sum((last_air_time - threshold) * first_contact, dim=1) # no reward for zero command reward *= torch.norm(env.command_manager.get_command(command_name)[:, :2], dim=1) > 0.1 return reward def feet_air_time_positive_biped(env, command_name: str, threshold: float, sensor_cfg: SceneEntityCfg) -> torch.Tensor: """Reward long steps taken by the feet for bipeds. This function rewards the agent for taking steps up to a specified threshold and also keep one foot at a time in the air. If the commands are small (i.e. the agent is not supposed to take a step), then the reward is zero. """ contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] # compute the reward air_time = contact_sensor.data.current_air_time[:, sensor_cfg.body_ids] contact_time = contact_sensor.data.current_contact_time[:, sensor_cfg.body_ids] in_contact = contact_time > 0.0 in_mode_time = torch.where(in_contact, contact_time, air_time) single_stance = torch.sum(in_contact.int(), dim=1) == 1 reward = torch.min(torch.where(single_stance.unsqueeze(-1), in_mode_time, 0.0), dim=1)[0] reward = torch.clamp(reward, max=threshold) # no reward for zero command reward *= torch.norm(env.command_manager.get_command(command_name)[:, :2], dim=1) > 0.1 return reward
2,472
Python
45.660376
119
0.716019
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/config/__init__.py
"""Configurations for velocity-based locomotion environments.""" # We leave this file empty since we don't want to expose any configs in this package directly. # We still need this file to import the "config" module in the parent package.
240
Python
47.199991
94
0.775
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/rough_env_cfg.py
from omni.isaac.orbit.utils import configclass from orbit.ext_template.tasks.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg ## # Pre-defined configs ## from omni.isaac.orbit_assets.anymal import ANYMAL_D_CFG # isort: skip @configclass class AnymalDRoughEnvCfg(LocomotionVelocityRoughEnvCfg): def __post_init__(self): # post init of parent super().__post_init__() # switch robot to anymal-d self.scene.robot = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") @configclass class AnymalDRoughEnvCfg_PLAY(AnymalDRoughEnvCfg): def __post_init__(self): # post init of parent super().__post_init__() # make a smaller scene for play self.scene.num_envs = 50 self.scene.env_spacing = 2.5 # spawn the robot randomly in the grid (instead of their terrain levels) self.scene.terrain.max_init_terrain_level = None # reduce the number of terrains to save memory if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.num_rows = 5 self.scene.terrain.terrain_generator.num_cols = 5 self.scene.terrain.terrain_generator.curriculum = False # disable randomization for play self.observations.policy.enable_corruption = False # remove random pushing self.randomization.base_external_force_torque = None self.randomization.push_robot = None
1,485
Python
34.380952
103
0.682828
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/flat_env_cfg.py
from omni.isaac.orbit.utils import configclass from .rough_env_cfg import AnymalDRoughEnvCfg @configclass class AnymalDFlatEnvCfg(AnymalDRoughEnvCfg): def __post_init__(self): # post init of parent super().__post_init__() # override rewards self.rewards.flat_orientation_l2.weight = -5.0 self.rewards.dof_torques_l2.weight = -2.5e-5 self.rewards.feet_air_time.weight = 0.5 # change terrain to flat self.scene.terrain.terrain_type = "plane" self.scene.terrain.terrain_generator = None # no height scan self.scene.height_scanner = None self.observations.policy.height_scan = None # no terrain curriculum self.curriculum.terrain_levels = None class AnymalDFlatEnvCfg_PLAY(AnymalDFlatEnvCfg): def __post_init__(self) -> None: # post init of parent super().__post_init__() # make a smaller scene for play self.scene.num_envs = 50 self.scene.env_spacing = 2.5 # disable randomization for play self.observations.policy.enable_corruption = False # remove random pushing self.randomization.base_external_force_torque = None self.randomization.push_robot = None
1,259
Python
31.307692
60
0.648133
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/__init__.py
import gymnasium as gym from . import agents, flat_env_cfg, rough_env_cfg ## # Register Gym environments. ## gym.register( id="Template-Velocity-Flat-Anymal-D-v0", entry_point="omni.isaac.orbit.envs:RLTaskEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": flat_env_cfg.AnymalDFlatEnvCfg, "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDFlatPPORunnerCfg, }, ) gym.register( id="Template-Velocity-Flat-Anymal-D-Play-v0", entry_point="omni.isaac.orbit.envs:RLTaskEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": flat_env_cfg.AnymalDFlatEnvCfg_PLAY, "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDFlatPPORunnerCfg, }, ) gym.register( id="Template-Velocity-Rough-Anymal-D-v0", entry_point="omni.isaac.orbit.envs:RLTaskEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": rough_env_cfg.AnymalDRoughEnvCfg, "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDRoughPPORunnerCfg, }, ) gym.register( id="Template-Velocity-Rough-Anymal-D-Play-v0", entry_point="omni.isaac.orbit.envs:RLTaskEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": rough_env_cfg.AnymalDRoughEnvCfg_PLAY, "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDRoughPPORunnerCfg, }, )
1,351
Python
27.166666
77
0.680977
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/agents/rsl_rl_cfg.py
from omni.isaac.orbit.utils import configclass from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import ( RslRlOnPolicyRunnerCfg, RslRlPpoActorCriticCfg, RslRlPpoAlgorithmCfg, ) @configclass class AnymalDRoughPPORunnerCfg(RslRlOnPolicyRunnerCfg): num_steps_per_env = 24 max_iterations = 1500 save_interval = 50 experiment_name = "anymal_d_rough" empirical_normalization = False policy = RslRlPpoActorCriticCfg( init_noise_std=1.0, actor_hidden_dims=[512, 256, 128], critic_hidden_dims=[512, 256, 128], activation="elu", ) algorithm = RslRlPpoAlgorithmCfg( value_loss_coef=1.0, use_clipped_value_loss=True, clip_param=0.2, entropy_coef=0.005, num_learning_epochs=5, num_mini_batches=4, learning_rate=1.0e-3, schedule="adaptive", gamma=0.99, lam=0.95, desired_kl=0.01, max_grad_norm=1.0, ) @configclass class AnymalDFlatPPORunnerCfg(AnymalDRoughPPORunnerCfg): def __post_init__(self): super().__post_init__() self.max_iterations = 300 self.experiment_name = "anymal_d_flat" self.policy.actor_hidden_dims = [128, 128, 128] self.policy.critic_hidden_dims = [128, 128, 128]
1,294
Python
26.553191
58
0.636012
levi-kennedy/orbit.vlmrew/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/agents/__init__.py
from . import rsl_rl_cfg # noqa: F401, F403
45
Python
21.999989
44
0.666667
levi-kennedy/orbit.vlmrew/docs/CHANGELOG.rst
Changelog --------- 0.1.0 (2024-01-29) ~~~~~~~~~~~~~~~~~~ Added ^^^^^ * Created an initial template for building an extension or project based on Orbit
155
reStructuredText
13.181817
81
0.593548
Innoactive/Innoactive-Portal-Omniverse-Extension/README.md
# Innoactive Portal Omniverse Extension This extension for NVIDIA Omniverse allows you to create a sharing link to Innoactive Portal that will allow users to launch the USD file with Omniverse Enterprise in the cloud and stream it into their browser and/or Standalone VR headset. ## How it works: 1. Install the extension 2. Copy the sharing link and sent it to the user 3. User clicks the sharing link and can use USD file with Omniverse Enterprise on Innoactive Portal cloud. ## Benefits: - Users can contribute and review USD files without need for a own workstation - XR cloud streaming supported: stream not only to the browser but even to a Standalone VR headset - Compliant with your IT: Both SaaS and Self-hosted options available ![Innoactive Omniverse Extension](https://github.com/Innoactive/Portal-Omniverse-Extension/blob/master/exts/innoactive.omniverse/data/preview_readme.png?raw=true) ## Requirements: - Innoactive Portal Account (get one at https://innoactive.io/) - NVIDIA Omniverse Enterprise license - USD file needs to be hosted on your Nucleus Server - Users need to have access permissions to the USD file on the Nucleus Server - Users need to have a Innoactive Portal user account and access permissions to the Omniverse runtime you want to use ## Installation: 1. In Omniverse, go to "Window / Extensions / Options / Settings" 2. Add this to the Extension Search Paths: git://github.com/Innoactive/Innoactive-Portal-Omniverse-Extension?branch=main&dir=exts 3. Search for "Innoactive" in "Third Party" and enable the Innoactive extension (innoactive.omniverse) 4. Enable "autoload" if desired ## Usage: 1. Load a USD file from Nucleus Server 2. Open Innoactive Extension 3. Click "From Stage" to load the current USD URL 2. Select OV runtime to use for the stream 3. Select streaming mode: browser, VR (CloudXR), local (no streaming) 4. Configure Base Url to match Innoactive Portal cloud domain 5. Click "Test" to start a cloud streaming session yourself 6. Click "Copy" to copy the sharing URL to the clipboard. 7. Send the sharing link to the user you want to view the USD file via cloud streaming Hints: - Ensure that the user has a Innoactive Portal account (Click "Invite user" button if needed) - Ensure that the user has access permissions for the selected Omniverse runtime Please contact [Innoactive Support](https://www.innoactive.io/support) for any questions
2,406
Markdown
51.326086
239
0.788861
Innoactive/Innoactive-Portal-Omniverse-Extension/tools/scripts/link_app.py
import argparse import json import os import sys import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,814
Python
32.117647
133
0.562189
Innoactive/Innoactive-Portal-Omniverse-Extension/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
Innoactive/Innoactive-Portal-Omniverse-Extension/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 shutil import sys import tempfile import zipfile __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,844
Python
33.166666
108
0.703362
Innoactive/Innoactive-Portal-Omniverse-Extension/exts/innoactive.omniverse/innoactive/omniverse/extension.py
import omni.ext import omni.ui as ui from omni.ui import color as cl import omni.kit import carb import subprocess import os import webbrowser import threading from pxr import Usd import omni.usd from urllib.parse import quote LABEL_WIDTH = 120 HEIGHT = 24 VSPACING = 8 HSPACING = 5 MODES = ("browser", "VR", "local") MODES_TECHNICAL = ("cloud/browser", "cloud/standalone", "local/windows") APPS = ("Omniverse USD Explorer 2023.2.1", "Omniverse USD Composer 2023.2.3", "Omniverse USD Composer 2023.2.3 with Cesium Extension") APP_IDS = (4006, 3757, 4339) DEFAULT_BASE_URL = "https://[yourcompany].innoactive.io" DEFAULT_APP_ID = 3757 DEFAULT_MODE = "cloud/browser" settings = carb.settings.get_settings() # Public functions def get_sharing_link(): print("[innoactive.omniverse] get_sharing_link ") return self._sharing_url_model.as_string # 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 DeInnoactiveExtension(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 copy_to_clipboard(self, text): try: if os.name == 'nt': # For Windows subprocess.run('clip', universal_newlines=True, input=text, shell=True) elif os.name == 'posix': if os.system("which pbcopy") == 0: # macOS has pbcopy subprocess.run('pbcopy', universal_newlines=True, input=text) elif os.system("which xclip") == 0 or os.system("which xsel") == 0: # Linux has xclip or xsel subprocess.run('xclip -selection clipboard', universal_newlines=True, input=text, shell=True) else: print("Clipboard utilities pbcopy, xclip, or xsel not found.") return False else: print("Unsupported OS.") return False print("Text copied successfully.") return True except Exception as e: print(f"Failed to copy text: {e}") return False def set_notification(self, value, label): self._notification_label.text = "" self._notification_label.visible = False self._warning_label.text = "" self._warning_label.visible = False label.text = value label.visible = True def delete_notification(): label.text = "" label.visible = False timer = threading.Timer(5, delete_notification) timer.start() def is_sharable_usd(self, file_path): return file_path.startswith("omniverse://") or file_path.startswith("http://") or file_path.startswith("https://") # and not file_path.startswith("omniverse://localhost") def update_sharing_link(self): args = quote("--usd "+self._usd_url_model.as_string, safe='') self._sharing_url_model.as_string = self._base_url_model.as_string + "/apps/" + self._app_id_model.as_string + "/launch/" + self._mode_str_model.as_string + "?args=" + args self._sharing_url_model_label.text = self._sharing_url_model.as_string def on_value_changed(self, item_model): self.update_sharing_link() self.save_settings() def on_usd_value_changed(self, item_model): self.update_sharing_link() self.save_settings() def on_mode_changed(self, item_model, item): value_model = item_model.get_item_value_model(item) current_index = value_model.as_int self._mode_str_model.as_string = MODES_TECHNICAL[current_index] self.update_sharing_link() self.save_settings() def on_app_changed(self, item_model, item): value_model = item_model.get_item_value_model(item) current_index = value_model.as_int self._app_id_model.as_int = APP_IDS[current_index] self.update_sharing_link() self.save_settings() def save_settings(self): settings.set("/persistent/exts/de/innoactive/baseUrl", self._base_url_model.as_string) settings.set("/persistent/exts/de/innoactive/renderMode", self._mode_str_model.as_string) settings.set("/persistent/exts/de/innoactive/appId", self._app_id_model.as_int) def load_settings(self): try: self._base_url_model.as_string = settings.get("/persistent/exts/de/innoactive/baseUrl") self._mode_str_model.as_string = settings.get("/persistent/exts/de/innoactive/renderMode") self._app_id_model.as_int = settings.get("/persistent/exts/de/innoactive/appId") except Exception as e: self._base_url_model.as_string = DEFAULT_BASE_URL self._mode_str_model.as_string = DEFAULT_MODE self._app_id_model.as_int = DEFAULT_APP_ID def clear_usd(self): # Clear USD file from field self._usd_url_model.as_string = "" def set_stage_usd(self, at_autoload=False): # Implement logic to fetch the currently opened USD file path try: stage = omni.usd.get_context().get_stage() rootLayer = stage.GetRootLayer() file_path = rootLayer.realPath if rootLayer else "" if self.is_sharable_usd(file_path): self._usd_url_model.as_string = file_path else: if not at_autoload: self.set_notification("Please load a valid omniverse:// or http(s):// USD file URL to your stage.", self._warning_label) self._usd_url_model.as_string = "" except Exception as e: if not at_autoload: self.set_notification("Please load a valid omniverse:// or http(s):// USD file URL to your stage.", self._warning_label) self._usd_url_model.as_string = "" def validate_form(self): if not self._usd_url_model.as_string: self.set_notification("No USD file selected. Please select a valid omniverse:// or http(s):// USD file URL", self._warning_label) elif not self.is_sharable_usd(self._usd_url_model.as_string): self.set_notification("USD file is not shareable. Use omniverse:// or http(s):// format.", self._warning_label) elif self._base_url_model.as_string == DEFAULT_BASE_URL: self.set_notification("Configure Base URL to match your organization's Innoactive Portal domain name.", self._warning_label) else: return True return False def copy_url(self): # Copy the generated link to clipboard if self.validate_form(): self.copy_to_clipboard(self._sharing_url_model.as_string) self.set_notification("Sharing link copied to clipboard.", self._notification_label) def open_url(self): if self.validate_form(): webbrowser.open_new_tab(self._sharing_url_model.as_string) self.set_notification("Sharing link opened in browser.", self._notification_label) def open_invite_url(self): if self.validate_form(): invite_url = self._base_url_model.as_string + "/control-panel/v2/users" webbrowser.open_new_tab(invite_url) def on_shutdown(self): print("[innoactive.omniverse] shutdown") def on_startup(self, ext_id): print("Innoactive startup") manager = omni.kit.app.get_app().get_extension_manager() ext_path = manager.get_extension_path_by_module("innoactive.omniverse") self._window = ui.Window("Innoactive Portal", width=600, height=400) with self._window.frame: with ui.VStack(spacing=VSPACING, height=0): with ui.HStack(spacing=HSPACING): img = ui.Image(height=80, alignment=ui.Alignment.RIGHT) img.source_url = ext_path + "/data/innoactive_logo.png" with ui.HStack(spacing=HSPACING): ui.Label("USD file", name="usd_url", width=LABEL_WIDTH, height=HEIGHT, tooltip="Ensure the USD file is hosted on Nucleus and the user with whom you want to share access has permissions to access that file on Nucleus Server.") self._usd_url_model = ui.SimpleStringModel() self._usd_url_model.as_string = "" ui.StringField(model=self._usd_url_model, height=HEIGHT, word_wrap=True) self._usd_url_model_changed = self._usd_url_model.subscribe_value_changed_fn(self.on_usd_value_changed) ui.Button("From Stage", clicked_fn=self.set_stage_usd, width=90, height=HEIGHT, tooltip="Use the currently loaded USD file from Stage") with ui.HStack(spacing=HSPACING): ui.Label("Runtime", name="app", width=LABEL_WIDTH, height=HEIGHT, tooltip="Select the OV Kit runtime you want to use. You can upload your own runtimes, please contact Innoactive support.") self._app_id_model = ui.SimpleStringModel() try: self._app_id_model.as_int = settings.get("/persistent/exts/de/innoactive/appId") except Exception as e: self._app_id_model.as_int = DEFAULT_APP_ID self._app_model = ui.ComboBox(APP_IDS.index(self._app_id_model.as_int), *APPS).model self._app_model_changed = self._app_model.subscribe_item_changed_fn(self.on_app_changed) with ui.HStack(spacing=HSPACING): ui.Label("Streaming Mode", name="mode", width=LABEL_WIDTH, height=HEIGHT, tooltip="Select weather the link shall start a browser stream, VR stream or a locally rendered session") self._mode_str_model = ui.SimpleStringModel() try: self._mode_str_model.as_string = settings.get("/persistent/exts/de/innoactive/renderMode") except Exception as e: self._mode_str_model.as_string = DEFAULT_MODE print("renderMode: " + self._mode_str_model.as_string) self._mode_model = ui.ComboBox(MODES_TECHNICAL.index(self._mode_str_model.as_string), *MODES).model self._mode_model_changed = self._mode_model.subscribe_item_changed_fn(self.on_mode_changed) with ui.HStack(spacing=HSPACING): ui.Label("Base Url", name="base_url", width=LABEL_WIDTH, height=HEIGHT, tooltip="Set this to your match your Innoactive Portal cloud domain URL") self._base_url_model = ui.SimpleStringModel() try: self._base_url_model.as_string = settings.get("/persistent/exts/de/innoactive/baseUrl") except Exception as e: self._base_url_model.as_string = DEFAULT_BASE_URL ui.StringField(model=self._base_url_model, height=HEIGHT, word_wrap=True) self._base_url_model_changed = self._base_url_model.subscribe_value_changed_fn(self.on_value_changed) ui.Line() with ui.HStack(spacing=HSPACING): ui.Label("Sharing URL", name="sharing_url", width=LABEL_WIDTH, height=HEIGHT, tooltip="Copy and share this link with a user. You need to invite the user to Innoactive Portal as well.") self._sharing_url_model = ui.SimpleStringModel() self._sharing_url_model_label = ui.Label("", word_wrap=True, alignment=ui.Alignment.TOP) with ui.HStack(spacing=HSPACING): ui.Spacer( width=LABEL_WIDTH) self.button_copy = ui.Button("Copy", clicked_fn=self.copy_url, width=60, height=HEIGHT, tooltip="Copy the sharing link to the clipboard") self.button_test = ui.Button("Test", clicked_fn=self.open_url, width=60, height=HEIGHT, tooltip="Test the sharink link on your PC") self.button_invite = ui.Button("Invite user", clicked_fn=self.open_invite_url, width=90, height=HEIGHT, tooltip="Invite a user to Innoactive Portal") with ui.HStack(spacing=HSPACING, style={"Notification": {"color": cl("#76b900")}, "Error": {"color": cl("#d48f09")}}): ui.Spacer( width=LABEL_WIDTH) with ui.VStack(spacing=0, height=0): self._notification_label = ui.Label("", word_wrap=True, name="notification", height=HEIGHT, visible=False, style_type_name_override="Notification") self._warning_label = ui.Label("", word_wrap=True, name="notification", height=HEIGHT, visible=False, style_type_name_override="Error") self.load_settings() self.update_sharing_link() self.set_stage_usd(at_autoload=True)
13,222
Python
50.451362
245
0.608153
Innoactive/Innoactive-Portal-Omniverse-Extension/exts/innoactive.omniverse/innoactive/omniverse/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
Innoactive/Innoactive-Portal-Omniverse-Extension/exts/innoactive.omniverse/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.1" # Lists people or organizations that are considered the "authors" of the package. authors = ["Innoactive"] # The title and description fields are primarily for displaying extension info in UI title = "Innoactive" description="Innoactive Portal Omniverse Extension allows to create a sharing link to access a USD file using Innoactive Streaming platform without a Workstation." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "https://github.com/Innoactive/Innoactive-Portal-Omniverse-Extension/" # One of categories for UI. category = "Cloud" # Keywords for the extension keywords = ["kit", "innoactive", "portal", "cloudxr", "streaming"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import innoactive.omniverse". [[python.module]] name = "innoactive.omniverse" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,751
TOML
35.499999
163
0.754997
Innoactive/Innoactive-Portal-Omniverse-Extension/exts/innoactive.omniverse/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.1] - 2024-02-13 - Added support to select USD Composer with Cesium ## [1.0.0] - 2024-02-08 - Initial version of Innoactive Omniverse Extension
249
Markdown
19.833332
80
0.702811
Innoactive/Innoactive-Portal-Omniverse-Extension/exts/innoactive.omniverse/docs/README.md
# Innoactive Portal Omniverse Extension This extension for NVIDIA Omniverse allows you to create a sharing link to Innoactive Portal that will allow users to launch the USD file with Omniverse Enterprise in the cloud and stream it into their browser and/or Standalone VR headset. ## How it works: 1. Copy the sharing link and sent it to the user 2. User clicks the sharing link and can use USD file with Omniverse Enterprise on Innoactive Portal cloud. ## Benefits: - Users can contribute and review USD files without need for a own workstation - XR cloud streaming supported: stream not only to the browser but even to a Standalone VR headset - Compliant with your IT: Both SaaS and Self-hosted options available ## Requirements: - Innoactive Portal Account (get one at https://innoactive.io/) - NVIDIA Omniverse Enterprise license - USD file needs to be hosted on your Nucleus Server - Users need to have access permissions to the USD file on the Nucleus Server - Users need to have a Innoactive Portal user account and access permissions to the Omniverse runtime you want to use ## Usage: 1. Load a USD file from Nucleus Server 2. Open Innoactive Extension 3. Click "From Stage" to load the current USD URL 2. Select OV runtime to use for the stream 3. Select streaming mode: browser, VR (CloudXR), local (no streaming) 4. Configure Base Url to match Innoactive Portal cloud domain 5. Click "Test" to start a cloud streaming session yourself 6. Click "Copy" to copy the sharing URL to the clipboard. 7. Send the sharing link to the user you want to view the USD file via cloud streaming Hints: - Ensure that the user has a Innoactive Portal account (Click "Invite user" button if needed) - Ensure that the user has access permissions for the selected Omniverse runtime Please contact Innoactive Support for any questions
1,832
Markdown
47.236841
239
0.78821
jasonsaini/OmniverseCubeClickExtension/README.md
# 🌌 Omniverse Cube Click Extension ![image](https://github.com/jasonsaini/OmniverseCubeClickExtension/assets/69808698/fced4d28-4ce5-48d3-b3c6-9ced86cd1b03) ## 📖 Introduction Welcome to `OmniverseCubeSpawner`! This repository contains a tutorial-based NVIDIA Omniverse extension that allows users to spawn a 3D cube in the scene with a simple button click. Check out the tutorial I followed [here](https://www.youtube.com/watch?v=eGxV_PGNpOg&t=20s).
451
Markdown
55.499993
181
0.800443
jasonsaini/OmniverseCubeClickExtension/spawn_cube/README.md
# Extension Project Template This project was automatically generated. - `app` - It is a folder link to the location of your *Omniverse Kit* based app. - `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path). Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better. Look for "spawn.cube" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately. Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.: ``` > app\omni.code.bat --ext-folder exts --enable company.hello.world ``` # App Link Setup If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Sharing Your Extensions This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths. Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts` Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual. To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
2,034
Markdown
37.396226
258
0.756637
jasonsaini/OmniverseCubeClickExtension/spawn_cube/tools/scripts/link_app.py
import argparse import json import os import sys import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,814
Python
32.117647
133
0.562189
jasonsaini/OmniverseCubeClickExtension/spawn_cube/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
jasonsaini/OmniverseCubeClickExtension/spawn_cube/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 shutil import sys import tempfile import zipfile __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,844
Python
33.166666
108
0.703362
jasonsaini/OmniverseCubeClickExtension/spawn_cube/exts/spawn.cube/spawn/cube/extension.py
import omni.ext import omni.ui as ui # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print("[spawn.cube] some_public_function was called with x: ", x) return x ** x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class SpawnCubeExtension(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("[spawn.cube] spawn cube startup") self._count = 0 self._window = ui.Window("Spawn a cube", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("Cube Spawner") def on_click(): omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Cube", attributes={'size:':100, 'extent': [(-50,-50,-50), (50,50,50)]}) print("Cube spawned!") def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Spawn Cube", clicked_fn=on_click) #ui.Button("Reset", clicked_fn=on_reset) def on_shutdown(self): print("[spawn.cube] spawn cube shutdown")
1,661
Python
36.772726
158
0.608067