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
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/omni/sphereflake/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/omni/sphereflake/_widgets.py
from functools import partial from typing import List import omni.ui as ui from . import styles class CheckBoxGroupModel: def __init__(self, option_names:List): self.options = [] self.bool_models = [] self.subscriptions = [] self._single_callbacks = [] self._group_callbacks = [] for option in option_names: self.add_checkbox_option(option) def add_checkbox_option(self, option_name): self.options.append(option_name) bool_model = ui.SimpleBoolModel() next_index = len(self.bool_models) self.bool_models.append(bool_model) self.subscriptions.append(bool_model.subscribe_value_changed_fn(partial(self.on_model_value_changed, next_index))) return bool_model def subscribe_value_changed_fn(self, callback_fn): self._single_callbacks.append(callback_fn) def subscribe_group_changed_fn(self, callback_fn): self._group_callbacks.append(callback_fn) def on_model_value_changed(self, index:int, model:ui.SimpleBoolModel): for callback in self._single_callbacks: option = self.options[index] callback(option, model.as_bool) for callback in self._group_callbacks: checkbox_values = [] for name, bool_model in zip(self.options, self.bool_models): checkbox_values.append((name, bool_model.as_bool)) callback(checkbox_values) def get_bool_model(self, option_name): index = self.options.index(option_name) return self.bool_models[index] def get_checkbox_options(self): return self.options def destroy(self): self.subscriptions = None self._single_callbacks = None self._group_callbacks = None class CheckBoxGroup: def __init__(self, group_name:str, model:CheckBoxGroupModel): self.group_name = group_name self.model = model self._build_widget() def _build_widget(self): with ui.VStack(width=0, height=0, style=styles.checkbox_group_style): ui.Label(f"{self.group_name}:") for option in self.model.get_checkbox_options(): with ui.HStack(name="checkbox_row", width=0, height=0): ui.CheckBox(model=self.model.get_bool_model(option)) ui.Label(option, name="cb_label") def destroy(self): self.model.destroy() class BaseTab: def __init__(self, name): self.name = name def build_fn(self): """Builds the contents for the tab. You must implement this function with the UI construction code that you want for you tab. This is set to be called by a ui.Frame so it must have only a single top-level widget. """ raise NotImplementedError("You must implement Tab.build_fn") class TabGroup: def __init__(self, tabs: List[BaseTab]): self.frame = ui.Frame(build_fn=self._build_widget) if not tabs: raise ValueError("You must provide at least one BaseTab object.") self.tabs = tabs self.tab_containers = [] self.tab_headers = [] def _build_widget(self): with ui.ZStack(style=styles.tab_group_style): ui.Rectangle(style_type_name_override="TabGroupBorder") with ui.VStack(): ui.Spacer(height=1) with ui.ZStack(height=0, name="TabGroupHeader"): ui.Rectangle(name="TabGroupHeader") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(height=0, spacing=4): for x, tab in enumerate(self.tabs): tab_header = ui.ZStack(width=0, style=styles.tab_style) self.tab_headers.append(tab_header) with tab_header: rect = ui.Rectangle() rect.set_mouse_released_fn(partial(self._tab_clicked, x)) ui.Label(tab.name) with ui.ZStack(): for x, tab in enumerate(self.tabs): container_frame = ui.Frame(build_fn=tab.build_fn) self.tab_containers.append(container_frame) container_frame.visible = False # Initialize first tab self.select_tab(0) def select_tab(self, index: int): for x in range(len(self.tabs)): if x == index: self.tab_containers[x].visible = True self.tab_headers[x].selected = True else: self.tab_containers[x].visible = False self.tab_headers[x].selected = False def _tab_clicked(self, index, x, y, button, modifier): if button == 0: self.select_tab(index) def append_tab(self, tab: BaseTab): pass def destroy(self): self.frame.destroy()
5,092
Python
35.905797
122
0.5652
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/omni/sphereflake/ovut.py
import omni.kit.commands as okc import omni.usd import os import sys import math from pxr import Gf, Sdf, UsdShade from typing import Tuple, List import carb.settings _settings = None def _init_settings(): global _settings if _settings is None: _settings = carb.settings.get_settings() return _settings def get_setting(name, default, db=False): settings = _init_settings() key = f"/persistent/omni/sphereflake/{name}" val = settings.get(key) if db: oval = val if oval is None: oval = "None" if val is None: val = default if db: print(f"get_setting {name} {oval} {val}") return val def save_setting(name, value): settings = _init_settings() key = f"/persistent/omni/sphereflake/{name}" settings.set(key, value) def truncf(number, digits) -> float: # Improve accuracy with floating point operations, to avoid truncate(16.4, 2) = 16.39 or truncate(-1.13, 2) = -1.12 nbDecimals = len(str(number).split('.')[1]) if nbDecimals <= digits: return number stepper = 10.0 ** digits return math.trunc(stepper * number) / stepper def delete_if_exists(primpath: str) -> None: ctx = omni.usd.get_context() stage = ctx.get_stage() if stage.GetPrimAtPath(primpath): stage.RemovePrim(primpath) # okc.execute("DeletePrimsCommand", paths=[primpath]) def cross_product(v1: Gf.Vec3f, v2: Gf.Vec3f) -> Gf.Vec3f: x = v1[1] * v2[2] - v1[2] * v2[1] y = v1[2] * v2[0] - v1[0] * v2[2] z = v1[0] * v2[1] - v1[1] * v2[0] rv = Gf.Vec3f(x, y, z) return rv def write_out_path(fname: str = 'd:/nv/ov/path.txt') -> None: # Write out the path to a file path = os.environ["PATH"] with open(fname, "w") as f: npath = path.replace(";", "\n") f.write(npath) def write_out_syspath(fname: str = 'd:/nv/ov/syspath.txt', indent=False) -> None: # Write out the python syspath to a file # Indent should be True if to be used for the settings.json python.analsys.extraPaths setting pplist = sys.path with open(fname, 'w') as f: for line in pplist: nline = line.replace("\\", "/") if indent: nnline = f" \"{nline}\",\n" else: nnline = f"\"{nline}\",\n" f.write(nnline) def read_in_syspath(fname: str = 'd:/nv/ov/syspath.txt') -> None: # Read in the python path from a file with open(fname, 'r') as f: for line in f: nline = line.replace(',', '') nline = nline.replace('"', '') nline = nline.replace('"', '') nline = nline.replace('\n', '') nline = nline.replace(' ', '') sys.path.append(nline) class MatMan(): matlib = {} def __init__(self) -> None: self.CreateMaterials() pass def MakePreviewSurfaceTexMateral(self, matname: str, fname: str): # This is all materials matpath = "/World/Looks" mlname = f'{matpath}/boardMat_{fname.replace(".","_")}' stage = omni.usd.get_context().get_stage() material = UsdShade.Material.Define(stage, mlname) pbrShader = UsdShade.Shader.Define(stage, f'{mlname}/PBRShader') pbrShader.CreateIdAttr("UsdPreviewSurface") pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4) pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0) material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface") stReader = UsdShade.Shader.Define(stage, f'{matpath}/stReader') stReader.CreateIdAttr('UsdPrimvarReader_float2') diffuseTextureSampler = UsdShade.Shader.Define(stage, f'{matpath}/diffuseTexture') diffuseTextureSampler.CreateIdAttr('UsdUVTexture') ASSETS_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) # print(f"ASSETS_DIRECTORY {ASSETS_DIRECTORY}") texfile = f"{ASSETS_DIRECTORY}\\{fname}" # print(texfile) # print(os.path.exists(texfile)) diffuseTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(texfile) diffuseTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader.ConnectableAPI(), 'result') diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3) pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource( diffuseTextureSampler.ConnectableAPI(), 'rgb') stInput = material.CreateInput('frame:stPrimvarName', Sdf.ValueTypeNames.Token) stInput.Set('st') stReader.CreateInput('varname', Sdf.ValueTypeNames.Token).ConnectToSource(stInput) self.matlib[matname]["mat"] = material return material def SplitRgb(self, rgb: str) -> Tuple[float, float, float]: sar = rgb.split(",") r = float(sar[0]) g = float(sar[1]) b = float(sar[2]) return (r, g, b) def MakePreviewSurfaceMaterial(self, matname: str, rgb: str): mtl_path = Sdf.Path(f"/World/Looks/Presurf_{matname}") stage = omni.usd.get_context().get_stage() mtl = UsdShade.Material.Define(stage, mtl_path) shader = UsdShade.Shader.Define(stage, mtl_path.AppendPath("Shader")) shader.CreateIdAttr("UsdPreviewSurface") rgbtup = self.SplitRgb(rgb) shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(rgbtup) shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.5) shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0) mtl.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") # self.matlib[matname] = {"name": matname, "typ": "mtl", "mat": mtl} self.matlib[matname]["mat"] = mtl return mtl refCount: int = 0 fetchCount: int = 0 skipCount: int = 0 def CopyRemoteMaterial(self, matname, urlbranch, force=False): print(f"CopyRemoteMaterial matname:{matname} urlbranch:{urlbranch} force:{force}") stage = omni.usd.get_context().get_stage() baseurl = 'https://omniverse-content-production.s3.us-west-2.amazonaws.com' url = f'{baseurl}/Materials/{urlbranch}.mdl' mpath = f'/World/Looks/{matname}' action = "" # Note we should not execute the next command if the material already exists if force or not stage.GetPrimAtPath(mpath): okc.execute('CreateMdlMaterialPrimCommand', mtl_url=url, mtl_name=matname, mtl_path=mpath) action = "fetch" self.fetchCount += 1 else: action = "skip" self.skipCount += 1 mtl: UsdShade.Material = UsdShade.Material(stage.GetPrimAtPath(mpath)) print(f"CopyRemoteMaterial {mpath} mtl:{mtl} action:{action}") # self.matlib[matname] = {"name": matname, "typ": "rgb", "mat": mtl} self.matlib[matname]["mat"] = mtl return mtl def RealizeMaterial(self, matname: str): typ = self.matlib[matname]["typ"] spec = self.matlib[matname]["spec"] if typ == "mtl": self.CopyRemoteMaterial(matname, spec) elif typ == "tex": self.MakePreviewSurfaceTexMateral(matname, spec) else: self.MakePreviewSurfaceMaterial(matname, spec) self.matlib[matname]["realized"] = True def SetupMaterial(self, matname: str, typ: str, spec: str): # print(f"SetupMaterial {matname} {typ} {spec}") matpath = f"/World/Looks/{matname}" self.matlib[matname] = {"name": matname, "typ": typ, "mat": None, "path": matpath, "realized": False, "spec": spec} def CreateMaterials(self): self.SetupMaterial("red", "rgb", "1,0,0") self.SetupMaterial("green", "rgb", "0,1,0") self.SetupMaterial("blue", "rgb", "0,0,1") self.SetupMaterial("yellow", "rgb", "1,1,0") self.SetupMaterial("cyan", "rgb", "0,1,1") self.SetupMaterial("magenta", "rgb", "1,0,1") self.SetupMaterial("white", "rgb", "1,1,1") self.SetupMaterial("black", "rgb", "0,0,0") self.SetupMaterial("Blue_Glass", "mtl", "Base/Glass/Blue_Glass") self.SetupMaterial("Red_Glass", "mtl", "Base/Glass/Red_Glass") self.SetupMaterial("Green_Glass", "mtl", "Base/Glass/Green_Glass") self.SetupMaterial("Clear_Glass", "mtl", "Base/Glass/Clear_Glass") self.SetupMaterial("Mirror", "mtl", "Base/Glass/Mirror") self.SetupMaterial("sunset_texture", "tex", "sunset.png") def GetMaterialNames(self) -> List[str]: return list(self.matlib.keys()) def GetMaterial(self, key): self.refCount += 1 if key in self.matlib: if not self.matlib[key]["realized"]: self.RealizeMaterial(key) rv = self.matlib[key]["mat"] else: rv = None return rv
9,205
Python
37.041322
119
0.596306
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/omni/sphereflake/sfwindow.py
import carb.events import omni.ui as ui from omni.ui import color as clr import asyncio from ._widgets import TabGroup, BaseTab from .sphereflake import SphereMeshFactory, SphereFlakeFactory from .sfcontrols import SfControls from .ovut import get_setting, save_setting class SfcWindow(ui.Window): darkgreen = clr("#004000") darkblue = clr("#000040") darkred = clr("#400000") darkyellow = clr("#404000") darkpurple = clr("#400040") darkcyan = clr("#004040") marg = 2 # Status _statuslabel: ui.Label = None _memlabel: ui.Label = None # Sphereflake params prframe: ui.CollapsableFrame = None drframe: ui.CollapsableFrame = None docollapse_prframe = False docollapse_drframe = False _sf_depth_but: ui.Button = None _sf_spawn_but: ui.Button = None _sf_nlat_but: ui.Button = None _sf_nlng_but: ui.Button = None _sf_radratio_slider_model: ui.SimpleFloatModel = None _genmodebox: ui.ComboBox = None _genmodebox_model: ui.SimpleIntModel = None _genformbox: ui.ComboBox = None _genformbox_model: ui.SimpleIntModel = None # Material tab _sf_matbox: ui.ComboBox = None _sf_matbox_model: ui.SimpleIntModel = None _sf_alt_matbox: ui.ComboBox = None _sf_alt_matbox_model: ui.SimpleIntModel = None _bb_matbox: ui.ComboBox = None _bb_matbox_model: ui.SimpleIntModel = None _sf_floor_matbox: ui.ComboBox = None _sf_floor_matbox_model: ui.SimpleIntModel = None # Options writelog_checkbox: ui.CheckBox = None writelog_checkbox_model = None writelog_seriesname: ui.StringField = None writelog_seriesname_model = None # state sfc: SfControls smf: SphereMeshFactory sff: SphereFlakeFactory def __init__(self, *args, **kwargs): super().__init__(title="SphereFlake Controls", height=300, width=300, *args, **kwargs) print(f"SfcWindow.__init__ (trc)") self.sfc = kwargs["sfc"] self.sfc.sfw = self # intentionally circular self.smf = self.sfc.smf self.sff = self.sfc.sff self.LoadSettings() self.BuildControlModels() self.BuildWindow() self.sfc.LateInit() def BuildControlModels(self): # models for controls that are used in the logic need to be built outside the build_fn # since that will only be called when the tab is selected and displayed sfc = self.sfc sff = sfc.sff # sphereflake params self._sf_radratio_slider_model = ui.SimpleFloatModel(sff.p_radratio) idx = sff.GetGenModes().index(sff.p_genmode) self._genmodebox_model = ui.SimpleIntModel(idx) idx = sff.GetGenForms().index(sff.p_genform) self._genformbox_model = ui.SimpleIntModel(idx) # materials matlist = sfc._matkeys idx = matlist.index(sff.p_sf_matname) self._sf_matbox_model = ui.SimpleIntModel(idx) idx = matlist.index(sff.p_sf_alt_matname) self._sf_alt_matbox_model = ui.SimpleIntModel(idx) idx = matlist.index(sff.p_bb_matname) self._bb_matbox_model = ui.SimpleIntModel(idx) idx = matlist.index(sfc._current_floor_material_name) self._sf_floor_matbox_model = ui.SimpleIntModel(idx) # options self.writelog_checkbox_model = ui.SimpleBoolModel(sfc.p_writelog) self.writelog_seriesname_model = ui.SimpleStringModel(sfc.p_logseriesname) def BuildWindow(self): print("SfcWindow.BuildWindow (trc)") sfc = self.sfc with self.frame: with ui.VStack(): t1 = SfcTabMulti(self) t2 = SfcTabSphereFlake(self) t3 = SfcTabShapes(self) t4 = SfcTabMaterials(self) t5 = SfcTabOptions(self) self.tab_group = TabGroup([t1, t2, t3, t4, t5]) self._statuslabel = ui.Label("Status: Ready") self._memlabel = ui.Button("Memory tot/used/free", clicked_fn=sfc.UpdateGpuMemory) ui.Button("Clear Primitives", style={'background_color': self.darkyellow}, clicked_fn=lambda: sfc.on_click_clearprims()) def DockWindow(self, wintitle="Property"): print(f"Docking to {wintitle} (trc)") handle = ui._ui.Workspace.get_window(wintitle) self.dock_in(handle, ui._ui.DockPosition.SAME) self.deferred_dock_in(wintitle, ui._ui.DockPolicy.TARGET_WINDOW_IS_ACTIVE) def LoadSettings(self): # print("SfcWindow.LoadSettings") self.docollapse_prframe = get_setting("ui_pr_frame_collapsed", False) self.docollapse_drframe = get_setting("ui_dr_frame_collapsed", False) # print(f"docollapse_prframe: {self.docollapse_prframe} docollapse_drframe: {self.docollapse_drframe}") def SaveSettings(self): # print("SfcWindow.SaveSettings") if (self.prframe is not None): save_setting("ui_pr_frame_collapsed", self.prframe.collapsed) if (self.drframe is not None): save_setting("ui_dr_frame_collapsed", self.drframe.collapsed) # print(f"docollapse_prframe: {self.prframe.collapsed} docollapse_drframe: {self.drframe.collapsed}") class SfcTabMulti(BaseTab): sfw: SfcWindow sfc: SfControls def __init__(self, sfw: SfcWindow): super().__init__("Multi") self.sfw = sfw self.sfc = sfw.sfc # print(f"SfcTabMulti.init {type(sfc)}") def build_fn(self): print("SfcTabMulti.build_fn (trc)") sfw: SfcWindow = self.sfw sfc: SfControls = self.sfc sff: SphereFlakeFactory = self.sfw.sff # print(f"SfcTabMulti.build_fn {type(sfc)}") with ui.VStack(style={"margin": sfw.marg}): with ui.VStack(): with ui.HStack(): clkfn = lambda: asyncio.ensure_future(sfc.on_click_multi_sphereflake()) # noqa : E731 sfw._msf_spawn_but = ui.Button("Multi ShereFlake", style={'background_color': sfw.darkred}, clicked_fn=clkfn) with ui.VStack(width=200): clkfn = lambda x, y, b, m: sfc.on_click_sfx(x, y, b, m) # noqa : E731 sfw._nsf_x_but = ui.Button(f"SF x: {sff.p_nsfx}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) clkfn = lambda x, y, b, m: sfc.on_click_sfy(x, y, b, m) # noqa : E731 sfw._nsf_y_but = ui.Button(f"SF y: {sff.p_nsfy}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) clkfn = lambda x, y, b, m: sfc.on_click_sfz(x, y, b, m) # noqa : E731 sfw._nsf_z_but = ui.Button(f"SF z: {sff.p_nsfz}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) sfw._tog_bounds_but = ui.Button(f"Bounds:{sfc._bounds_visible}", style={'background_color': sfw.darkcyan}, clicked_fn=sfc.toggle_bounds) sfw.prframe = ui.CollapsableFrame("Partial Renders", collapsed=sfw.docollapse_prframe) with sfw.prframe: with ui.VStack(): sfw._partial_render_but = ui.Button(f"Partial Render {sff.p_partialRender}", style={'background_color': sfw.darkcyan}, clicked_fn=sfc.toggle_partial_render) with ui.HStack(): clkfn = lambda x, y, b, m: sfc.on_click_parital_sfsx(x, y, b, m) # noqa : E731 sfw._part_nsf_sx_but = ui.Button(f"SF partial sx: {sff.p_partial_ssfx}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) clkfn = lambda x, y, b, m: sfc.on_click_parital_sfsy(x, y, b, m) # noqa : E731 sfw._part_nsf_sy_but = ui.Button(f"SF partial sy: {sff.p_partial_ssfy}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) clkfn = lambda x, y, b, m: sfc.on_click_parital_sfsz(x, y, b, m) # noqa : E731 sfw._part_nsf_sz_but = ui.Button(f"SF partial sz: {sff.p_partial_ssfz}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) with ui.HStack(): clkfn = lambda x, y, b, m: sfc.on_click_parital_sfnx(x, y, b, m) # noqa : E731 sfw._part_nsf_nx_but = ui.Button(f"SF partial nx: {sff.p_partial_nsfx}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) clkfn = lambda x, y, b, m: sfc.on_click_parital_sfny(x, y, b, m) # noqa : E731 sfw._part_nsf_ny_but = ui.Button(f"SF partial ny: {sff.p_partial_nsfy}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) clkfn = lambda x, y, b, m: sfc.on_click_parital_sfnz(x, y, b, m) # noqa : E731 sfw._part_nsf_nz_but = ui.Button(f"SF partial nz: {sff.p_partial_nsfz}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) sfw.drframe = ui.CollapsableFrame("Distributed Renders", collapsed=sfw.docollapse_drframe) with sfw.drframe: with ui.VStack(): sfw._parallel_render_but = ui.Button(f"Distributed Render {sff.p_parallelRender}", style={'background_color': sfw.darkcyan}, clicked_fn=sfc.toggle_parallel_render) with ui.HStack(): clkfn = lambda x, y, b, m: sfc.on_click_parallel_nxbatch(x, y, b, m) # noqa : E731 sfw._parallel_nxbatch_but = ui.Button(f"SF batch x: {sff.p_parallel_nxbatch}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) clkfn = lambda x, y, b, m: sfc.on_click_parallel_nybatch(x, y, b, m) # noqa : E731 sfw._parallel_nybatch_but = ui.Button(f"SF batch y: {sff.p_parallel_nybatch}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) clkfn = lambda x, y, b, m: sfc.on_click_parallel_nzbatch(x, y, b, m) # noqa : E731 sfw._parallel_nzbatch_but = ui.Button(f"SF batch z: {sff.p_parallel_nzbatch}", style={'background_color': sfw.darkblue}, mouse_pressed_fn=clkfn) class SfcTabSphereFlake(BaseTab): sfc: SfControls = None def __init__(self, sfw: SfcWindow): super().__init__("SphereFlake") self.sfw = sfw self.sfc = sfw.sfc def build_fn(self): print("SfcTabSphereFlake.build_fn (trc)") sfw = self.sfw sfc = self.sfc sff = self.sfw.sff smf = self.sfw.smf # print(f"SfcTabMulti.build_fn sfc:{type(sfc)} ") with ui.VStack(style={"margin": sfw.marg}): with ui.VStack(): with ui.HStack(): sfw._sf_spawn_but = ui.Button("Spawn SphereFlake", style={'background_color': sfw.darkred}, clicked_fn=lambda: sfc.on_click_sphereflake()) with ui.VStack(width=200): sfw._sf_depth_but = ui.Button(f"Depth:{sff.p_depth}", style={'background_color': sfw.darkgreen}, mouse_pressed_fn= # noqa : E251 lambda x, y, b, m: sfc.on_click_sfdepth(x, y, b, m)) with ui.HStack(): ui.Label("Radius Ratio: ", style={'background_color': sfw.darkgreen}, width=50) sfw._sf_radratio_slider = ui.FloatSlider(model=sfw._sf_radratio_slider_model, min=0.0, max=1.0, step=0.01, style={'background_color': sfw.darkblue}).model # SF Gen Mode Combo Box with ui.HStack(): ui.Label("Gen Mode:") model = sfw._genmodebox_model idx = model.as_int sfw._genmodebox_model = ui.ComboBox(idx, *sff.GetGenModes()).model.get_item_value_model() # SF Form Combo Box with ui.HStack(): ui.Label("Gen Form1:") model = sfw._genformbox_model idx = model.as_int sfw._genformbox_model = ui.ComboBox(idx, *sff.GetGenForms()).model.get_item_value_model() with ui.VStack(): sfw._sf_nlat_but = ui.Button(f"Nlat:{smf.p_nlat}", style={'background_color': sfw.darkgreen}, mouse_pressed_fn= # noqa : E251 lambda x, y, b, m: sfc.on_click_nlat(x, y, b, m)) sfw._sf_nlng_but = ui.Button(f"Nlng:{smf.p_nlng}", style={'background_color': sfw.darkgreen}, mouse_pressed_fn= # noqa : E251 lambda x, y, b, m: sfc.on_click_nlng(x, y, b, m)) class SfcTabShapes(BaseTab): sfw: SfcWindow sfc: SfControls def __init__(self, sfw: SfcWindow): super().__init__("Shapes") self.sfw = sfw self.sfc = sfw.sfc def build_fn(self): print("SfcTabShapes.build_fn (trc)") sfc = self.sfc sfw = self.sfw # print(f"SfcTabShapes.build_fn {type(sfc)}") with ui.VStack(style={"margin": sfw.marg}): with ui.HStack(): sfw._sf_spawn_but = ui.Button("Spawn Prim", style={'background_color': sfw.darkred}, clicked_fn=lambda: sfc.on_click_spawnprim()) sfw._sf_primtospawn_but = ui.Button(f"{sfc._curprim}", style={'background_color': sfw.darkpurple}, clicked_fn=lambda: sfc.on_click_changeprim()) class SfcTabMaterials(BaseTab): sfw: SfcWindow sfc: SfControls def __init__(self, sfw: SfcWindow): super().__init__("Materials") self.sfw = sfw self.sfc = sfw.sfc # print("SfcTabMaterials.build_fn {sfc}") def build_fn(self): print("SfcTabMaterials.build_fn (trc)") sfw = self.sfw sfc = self.sfc with ui.VStack(style={"margin": sfw.marg}): # Material Combo Box with ui.HStack(): ui.Label("SF Material 1:") idx = sfc._matkeys.index(sfc._current_material_name) sfw._sf_matbox = ui.ComboBox(idx, *sfc._matkeys) sfw._sf_matbox_model = sfw._sf_matbox.model.get_item_value_model() print("built sfw._sf_matbox") with ui.HStack(): ui.Label("SF Material 2:") # use the alternate material name idx = sfc._matkeys.index(sfc._current_alt_material_name) sfw._sf_alt_matbox = ui.ComboBox(idx, *sfc._matkeys) sfw._sf_alt_matbox_model = sfw._sf_alt_matbox.model.get_item_value_model() print("built sfw._sf_matbox") # Bounds Material Combo Box with ui.HStack(): ui.Label("Bounds Material:") idx = sfc._matkeys.index(sfc._current_bbox_material_name) sfw._bb_matbox = ui.ComboBox(idx, *sfc._matkeys) sfw._bb_matbox_model = sfw._bb_matbox.model.get_item_value_model() # Bounds Material Combo Box with ui.HStack(): ui.Label("Floor Material:") idx = sfc._matkeys.index(sfc._current_floor_material_name) sfw._sf_floor_matbox = ui.ComboBox(idx, *sfc._matkeys) sfw._sf_floor_matbox_model = sfw._sf_floor_matbox.model.get_item_value_model() class SfcTabOptions(BaseTab): sfw: SfcWindow sfc: SfControls def __init__(self, sfw: SfcWindow): super().__init__("Options") self.sfw = sfw self.sfc = sfw.sfc # print("SfcTabOptions.build_fn {sfc}") def build_fn(self): print("SfcTabOptions.build_fn (trc)") sfw = self.sfw sfc = self.sfc # noqa : F841 with ui.VStack(style={"margin": sfw.marg}): with ui.HStack(): ui.Label("Write Perf Log: ") sfw.writelog_checkbox = ui.CheckBox(model=sfw.writelog_checkbox_model, width=40, height=10, name="writelog", visible=True) with ui.HStack(): ui.Label("Log Series Name:") sfw.writelog_seriesname = ui.StringField(model=sfw.writelog_seriesname_model, width=200, height=20, visible=True)
19,270
Python
46.818858
117
0.486404
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/omni/sphereflake/spheremesh.py
import omni.kit.commands as okc import omni.usd import math import numpy as np from pxr import Gf, Sdf, Usd, UsdGeom, UsdShade, Vt from .ovut import MatMan, delete_if_exists class SphereMeshFactoryV1(): _show_normals = False _matman = None _nlat = 8 _nlng = 8 _total_quads = 0 def __init__(self) -> None: # self._stage = omni.usd.get_context().get_stage() pass def GenPrep(self): pass def LoadSettings(self): print("SphereMeshFactoryV1.LoadSettings (trc)") def MakeMarker(self, name: str, matname: str, cenpt: Gf.Vec3f, rad: float): # print(f"MakeMarker {name} {cenpt} {rad}") primpath = f"/World/markers/{name}" delete_if_exists(primpath) okc.execute('CreateMeshPrimWithDefaultXform', prim_type="Sphere", prim_path=primpath) sz = rad/100 okc.execute('TransformMultiPrimsSRTCpp', count=1, paths=[primpath], new_scales=[sz, sz, sz], new_translations=[cenpt[0], cenpt[1], cenpt[2]]) stage = omni.usd.get_context().get_stage() prim: Usd.Prim = stage.GetPrimAtPath(primpath) mtl = self._matman.GetMaterial(matname) UsdShade.MaterialBindingAPI(prim).Bind(mtl) def CreateMesh(self, name: str, matname: str, cenpt: Gf.Vec3f, radius: float): # This will create nlat*nlog quads or twice that many triangles # it will need nlat+1 vertices in the latitude direction and nlong vertices in the longitude direction # so a total of (nlat+1)*(nlong) vertices stage = omni.usd.get_context().get_stage() spheremesh = UsdGeom.Mesh.Define(stage, name) nlat = self._nlat nlng = self._nlng vtxcnt = int(0) pts = [] nrm = [] txc = [] fvc = [] idx = [] polegap = 0.01 # prevents the vertices from being exactly on the poles for i in range(nlat+1): for j in range(nlng): theta = polegap + (i * (math.pi-2*polegap) / float(nlat)) phi = j * 2 * math.pi / float(nlng) nx = math.sin(theta) * math.cos(phi) ny = math.cos(theta) nz = math.sin(theta) * math.sin(phi) x = radius * nx y = radius * ny z = radius * nz rawpt = Gf.Vec3f(x, y, z) nrmvek = Gf.Vec3f(nx, ny, nz) pt = rawpt + cenpt nrm.append(nrmvek) pts.append(pt) txc.append((x, y)) if self._show_normals: ptname = f"ppt_{i}_{j}" npt = Gf.Vec3f(x+nx, y+ny, z+nz) nmname = f"npt_{i}_{j}" self.MakeMarker(ptname, "red", pt, 1) self.MakeMarker(nmname, "blue", npt, 1) for i in range(nlat): offset = i * nlng for j in range(nlng): fvc.append(int(4)) if j < nlng - 1: i1 = offset+j i2 = offset+j+1 i3 = offset+j+nlng+1 i4 = offset+j+nlng else: i1 = offset+j i2 = offset i3 = offset+nlng i4 = offset+j+nlng idx.extend([i1, i2, i3, i4]) # print(f"i:{i} j:{j} vtxcnt:{vtxcnt} i1:{i1} i2:{i2} i3:{i3} i4:{i4}") vtxcnt += 1 # print(len(pts), len(txc), len(fvc), len(idx)) spheremesh.CreatePointsAttr(pts) spheremesh.CreateNormalsAttr(nrm) spheremesh.CreateFaceVertexCountsAttr(fvc) spheremesh.CreateFaceVertexIndicesAttr(idx) spheremesh.CreateExtentAttr([(-radius, -radius, -radius), (radius, radius, radius)]) texCoords = UsdGeom.PrimvarsAPI(spheremesh).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying) texCoords.Set(txc) # prim: Usd.Prim = self._stage.GetPrimAtPath(primpath) mtl = self._matman.GetMaterial(matname) UsdShade.MaterialBindingAPI(spheremesh).Bind(mtl) self._total_quads += len(fvc) # face vertex counts return spheremesh class SphereMeshFactory(): _show_normals = False _matman: MatMan = None p_nlat = 8 p_nlng = 8 _total_quads = 0 _dotexcoords = True def __init__(self, matman: MatMan) -> None: self._matman = matman # self._stage = omni.usd.get_context().get_stage() def GenPrep(self): self._nquads = self.p_nlat*self.p_nlng self._nverts = (self.p_nlat+1)*(self.p_nlng) self._normbuf = np.zeros((self._nverts, 3), dtype=np.float32) self._txtrbuf = np.zeros((self._nverts, 2), dtype=np.float32) self._facebuf = np.zeros((self._nquads, 1), dtype=np.int32) self._vidxbuf = np.zeros((self._nquads, 4), dtype=np.int32) self.MakeArrays() def Clear(self): pass def MakeMarker(self, name: str, matname: str, cenpt: Gf.Vec3f, rad: float): # print(f"MakeMarker {name} {cenpt} {rad}") primpath = f"/World/markers/{name}" delete_if_exists(primpath) okc.execute('CreateMeshPrimWithDefaultXform', prim_type="Sphere", prim_path=primpath) sz = rad/100 okc.execute('TransformMultiPrimsSRTCpp', count=1, paths=[primpath], new_scales=[sz, sz, sz], new_translations=[cenpt[0], cenpt[1], cenpt[2]]) stage = omni.usd.get_context().get_stage() prim: Usd.Prim = stage.GetPrimAtPath(primpath) mtl = self._matman.GetMaterial(matname) UsdShade.MaterialBindingAPI(prim).Bind(mtl) def MakeArrays(self): nlat = self.p_nlat nlong = self.p_nlng for i in range(nlat): offset = i * nlong for j in range(nlong): if j < nlong - 1: i1 = offset+j i2 = offset+j+1 i3 = offset+j+nlong+1 i4 = offset+j+nlong else: i1 = offset+j i2 = offset i3 = offset+nlong i4 = offset+j+nlong vidx = i*nlong+j self._facebuf[vidx] = 4 self._vidxbuf[vidx] = [i1, i2, i3, i4] polegap = 0.01 # prevents the vertices from being exactly on the poles for i in range(nlat+1): theta = polegap + (i * (math.pi-2*polegap) / float(nlat)) st = math.sin(theta) ct = math.cos(theta) for j in range(nlong): phi = j * 2 * math.pi / float(nlong) sp = math.sin(phi) cp = math.cos(phi) nx = st*cp ny = ct nz = st*sp nrmvek = Gf.Vec3f(nx, ny, nz) vidx = i*nlong+j self._normbuf[vidx] = nrmvek self._txtrbuf[vidx] = (nx, ny) # print("MakeArrays done") def ShowNormals(self, vertbuf): nlat = self.p_nlat nlong = self.p_nlng for i in range(nlat+1): for j in range(nlong): vidx = i*nlong+j ptname = f"ppt_{i}_{j}" (x, y, z) = vertbuf[vidx] (nx, ny, nz) = self._nromtbuf[vidx] pt = Gf.Vec3f(x, y, z) npt = Gf.Vec3f(x+nx, y+ny, z+nz) nmname = f"npt_{i}_{j}" self.MakeMarker(ptname, "red", pt, 1) self.MakeMarker(nmname, "blue", npt, 1) def CreateMesh(self, name: str, matname: str, cenpt: Gf.Vec3f, radius: float): # This will create nlat*nlog quads or twice that many triangles # it will need nlat+1 vertices in the latitude direction and nlong vertices in the longitude direction # so a total of (nlat+1)*(nlong) vertices stage = omni.usd.get_context().get_stage() spheremesh = UsdGeom.Mesh.Define(stage, name) # note that vertbuf is local to this function allowing it to be changed in a multithreaded environment vertbuf = self._normbuf*radius + cenpt if self._show_normals: self.ShowNormals(vertbuf) if self._dotexcoords: texCoords = UsdGeom.PrimvarsAPI(spheremesh).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying) texCoords.Set(Vt.Vec2fArray.FromNumpy(self._txtrbuf)) spheremesh.CreatePointsAttr(Vt.Vec3dArray.FromNumpy(vertbuf)) spheremesh.CreateNormalsAttr(Vt.Vec3dArray.FromNumpy(self._normbuf)) spheremesh.CreateFaceVertexCountsAttr(Vt.IntArrayFromBuffer(self._facebuf)) spheremesh.CreateFaceVertexIndicesAttr(Vt.IntArrayFromBuffer(self._vidxbuf)) mtl = self._matman.GetMaterial(matname) UsdShade.MaterialBindingAPI(spheremesh).Bind(mtl) self._total_quads += self._nquads # face vertex counts return None async def CreateVertBuf(self, radius, cenpt): vertbuf = self._normbuf*radius + cenpt return vertbuf async def CreateStuff(self, spheremesh, vertbuf, normbuf, facebuf, vidxbuf): spheremesh.CreatePointsAttr(Vt.Vec3dArray.FromNumpy(vertbuf)) spheremesh.CreateNormalsAttr(Vt.Vec3dArray.FromNumpy(normbuf)) spheremesh.CreateFaceVertexCountsAttr(Vt.IntArrayFromBuffer(facebuf)) spheremesh.CreateFaceVertexIndicesAttr(Vt.IntArrayFromBuffer(vidxbuf)) return async def CreateMeshAsync(self, name: str, matname: str, cenpt: Gf.Vec3f, radius: float): # This will create nlat*nlog quads or twice that many triangles # it will need nlat+1 vertices in the latitude direction and nlong vertices in the longitude direction # so a total of (nlat+1)*(nlong) vertices stage = omni.usd.get_context().get_stage() spheremesh = UsdGeom.Mesh.Define(stage, name) # note that vertbuf is local to this function allowing it to be changed in a multithreaded environment vertbuf = await self.CreateVertBuf(radius, cenpt) if self._show_normals: self.ShowNormals(vertbuf) if self._dotexcoords: texCoords = UsdGeom.PrimvarsAPI(spheremesh).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying) texCoords.Set(Vt.Vec2fArray.FromNumpy(self._txtrbuf)) await self.CreateStuff(spheremesh, vertbuf, self._normbuf, self._facebuf, self._vidxbuf) mtl = self._matman.GetMaterial(matname) UsdShade.MaterialBindingAPI(spheremesh).Bind(mtl) self._total_quads += self._nquads # face vertex counts return None
11,256
Python
38.36014
110
0.543088
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/omni/sphereflake/tests/testsyspath.py
import sys def write_out_syspath(fname: str = 'd:/nv/ov/syspath.txt', indent=False) -> None: # Write out the python syspath to a file # Indent should be True if to be used for the settings.json python.analsys.extraPaths setting pplist = sys.path with open(fname, 'w') as f: for line in pplist: nline = line.replace("\\", "/") if indent: nnline = f" \"{nline}\",\n" else: nnline = f"\"{nline}\",\n" f.write(nnline) def read_in_syspath(fname: str = 'd:/nv/ov/syspath.txt') -> None: # Read in the python path from a file with open(fname, 'r') as f: for line in f: nline = line.replace(',', '') nline = nline.replace('"', '') nline = nline.replace('"', '') nline = nline.replace('\n', '') nline = nline.replace(' ', '') sys.path.append(nline) write_out_syspath("syspath-before.txt") read_in_syspath("syspath-before.txt") write_out_syspath("syspath-after.txt")
1,084
Python
30.911764
97
0.52952
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/omni/sphereflake/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/omni/sphereflake/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 omni.example.spawn_prims # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = omni.example.spawn_prims.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,684
Python
34.851063
142
0.682898
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/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
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/docs/README.md
# Python SphereFlake Benchmark This creates an adjustable number of SphereFlakes with a variety of methods for the puruposes of benchmarking Omniverse
153
Markdown
29.799994
119
0.836601
mike-wise/kit-exts-spawn-prims/exts/omni.sphereflake/docs/index.rst
omni.example.spawn_prims ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"omni.example.spawn_prims" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
349
reStructuredText
15.666666
43
0.624642
sajith0481/kit-extension-template/README.md
# *Omniverse Kit* Extensions Project Template This project is a template for developing extensions for *Omniverse Kit*. # Getting Started ## Install Omniverse and some Apps 1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download) 2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*. ## Add a new extension to your *Omniverse App* 1. Fork and clone this repo, for example in `C:\projects\kit-extension-template` 2. In the *Omniverse App* open extension manager: *Window* &rarr; *Extensions*. 3. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar. 4. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `exts` subfolder there as another search path: `C:\projects\kit-extension-template\exts` ![Extension Manager Window](/images/add-ext-search-path.png) 5. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it. 6. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload. ### Few tips * Now that `exts` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*. * Look at the *Console* window for warnings and errors. It also has a small button to open current log file. * All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`. * Extension name is a folder name in `exts` folder, in this example: `omni.hello.world`. * Most important thing extension has is a config file: `extension.toml`, take a peek. ## Next Steps: Alternative way to add a new extension To get a better understanding and learn a few other things, we recommend following next steps: 1. Remove search path added in the previous section. 1. Open this cloned repo using Visual Studio Code: `code C:\projects\kit-extension-template`. It will suggest installing a few extensions to improve python experience. 2. In the terminal (CTRL + \`) run `link_app.bat` (more in [Linking with an *Omniverse* app](#linking-with-an-omniverse-app) section). 3. Run this app with `exts` folder added as an extensions search path and new extension enabled: ```bash > app\omni.code.bat --ext-folder exts --enable omni.hello.world ``` - `--ext-folder [path]` - adds new folder to the search path - `--enable [extension]` - enables an extension on startup. Use `-h` for help: ```bash > app\omni.code.bat -h ``` 4. After the *App* started you should see: * new "My Window" window popup. * extension search paths in *Extensions* window as in the previous section. * extension enabled in the list of extensions. 5. If you look inside `omni.code.bat` or any other *Omniverse App*, they all run *Omniverse Kit* (`kit.exe`). *Omniverse Kit* is the Omniverse Application runtime that powers *Apps* build out of extensions. Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Code*: ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world ``` It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!): ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world --enable omni.kit.window.extensions ``` You should see a menu in the top left. From here you can enable more extensions from the UI. ### Few tips * In the *Extensions* window, press *Bread* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be: all extensions and dependencies. * Extensions system documentation: http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/extensions.html # Running Tests To run tests we run a new process where only the tested extension (and it's dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests: 1. Run: `app\kit\test_ext.bat omni.hello.world --ext-folder exts` That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code! 2. Alternatively, in *Extension Manager* (*Window &rarr; Extensions*) find your extension, click on *TESTS* tab, click *Run Test* For more information about testing refer to: [testing doc](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/ext_testing.html). # Linking with an *Omniverse* app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app create ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Adding a new extension Adding a new extension is as simple as copying and renaming existing one: 1. copy `exts/omni.hello.world` to `exts/[new extension name]` 2. rename python module (namespace) in `exts/[new extension name]/omni/hello/world` to `exts/[new extension name]/[new python module]` 3. update `exts/[new extension name]/config/extension.toml`, most importantly specify new python module to load: ```toml [[python.module]] name = "[new python module]" ``` No restart is needed, you should be able to find and enable `[new extension name]` in extension manager. # Sharing extensions To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). 1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery. 2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes. # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
6,864
Markdown
47.687943
318
0.750291
sajith0481/kit-extension-template/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
sajith0481/kit-extension-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
sajith0481/kit-extension-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 shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
sajith0481/kit-extension-template/exts/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 = "Sajith's Spawn a Cube" 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-extension-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,199
TOML
26.272727
105
0.737281
sajith0481/kit-extension-template/exts/omni.hello.world/omni/hello/world/extension.py
import omni.ext import omni.ui as ui import omni.kit.commands # 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("Spawn a cube", width=300, height=300) with self._window.frame: with ui.VStack(): ui.Label("Some label") def on_click(): print("made a cube!") omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Cube', attributes={'size': 100.0, 'extent': [(-50.0, -50.0, -50.0), (50.0, 50.0, 50.0)]}) ui.Button("Spawn Cube", clicked_fn=lambda: on_click()) def on_shutdown(self): print("[omni.hello.world] MyExtension shutdown")
1,543
Python
36.658536
119
0.625405
sajith0481/kit-extension-template/exts/omni.hello.world/omni/hello/world/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
sajith0481/kit-extension-template/exts/omni.hello.world/omni/hello/world/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
sajith0481/kit-extension-template/exts/omni.hello.world/omni/hello/world/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 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")
1,668
Python
34.510638
142
0.681055
sajith0481/kit-extension-template/exts/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
sajith0481/kit-extension-template/exts/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
parkerjgit/omniverse-sandbox/README.md
# Omniverse Sandbox This repository is a sandbox for minimal examples and proofs of concept. See readme files in subdirectories for details: * [Omniverse KIT Extensions](./poc.extensions/readme.md) * [Omniverse Farm on AKS](./poc.farmOnAks/readme.md) * [Omniverse Farm on Windows](./poc.farmOnWindows/readme.md) * [Omniverse Farm on Linux](./poc.farmOnLinux/readme.md) ## References * [A Deep Dive into Building Microservices with Omniverse](https://www.nvidia.com/en-us/on-demand/session/gtcfall21-a31204/) * [Companion Code to A Deep Dive into Building Microservices with Omniverse](https://github.com/NVIDIA-Omniverse/deep-dive-into-microservices) * [Developer Breakout: Build Your Own Microservices on Omniverse](https://www.nvidia.com/en-us/on-demand/session/gtcspring22-se2306/) * [Omniverse Kit: Microservices](https://www.youtube.com/watch?v=oSOhtxPJ5CU) * [Omniverse microservice tutorials, 1](http://localhost:8211/tutorials/docs/source/extensions/omni.services.tutorials.one/docs/README.html) * [Microservice Tutorial 1 Video](https://drive.google.com/file/d/1zzX4BJ9MLdfo2VMhFDsAISFGBKBhko2P/view) * [Omniverse microservice tutorials, 2](http://localhost:8211/tutorials/docs/source/extensions/omni.services.tutorials.two/docs/README.html) * [Microservice Tutorial 2 Video](https://drive.google.com/file/d/1QBu6zfl2CWMFMfWf_Ui0MUiNK4VHgZHZ/view) * [Omniverse Kit Extensions Project Template](https://github.com/NVIDIA-Omniverse/kit-extension-template) * [Omniverse Services](https://docs.omniverse.nvidia.com/prod_services/prod_services/overview.html)
1,566
Markdown
73.619044
142
0.794381
parkerjgit/omniverse-sandbox/poc.farmOnWindows/readme.md
# Omniverse Farm on Windows (local) Proof of concept for installing and running farm as standalone service on local windows machine. ## Prerequisites * [Omniverse Launcher](https://docs.omniverse.nvidia.com/prod_launcher/prod_launcher/installing_launcher.html) installed. ## Setup 1. Setup Queue 1. Install/launch Farm Queue (service) from Omniverse Launcher 1. Configure Queue URL (for agents to connect. Also, this is base url for api endpoint) 1. Navigate to Queue Management dashboard(s): ```sh # http://<queue_url>/queue/management/ui/ # http://<queue_url>/queue/management/dashboard http://localhost:8222/queue/management/ui/ http://localhost:8222/queue/management/dashboard ``` 1. Find Queue Management API docs ```sh # http://<queue_url>/docs http://localhost:8222/docs ``` 1. Perform health check ``` curl -X GET 'http://localhost:8222/status' \ -H 'accept: application/json' ``` 1. Setup Agent 1. Install/launch Farm Agent from Omniverse Launcher 1. Connect Agent to Queue by configuring the Queue address (and clicking "Connect"): ```sh # http://<queue_url> http://localhost:8222 ``` 1. Configure Job directories: ``` C:\Users\nycjyp\Code\sandbox\omniverse\poc.farmOnWindows\agent\jobs\* ``` 1. Navigate to Job Management Dashboard: ```sh # http://<agent_url>/agent/management/ui/ http://localhost:8223/agent/management/ui/ ``` 1. Find Agent Management API docs: ```sh # http://<agent_url>/docs http://localhost:8223/docs ``` 1. Perform health check ``` curl -X GET 'http://localhost:8223/status' \ -H 'accept: application/json' ``` ## first job (simple command) 1. Create `hello-omniverse.kit` file in `hello-omniverse` folder within the configured `jobs` directory and copy and paste contents of [hello world example](https://docs.omniverse.nvidia.com/app_farm/app_farm/guides/creating_job_definitions.html#job-definition-schema-system-executables) (see [schema](https://docs.omniverse.nvidia.com/app_farm/app_farm/guides/creating_job_definitions.html#schema-reference)) 1. Verify Job has been added by Getting list of jobs ``` curl -X GET 'http://localhost:8223/agent/operator/available' \ -H 'accept: application/json' ``` 1. Submit task using `queue/management/tasks/submit` endpoint: ``` curl -X POST "http://localhost:8222/queue/management/tasks/submit" \ --header "Accept: application/json" \ --header "Content-Type: application/json" \ --data '{"user":"my-user-id","task_type":"hello-omniverse","task_args":{},"task_comment":"My first job!"}' ``` 1. Get Status of task: ```sh # of task with task id (returned when you submitted task) curl -X GET 'http://localhost:8222/queue/management/tasks/info/848973c4-5864-416b-976f-56a94cfc8258' \ -H 'accept: application/json' # of all tasks matching type: curl -X GET 'http://localhost:8222/queue/management/tasks/list?task_type=hello-omniverse' \ -H 'accept: application/json' ``` * Note, "echo" command was not found, so replaced with "systeminfo" and removed args. ## second job (simple python script) ## ISSUES * getting echo not found error back from agent. * when I add job directories ## Questions: * where is api docs for queue? https://forums.developer.nvidia.com/t/farm-queue-management-api-documentation/237548 * how to package script and dependencies? * how to verify when agents are registered for job? * How do we distribute jobs to agents?
3,746
Markdown
37.628866
409
0.658836
parkerjgit/omniverse-sandbox/poc.extensions/readme.md
# Creating microservice extensions ## Minimal Service 1. Prerequisites: * Kit installed and added to path. 1. Register request handler with an endpoint: ```py from omni.services.core import main def hello_world(): return "hello world" main.register_endpoint("get", "/hello-world", hello_world) ``` 1. Start service with `kit.exe` by passing config. ``` kit \ --exec hello_world.py \ --enable omni.services.core \ --enable omni.services.transport.server.http \ --/exts/omni.kit.registry.nucleus/registries/0/name=kit/services \ --/exts/omni.kit.registry.nucleus/registries/0/url=https://dw290v42wisod.cloudfront.net/exts/kit/services ``` > Note, should see "app ready" logged after all dependancies are resolved and started up. 1. Navigate to OpenAPI docs at `http://localhost:8011/docs` which now includes `/hello-world` endpoint. 1. Test endpoint: ``` curl -X 'GET' \ 'http://localhost:8011/hello-world' \ -H 'accept: application/json' ``` ## Simple Service (linked to app) 1. Generate "New Extension Template Project" scaffolding, from Omniverse Code Extensions tab, by clicking "+" icon. * **name** - repo root directory, can be anything, e.g. "simple-service" * **id** - python module (namespace), e.g. "poc.services.simple" 1. [If nec.] [Link with Omniverse app](https://github.com/NVIDIA-Omniverse/kit-extension-template#linking-with-an-omniverse-app) ``` link_app.sh --app kit ``` 1. Verify that python module is correctly specified in [config/extension.toml](./simple-service/exts/poc.services.simple/config/extension.toml) file: ```toml # available as "import poc.services.simple" [[python.module]] name = "poc.services.simple" ``` 1. Add `omni.services.core` to dependancies in [config/extension.toml](./simple-service/exts/poc.services.simple/config/extension.toml) file: ```toml [dependencies] "omni.services.core" = {} ``` 1. Implement `on_startup` and `on_shutdown` methods to register/deregister handler with endpoint (in [extension.py](./simple-service/exts/poc.services.simple/poc/services/simple/extension.py) file): ```py import omni.ext from omni.services.core import main def hello_world(): return "hello world" class PocServicesSimpleExtension(omni.ext.IExt): def on_startup(self, ext_id): main.register_endpoint("get", "/hello-world", hello_world) def on_shutdown(self): main.deregister_endpoint("get", "/hello-world") ``` 1. Launch Omniverse Code with `poc.services.simple` extension enabled ``` app\omni.code.bat ^ --ext-folder ./exts ^ --enable poc.services.simple ``` 1. Navigate to OpenAPI docs at `http://localhost:8211/docs` which include `/hello-world` endpoint. (Note, port will depend on host application. See below) 1. Test endpoint: ``` curl -X 'GET' \ 'http://localhost:8211/hello-world' \ -H 'accept: application/json' ``` Notes: * Omniverse applications run a webserver and expose an api by default, so if you are running service from an UI app, e.g. Code, Create, etc, then you do not need to manually run a webserver, eg., with `omni.services.transport.server.http`. Note, by default, single instances of omniverse applications use the following ports: Kit - 8011, Create - 8111, Code - 8211. * Get Port: ```py import carb http_server_port = carb.settings.get_settings().get_as_int("exts/omni.services.transport.server.http/port") carb.log_info(f"The OpenAPI specifications can be accessed at: http://localhost:{http_server_port}/docs") ``` * Configure Port: ```toml "omni.services.transport.server.http".port = 8311 ``` ## Headless service 1. Prerequisites * Kit installed and added to path 1. Clone [Omniverse Kit Extensions Project Template](https://github.com/NVIDIA-Omniverse/kit-extension-template) into project root ``` git clone [email protected]:NVIDIA-Omniverse/kit-extension-template.git . ``` 1. Link with omniverse app (creates app sym link) ```sh # windows link_app.bat --app code # linux link_app.sh -app code ``` 1. Start service by passing configuration to `kit.exe` ``` app/kit.exe \ --ext-folder ./exts \ --enable poc.services.headless \ --enable omni.services.transport.server.http \ --/exts/omni.kit.registry.nucleus/registries/0/name=kit/services \ --/exts/omni.kit.registry.nucleus/registries/0/url=https://dw290v42wisod.cloudfront.net/exts/kit/services ``` > Note Omniverse services extensions do not ship with kit, which is why we are passing in registery name and address, where they can be downloaded from. > While we can launch extension headlessly this way, if we *really* want to run headlessly, we should [create an app](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/104.0/guide/creating_kit_apps.html#building-an-app) (ie., an entry point). Recall, that an app is just a `.kit` file. 1. Create App, ie., a `.kit` file: ```toml [settings.app.exts.folders] '++' = ["./exts"] [settings.exts] "omni.services.transport.server.http".port = 8311 "omni.kit.registry.nucleus".registries = [ { name = "kit/services", url = "https://dw290v42wisod.cloudfront.net/exts/kit/services"}, ] [dependencies] "omni.services.transport.server.http" = {} "poc.services.headless" = {} ``` 1. Start service ``` kit headless-service.kit ``` ## Advanced Service 1. Prerequisites * Kit installed and added to path 1. Clone [Omniverse Kit Extensions Project Template](https://github.com/NVIDIA-Omniverse/kit-extension-template) into project root ``` git clone [email protected]:NVIDIA-Omniverse/kit-extension-template.git . ``` 1. Create app sym link (ie. [Linking with an Omniverse app](https://github.com/NVIDIA-Omniverse/kit-extension-template#linking-with-an-omniverse-app)) ```sh link_app.bat --app code # windows link_app.sh --app code # linux ``` 1. Start Code w/ service enabled (ie. [Add a new extension to your Omniverse App](https://github.com/NVIDIA-Omniverse/kit-extension-template#add-a-new-extension-to-your-omniverse-app)) ``` ./app/kit/kit.exe \ ./app/apps/omni.code.kit \ --ext-folder ./exts \ --enable omni.hello.world \ --enable poc.services.adv \ --enable omni.services.assets.validate \ --enable omni.services.assets.convert \ --/exts/omni.kit.registry.nucleus/registries/0/name=kit/services \ --/exts/omni.kit.registry.nucleus/registries/0/url=https://dw290v42wisod.cloudfront.net/exts/kit/services ``` 1. Start service headlessly ``` kit adv-service.kit ``` * get extension name error expected. 1. Test endpoint ``` curl -X 'POST' \ 'http://localhost:8311/viewport-capture/capture' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "usd_stage_path": "omniverse://a6f20fa6-28fe-4e4d-8b5f-ca35bc7f5c90.cne.ngc.nvidia.com/NVIDIA/Samples/Astronaut/Astronaut.usd" }' ``` Notes: * `carb.log_warn()` logs to stdout. * `carb.settings.get_settings().get_as_string` gets arbitrary settings from config Questions: * How to install launcher on wsl2? ## Containerized Service 1. [If nec.] Generate API Key [here](https://ngc.nvidia.com/setup/api-key) 1. Login to nvcr.io using API Key and username '$oauthtoken' ``` docker login nvcr.io ``` 1. Create a [dockerfile](./containerized-service/dockerfile) that adds [hello_world.py](./containerized-service/hello_world.py) to [KIT SDK base image](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/omniverse/containers/kit) ```dockerfile # Start with Kit Base image FROM nvcr.io/nvidia/omniverse/kit:103.5.1 # Install services dependencies on image (omni.services does not ship with Kit) # This code is pulled from a extension registry and the --ext-precache-mode will pull down the extensions and exit. RUN /opt/nvidia/omniverse/kit-sdk-launcher/kit \ --ext-precache-mode \ --enable omni.services.core \ --enable omni.services.transport.server.http \ --/exts/omni.kit.registry.nucleus/registries/0/name=kit/services \ --/exts/omni.kit.registry.nucleus/registries/0/url=https://dw290v42wisod.cloudfront.net/exts/kit/services \ --allow-root # Add script to image COPY hello_world.py /hello_world.py # Declare *intention* for container to use port 8011 at runtime EXPOSE 8011/tcp # Configure container as an executable ENTRYPOINT [ \ "/opt/nvidia/omniverse/kit-sdk-launcher/kit", \ "--exec", "hello_world.py", \ "--enable omni.services.core", \ "--enable", "omni.services.transport.server.http", \ "--allow-root"] ``` 1. Build a new image from dockerfile named "hello-world" ```sh docker build -t hello-world . docker images hello-world ``` 1. Create a new executable container from latest hello-world image and run it locally on port 8011. ``` docker run -it -p 8011:8011 hello-world:latest ``` 1. Navigate to OpenAPI docs at `http://localhost:8011/docs` which now include `/hello-world` endpoint. 1. Test endpoint: ``` curl -X 'GET' \ 'http://localhost:8011/hello-world' \ -H 'accept: application/json' ``` ## Deploy Containerized App to ACI 1. Host in container registry 1. [if nec] Create an Azure Container Registry (ACR) ```sh # az acr create --resource-group <resource-group> --name <acrName> --sku Basic az acr create --resource-group dt-sandbox-resources --name ovfarmacr --sku Basic --admin-enabled true ``` 1. Log in to container registry ```sh # az acr login --name <acrName> az acr login --name ovfarmacr ``` 1. Tag image ```sh # get full name of ACR instance (e.g., ovfarmacr.azurecr.io) az acr show --name ovfarmacr --query loginServer --output table # docker tag <source_image>:<tag> <acr_name>.azurecr.io/<target_image>:<tag> docker tag hello-world:latest ovfarmacr.azurecr.io/hello-world:latest ``` 1. Push image to container registry ```sh docker push ovfarmacr.azurecr.io/hello-world:latest # verify image is now stored in registry az acr repository show --name ovfarmacr --repository hello-world az acr repository list --name ovfarmacr --output table az acr repository show-tags --name ovfarmacr --repository hello-world --output table ``` 1. Deploy App (using az container create) 1. Get ACR credentials ``` az acr credential show -g dt-sandbox-resources -n ovfarmacr ``` 1. Create Container Group ``` ACR_PASSWORD=<acr_password> az container create \ --resource-group dt-sandbox-resources \ --name ov-demo-microservice \ --image ovfarmacr.azurecr.io/hello-world:latest \ --registry-login-server ovfarmacr.azurecr.io \ --registry-username ovfarmacr \ --registry-password $ACR_PASSWORD \ --ip-address Public \ --dns-name-label ov-demo-microservice \ --ports 8011 ``` 1. test endpoints ``` http://ov-demo-microservice.eastus.azurecontainer.io:8011/docs http://ov-demo-microservice.eastus.azurecontainer.io:8011/hello-world http://ov-demo-microservice.eastus.azurecontainer.io:8011/status ``` ## Azure storage stervice 1. Start service headlessly ``` kit app.kit ``` 1. Start service in container ``` docker compose up ``` 1. Clear container cache and restart service ``` docker compose down --rmi local --volumes --remove-orphans docker compose build --no-cache docker compose up ``` ## Ref * [Omniverse Services Getting Started](https://docs.omniverse.nvidia.com/prod_services/prod_services/design/getting_started.html) * [Omniverse microservice tutorials, 1](http://localhost:8211/tutorials/docs/source/extensions/omni.services.tutorials.one/docs/README.html) * [Omniverse microservice tutorials, 2](http://localhost:8211/tutorials/docs/source/extensions/omni.services.tutorials.two/docs/README.html) * [Omniverse Kit Extensions Project Template](https://github.com/NVIDIA-Omniverse/kit-extension-template) * [Companion Code to A Deep Dive into Building Microservices with Omniverse](https://github.com/NVIDIA-Omniverse/deep-dive-into-microservices) * [Tutorial: Implementing a Viewport Capture Service](https://docs.omniverse.nvidia.com/prod_services/prod_services/tutorials/viewport-capture/index.html)
12,923
Markdown
38.888889
365
0.668266
parkerjgit/omniverse-sandbox/poc.extensions/minimal-service/hello_world.py
from omni.services.core import main def hello_world(): return "hello world" main.register_endpoint("get", "/hello-world", hello_world)
140
Python
22.499996
58
0.728571
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/README.md
# *Omniverse Kit* Extensions Project Template This project is a template for developing extensions for *Omniverse Kit*. # Getting Started ## Install Omniverse and some Apps 1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download) 2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*. ## Add a new extension to your *Omniverse App* 1. Fork and clone this repo, for example in `C:\projects\kit-extension-template` 2. In the *Omniverse App* open extension manager: *Window* &rarr; *Extensions*. 3. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar. 4. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `exts` subfolder there as another search path: `C:\projects\kit-extension-template\exts` ![Extension Manager Window](/images/add-ext-search-path.png) 5. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it. 6. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload. ### Few tips * Now that `exts` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*. * Look at the *Console* window for warnings and errors. It also has a small button to open current log file. * All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`. * Extension name is a folder name in `exts` folder, in this example: `omni.hello.world`. * Most important thing extension has is a config file: `extension.toml`, take a peek. ## Next Steps: Alternative way to add a new extension To get a better understanding and learn a few other things, we recommend following next steps: 1. Remove search path added in the previous section. 1. Open this cloned repo using Visual Studio Code: `code C:\projects\kit-extension-template`. It will suggest installing a few extensions to improve python experience. 2. In the terminal (CTRL + \`) run `link_app.bat` (more in [Linking with an *Omniverse* app](#linking-with-an-omniverse-app) section). 3. Run this app with `exts` folder added as an extensions search path and new extension enabled: ```bash > app\omni.code.bat --ext-folder exts --enable omni.hello.world ``` - `--ext-folder [path]` - adds new folder to the search path - `--enable [extension]` - enables an extension on startup. Use `-h` for help: ```bash > app\omni.code.bat -h ``` 4. After the *App* started you should see: * new "My Window" window popup. * extension search paths in *Extensions* window as in the previous section. * extension enabled in the list of extensions. 5. If you look inside `omni.code.bat` or any other *Omniverse App*, they all run *Omniverse Kit* (`kit.exe`). *Omniverse Kit* is the Omniverse Application runtime that powers *Apps* build out of extensions. Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Code*: ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world ``` It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!): ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world --enable omni.kit.window.extensions ``` You should see a menu in the top left. From here you can enable more extensions from the UI. ### Few tips * In the *Extensions* window, press *Bread* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be: all extensions and dependencies. * Extensions system documentation: http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/extensions.html # Running Tests To run tests we run a new process where only the tested extension (and it's dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests: 1. Run: `app\kit\test_ext.bat omni.hello.world --ext-folder exts` That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code! 2. Alternatively, in *Extension Manager* (*Window &rarr; Extensions*) find your extension, click on *TESTS* tab, click *Run Test* For more information about testing refer to: [testing doc](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/ext_testing.html). # Linking with an *Omniverse* app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app create ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Adding a new extension Adding a new extension is as simple as copying and renaming existing one: 1. copy `exts/omni.hello.world` to `exts/[new extension name]` 2. rename python module (namespace) in `exts/[new extension name]/omni/hello/world` to `exts/[new extension name]/[new python module]` 3. update `exts/[new extension name]/config/extension.toml`, most importantly specify new python module to load: ```toml [[python.module]] name = "[new python module]" ``` No restart is needed, you should be able to find and enable `[new extension name]` in extension manager. # Sharing extensions To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). 1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery. 2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes. # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
6,864
Markdown
47.687943
318
0.750291
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/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
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/poc.services.adv/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 = "Viewport capture service" description = "Sample service example demonstrating the creation of microservices using Omniverse." # 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/parkerjgit/omniverse-sandbox/tree/main/poc.extensions/adv-service" # One of categories for UI. category = "services" # Keywords for the extension keywords = ["kit", "service"] # 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.menu.edit" = {} "omni.kit.actions.core" = {} "omni.services.core" = {} "omni.services.transport.server.http" = {} "omni.usd" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "poc.services.adv" # Settings of our extension: [settings.exts."poc.services.adv"] # URL prefix where the service will be mounted, where our API will be available to handle incoming requests. # # Defining this as a setting makes it easy to change or rebrand the endpoint using only command-line or KIT-file # configuration instructions, should extensions ever feature conflicting endpoint naming conventions. url_prefix = "/viewport-capture" # Path from where the captured images will be served from, when exposed to clients. # # This path will be mounted as a child of the `url_prefix` setting, and expressed as a formatted join of the # `{url_prefix}{capture_path}` settings. capture_path = "/static" # Name of the directory on the server where captured images will be stored: capture_directory = "captured_stage_images"
2,022
TOML
33.87931
112
0.754698
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/poc.services.adv/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
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/poc.services.adv/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
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/poc.services.adv/poc/services/adv/extension.py
import os from fastapi.staticfiles import StaticFiles import carb import omni.ext from omni.services.core import main # As most of the features of our API are implemented by the means of function handlers in the `/services` sub-folder, # the main duty of our extension entrypoint is to register our Service's `@router` and dictate when its capability # should be enabled or disabled under the guidance of the User or the dependency system. from .services.capture import router # For convenience, let's also reuse the utility methods we already created to handle and format the storage location of # the captured images so they can be accessed by clients using the server, once API responses are issued from our # Service: from .utils import get_captured_image_directory, get_captured_image_path # Any class derived from `omni.ext.IExt` in the top level module (defined in the `python.module` section of the # `extension.toml` file) will be instantiated when the extension is enabled, and its `on_startup(ext_id)` method # will be called. When disabled or when the application is shut down, its `on_shutdown()` will be called. class ViewportCaptureExtension(omni.ext.IExt): """Sample extension illustrating registration of a service.""" # `ext_id` is the unique identifier of the extension, containing its name and semantic version number. This # identifier can be used in conjunction with the Extension Manager to query for additional information, such # as the extension's location on the filesystem. def on_startup(self, ext_id: str) -> None: ext_name = ext_id.split("-")[0] carb.log_info("ViewportCaptureExtension startup") # At this point, we register our Service's `router` under the prefix we gave our API using the settings system, # to facilitate its configuration and to ensure it is unique from all other extensions we may have enabled: url_prefix = carb.settings.get_settings().get_as_string(f"exts/{ext_name}/url_prefix") main.register_router(router=router, prefix=url_prefix, tags=["Viewport capture"],) # Proceed to create a temporary directory in the Omniverse application file hierarchy where captured stage # images will be stored, until the application is shut down: captured_stage_images_directory = get_captured_image_directory() if not os.path.exists(captured_stage_images_directory): os.makedirs(captured_stage_images_directory) # Register this location as a mount, so its content is served by the web server bundled with the Omniverse # application instance, thus making the captured image available on the network: main.register_mount( path=get_captured_image_path(), app=StaticFiles(directory=captured_stage_images_directory, html=True), name="captured-stage-images", ) def on_shutdown(self) -> None: carb.log_info("ViewportCaptureExtension shutdown") # When disabling the extension or shutting down the instance of the Omniverse application, let's make sure we # also deregister our Service's `router` in order to avoid our API being erroneously advertised as present as # part of the OpenAPI specification despite our handler function no longer being available: main.deregister_router(router=router) main.deregister_mount(path=get_captured_image_path())
3,424
Python
57.050846
119
0.735689
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/poc.services.adv/poc/services/adv/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/poc.services.adv/poc/services/adv/utils.py
import asyncio import os import shutil from typing import Optional, Tuple import carb.settings import carb.tokens import omni.kit.actions.core import omni.kit.app import omni.usd # Let's include a small utility method to facilitate obtaining the name of the extension our code is bundled with. # While we could certainly store and share the `ext_id` provided to the `on_startup()` method of our Extension, this # alternative method of obtaining the name of our extension can also make our code more portable across projects, as it # may allow you to keep your code changes located closer together and not have to spread them up to the main entrypoint # of your extension. def get_extension_name() -> str: """ Return the name of the Extension where the module is defined. Args: None Returns: str: The name of the Extension where the module is defined. """ extension_manager = omni.kit.app.get_app().get_extension_manager() extension_id = extension_manager.get_extension_id_by_module(__name__) extension_name = extension_id.split("-")[0] return extension_name # Building on the utility method just above, this helper method helps us retrieve the path where captured images are # served from the web server, so they can be presented to clients over the network. def get_captured_image_path() -> str: """ Return the path where the captured images can be retrieved from the server, in the `/{url_prefix}/{capture_path}` format. Args: None Returns: str: The path where the captured images can be retrieved from the server. """ extension_name = get_extension_name() settings = carb.settings.get_settings() url_prefix = settings.get_as_string(f"exts/{extension_name}/url_prefix") capture_path = settings.get_as_string(f"exts/{extension_name}/capture_path") captured_images_path = f"{url_prefix}{capture_path}" return captured_images_path # In a similar fashion to the utility method above, this helper method helps us retrieve the path on disk where the # captured images are stored on the server. This makes it possible to map this storage location known to the server to a # publicly-accessible location on the server, from which clients will be able to fetch the captured images once their # web-friendly names have been communicated to clients through our Service's response. def get_captured_image_directory() -> str: """ Return the location on disk where the captured images will be stored, and from which they will be served by the web server after being mounted. In order to avoid growing the size of this static folder indefinitely, images will be stored under the `${temp}` folder of the Omniverse application folder, which is emptied when the application is shut down. Args: None Returns: str: The location on disk where the captured images will be stored. """ extension_name = _get_extension_name() capture_directory_name = carb.settings.get_settings().get_as_string(f"exts/{extension_name}/capture_directory") temp_kit_directory = carb.tokens.get_tokens_interface().resolve("${temp}") captured_stage_images_directory = os.path.join(temp_kit_directory, capture_directory_name) return captured_stage_images_directory # This is the main utility method of our collection so far. This small helper builds on the existing capability of the # "Edit > Capture Screenshot" feature already available in the menu to capture an image from the Omniverse application # currently running. Upon completion, the captured image is moved to the storage location that is mapped to a # web-accessible path so that clients are able to retrieve the screenshot once they are informed of the image's unique # name when our Service issues its response. async def capture_viewport(usd_stage_path: str) -> Tuple[bool, Optional[str], Optional[str]]: """ Capture the viewport, by executing the action already registered in the "Edit > Capture Screenshot" menu. Args: usd_stage_path (str): Path of the USD stage to open in the application's viewport. Returns: Tuple[bool, Optional[str], Optional[str]]: A tuple containing a flag indicating the success of the operation, the path of the captured image on the web server, along with an optional error message in case of error. """ success: bool = omni.usd.get_context().open_stage(usd_stage_path) captured_image_path: Optional[str] = None error_message: Optional[str] = None if success: event = asyncio.Event() menu_action_success: bool = False capture_screenshot_filepath: Optional[str] = None def callback(success: bool, captured_image_path: str) -> None: nonlocal menu_action_success, capture_screenshot_filepath menu_action_success = success capture_screenshot_filepath = captured_image_path event.set() omni.kit.actions.core.execute_action("omni.kit.menu.edit", "capture_screenshot", callback) await event.wait() await asyncio.sleep(delay=1.0) if menu_action_success: # Move the screenshot to the location from where it can be served over the network: destination_filename = os.path.basename(capture_screenshot_filepath) destination_filepath = os.path.join(get_captured_image_directory(), destination_filename) shutil.move(src=capture_screenshot_filepath, dst=destination_filepath) # Record the final location of the captured image, along with the status of the operation: captured_image_path = os.path.join(get_captured_image_path(), destination_filename) success = menu_action_success else: error_message = f"Unable to open stage \"{usd_stage_path}\"." return (success, captured_image_path, error_message)
5,924
Python
43.548872
120
0.716408
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/poc.services.adv/poc/services/adv/services/capture.py
from typing import Optional from pydantic import BaseModel, Field import carb from omni.services.core import routers from ..utils import capture_viewport router = routers.ServiceAPIRouter() # Let's define a model to handle the parsing of incoming requests. # # Using `pydantic` to handle data-parsing duties makes it less cumbersome for us to do express types, default values, # minimum/maximum values, etc. while also taking care of documenting input and output properties of our service using # the OpenAPI specification format. class ViewportCaptureRequestModel(BaseModel): """Model describing the request to capture a viewport as an image.""" usd_stage_path: str = Field( ..., title="Path of the USD stage for which to capture an image", description="Location where the USD stage to capture can be found.", ) # If required, add additional capture response options in subsequent iterations. # [...] # We will also define a model to handle the delivery of responses back to clients. # # Just like the model used to handle incoming requests, the model to deliver responses will not only help define # default values of response parameters, but also in documenting the values clients can expect using the OpenAPI # specification format. class ViewportCaptureResponseModel(BaseModel): """Model describing the response to the request to capture a viewport as an image.""" success: bool = Field( False, title="Capture status", description="Status of the capture of the given USD stage.", ) captured_image_path: Optional[str] = Field( None, title="Captured image path", description="Path of the captured image, hosted on the current server.", ) error_message: Optional[str] = Field( None, title="Error message", description="Optional error message in case the operation was not successful.", ) # If required, add additional capture response options in subsequent iterations. # [...] # Using the `@router` annotation, we'll tag our `capture` function handler to document the responses and path of the # API, once again using the OpenAPI specification format. @router.post( path="/capture", summary="Capture a given USD stage", description="Capture a given USD stage as an image.", response_model=ViewportCaptureResponseModel, ) async def capture(request: ViewportCaptureRequestModel,) -> ViewportCaptureResponseModel: # For now, let's just print incoming request to the log to confirm all components of our extension are properly # wired together: carb.log_warn(f"Received a request to capture an image of \"{request.usd_stage_path}\".") success, captured_image_path, error_message = await capture_viewport(usd_stage_path=request.usd_stage_path) # Let's return a JSON response, indicating that the viewport capture operation failed to avoid misinterpreting the # current lack of image output as a failure: return ViewportCaptureResponseModel( success=success, captured_image_path=captured_image_path, error_message=error_message, )
3,163
Python
40.090909
118
0.726842
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.convert/config/extension.toml
[package] version = "1.0.0" title = "Asset conversion service" description = "A simple demonstration of an asset conversion microservice." authors = ["Omniverse Kit Team"] preview_image = "data/preview_image.png" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" repository = "" category = "Example" keywords = ["kit", "service", "asset", "conversion", "example"] [dependencies] "omni.client" = {} "omni.kit.asset_converter" = {} "omni.kit.pip_archive" = {} "omni.services.assets.validate" = {} "omni.services.core" = {} "omni.services.client" = {} "omni.services.facilities.database.manager" = {} # The main Python module this extension provides, it will be publicly available as # "import omni.services.assets.convert": [[python.module]] name = "omni.services.assets.convert" [settings.exts."omni.services.assets.convert"] # URL prefix where the conversion service will be mounted: url_prefix = "/assets" # Database settings, using an SQLite database for demonstration purposes: [settings.exts."omni.services.assets.convert".dbs.asset-conversions] connection_string = "sqlite:///${data}/asset-conversions.db"
1,123
TOML
32.058823
82
0.732858
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.convert/omni/services/assets/convert/extension.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio import carb import omni.ext from omni.services.core import main from omni.services.facilities.database.manager import DatabaseManagerFacility from .services import router class AssetConversionServiceExtension(omni.ext.IExt): """Asset conversion extension.""" def on_startup(self, ext_id) -> None: ext_name = ext_id.split("-")[0] url_prefix = carb.settings.get_settings_interface().get(f"exts/{ext_name}/url_prefix") # Setup the database facility: self._database_facility = DatabaseManagerFacility(ext_name=ext_name) self._db_ready = asyncio.ensure_future(self._initialize_db()) # Register the database facility with the router, so it can be used by service endpoints: router.register_facility("db_manager", self._database_facility) main.register_router(router=router, prefix=url_prefix, tags=["Assets"]) main.get_app().title = "Omniverse Farm" main.get_app().description = "A microservice-based framework for distributed task execution." tags_metadata = { "name": "Assets", "description": "Manage assets submitted to the Queue." } if not main.get_app().openapi_tags: main.get_app().openapi_tags = [] main.get_app().openapi_tags.append(tags_metadata) def on_shutdown(self) -> None: if self._db_ready: self._db_ready.cancel() self._db_ready = None main.deregister_router(router=router) async def _initialize_db(self) -> None: """Initialize the database to be used to store asset conversion results.""" async with self._database_facility.get("asset-conversions") as db: table_columns = [ "id INTEGER PRIMARY KEY AUTOINCREMENT", "source_asset VARCHAR(256) NOT NULL", "destination_asset VARCHAR(256) NOT NULL", "success BOOLEAN NOT NULL", ] await db.execute(query=f"CREATE TABLE IF NOT EXISTS AssetConversions ({', '.join(table_columns)});")
2,511
Python
39.516128
112
0.66826
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.convert/omni/services/assets/convert/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from .extension import *
452
Python
44.299996
76
0.807522
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.convert/omni/services/assets/convert/services/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from .convert import *
450
Python
44.099996
76
0.806667
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.convert/omni/services/assets/convert/services/convert.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import Dict from pydantic import BaseModel, Field from omni.services.client import AsyncClient from omni.services.core import routers import omni.usd router = routers.ServiceAPIRouter() class ConversionRequestModel(BaseModel): """Model describing the request to convert a given asset to a different format.""" import_path: str = Field( ..., title="Path of the source asset to be converted", description="Location where the asset to convert can be located by an Agent.", ) output_path: str = Field( ..., title="Output path where to store the converted asset", description="Location where to place the converted asset.", ) converter_settings: Dict = Field( {}, title="Converter settings", description="Settings to provide to the Kit Asset Converter extension in order to perform the conversion.", ) class ConversionResponseModel(BaseModel): """Model describing the response to the request to convert a given USD asset.""" status: str = Field( ..., title="Conversion status", description="Status of the conversion of the given asset.", ) @router.post( path="/convert", summary="Convert assets to a different format", description="Convert the given asset into a different format.", response_model=ConversionResponseModel, ) @router.post("/convert") async def run( req: ConversionRequestModel, db_manager=router.get_facility("db_manager"), ) -> ConversionResponseModel: # Convert the given asset: task = omni.kit.asset_converter.get_instance().create_converter_task( import_path=req.import_path, output_path=req.output_path, progress_callback=lambda current, total: print(f"Conversion progress: {current/total*100.0}%"), asset_converter_context=req.converter_settings,) success = await task.wait_until_finished() if not success: detailed_status_code = task.get_status() detailed_status_error_string = task.get_detailed_error() raise Exception(f"Failed to convert \"{req.import_path}\". Error: {detailed_status_code}, {detailed_status_error_string}") # Execute the validation service exposed by the "omni.service.assets.validate" extension: client = AsyncClient("local://") validation_result = await client.assets.validate( scene_path=req.import_path, expected_camera_count=5, ) # Record the result of the validation in the database: query = """ INSERT INTO AssetConversions (source_asset, destination_asset, success) VALUES (:source_asset, :destination_asset, :success) """ values = { "source_asset": req.import_path, "destination_asset": req.output_path, "success": 1 if validation_result["success"] else 0, } async with db_manager.get("asset-conversions") as db: await db.execute(query=query, values=values) return ConversionResponseModel(status="finished")
3,449
Python
35.315789
130
0.696724
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.convert/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.0] - 2021-11-10 ### Added - Initial release for GTC November 2021.
328
Markdown
31.899997
168
0.728659
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.convert/docs/README.md
# Asset Conversion Service [omni.services.assets.convert] ## About A simple extension demonstrating writing a microservice to convert assets using Omniverse Kit-based applications. ## Usage Once enabled, the extension will expose a `/assets/convert` service endpoint, which can be explored from the list of available microservice endpoints exposed by the application: * For *Kit*: http://localhost:8011/docs * For *Create*: http://localhost:8111/docs * For *Isaac Sim*: http://localhost:8211/docs ## Running the extension To enable and execute the extension, from the root of the repository: **On Windows:** ```batch REM Link the extension against a Kit-based application from the Launcher: link_app.bat C:/Users/<username>/AppData/Local/ov/pkg/create-2021.3.7 REM Launch Create, with the extension enabled: app/omni.create.bat ^ --ext-folder C:\Users\<username>\AppData\Local\ov\pkg\farm-queue-102.1.0\exts-farm-queue ^ --ext-folder ./exts ^ --enable omni.services.assets.convert ``` **On Linux:** ```shell # Link the extension against a Kit-based application from the Launcher: ./link_app.sh ~/.local/share/ov/pkg/create-2021.3.7 # Launch Create, with the extension enabled: ./app/omni.create.sh \ --ext-folder ~/.local/share/ov/pkg/farm-queue-102.1.0/exts-farm-queue \ --ext-folder ./exts \ --enable omni.services.assets.convert ``` To launch this small demo pipeline, all that remains is integrating some UI components to let Users submit tasks to the service, or start one from the command-line: ```shell curl -X 'POST' \ 'http://localhost:8011/assets/convert' \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "import_path": "/full/path/to/source_content.usd", "output_path": "/full/path/to/destination_content.obj", "converter_settings": {} }' ```
1,836
Markdown
32.399999
177
0.724401
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.validate/config/extension.toml
[package] version = "1.0.0" title = "Asset validation service" description = "A simple demonstration of an asset validation microservice." authors = ["Omniverse Kit Team"] preview_image = "data/preview_image.png" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" repository = "" category = "Example" keywords = ["kit", "service", "asset", "validation", "example"] [dependencies] "omni.services.core" = {} "omni.usd" = {} # The main Python module this extension provides, it will be publicly available as # "import omni.services.assets.validate": [[python.module]] name = "omni.services.assets.validate" [settings.exts."omni.services.assets.validate"] # URL prefix where the validation service will be mounted: url_prefix = "/assets"
744
TOML
28.799999
82
0.729839
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.validate/omni/services/assets/validate/extension.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import carb import omni.ext from omni.services.core import main from .services import router class AssetValidationServiceExtension(omni.ext.IExt): """Asset validation extension.""" def on_startup(self, ext_id) -> None: ext_name = ext_id.split("-")[0] url_prefix = carb.settings.get_settings_interface().get(f"exts/{ext_name}/url_prefix") main.register_router(router=router, prefix=url_prefix, tags=["Assets"]) main.get_app().title = "Omniverse Farm" main.get_app().description = "A microservice-based framework for distributed task execution." tags_metadata = { "name": "Assets", "description": "Manage assets submitted to the Queue." } if not main.get_app().openapi_tags: main.get_app().openapi_tags = [] main.get_app().openapi_tags.append(tags_metadata) def on_shutdown(self) -> None: main.deregister_router(router=router)
1,388
Python
35.552631
101
0.693804
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.validate/omni/services/assets/validate/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from .extension import *
452
Python
44.299996
76
0.807522
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.validate/omni/services/assets/validate/services/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from .validate import *
451
Python
44.199996
76
0.807095
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.validate/omni/services/assets/validate/services/validate.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio from typing import List, Optional from pxr import UsdGeom from pydantic import BaseModel, Field import carb from omni.services.core import routers import omni.usd router = routers.ServiceAPIRouter() class ValidationRequestModel(BaseModel): """Model describing the request to validate a given USD stage.""" scene_path: str = Field( ..., title="USD scene path", description="Full path to the USD scene to validate, hosted on a location accessible to the Agent.", ) expected_camera_count: int = Field( ..., title="Expected number of cameras", description="Expected number of cameras to find in the scene.", ) class ValidationResponsetModel(BaseModel): """Model describing the response to the request to validate a given USD stage.""" success: bool = Field( ..., title="Success", description="Flag indicating if the validation was successful.", ) actual_camera_count: int = Field( ..., title="Number of cameras found", description="Actual number of cameras found in the scene.", ) async def load_usd_stage(usd_file: str, stage_load_timeout: Optional[float] = None) -> bool: """ Load the given USD stage into the Kit runtime. Args: usd_file (str): Location of the stage to open. stage_load_timeout (Optional[float]): Maximum duration for which to wait before considering a loading timeout. Returns: bool: A flag indicating whether or not the given USD stage was successfully loaded. """ success, error = await omni.usd.get_context().open_stage_async(usd_file) if not success: carb.log_error(f"Unable to open \"{usd_file}\": {str(error)}") raise Exception(f"Unable to open \"{usd_file}\".") carb.log_info("Stage opened. Waiting for \"ASSETS_LOADED\" event.") usd_context = omni.usd.get_context() if usd_context.get_stage_state() != omni.usd.StageState.OPENED: while True: try: event, _ = await asyncio.wait_for(usd_context.next_stage_event_async(), timeout=stage_load_timeout) if event == int(omni.usd.StageEventType.ASSETS_LOADED): carb.log_info(f"Assets for \"{usd_file}\" loaded") return True except asyncio.TimeoutError: _, files_loaded, total_files = usd_context.get_stage_loading_status() if files_loaded == total_files: carb.log_warn("Timed out waiting for \"ASSETS_LOADED\" event but all files seem to have loaded.") return False raise Exception(f"Timed out waiting for \"ASSETS_LOADED\" event for \"{usd_file}\". Aborting.") def get_all_stage_cameras() -> List[UsdGeom.Camera]: """ Return the list of all USD cameras found the current USD stage. Args: None Returns: List[UsdGeom.Camera]: The list of all USD cameras found in the current USD stage. """ cameras: List[UsdGeom.Camera] = [] stage = omni.usd.get_context().get_stage() for prim in stage.TraverseAll(): if prim.IsA(UsdGeom.Camera): cameras.append(UsdGeom.Camera(prim)) return cameras @router.post( path="/validate", summary="Validate assets for conformity", description="Validate that the USD Stage at the given location conforms to pre-determined validation rules.", response_model=ValidationResponsetModel, ) async def run(req: ValidationRequestModel) -> ValidationResponsetModel: # Load the USD stage: await load_usd_stage(usd_file=req.scene_path) # Perform the validation. # # NOTE: For demonstration purposes, we are only considering the number of cameras present in the given USD scene to # demonstrate integration with tools and workflows. stage_cameras = get_all_stage_cameras() camera_count = len(stage_cameras) validation_success = camera_count == req.expected_camera_count # Return the validation results: return ValidationResponsetModel( success=validation_success, actual_camera_count=camera_count, )
4,606
Python
34.167939
119
0.668693
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.validate/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.0] - 2021-11-10 ### Added - Initial release for GTC November 2021.
328
Markdown
31.899997
168
0.728659
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.services.assets.validate/docs/README.md
# Asset Validation Service [omni.services.assets.validate] ## About A simple extension demonstrating writing a microservice to validate assets using Omniverse Kit-based applications. ## Usage Once enabled, the extension will expose a `/assets/validate` service endpoint, which can be explored from the list of available microservice endpoints exposed by the application: * For *Kit*: http://localhost:8011/docs * For *Create*: http://localhost:8111/docs * For *Isaac Sim*: http://localhost:8211/docs ## Running the extension To enable and execute the extension, from the root of the repository: **On Windows:** ```batch REM Link the extension against a Kit-based application from the Launcher: link_app.bat C:/Users/<username>/AppData/Local/ov/pkg/create-2021.3.7 REM Launch Create, with the extension enabled: app/omni.create.bat ^ --ext-folder ./exts ^ --enable omni.services.assets.validate ``` **On Linux:** ```shell # Link the extension against a Kit-based application from the Launcher: ./link_app.sh ~/.local/share/ov/pkg/create-2021.3.7 # Launch Create, with the extension enabled: ./app/omni.create.sh \ --ext-folder ./exts \ --enable omni.services.assets.validate ```
1,208
Markdown
29.224999
178
0.741722
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/asset_converter_native_bindings/__init__.py
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """This module contains bindings and helpers to omniverse_asset_converter interface. You can use it as follows: >>> def progress_callback(progress, total_steps): >>> # pass >>> >>> async with OmniAssetConverter(in_filename, out_filename, progress_callback) as converter: >>> status = converter.get_status() if status == OmniConverterStatus.OK: pass # Handle success else: error_message = converter.get_detailed_error() pass # Handle failure """ import asyncio import os, sys, ctypes import traceback from pxr import Plug # preload dep libs into the process if sys.platform == "win32": ctypes.WinDLL(os.path.join(os.path.dirname(__file__), "libs/draco.dll")) ctypes.WinDLL(os.path.join(os.path.dirname(__file__), "libs/assimp-vc141-mt.dll")) ctypes.WinDLL(os.path.join(os.path.dirname(__file__), "libs/libfbxsdk.dll")) ctypes.WinDLL(os.path.join(os.path.dirname(__file__), "libs/omniverse_asset_converter.dll")) elif sys.platform == "linux": ctypes.CDLL(os.path.join(os.path.dirname(__file__), "libs/libassimp.so")) ctypes.CDLL(os.path.join(os.path.dirname(__file__), "libs/libxml2.so"), mode=ctypes.RTLD_GLOBAL) # ctypes.CDLL(os.path.join(os.path.dirname(__file__), 'libs/libfbxsdk.so')) ctypes.CDLL(os.path.join(os.path.dirname(__file__), "libs/libomniverse_asset_converter.so")) from ._assetconverter import * # Register usd plugin to read asset directly into USD. pluginsRoot = os.path.join(os.path.dirname(__file__), "libs/resources") Plug.Registry().RegisterPlugins(pluginsRoot) class OmniAssetConverter: __future_progress_callbacks = {} __future_material_loaders = {} __read_callback = None __binary_write_callback = None __progress_callback_is_set = False __material_loader_is_set = False __fallback_material_loader = None def __init__( self, in_file, out_file, progress_callback=None, ignore_material=False, ignore_animation=False, single_mesh=False, smooth_normals=False, ignore_cameras=False, preview_surface=False, support_point_instancer=False, as_shapenet=False, embed_mdl_in_usd=True, use_meter_as_world_unit=False, create_world_as_default_root_prim=True, ignore_lights=False, embed_textures=False, material_loader=None, convert_fbx_to_y_up=False, convert_fbx_to_z_up=False, keep_all_materials=False, merge_all_meshes=False, use_double_precision_to_usd_transform_op=False, ignore_pivots=False, disable_instancing=False, export_hidden_props=False, baking_scales=False ): """ Constructor. Args: in_file (str): Asset file path to be converted. out_file (str): Output usd file. progress_callback: (Callable[int, int]): Progress callback of this task. The first param is the progress, and second one is the total steps. ignore_animation (bool): Whether to export animation. ignore_material (bool): Whether to export materials. single_mesh (bool): Export Single props USD even there are native instancing in the imported assets. By default, it will export separate USD files for instancing assets. smooth_normals (bool): Generate smooth normals for every mesh. ignore_cameras (bool): Whether to export camera. preview_surface (bool): Whether to export preview surface of USD. support_point_instancer (bool): DEPRECATED: Whether to use point instancer for mesh instances (deprecated). as_shapenet (bool): DEPRECATED: Input is expected to be a shapenet obj file. embed_mdl_in_usd (bool): DEPRECATED: Embeds mdl into usd without generate on-disk files. use_meter_as_world_unit (bool): Uses meter as world unit. By default, it's centimeter for usd. create_world_as_default_root_prim (bool): Whether to create /World as default root prim. ignore_cameras (bool): Whether to export light. embed_textures (bool): Whether to embed textures for export. material_loader (Callable[OmniConveterFuture, OmniConverterMaterialDescription): Material loader for this task. convert_fbx_to_y_up (bool): Whether to convert imported fbx stage to Maya Y-Up. convert_fbx_to_z_up (bool): Whether to convert imported fbx stage to Maya Z-Up. keep_all_materials (bool): Whether to keep all materials including those ones that are not referenced by any meshes. merge_all_meshes (bool): Whether to merge all meshes as a single one. use_double_precision_to_usd_transform_op (bool): Whether to use double precision for all USD transform op. It's double3 for translate op, float3 for pivot, scale and rotation by default. ignore_pivots (bool): Don't import pivots from assets. disable_instancing (bool): Disables scene instancing for USD export. That the instanceable flag for all prims will always to false even native assets have instancing. export_hidden_props (bool): Export props that are hidden or not. baking_scales (bool): Baking scales into mesh for fbx import. """ self._in_file = in_file self._out_file = out_file self._status = OmniConverterStatus.IN_PROGRESS self._detailed_error = "" self._progress_callback = progress_callback self._material_loader = material_loader self._ignore_animation = ignore_animation self._ignore_material = ignore_material self._single_mesh = single_mesh self._smooth_normals = smooth_normals self._ignore_cameras = ignore_cameras self._preview_surface = preview_surface self._support_point_instancer = support_point_instancer self._as_shapenet = as_shapenet self._embed_mdl_in_usd = embed_mdl_in_usd self._use_meter_as_world_unit = use_meter_as_world_unit self._create_world_as_default_root_prim = create_world_as_default_root_prim self._ignore_lights = ignore_lights self._embed_textures = embed_textures self._convert_fbx_to_y_up = convert_fbx_to_y_up self._convert_fbx_to_z_up = convert_fbx_to_z_up self._keep_all_materials = keep_all_materials self._merge_all_meshes = merge_all_meshes self._use_double_precision_to_usd_transform_op = use_double_precision_to_usd_transform_op self._ignore_pivots = ignore_pivots self._disable_instancing = disable_instancing self._export_hidden_props = export_hidden_props self._baking_scales = baking_scales self._future = None if not OmniAssetConverter.__progress_callback_is_set: omniConverterSetProgressCallback(OmniAssetConverter._importer_progress_callback) OmniAssetConverter.__progress_callback_is_set = True if not OmniAssetConverter.__material_loader_is_set: omniConverterSetMaterialCallback(OmniAssetConverter._importer_material_loader) OmniAssetConverter.__material_loader_is_set = True @staticmethod def major_version() -> int: return OMNI_CONVERTER_MAJOR_VERSION @staticmethod def minor_version() -> int: return OMNI_CONVERTER_MINOR_VERSION @classmethod def set_cache_folder(cls, cache_folder): """Sets the cache store for USD conversion with USD plugin. Args: cache_folder (str): Location of cache folder on your system. """ omniConverterSetCacheFolder(cache_folder) @classmethod def set_log_callback(cls, callback): """Sets log callback globally. Args: callback (Callable[str]): Log callback. """ omniConverterSetLogCallback(callback) @classmethod def set_progress_callback(cls, callback): """Sets progress callback globally. This is used to monitor the asset convert progress. Args: callback (Callable[OmniConverterFuture, int, int]): Callback to be called with converting future, current progress, and total steps. """ omniConverterSetProgressCallback(callback) @classmethod def set_file_callback( cls, mkdir_callback, binary_write_callback, file_exists_callback, read_callback, layer_write_callback=None, file_copy_callback=None, ): """Sets calbacks for file operations. This is used to override the file operations so it could be used to read asset from remote repository. By default, it will use fallback functions that support only to read from local disk. Args: mkdir_callback (Callable[str]): Function to create dir with path. binary_write_callback (Callable[str, Buffer]): Function to write binary with path and content. file_exists_callback (Callable[str]): Function to check file existence with path. read_callback (Callable[str] -> bytes): Function to read bytes from path. layer_write_callback (Callable[str, str]): Function to write layer content with target path and layer identifier. file_copy_callback (Callable[str, str]): Function to copy file to target path with target path and source path. """ cls.__read_callback = read_callback cls.__binary_write_callback = binary_write_callback if read_callback: _internal_read_callback = cls._importer_read_callback else: _internal_read_callback = None if binary_write_callback: _internal_write_callback = cls._importer_write_callback else: _internal_write_callback = None omniConverterSetFileCallbacks( mkdir_callback, _internal_write_callback, file_exists_callback, _internal_read_callback, layer_write_callback, file_copy_callback, ) @classmethod def set_material_loader(cls, material_loader): """Sets material loader to intercept material loading. This function is deprecated since material loader is moved to constructor to make it customized per task. You can still set material load with this function which will work as a global fallback one if no material loader is provided to the constructor. Args: material_loader (Callable[OmniConverterMaterialDescription]): Function that takes material description as param. """ OmniAssetConverter.__fallback_material_loader = material_loader @classmethod def populate_all_materials(cls, asset_path): """Populates all material descriptions from assets. Args: asset_path (str): Asset path. Only FBX is supported currently. Returns: ([OmniConverterMaterialDescription]): Array of material descriptions. """ return omniConverterPopulateMaterials(asset_path) @classmethod def _importer_write_callback(cls, path, blob): if not cls.__binary_write_callback: return False return cls.__binary_write_callback(path, memoryview(blob)) @classmethod def _importer_read_callback(cls, path, blob): if not cls.__read_callback: return False file_bytes = bytes(cls.__read_callback(path)) if file_bytes: blob.assign(file_bytes) return True else: return False @classmethod def _importer_progress_callback(cls, future, progress, total): callback = cls.__future_progress_callbacks.get(future, None) if callback: callback(progress, total) @classmethod def _importer_material_loader(cls, future, material_description): callback = cls.__future_material_loaders.get(future, None) if callback: return callback(material_description) elif OmniAssetConverter.__fallback_material_loader: return OmniAssetConverter.__fallback_material_loader(material_description) else: return None @classmethod def shutdown(cls): """Cleans up all setups. After this, all callbacks will be reset to fallback ones.""" cls.__read_callback = None cls.set_file_callback(None, None, None, None, None, None) cls.set_log_callback(None) cls.set_progress_callback(None) cls.set_material_loader(None) cls.__material_loader_is_set = False cls.__progress_callback_is_set = False cls.__future_progress_callbacks = {} cls.__future_material_loaders = {} cls.__fallback_material_loader = None def get_status(self): """Gets the status of this task. See `OmniConverterStatus`.""" return self._status def get_detailed_error(self): """Gets the detailed error of this task if status is not OmniConverterStatus.OK""" return self._detailed_error def cancel(self): """Cancels this task.""" if self._future: omniConverterCancelFuture(self._future) self._status = omniConverterCheckFutureStatus(self._future) self._detailed_error = omniConverterGetFutureDetailedError(self._future) async def __aenter__(self): flags = 0 if self._ignore_animation: flags |= OMNI_CONVERTER_FLAGS_IGNORE_ANIMATION if self._ignore_material: flags |= OMNI_CONVERTER_FLAGS_IGNORE_MATERIALS if self._single_mesh: flags |= OMNI_CONVERTER_FLAGS_SINGLE_MESH_FILE if self._smooth_normals: flags |= OMNI_CONVERTER_FLAGS_GEN_SMOOTH_NORMALS if self._ignore_cameras: flags |= OMNI_CONVERTER_FLAGS_IGNORE_CAMERAS if self._preview_surface: flags |= OMNI_CONVERTER_FLAGS_EXPORT_PREVIEW_SURFACE if self._support_point_instancer: flags |= OMNI_CONVERTER_FLAGS_SUPPORT_POINTER_INSTANCER if self._as_shapenet: flags |= OMNI_CONVERTER_FLAGS_EXPORT_AS_SHAPENET if self._embed_mdl_in_usd: flags |= OMNI_CONVERTER_FLAGS_EMBED_MDL if self._use_meter_as_world_unit: flags |= OMNI_CONVERTER_FLAGS_USE_METER_PER_UNIT if self._create_world_as_default_root_prim: flags |= OMNI_CONVERTER_FLAGS_CREATE_WORLD_AS_DEFAULT_PRIM if self._ignore_lights: flags |= OMNI_CONVERTER_FLAGS_IGNORE_LIGHTS if self._embed_textures: flags |= OMNI_CONVERTER_FLAGS_EMBED_TEXTURES if self._convert_fbx_to_y_up: flags |= OMNI_CONVERTER_FLAGS_FBX_CONVERT_TO_Y_UP if self._convert_fbx_to_z_up: flags |= OMNI_CONVERTER_FLAGS_FBX_CONVERT_TO_Z_UP if self._keep_all_materials: flags |= OMNI_CONVERTER_FLAGS_KEEP_ALL_MATERIALS if self._merge_all_meshes: flags |= OMNI_CONVERTER_FLAGS_MERGE_ALL_MESHES if self._use_double_precision_to_usd_transform_op: flags |= OMNI_CONVERTER_FLAGS_USE_DOUBLE_PRECISION_FOR_USD_TRANSFORM_OP if self._ignore_pivots: flags |= OMNI_CONVERTER_FLAGS_IGNORE_PIVOTS if self._disable_instancing: flags |= OMNI_CONVERTER_FLAGS_DISABLE_INSTANCING if self._export_hidden_props: flags |= OMNI_CONVERTER_FLAGS_EXPORT_HIDDEN_PROPS if self._baking_scales: flags |= OMNI_CONVERTER_FLAGS_FBX_BAKING_SCALES_INTO_MESH try: self._future = omniConverterCreateAsset(self._in_file, self._out_file, flags) if self._progress_callback: OmniAssetConverter.__future_progress_callbacks[self._future] = self._progress_callback if self._material_loader: OmniAssetConverter.__future_material_loaders[self._future] = self._material_loader status = OmniConverterStatus.IN_PROGRESS while True: status = omniConverterCheckFutureStatus(self._future) if status == OmniConverterStatus.IN_PROGRESS: await asyncio.sleep(0.1) else: break self._status = status self._detailed_error = omniConverterGetFutureDetailedError(self._future) except Exception as e: traceback.print_exc() self._status = OmniConverterStatus.UNKNOWN self._detailed_error = f"Failed to convert {self._in_file} with error: str(e)." return self async def __aexit__(self, exc_type, exc, tb): OmniAssetConverter.__future_progress_callbacks.pop(self._future, None) OmniAssetConverter.__future_material_loaders.pop(self._future, None) omniConverterReleaseFuture(self._future) self._future = None
17,735
Python
38.677852
178
0.639075
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/PACKAGE-LICENSES/sha1-LICENSE.md
============ SHA-1 in C++ ============ 100% Public Domain. Original C Code -- Steve Reid <[email protected]> Small changes to fit into bglibs -- Bruce Guenter <[email protected]> Translation to simpler C++ Code -- Volker Diels-Grabsch <[email protected]> Safety fixes -- Eugene Hopkinson <slowriot at voxelstorm dot com> Header-only library -- Zlatko Michailov <[email protected]>
383
Markdown
22.999999
53
0.694517
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/PACKAGE-LICENSES/omniverse-asset-converter-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
413
Markdown
50.749994
74
0.837772
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/PACKAGE-LICENSES/omni.kit.asset_converter-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/PACKAGE-LICENSES/pybind11-LICENSE.md
Copyright (c) 2016 Wenzel Jakob <[email protected]>, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Please also refer to the file CONTRIBUTING.md, which clarifies licensing of external contributions to this project including patches, pull requests, etc.
1,676
Markdown
54.899998
79
0.809666
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/PACKAGE-LICENSES/tinyobjloader-LICENSE.md
The MIT License (MIT) Copyright (c) 2012-2019 Syoyo Fujita and many contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------- mapbox/earcut.hpp ISC License Copyright (c) 2015, Mapbox Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1,902
Markdown
43.255813
80
0.790221
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/PACKAGE-LICENSES/usd-LICENSE.md
Universal Scene Description (USD) components are licensed under the following terms: Modified Apache 2.0 License TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor and its affiliates, except as required to comply with Section 4(c) of the License and to reproduce the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. ============================================================ RapidJSON ============================================================ Tencent is pleased to support the open source community by making RapidJSON available. Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License. If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license. A copy of the MIT License is included in this file. Other dependencies and licenses: Open Source Software Licensed Under the BSD License: -------------------------------------------------------------------- The msinttypes r29 Copyright (c) 2006-2013 Alexander Chemeris All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Open Source Software Licensed Under the JSON License: -------------------------------------------------------------------- json.org Copyright (c) 2002 JSON.org All Rights Reserved. JSON_checker Copyright (c) 2002 JSON.org All Rights Reserved. Terms of the JSON License: --------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Terms of the MIT License: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================ pygilstate_check ============================================================ The MIT License (MIT) Copyright (c) 2014, Pankaj Pandey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================ double-conversion ============================================================ Copyright 2006-2011, the V8 project authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================ OpenEXR/IlmBase/Half ============================================================ /////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// ============================================================ Apple Technical Q&A QA1361 - Detecting the Debugger https://developer.apple.com/library/content/qa/qa1361/_index.html ============================================================ Sample code project: Detecting the Debugger Version: 1.0 Abstract: Shows how to determine if code is being run under the debugger. IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================ LZ4 ============================================================ LZ4 - Fast LZ compression algorithm Copyright (C) 2011-2017, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You can contact the author at : - LZ4 homepage : http://www.lz4.org - LZ4 source repository : https://github.com/lz4/lz4 ============================================================ stb ============================================================ stb_image - v2.19 - public domain image loader - http://nothings.org/stb no warranty implied; use at your own risk stb_image_resize - v0.95 - public domain image resizing by Jorge L Rodriguez (@VinoBS) - 2014 http://github.com/nothings/stb stb_image_write - v1.09 - public domain - http://nothings.org/stb/stb_image_write.h writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 no warranty implied; use at your own risk ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26,573
Markdown
57.792035
739
0.727317
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/PACKAGE-LICENSES/assimp-LICENSE.md
Open Asset Import Library (assimp) Copyright (c) 2006-2016, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************************** AN EXCEPTION applies to all files in the ./test/models-nonbsd folder. These are 3d models for testing purposes, from various free sources on the internet. They are - unless otherwise stated - copyright of their respective creators, which may impose additional requirements on the use of their work. For any of these models, see <model-name>.source.txt for more legal information. Contact us if you are a copyright holder and believe that we credited you inproperly or if you don't want your files to appear in the repository. ****************************************************************************** Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors http://code.google.com/p/poly2tri/ All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Poly2Tri nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3,791
Markdown
46.999999
81
0.772619
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/PACKAGE-LICENSES/libxml2-LICENSE.md
Except where otherwise noted in the source code (e.g. the files hash.c, list.c and the trio files, which are covered by a similar licence but with different Copyright notices) all the files are: Copyright (C) 1998-2012 Daniel Veillard. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is fur- nished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIT- NESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1,288
Markdown
55.043476
77
0.798137
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/config/extension.toml
[package] title = "Asset Converter" description = "The asset converter API for converting assets. It supports conversion between assets like OBJ, GLTF, FBX and USD." version = "1.2.39" changelog = "docs/CHANGELOG.md" readme = "docs/README.md" category = "Utility" repository = "" # 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" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] [core] # Load at the start, load all schemas with order -100 (with order -1000 the USD libs are loaded) order = -100 toggleable = false [dependencies] "omni.usd" = {} "omni.client" = {} "omni.usd.libs" = {} [[python.module]] name = "omni.kit.asset_converter" # Add this to create package with platform and config information. [[native.plugin]] recursive = false # Extension test settings [[test]] stdoutFailPatterns.include = [] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/app/file/ignoreUnsavedOnExit=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", ] dependencies = [ "omni.hydra.pxr", "omni.kit.window.viewport", "omni.kit.window.content_browser", "omni.kit.window.viewport", "omni.kit.window.stage", "omni.kit.widget.layers", "omni.kit.property.bundle", "omni.kit.window.console", "omni.kit.window.status_bar", "omni.kit.quicklayout", # arranges the windows correctly "omni.kit.ui_test", "omni.kit.test_suite.helpers", ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop "*Cannot use omni.hydra.pxr without OpenGL interop*", # Linux TC configs with multi-GPU might not have OpenGL available ]
2,080
TOML
28.728571
129
0.70625
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/config/extension.gen.toml
[package] [package.target] platform = ["windows-x86_64"] config = ["release"] python = ["cp37"] [package.publish] date = 1666794213 kitVersion = "104.0+release.92238.1ca55f8d.tc" buildNumber = "104.0+master.559.6933238c.tc"
224
TOML
21.499998
46
0.71875
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/__init__.py
from .impl import *
20
Python
9.499995
19
0.7
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/native_bindings/__init__.py
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from asset_converter_native_bindings._assetconverter import * from asset_converter_native_bindings import OmniAssetConverter
558
Python
49.818177
76
0.820789
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/tests/drag_drop_usd_stage.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from pathlib import Path import inspect import os import platform import unittest import glob import carb import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from pxr import Sdf, UsdGeom, Usd from omni.kit import ui_test from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, set_content_browser_grid_view, get_content_browser_path_item, get_prims class DragDropUsdStage(AsyncTestCase): def verify_dragged_references(self, prim_name, file_path, prims): if os.path.splitext(file_path)[1] in [".usd", ".usda", ".usdc", ".fbx", ".gltf", ".obj"]: self.assertTrue(len(prims) >= 2) self.assertTrue(prims[0].GetPath().pathString == f"/World/{prim_name}") self.assertTrue(prims[0].GetPrimPath().pathString == f"/World/{prim_name}") external_refs = omni.usd.get_composed_references_from_prim(prims[1]) self.assertTrue(len(external_refs) == 0) external_refs = omni.usd.get_composed_references_from_prim(prims[0]) self.assertTrue(len(external_refs) >= 1) prim_ref = external_refs[0][0] self.assertTrue(prim_ref.customData == {}) self.assertTrue(prim_ref.layerOffset == Sdf.LayerOffset()) self.assertTrue(prim_ref.primPath == Sdf.Path()) self.assertTrue(prim_ref.assetPath.lower() == file_path.lower()) else: self.assertTrue(len(prims) == 0) async def create_stage(self): await omni.usd.get_context().new_stage_async() await wait_stage_loading() # Create defaultPrim usd_context = omni.usd.get_context() settings = carb.settings.get_settings() default_prim_name = settings.get("/persistent/app/stage/defaultPrimName") rootname = f"/{default_prim_name}" stage = usd_context.get_stage() with Usd.EditContext(stage, stage.GetRootLayer()): default_prim = UsdGeom.Xform.Define(stage, Sdf.Path(rootname)).GetPrim() stage.SetDefaultPrim(default_prim) stage_prims = get_prims(stage) return stage, stage_prims async def iter_prims_to_drag(self): for path in glob.glob(get_test_data_path(__name__, "../*")): prim_path = os.path.abspath(path).replace("\\", "/") item = await get_content_browser_path_item(prim_path) yield item, prim_path async def test_l1_drag_drop_usd_stage(self): if inspect.iscoroutinefunction(set_content_browser_grid_view): await set_content_browser_grid_view(False) else: set_content_browser_grid_view(False) await ui_test.find("Stage").focus() await ui_test.find("Content").focus() async for item, prim_path in self.iter_prims_to_drag(): if os.path.splitext(item.path)[1] not in [".usd", ".usda", ".usdc", ".fbx", ".gltf", ".obj"]: continue # create stage stage, stage_prims = await self.create_stage() # drag/drop stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await item.drag_and_drop(stage_tree.center) await wait_stage_loading() # verify self.verify_dragged_references(Path(prim_path).stem, prim_path, get_prims(stage, stage_prims))
3,833
Python
42.568181
151
0.64336
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/tests/test_asset_converter.py
import os import carb.tokens import omni.kit.test import omni.kit.asset_converter from pathlib import Path from pxr import Sdf, Usd # NOTE: those tests belong to omni.kit.asset_converter extension. class TestAssetConverter(omni.kit.test.AsyncTestCaseFailOnLogError): def get_test_dir(self): token = carb.tokens.get_tokens_interface() data_dir = token.resolve("${temp}") return f"{data_dir}/asset_converter_tests" async def setUp(self): pass async def tearDown(self): await omni.client.delete_async(self.get_test_dir()) async def test_convert_assets_to_usd(self): current_path = Path(__file__).parent # invalid_mesh.obj includes an invalid mesh that has zero points for file in ["cube.fbx", "cube.obj", "cube.gltf"]: test_data_path = str(current_path.parent.parent.parent.parent.joinpath("data").joinpath(file)) converter_manager = omni.kit.asset_converter.get_instance() context = omni.kit.asset_converter.AssetConverterContext() context.keep_all_materials = True context.merge_all_meshes = True output_path = self.get_test_dir() + "/test.usd" task = converter_manager.create_converter_task(test_data_path, output_path, None, context) success = await task.wait_until_finished() self.assertTrue(success, f"Failed to convert asset {file}.") self.assertTrue(Path(output_path).is_file(), f"Failed to convert asset {file}.") await omni.client.delete_async(self.get_test_dir()) async def test_convert_usd_to_other_formats(self): current_path = Path(__file__).parent test_data_path = str(current_path.parent.parent.parent.parent.joinpath("data").joinpath("cube.fbx")) converter_manager = omni.kit.asset_converter.get_instance() context = omni.kit.asset_converter.AssetConverterContext() output_path = self.get_test_dir() + "/test.usd" # Creates usd firstly task = converter_manager.create_converter_task(test_data_path, output_path, None, context) success = await task.wait_until_finished() self.assertTrue(success) self.assertTrue(Path(output_path).is_file()) for asset_name in ["test.fbx", "test.obj", "test.gltf"]: asset_path = self.get_test_dir() + f"/{asset_name}" task = converter_manager.create_converter_task(output_path, asset_path, None, context) success = await task.wait_until_finished() self.assertTrue(success) self.assertTrue(Path(asset_path).is_file()) async def test_convert_assets_to_anonymous_layer(self): layer = Sdf.Layer.CreateAnonymous() current_path = Path(__file__).parent for file in ["cube.fbx", "cube.obj", "cube.gltf"]: test_data_path = str(current_path.parent.parent.parent.parent.joinpath("data").joinpath(file)) converter_manager = omni.kit.asset_converter.get_instance() context = omni.kit.asset_converter.AssetConverterContext() context.keep_all_materials = True context.merge_all_meshes = True context.baking_scales = True task = converter_manager.create_converter_task(test_data_path, layer.identifier, None, context) success = await task.wait_until_finished() self.assertTrue(success, f"Failed to convert asset {file}.") await omni.client.delete_async(self.get_test_dir()) async def test_open_non_usd(self): current_path = Path(__file__).parent for file in ["cube.fbx", "cube.obj", "cube.gltf"]: test_data_path = str(current_path.parent.parent.parent.parent.joinpath("data").joinpath(file)) self.assertIsNotNone(Usd.Stage.Open(test_data_path)) async def test_overwrite_opened_stage(self): current_path = Path(__file__).parent output_path = self.get_test_dir() + "/test.usd" opened = False for i in range(10): test_data_path = str(current_path.parent.parent.parent.parent.joinpath("data").joinpath("cube.fbx")) converter_manager = omni.kit.asset_converter.get_instance() context = omni.kit.asset_converter.AssetConverterContext() task = converter_manager.create_converter_task(test_data_path, output_path, None, context, None, True) success = await task.wait_until_finished() self.assertTrue(success, "Failed to convert asset cube.fbx.") # For the first round, opening this stage for next overwrite if not opened: await omni.usd.get_context().open_stage_async(output_path) opened = True await omni.client.delete_async(self.get_test_dir())
4,827
Python
47.767676
114
0.642635
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/tests/__init__.py
from .test_asset_converter import * try: from .drag_drop_usd_layer import * from .drag_drop_usd_stage import * from .drag_drop_usd_viewport import * except: pass
178
Python
21.374997
41
0.685393
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/tests/drag_drop_usd_layer.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from pathlib import Path import inspect import os import platform import unittest import glob import carb import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from pxr import Sdf, UsdGeom, Usd from omni.kit import ui_test from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, set_content_browser_grid_view, get_content_browser_path_item, get_prims class DragDropUsdLayer(AsyncTestCase): def verify_dragged_references(self, prim_name, file_path, prims): if os.path.splitext(file_path)[1] in [".usd", ".usda", ".usdc", ".fbx", ".gltf", ".obj"]: self.assertTrue(len(prims) >= 2) self.assertTrue(prims[0].GetPath().pathString == f"/World/{prim_name}") self.assertTrue(prims[0].GetPrimPath().pathString == f"/World/{prim_name}") external_refs = omni.usd.get_composed_references_from_prim(prims[1]) self.assertTrue(len(external_refs) == 0) external_refs = omni.usd.get_composed_references_from_prim(prims[0]) self.assertTrue(len(external_refs) == 1) prim_ref = external_refs[0][0] self.assertTrue(prim_ref.customData == {}) self.assertTrue(prim_ref.layerOffset == Sdf.LayerOffset()) self.assertTrue(prim_ref.primPath == Sdf.Path()) self.assertTrue(prim_ref.assetPath.lower() == file_path.lower()) else: self.assertTrue(len(prims) == 0) def verify_dragged_layers(self, prim_name, file_path, prims): if os.path.splitext(file_path)[1] in [".usd", ".usda", ".usdc", ".fbx", ".gltf", ".obj"]: self.assertTrue(len(prims) >= 1) else: self.assertTrue(len(prims) == 0) async def create_stage(self): await omni.usd.get_context().new_stage_async() await wait_stage_loading() # Create defaultPrim usd_context = omni.usd.get_context() settings = carb.settings.get_settings() default_prim_name = settings.get("/persistent/app/stage/defaultPrimName") rootname = f"/{default_prim_name}" stage = usd_context.get_stage() with Usd.EditContext(stage, stage.GetRootLayer()): default_prim = UsdGeom.Xform.Define(stage, Sdf.Path(rootname)).GetPrim() stage.SetDefaultPrim(default_prim) stage_prims = get_prims(stage) return stage, stage_prims async def iter_prims_to_drag(self): for path in glob.glob(get_test_data_path(__name__, "../*")): prim_path = os.path.abspath(path).replace("\\", "/") item = await get_content_browser_path_item(prim_path) yield item, prim_path async def test_l1_drag_drop_usd_layer(self): if inspect.iscoroutinefunction(set_content_browser_grid_view): await set_content_browser_grid_view(False) else: set_content_browser_grid_view(False) await ui_test.find("Layer").focus() async for item, prim_path in self.iter_prims_to_drag(): if os.path.splitext(item.path)[1] not in [".usd", ".usda", ".usdc", ".fbx", ".gltf", ".obj"]: continue # create new stage stage, stage_prims = await self.create_stage() # get end_pos which is center bottom of window layer_tree = ui_test.find("Layer//Frame/**/TreeView[*]") end_pos = layer_tree.center # drag/drop await item.drag_and_drop(end_pos) #verify new prims were created self.verify_dragged_layers(Path(prim_path).stem, prim_path, get_prims(stage, stage_prims))
4,100
Python
42.168421
151
0.635122
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/tests/drag_drop_usd_viewport.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from pathlib import Path import inspect import os import platform import unittest import glob import carb import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from pxr import Sdf, UsdGeom, Usd from omni.kit import ui_test from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, set_content_browser_grid_view, get_content_browser_path_item, get_prims class TestDragDropUSD(AsyncTestCase): def verify_dragged_references(self, prim_name, file_path, prims): if os.path.splitext(file_path)[1] in [".usd", ".usda", ".usdc", ".fbx", ".gltf", ".obj"]: self.assertTrue(len(prims) >= 2) self.assertTrue(prims[0].GetPath().pathString == f"/World/{prim_name}") self.assertTrue(prims[0].GetPrimPath().pathString == f"/World/{prim_name}") external_refs = omni.usd.get_composed_references_from_prim(prims[1]) self.assertTrue(len(external_refs) == 0) external_refs = omni.usd.get_composed_references_from_prim(prims[0]) self.assertTrue(len(external_refs) >= 1) prim_ref = external_refs[0][0] self.assertTrue(prim_ref.customData == {}) self.assertTrue(prim_ref.layerOffset == Sdf.LayerOffset()) self.assertTrue(prim_ref.primPath == Sdf.Path()) self.assertTrue(prim_ref.assetPath.lower() == file_path.lower()) else: self.assertTrue(len(prims) == 0) async def create_stage(self): await omni.usd.get_context().new_stage_async() await wait_stage_loading() # Create defaultPrim usd_context = omni.usd.get_context() settings = carb.settings.get_settings() default_prim_name = settings.get("/persistent/app/stage/defaultPrimName") rootname = f"/{default_prim_name}" stage = usd_context.get_stage() with Usd.EditContext(stage, stage.GetRootLayer()): default_prim = UsdGeom.Xform.Define(stage, Sdf.Path(rootname)).GetPrim() stage.SetDefaultPrim(default_prim) stage_prims = get_prims(stage) return stage, stage_prims async def iter_prims_to_drag(self): for path in glob.glob(get_test_data_path(__name__, "../*")): prim_path = os.path.abspath(path).replace("\\", "/") item = await get_content_browser_path_item(prim_path) yield item, prim_path async def test_l1_drag_drop_usd_viewport(self): if inspect.iscoroutinefunction(set_content_browser_grid_view): await set_content_browser_grid_view(False) else: set_content_browser_grid_view(False) await ui_test.find("Content").focus() viewport = ui_test.find("Viewport") await viewport.focus() end_pos = viewport.center async for item, prim_path in self.iter_prims_to_drag(): if os.path.splitext(item.path)[1] not in [".usd", ".usda", ".usdc", ".fbx", ".gltf", ".obj"]: continue # create stage stage, stage_prims = await self.create_stage() # drag/drop to centre of viewport await item.drag_and_drop(end_pos) # verify new prims self.verify_dragged_references(Path(prim_path).stem, prim_path, get_prims(stage, stage_prims))
3,773
Python
41.886363
151
0.646965
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/impl/task_manager.py
import asyncio import carb import os import omni.usd from ..native_bindings import * from .omni_client_wrapper import OmniClientWrapper from .context import AssetConverterContext class AssetConverterFutureWrapper: def __init__(self, import_path, output_path, import_context, future, close_stage_and_reopen_if_opened): super().__init__() self._native_future = future self._cancelled = False self._import_path = import_path self._output_path = output_path self._import_context = import_context self._is_finished = False self._task_done_callbacks = [] self._close_stage_and_reopen_if_opened = close_stage_and_reopen_if_opened self._error_message = "" self._status = OmniConverterStatus.OK def add_task_done_callback(self, callback): if callback not in self._task_done_callbacks: self._task_done_callbacks.append(callback) def remove_task_done_callback(self, callback): if callback in self._task_done_callbacks: self._task_done_callbacks.remove(callback) def cancel(self): if not self._cancelled: self._native_future.cancel() self._cancelled = True def is_cancelled(self): return self._cancelled def is_finished(self): return self._is_finished def get_status(self): return self._status def get_error_message(self): return self._error_message def _notify_finished(self): for callback in self._task_done_callbacks: callback() async def wait_until_finished(self): if self.is_cancelled() or self.is_finished(): self._notify_finished() return not self.is_cancelled() self._status = OmniConverterStatus.OK self._error_message = "" usd_context = omni.usd.get_context() current_stage_url = usd_context.get_stage_url() opened = os.path.normpath(self._output_path) == os.path.normpath(current_stage_url) if not self._close_stage_and_reopen_if_opened and opened: self._error_message = f"Failed to import {self._import_path} as USD since output path {self._output_path} is opened already." carb.log_error(self._error_message) self._status = OmniConverterStatus.UNKNOWN return False try: if opened: await usd_context.close_stage_async() async with self._native_future as future: status = future.get_status() error = future.get_detailed_error() if status != OmniConverterStatus.OK: self._error_message = f"Couldn't Import Asset: {self._import_path}, code: {status}, error: {error}" self._status = status carb.log_error(self._error_message) return False if opened: await usd_context.open_stage_async(self._output_path) return True finally: self._is_finished = True AssetConverterTaskManager._task_map.discard(self) self._notify_finished() return False class AssetConverterTaskManager: _thread_loop = None _task_map = set() @staticmethod def on_startup(): AssetConverterTaskManager._thread_loop = None token = carb.tokens.get_tokens_interface() data_dir = token.resolve("${data}") cache_dir = os.path.join(data_dir, "omniverse_asset_converter_cache") cache_dir = cache_dir.replace("\\", "/") carb.log_info(f"Initialize asset converter with cache folder {cache_dir}...") OmniAssetConverter.set_cache_folder(cache_dir) OmniAssetConverter.set_log_callback(AssetConverterTaskManager._log_print) OmniAssetConverter.set_file_callback( None, AssetConverterTaskManager._asset_converter_binary_write, None, None, None, AssetConverterTaskManager._asset_converter_file_copy ) @staticmethod def on_shutdown(): for future_wrapper in AssetConverterTaskManager._task_map: future_wrapper.cancel() AssetConverterTaskManager._task_map.clear() OmniAssetConverter.shutdown() @staticmethod def remove_task(task): AssetConverterContext._task_map.discard(task) @staticmethod def create_converter_task( import_path: str, output_path: str, progress_callback, asset_converter_context: AssetConverterContext = None, material_loader=None, close_stage_and_reopen_if_opened=False ): # If not context is provided, creates a default one. if not asset_converter_context: asset_converter_context = AssetConverterContext() future = OmniAssetConverter( import_path, output_path, progress_callback, asset_converter_context.ignore_materials, asset_converter_context.ignore_animations, asset_converter_context.single_mesh, asset_converter_context.smooth_normals, asset_converter_context.ignore_camera, asset_converter_context.export_preview_surface, asset_converter_context.support_point_instancer, False, True, asset_converter_context.use_meter_as_world_unit, asset_converter_context.create_world_as_default_root_prim, asset_converter_context.ignore_light, asset_converter_context.embed_textures, material_loader=material_loader, convert_fbx_to_y_up=asset_converter_context.convert_fbx_to_y_up, convert_fbx_to_z_up=asset_converter_context.convert_fbx_to_z_up, keep_all_materials=asset_converter_context.keep_all_materials, merge_all_meshes=asset_converter_context.merge_all_meshes, use_double_precision_to_usd_transform_op=asset_converter_context.use_double_precision_to_usd_transform_op, ignore_pivots=asset_converter_context.ignore_pivots, disable_instancing=asset_converter_context.disabling_instancing, export_hidden_props=asset_converter_context.export_hidden_props, baking_scales=asset_converter_context.baking_scales ) wrapper = AssetConverterFutureWrapper(import_path, output_path, asset_converter_context, future, close_stage_and_reopen_if_opened) AssetConverterTaskManager._task_map.add(wrapper) return wrapper @staticmethod def _get_thread_loop(): if not AssetConverterTaskManager._thread_loop: AssetConverterTaskManager._thread_loop = asyncio.new_event_loop() return AssetConverterTaskManager._thread_loop @staticmethod def _log_print(message): carb.log_info(message) @staticmethod def _asset_converter_binary_write(path, data): return AssetConverterTaskManager._get_thread_loop().run_until_complete( OmniClientWrapper.write(path, bytearray(data)) ) @staticmethod def _asset_converter_file_copy(target_path, source_path): return AssetConverterTaskManager._get_thread_loop().run_until_complete( OmniClientWrapper.copy(source_path, target_path) )
7,388
Python
36.130653
138
0.635084
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/impl/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import os import weakref import omni.ext from typing import Callable from functools import partial from .omni_client_wrapper import OmniClientWrapper from .context import AssetConverterContext from .task_manager import AssetConverterTaskManager, AssetConverterFutureWrapper def get_instance(): global _global_instance if _global_instance and _global_instance(): return _global_instance() return None class AssetImporterExtension(omni.ext.IExt): def on_startup(self): global _global_instance _global_instance = weakref.ref(self) AssetConverterTaskManager.on_startup() def on_shutdown(self): global _global_instance _global_instance = None AssetConverterTaskManager.on_shutdown() def create_converter_task( self, import_path: str, output_path: str, progress_callback: Callable[[int], int] = None, asset_converter_context: AssetConverterContext = AssetConverterContext(), material_loader=None, close_stage_and_reopen_if_opened: bool = False ): """ Creates task to convert import_path to output_path. Currently, it supports to convert fbx/obj/glTF to USD, or USD to fbx/obj/glTF. Snippet to use it: >>> import asyncio >>> importer omni.kit.asset_converter as converter >>> >>> async def convert(...): >>> task_manger = converter.get_instance() >>> task = task_manger.create_converter_task(...) >>> success = await task.wait_until_finished() >>> if not success: >>> detailed_status_code = task.get_status() >>> detailed_status_error_string = task.get_error_message() NOTE: It uses FBX SDK for FBX convert and Assimp as fallback backend, so it should support all assets that Assimp supports. But only obj/glTF are fully verified. Args: import_path (str): The source asset to be converted. It could also be stage id that's cached in UsdUtils.StageCache since it supports to export loaded stage. output_path (str): The target asset. Asset format is decided by its extension. progress_callback(Callable[[int], int]): Progress callback to monitor the progress of conversion. The first param is the progress, and the second one is the total steps. asset_converter_context (omni.kit.asset_converter.AssetConverterContext): Context. material_loader (Callable[[omni.kit.asset_conerter.native_bindings.MaterialDescription], None]): You can set this to intercept the material loading. close_stage_and_reopen_if_opened (bool): If the output path has already been opened in the current UsdContext, it will close the current stage, then import and re-open it after import successfully if this flag is true. Otherwise, it will return False and report errors. """ return AssetConverterTaskManager.create_converter_task( import_path, output_path, progress_callback, asset_converter_context, material_loader, close_stage_and_reopen_if_opened )
3,971
Python
42.648351
131
0.630068
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/impl/__init__.py
from .extension import AssetImporterExtension, get_instance from .omni_client_wrapper import OmniClientWrapper from .context import *
134
Python
32.749992
59
0.843284
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/impl/omni_client_wrapper.py
import os import traceback import asyncio import carb import omni.client def _encode_content(content): if type(content) == str: payload = bytes(content.encode("utf-8")) elif type(content) != type(None): payload = bytes(content) else: payload = bytes() return payload class OmniClientWrapper: @staticmethod async def exists(path): try: result, entry = await omni.client.stat_async(path) return result == omni.client.Result.OK except Exception as e: traceback.print_exc() carb.log_error(str(e)) return False @staticmethod def exists_sync(path): try: result, entry = omni.client.stat(path) return result == omni.client.Result.OK except Exception as e: traceback.print_exc() carb.log_error(str(e)) return False @staticmethod async def write(path: str, content): carb.log_info(f"Writing {path}...") try: result = await omni.client.write_file_async(path, _encode_content(content)) if result != omni.client.Result.OK: carb.log_error(f"Cannot write {path}, error code: {result}.") return False except Exception as e: traceback.print_exc() carb.log_error(str(e)) return False finally: carb.log_info(f"Writing {path} done...") return True @staticmethod async def copy(src_path: str, dest_path: str): carb.log_info(f"Copying from {src_path} to {dest_path}...") try: result = await omni.client.copy_async(src_path, dest_path, omni.client.CopyBehavior.OVERWRITE) if result != omni.client.Result.OK: carb.log_error(f"Cannot copy from {src_path} to {dest_path}, error code: {result}.") return False else: return True except Exception as e: traceback.print_exc() carb.log_error(str(e)) finally: carb.log_info(f"Copying from {src_path} to {dest_path} done...") return False @staticmethod async def read(src_path: str): carb.log_info(f"Reading {src_path}...") try: result, version, content = await omni.client.read_file_async(src_path) if result == omni.client.Result.OK: return memoryview(content).tobytes() else: carb.log_error(f"Cannot read {src_path}, error code: {result}.") except Exception as e: traceback.print_exc() carb.log_error(str(e)) finally: carb.log_info(f"Reading {src_path} done...") return None @staticmethod async def create_folder(path): carb.log_info(f"Creating dir {path}...") result = await omni.client.create_folder_async(path) return result == omni.client.Result.OK or result == omni.client.Result.ERROR_ALREADY_EXISTS
3,052
Python
30.474226
106
0.56848
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/omni/kit/asset_converter/impl/context.py
from typing import Callable class AssetConverterContext: ignore_materials = False # Don't import/export materials ignore_animations = False # Don't import/export animations ignore_camera = False # Don't import/export cameras ignore_light = False # Don't import/export lights single_mesh = False # By default, instanced props will be export as single USD for reference. If # this flag is true, it will export all props into the same USD without instancing. smooth_normals = True # Smoothing normals, which is only for assimp backend. export_preview_surface = False # Imports material as UsdPreviewSurface instead of MDL for USD export support_point_instancer = False # Deprecated embed_mdl_in_usd = True # Deprecated. use_meter_as_world_unit = False # Sets world units to meters, this will also scale asset if it's centimeters model. create_world_as_default_root_prim = True # Creates /World as the root prim for Kit needs. embed_textures = True # Embedding textures into output. This is only enabled for FBX and glTF export. convert_fbx_to_y_up = False # Always use Y-up for fbx import. convert_fbx_to_z_up = False # Always use Z-up for fbx import. keep_all_materials = False # If it's to remove non-referenced materials. merge_all_meshes = False # Merges all meshes to single one if it can. use_double_precision_to_usd_transform_op = False # Uses double precision for all transform ops. ignore_pivots = False # Don't export pivots if assets support that. disabling_instancing = False # Don't export instancing assets with instanceable flag. export_hidden_props = False # By default, only visible props will be exported from USD exporter. baking_scales = False # Only for FBX. It's to bake scales into meshes. def to_dict(self): return { "ignore_materials": self.ignore_materials, "ignore_animations": self.ignore_animations, "ignore_camera": self.ignore_camera, "ignore_light": self.ignore_light, "single_mesh": self.single_mesh, "smooth_normals": self.smooth_normals, "export_preview_surface": self.export_preview_surface, "support_point_instancer": self.support_point_instancer, "embed_mdl_in_usd": self.embed_mdl_in_usd, "use_meter_as_world_unit": self.use_meter_as_world_unit, "create_world_as_default_root_prim": self.create_world_as_default_root_prim, "embed_textures": self.embed_textures, "convert_fbx_to_y_up": self.convert_fbx_to_y_up, "convert_fbx_to_z_up": self.convert_fbx_to_z_up, "keep_all_materials": self.keep_all_materials, "merge_all_meshes": self.merge_all_meshes, "use_double_precision_to_usd_transform_op": self.use_double_precision_to_usd_transform_op, "ignore_pivots": self.ignore_pivots, "disabling_instancing": self.disabling_instancing, "export_hidden_props": self.export_hidden_props, "baking_scales" : self.baking_scales }
3,232
Python
61.173076
123
0.655322
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/docs/CHANGELOG.md
# Changelog ## [1.2.39] - 2022-10-26 ### Changed - Update OmniverseAssetConverter library to 7.0.1303 to fix uv export of FBX when there are multi-subsets. ## [1.2.38] - 2022-10-11 ### Changed - Update OmniverseAssetConverter library to 7.0.1301 to avoid export fallback color for obj import. ## [1.2.37] - 2022-10-07 ### Changed - Update OmniverseAssetConverter library to 7.0.1300 to fix path resolve issue under linux when it's to reference glTF directly. ## [1.2.36] - 2022-09-08 ### Changed - Add support for BVH file imports. - Update OmniverseAssetConverter library to 7.0.1293. ## [1.2.35] - 2022-09-03 ### Changed - Update tests to pass for kit 104. ## [1.2.34] - 2022-09-01 ### Changed - Update OmniverseAssetConverter library to 7.0.1289. - Fix export crash caused by invalid normal data from usd. - Merge skeletons for glTF to have single skeleton. ## [1.2.33] - 2022-08-05 ### Changed - Update OmniverseAssetConverter library to 7.0.1286. - Fix issue of material naming conflict during USD export. - Export kind for root node during USD export. - Fix crash of exporting USD into OBJ caused by mal-formed USD data. ## [1.2.32] - 2022-07-22 ### Changed - Update OmniverseAssetConverter library to 7.0.1270. - Fix hang of USD plugin to reference glTF from server. - Improve glTF light import/export. ## [1.2.31] - 2022-06-07 ### Changed - Update OmniverseAssetConverter library to 7.0.1258. - OM-52881: Fix some glb file cause crashs in importer. ## [1.2.30] - 2022-05-19 ### Changed - Update OmniverseAssetConverter library to 7.0.1253. - OM-51000: support to pass file argument for specifying meter as world unit. - Improve file format plugin to import asset with original units instead of baking scalings. ## [1.2.29] - 2022-05-19 ### Changed - Update OmniverseAssetConverter library to 7.0.1250 to fix issue of converting assets to local path under linux. ## [1.2.28] - 2022-05-16 ### Changed - Update OmniverseAssetConverter library to 7.0.1245 - OM-50555: Fix fbx animation rotation - OM-50991: optimize uv export to fix texture load not properly ## [1.2.27] - 2022-05-12 ### Changed - Update OmniverseAssetConverter library to 7.0.1237 to fix pdb name issue for assimp library. ## [1.2.26] - 2022-05-07 ### Changed - Fix tests to make sure it will not fail for 103.1 release. ## [1.2.25] - 2022-05-04 ### Changed - Update OmniverseAssetConverter library to 7.0.1236. - OM-36894: Support fbx uv indices's import and export. - OM-34328: Support export lights for gltf. ## [1.2.24] - 2022-04-19 ### Changed - Update OmniverseAssetConverter library to 7.0.1225. - Fix naming issue of obj import if mesh names are empty. - Fix color space setup for material loader. - Fix geometric transform import for FBX. ## [1.2.23] - 2022-04-12 ### Changed - Update OmniverseAssetConverter library to 7.0.1219 to support dissovle attribute of MTL for obj importer. ## [1.2.22] - 2022-03-30 ### Changed - Bump version to update licensing build. ## [1.2.21] - 2022-03-29 ### Changed - Supports option to close current stage with import to avoid multi-threading issue if output path is opened already. ## [1.2.20] - 2022-03-28 ### Changed - Update OmniverseAssetConverter library to 7.0.1201 to support option to bake scales for FBX import. ## [1.2.19] - 2022-03-09 ### Changed - Update OmniverseAssetConverter library to 7.0.1197 to improve pivots support for exporter. - Fix issue that exports USD with pivots to gltf/obj. ## [1.2.18] - 2022-03-08 ### Changed - Update OmniverseAssetConverter library to 7.0.1192 to support to control hidden props export for USD exporter. ## [1.2.17] - 2022-03-04 ### Changed - Update OmniverseAssetConverter library to 7.0.1191 to improve animation import for FBX. - Fix issue of skeletal mesh import when skeleton is not attached to root node. - Fix issue of skeletal mesh if its joints is not provided, which should use global joints instead. - Fix crash of skeleton import if skeleton removed and skinning is still existed. - Fix issue of FBX importer that has possible naming conflict of nodes. - Supports to export all instances into single USD for DriveSim usecase. - Supports options to disable scene instancing for DriveSim usecase. ## [1.2.16] - 2022-02-22 ### Changed - Update OmniverseAssetConverter library to 7.0.1171 to improve multiple animation tracks import/export. ## [1.2.15] - 2022-02-16 ### Changed - Update OmniverseAssetConverter library to 7.0.1161 to remove instancing flag if glTF/glb is opened directly with file format plugin so it could be editable. ## [1.2.14] - 2022-02-15 ### Changed - Update OmniverseAssetConverter library to 7.0.1159 to fix a crash of fbx importer that accesses invalid attributes. ## [1.2.13] - 2022-02-15 ### Changed - Update OmniverseAssetConverter library to 7.0.1157 to improve glTF loading performance through file format plugin. ## [1.2.12] - 2022-02-13 ### Changed - Update OmniverseAssetConverter library to 7.0.1150 to fix a FBX exporter crash that's caused by empty uv set. ## [1.2.11] - 2022-02-11 ### Changed - Update OmniverseAssetConverter library to 7.0.1149 to fix a FBX exporter issue that ignores props under root node. ## [1.2.10] - 2022-02-11 ### Changed - Fix API docs. ## [1.2.9] - 2022-02-10 ### Changed - Update OmniverseAssetConverter library to 7.0.1148 to fix a crash caused by exporting obj files without materials. ## [1.2.8] - 2022-02-08 ### Changed - Update OmniverseAssetConverter library to 7.0.1145 to fix a crash that's caused by invalid path that includes "%" symbols. ## [1.2.7] - 2022-02-07 ### Changed - Update OmniverseAssetConverter library to 7.0.1143 to improve USD exporter to exclude proxy and guide prims. ## [1.2.6] - 2022-02-07 ### Changed - Update OmniverseAssetConverter library to 7.0.1142 to fix glTF import. - Uses default mime type based on extension name if it's not specified for textures. - Fix transparent material import. ## [1.2.5] - 2022-01-11 ### Changed - Update OmniverseAssetConverter library to 7.0.1138 to fix a regression to import assets to OV. ## [1.2.4] - 2022-01-09 ### Changed - Update OmniverseAssetConverter library to 7.0.1136. - Re-org skeletal animation. - Fix transform issue of obj export. - Improve export for FBX assets exported from Substance Painter to avoid exporting separate parts for the same mesh. ## [1.2.3] - 2021-12-30 ### Changed - Update OmniverseAssetConverter library to 7.0.1127 to export obj model as meshes instead of group of subsets so subsets can be pickable. ## [1.2.2] - 2021-12-29 ### Changed - Update OmniverseAssetConverter library to 7.0.1123 to use tinyobj for obj import. ## [1.2.1] - 2021-12-23 ### Changed - Update OmniverseAssetConverter library to 7.0.1117 to support override file copy to speed up copying file. - More optimization to avoid redundant IO to speed up glTF import. ## [1.2.0] - 2021-12-16 ### Changed - Update OmniverseAssetConverter library to 7.0.1115 to improve exporter. - Replace assimp with tinygltf for glTF import/export. - Refactoring stage structure to improve animation export. - Refactoring stage structure to support scene instancing. - Lots of improvement and bugfixes. ## [1.1.43] - 2021-12-01 ### Changed - Update OmniverseAssetConverter library to 7.0.1061 to rotation order issue of FBX import. - Add option to control pivots generation. - Use euler angles for rotation by default for FBX import. ## [1.1.42] - 2021-10-09 ### Changed - Update OmniverseAssetConverter library to 7.0.1041 to fix memory leak, and improve uv set import. ## [1.1.41] - 2021-10-08 ### Changed - Update OmniverseAssetConverter library to 7.0.1040 to fix opacity map export issue of FBX importer. ## [1.1.40] - 2021-10-06 ### Changed - Update OmniverseAssetConverter library to 7.0.1039 to improve exporter. ## [1.1.39] - 2021-09-30 ### Changed - Update initialization order to make sure format plugin loaded correctly. ## [1.1.38] - 2021-09-23 ### Changed - Update OmniverseAssetConverter library to 7.0.1024 to fix color space import of textures. ## [1.1.37] - 2021-09-22 ### Changed - Update OmniverseAssetConverter library to 7.0.1020 to improve exporter. - Supports to import/export glTF from/to UsdPreviewSurface and glTF MDL. - Supports to export USDZ to glTF. ## [1.1.36] - 2021-09-12 ### Changed - Update OmniverseAssetConverter library to 7.0.1012 to integrate latest glTF MDL to support transmission/sheen/texture transform extensions. ## [1.1.35] - 2021-09-07 ### Changed - Update OmniverseAssetConverter library to 7.0.1007 to use translate/orient/scale for transform to fix interpolation issues of animation samples of assimp importer. - Fix camera import of assimp importer. - Improve and fix rigid/skeletal animation import for glTF. ## [1.1.34] - 2021-09-03 ### Changed - Update OmniverseAssetConverter library to 7.0.1002 to fix crash caused by invalid memory access. ## [1.1.33] - 2021-09-03 ### Changed - Update OmniverseAssetConverter library to 7.0.999 to improve glTF import. - Fix material naming conflict for glTF import for USD exporter. - Fix tuple property set for material loader. ## [1.1.32] - 2021-09-01 ### Changed - Update OmniverseAssetConverter library to 7.0.989 to reduce artifacts size for linux. ## [1.1.31] - 2021-09-01 ### Changed - Update OmniverseAssetConverter library to 7.0.988 to fix linux build caused by DRACO symbol conflict between assimp and USD. ## [1.1.30] - 2021-08-30 ### Changed - Update OmniverseAssetConverter library to 7.0.984 to support import material as UsdPreviewSurface. - Enable support to import draco compressed meshes of glTF. ## [1.1.29] - 2021-08-09 ### Changed - Update OmniverseAssetConverter library to 7.0.962 to support export non-skinned skeleton. ## [1.1.28] - 2021-08-05 ### Changed - Update OmniverseAssetConverter library to 7.0.961 to fix camera animation issue. ## [1.1.27] - 2021-07-27 ### Changed - Update OmniverseAssetConverter library to 7.0.956 to check invalid mesh to avoid crash. ## [1.1.26] - 2021-07-22 ### Changed - Update AssetConverterContext to support a to_dict() function. ## [1.1.25] - 2021-07-10 ### Changed - Update OmniverseAssetConverter library to 7.0.950 for better glTF material import support. ## [1.1.24] - 2021-06-09 ### Fixes - Use copy on overwrite to avoid removing file firstly for files upload. ## [1.1.23] - 2021-06-07 ### Changed - Update OmniverseAssetConverter library to 7.0.943 to fix default prim issue of animation clip import. ## [1.1.22] - 2021-06-02 ### Changed - Add param for converter context to customize precision of USD transform op. ## [1.1.21] - 2021-06-02 ### Changed - Update OmniverseAssetConverter library to 7.0.942 for supporting customizing precision of USD transform op. ## [1.1.20] - 2021-05-25 ### Changed - Update OmniverseAssetConverter library to 7.0.941 for more glTF import improvement. ## [1.1.19] - 2021-05-10 ### Changed - Update OmniverseAssetConverter library to 7.0.933 to support pivot. ## [1.1.18] - 2021-05-07 ### Changed - Update OmniverseAssetConverter library to 7.0.928 to fix and improve glTF export. - Add glb import/export support. - Add embedding textures support for glTF/glb export support. ## [1.1.17] - 2021-05-06 ### Changed - Update OmniverseAssetConverter library to 7.0.925 to fix and improve glTF import. - Shorten library search path to mitigate long path issue. ### Fixes - Fix camera import and export issue. - Fix OmniPBR material export issue for FBX. ## [1.1.16] - 2021-05-05 ### Changed - Update assimp to latest. ### Fixes - Fix crash to import cameras from glTF. ## [1.1.15] - 2021-05-04 ### Changed - Update OmniverseAssetConverter library to 7.0.916 to provide WA for supporting pivots from FBX files. ## [1.1.14] - 2021-04-28 ### Changed - Update OmniverseAssetConverter library to 7.0.914 to include float type support and fix default/min/max issue of material loader. ## [1.1.13] - 2021-04-12 ### Fixes - Fix the crash to import FBX file that's over 2GB. ## [1.1.12] - 2021-03-30 ### Changed - Update extension icon. - Remove extension warning. ## [1.1.11] - 2021-03-29 ### Changed - Support to merge all static meshes if they are under the same transform and no skin meshes are there. ## [1.1.10] - 2021-03-24 ### Fixes - Fix anonymous USD export. - Fix crash of empty stage export to OBJ. ## [1.1.9] - 2021-03-24 ### Fixes - Fix texture populates for FBX that's referenced by property of texture object. ## [1.1.8] - 2021-03-23 ### Changed - Improve material export to display all material params for Kit editing. ## [1.1.7] - 2021-03-19 ### Changed - Shorten the length of native library path to avoid long path issue. ## [1.1.6] - 2021-03-06 ### Changed - Improve texture uploading to avoid those that are not referenced. ## [1.1.5] - 2021-03-05 ### Changed - Support to remove redundant materials that are not referenced by any meshes. ## [1.1.4] - 2021-02-20 ### Fixes - Fix issue that exports timesamples when it has no real transform animation. ## [1.1.3] - 2021-02-19 ### Fixes - More fixes to long path issue on windows. ## [1.1.2] - 2021-02-18 ### Fixes - Shorten the path length of native libraries to fix long path issue. ## [1.1.1] - 2021-02-16 ### Fixes - Fix obj export crash when there are no materials. ## [1.1.0] - 2021-02-15 ### Changed - Separate asset converter from Kit as standalone repo. ## [1.0.1] - 2021-01-26 ### Changed - Add animation export for FBX export. - Add options to support embedding textures for FBX export ### Fixes - Fix opacity map import/export for fbx. - Animation import fixes. ## [1.0.0] - 2021-01-19 ### Changed - Initial extension from original omni.kit.tool.asset_importer.
13,617
Markdown
32.624691
165
0.729823
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/docs/README.md
# Omniverse Asset Converter [omni.kit.asset_converter] This extension provides interfaces to convert common 3D formats, like, FBX, OBJ, GLTF, and etc, to USD and also supports to convert USD to those assets.
209
Markdown
51.499987
152
0.784689
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.kit.asset_converter-1.2.39+wx64.r.cp37/docs/index.rst
omni.kit.asset_converter ######################## Omniverse Asset Converter Introduction ============ This extension provides interfaces to convert common 3D formats, like, FBX, OBJ, GLTF, and etc, to USD and also supports to convert USD to those assets.
257
reStructuredText
27.666664
152
0.684825
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/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-extension-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,205
TOML
27.046511
105
0.740249
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.hello.world/omni/hello/world/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(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")
1,557
Python
34.40909
119
0.594733
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.hello.world/omni/hello/world/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.hello.world/omni/hello/world/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/omni.hello.world/omni/hello/world/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 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")
1,668
Python
34.510638
142
0.681055
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/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
parkerjgit/omniverse-sandbox/poc.extensions/adv-service/exts/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
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/docker-compose.yml
version: "3.9" services: ov-farm-connector: build: context: ./ dockerfile: dockerfile ports: - "8011:8011"
137
YAML
11.545453
28
0.562044
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/README.md
# *Omniverse Kit* Extensions Project Template This project is a template for developing extensions for *Omniverse Kit*. # Getting Started ## Install Omniverse and some Apps 1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download) 2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*. ## Add a new extension to your *Omniverse App* 1. Fork and clone this repo, for example in `C:\projects\kit-extension-template` 2. In the *Omniverse App* open extension manager: *Window* &rarr; *Extensions*. 3. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar. 4. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `exts` subfolder there as another search path: `C:\projects\kit-extension-template\exts` ![Extension Manager Window](/images/add-ext-search-path.png) 5. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it. 6. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload. ### Few tips * Now that `exts` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*. * Look at the *Console* window for warnings and errors. It also has a small button to open current log file. * All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`. * Extension name is a folder name in `exts` folder, in this example: `omni.hello.world`. * Most important thing extension has is a config file: `extension.toml`, take a peek. ## Next Steps: Alternative way to add a new extension To get a better understanding and learn a few other things, we recommend following next steps: 1. Remove search path added in the previous section. 1. Open this cloned repo using Visual Studio Code: `code C:\projects\kit-extension-template`. It will suggest installing a few extensions to improve python experience. 2. In the terminal (CTRL + \`) run `link_app.bat` (more in [Linking with an *Omniverse* app](#linking-with-an-omniverse-app) section). 3. Run this app with `exts` folder added as an extensions search path and new extension enabled: ```bash > app\omni.code.bat --ext-folder exts --enable omni.hello.world ``` - `--ext-folder [path]` - adds new folder to the search path - `--enable [extension]` - enables an extension on startup. Use `-h` for help: ```bash > app\omni.code.bat -h ``` 4. After the *App* started you should see: * new "My Window" window popup. * extension search paths in *Extensions* window as in the previous section. * extension enabled in the list of extensions. 5. If you look inside `omni.code.bat` or any other *Omniverse App*, they all run *Omniverse Kit* (`kit.exe`). *Omniverse Kit* is the Omniverse Application runtime that powers *Apps* build out of extensions. Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Code*: ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world ``` It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!): ```bash > app\kit\kit.exe --ext-folder exts --enable omni.hello.world --enable omni.kit.window.extensions ``` You should see a menu in the top left. From here you can enable more extensions from the UI. ### Few tips * In the *Extensions* window, press *Bread* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be: all extensions and dependencies. * Extensions system documentation: http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/extensions.html # Running Tests To run tests we run a new process where only the tested extension (and it's dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests: 1. Run: `app\kit\test_ext.bat omni.hello.world --ext-folder exts` That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code! 2. Alternatively, in *Extension Manager* (*Window &rarr; Extensions*) find your extension, click on *TESTS* tab, click *Run Test* For more information about testing refer to: [testing doc](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/ext_testing.html). # Linking with an *Omniverse* app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app create ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Adding a new extension Adding a new extension is as simple as copying and renaming existing one: 1. copy `exts/omni.hello.world` to `exts/[new extension name]` 2. rename python module (namespace) in `exts/[new extension name]/omni/hello/world` to `exts/[new extension name]/[new python module]` 3. update `exts/[new extension name]/config/extension.toml`, most importantly specify new python module to load: ```toml [[python.module]] name = "[new python module]" ``` No restart is needed, you should be able to find and enable `[new extension name]` in extension manager. # Sharing extensions To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). 1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery. 2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes. # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
6,864
Markdown
47.687943
318
0.750291
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/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
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/exts/poc.services.azure/config/extension.toml
[package] version = "1.0.0" authors = ["Josh Parker"] title = "poc services azure" description="A simple azure service" readme = "docs/README.md" changelog="docs/CHANGELOG.md" icon = "data/icon.png" [dependencies] "omni.services.core" = {} # Main python module this extension provides, it will be publicly available as "import poc.services.simple". [[python.module]] name = "poc.services.azure" # [python.pipapi] # archiveDirs = ["/usr/local/lib/python3.7/dist-packages/"] # use_online_index = false # requirements = [ # # "azure-storage-blob", # # "azure-data-tables", # ]
586
TOML
23.458332
108
0.691126
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/exts/poc.services.azure/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
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/exts/poc.services.azure/docs/README.md
# Python Extension Example [poc.services.simple] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
178
Markdown
34.799993
126
0.786517
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/exts/poc.services.azure/docs/index.rst
poc.services.simple ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"poc.services.simple" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
339
reStructuredText
15.190475
43
0.619469
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/exts/poc.services.azure/poc/services/azure/extension.py
import omni.ext from omni.services.core import main import sys for p in sys.path: print(p) from azure.storage.blob import BlobServiceClient from azure.data.tables import TableServiceClient # Paste in azure storage account connection string here ACCT_CONN_STR = "" def hello_azure_blob(): try: blob_service = BlobServiceClient.from_connection_string(ACCT_CONN_STR) print(f"hello azure blob: {blob_service.account_name}") return f"hello azure blob: {blob_service.account_name}" except ValueError as e: print("Connection string is invalid.") raise e except Exception as e: print("Failed to Connect to Azure Storage Account.") raise e def hello_azure_table(): try: table_service = TableServiceClient.from_connection_string(ACCT_CONN_STR) print(f"hello azure table: {table_service.account_name}") return f"hello azure table: {table_service.account_name}" except ValueError as e: print("Connection string is invalid.") raise e except Exception as e: print("Failed to Connect to Azure Storage Account.") raise e class PocServicesAzureExtension(omni.ext.IExt): def on_startup(self, ext_id): main.register_endpoint("get", "/hello_azure_blob", hello_azure_blob) main.register_endpoint("get", "/hello_azure_table", hello_azure_table) def on_shutdown(self): main.deregister_endpoint("get", "/hello_azure_blob") main.deregister_endpoint("get", "/hello_azure_table")
1,547
Python
30.591836
80
0.679379
parkerjgit/omniverse-sandbox/poc.extensions/azure-service/exts/poc.services.azure/poc/services/azure/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
parkerjgit/omniverse-sandbox/poc.extensions/simple-service/exts/poc.services.simple/config/extension.toml
[package] version = "1.0.0" authors = ["Josh Parker"] title = "poc services simple" description="A simple service extension" readme = "docs/README.md" changelog="docs/CHANGELOG.md" icon = "data/icon.png" [dependencies] "omni.services.core" = {} # Main python module this extension provides, it will be publicly available as "import poc.services.simple". [[python.module]] name = "poc.services.simple"
404
TOML
24.312498
108
0.730198
parkerjgit/omniverse-sandbox/poc.extensions/simple-service/exts/poc.services.simple/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
parkerjgit/omniverse-sandbox/poc.extensions/simple-service/exts/poc.services.simple/docs/README.md
# Python Extension Example [poc.services.simple] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
178
Markdown
34.799993
126
0.786517
parkerjgit/omniverse-sandbox/poc.extensions/simple-service/exts/poc.services.simple/docs/index.rst
poc.services.simple ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"poc.services.simple" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
339
reStructuredText
15.190475
43
0.619469
parkerjgit/omniverse-sandbox/poc.extensions/simple-service/exts/poc.services.simple/poc/services/simple/extension.py
import omni.ext from omni.services.core import main def hello_world(): return "hello super simple service!!" class PocServicesSimpleExtension(omni.ext.IExt): def on_startup(self, ext_id): main.register_endpoint("get", "/hello-world", hello_world) def on_shutdown(self): main.deregister_endpoint("get", "/hello-world")
350
Python
24.071427
66
0.694286