file_path
stringlengths 21
202
| content
stringlengths 12
1.02M
| size
int64 12
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 10
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/__init__.py | # NOTE: all imported classes must have different class names
from .extension import *
| 86 | Python | 27.999991 | 60 | 0.790698 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/ui_doc.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.
#
"""The documentation of the omni.ui aka UI Framework"""
from .abstract_model_doc import AbstractModelDoc
from .attribute_editor_demo import AttributeEditorWindow
from .canvas_frame_doc import CanvasFrameDoc
from .checkbox_doc import CheckBoxDoc
from .colorwidget_doc import ColorWidgetDoc
from .combobox_doc import ComboBoxDoc
from .custom_window_example import BrickSunStudyWindow
from .dnd_doc import DNDDoc
from .doc_page import DocPage
from .field_doc import FieldDoc
from .image_doc import ImageDoc
from .layout_doc import LayoutDoc
from .length_doc import LengthDoc
from .md_doc import MdDoc
from .menu_bar_doc import MenuBarDoc
from .menu_doc import MenuDoc
from .multifield_doc import MultiFieldDoc
from .plot_doc import PlotDoc
from .progressbar_doc import ProgressBarDoc
from .scrolling_frame_doc import ScrollingFrameDoc
from .shape_doc import ShapeDoc
from .slider_doc import SliderDoc
from .styling_doc import StylingDoc
from .treeview_doc import TreeViewDoc
from .widget_doc import WidgetDoc
from .window_doc import WindowDoc
from .workspace_doc import WorkspaceDoc
from omni.kit.documentation.builder import DocumentationBuilderWindow
from omni.kit.documentation.builder import DocumentationBuilderMd
from omni.ui import color as cl
from omni.ui import constant as fl
from pathlib import Path
import omni.kit.app as app
import omni.ui as ui
EXTENSION_NAME = "OMNI.UI Demo"
SPACING = 5
CURRENT_PATH = Path(__file__).parent
DOCS_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("docs")
MVD_PAGES = ["overview.md", "model.md", "delegate.md"]
class UIDoc(DocPage):
"""UI Doc Class"""
def __init__(self, extension_path):
super().__init__(extension_path)
self.omniverse_version, _, _ = app.get_app_interface().get_build_version().partition("-")
self.vertical_scrollbar_on = True
self._extension_path = extension_path
self._style_system = {
"Button": {
"background_color": 0xFFE1E1E1,
"border_color": 0xFFADADAD,
"border_width": 0.5,
"border_radius": 0.0,
"margin": 5.0,
"padding": 5.0,
},
"Button.Label": {"color": 0xFF000000},
"Button:hovered": {"background_color": 0xFFFBF1E5, "border_color": 0xFFD77800},
"Button:pressed": {"background_color": 0xFFF7E4CC, "border_color": 0xFF995400, "border_width": 1.0},
}
self._example_windows = {}
self._window_list = [["Attribute Editor", AttributeEditorWindow()], ["Custom Window", BrickSunStudyWindow()]]
self._mvd_pages = [DocumentationBuilderMd(DOCS_PATH.joinpath(filename)) for filename in MVD_PAGES]
self.index_list = [
["LAYOUT"],
[
"Arrangement of elements",
LayoutDoc(extension_path),
[
"HStack",
"VStack",
"ZStack",
"Spacing",
"Frame",
"VGrid",
"HGrid",
"CollapsableFrame",
"Placer",
"Visibility",
"Direction",
],
],
["Lengths", LengthDoc(extension_path), ["Pixel", "Percent", "Fraction"]],
["WIDGETS"],
["Styling", StylingDoc(extension_path), ["The Style Sheet Syntax", "Shades", "URL Shades", "Font Size"]],
[
"Base Widgets",
WidgetDoc(extension_path),
["Button", "RadioButton", "Label", "Tooltip", "Debug Color", "Font"],
],
["Menu", MenuDoc(extension_path), []],
["ScrollingFrame", ScrollingFrameDoc(extension_path), []],
["CanvasFrame", CanvasFrameDoc(extension_path), []],
["Image", ImageDoc(extension_path), []],
["CheckBox", CheckBoxDoc(extension_path), []],
["AbstractValueModel", AbstractModelDoc(extension_path), []],
["ComboBox", ComboBoxDoc(extension_path), []],
["ColorWidget", ColorWidgetDoc(extension_path), []],
["MultiField", MultiFieldDoc(extension_path), []],
["TreeView", TreeViewDoc(extension_path), []],
[
"Shapes",
ShapeDoc(extension_path),
["Rectangle", "Circle", "Triangle", "Line", "FreeRectangle", "FreeBezierCurve"],
],
["Fields", FieldDoc(extension_path), ["StringField"]],
["Sliders", SliderDoc(extension_path), ["FloatSlider", "IntSlider", "FloatDrag", "IntDrag"]],
["ProgressBar", ProgressBarDoc(extension_path), []],
["Plot", PlotDoc(extension_path), []],
["Drag and Drop", DNDDoc(extension_path), ["Minimal Example", "Styling and Tooltips"]],
]
# Add .md files here
self.index_list.append(["MODEL-DELEGATE-VIEW"])
for page in self._mvd_pages:
catalog = page.catalog
topic = catalog[0]["name"]
sub_topics = [c["name"] for c in catalog[0]["children"]]
self.index_list.append([topic, MdDoc(extension_path, page), sub_topics])
self.index_list += [
["WINDOWING SYSTEM"],
[
"Windows",
WindowDoc(extension_path),
["Window", "ToolBar", "Multiple Modal Windows", "Overlay Other Windows", "Workspace", "Popup"],
],
["MenuBar", MenuBarDoc(extension_path), ["MenuBar"]],
["Workspace", WorkspaceDoc(extension_path), ["Controlling Windows", "Capture Layout"]],
]
try:
# TODO(vyudin): can we remove?
import omni.kit.widget.webview
webview_enabled = True
except:
webview_enabled = False
if webview_enabled:
from .web_doc import WebViewWidgetDoc
web_view_widget_doc = WebViewWidgetDoc()
self.index_list += [
["WEB WIDGETS"],
["WebViewWidget", web_view_widget_doc, web_view_widget_doc.get_sections()],
]
def get_style(self):
cl.ui_docs_nvidia = cl("#76b900")
# Content
cl.ui_docs_bg = cl.white
cl.ui_docs_text = cl("#1a1a1a")
cl.ui_docs_h1_bg = cl.black
cl.ui_docs_code_bg = cl("#eeeeee")
cl.ui_docs_code_line = cl("#bbbbbb")
fl.ui_docs_code_radius = 2
fl.ui_docs_text_size = 18
# Catalog
cl.ui_docs_catalog_bg = cl.black
cl.ui_docs_catalog_hovered = cl("#1b1f20")
style = DocumentationBuilderWindow.get_style()
style.update({
"Button::placed:hovered": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2},
"CanvasFrame": {"background_color": 0xFFDDDDDD},
"Circle::blue": {"background_color": 0xFFFF1111, "border_color": 0xFF0000CC, "border_width": 2},
"Circle::default": {"background_color": 0xFF000000, "border_color": 0xFFFFFFFF, "border_width": 1},
"Circle::placed:pressed": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2},
"Circle::red": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2},
"Image::index_h2": {"color": 0xFF484849, "image_url": f"{self._extension_path}/icons/plus.svg"},
"Image::index_h2:selected": {"color": 0xFF5D5D5D, "image_url": f"{self._extension_path}/icons/minus.svg"},
"Image::omniverse_image": {"image_url": "resources/icons/ov_logo_square.png", "margin": 5},
"Label::caption": {"color": 0xFFFFFFFF, "font_size": 22.0, "margin_width": 10, "margin_height": 4},
"Label::code": {"color": cl.ui_docs_text},
"Label::index_h1": {
"color": cl.ui_docs_nvidia,
"font_size": 16.0,
"margin_height": 5,
"margin_width": 20,
},
"Label::index_h2": {"color": 0xFFD9D9D9, "font_size": 16.0, "margin_height": 5, "margin_width": 5},
"Label::index_h2:selected": {"color": 0xFF404040},
"Label::index_h3": {"color": 0xFF404040, "font_size": 16.0, "margin_height": 5, "margin_width": 30},
"Label::omniverse_version": {"font_size": 16.0, "color": 0xFF4D4D4D, "margin": 10},
"Label::section": {
"color": cl.ui_docs_nvidia,
"font_size": 22.0,
"margin_width": 10,
"margin_height": 4,
},
"Label::text": {"color": cl.ui_docs_text, "font_size": fl.ui_docs_text_size},
"Line::default": {"color": 0xFF000000, "border_width": 1},
"Line::demo": {"color": 0xFF555500, "border_width": 3},
"Line::separator": {"color": 0xFF111111, "border_width": 2},
"Line::underline": {"color": 0xFF444444, "border_width": 2},
"Rectangle::caption": {"background_color": cl.ui_docs_nvidia},
"Rectangle::code": {
"background_color": cl.ui_docs_code_bg,
"border_color": cl.ui_docs_code_line,
"border_width": 1.0,
"border_radius": fl.ui_docs_code_radius,
},
"Rectangle::placed:hovered": {
"background_color": 0xFFFF6E00,
"border_color": 0xFF111111,
"border_width": 2,
},
"Rectangle::section": {"background_color": cl.ui_docs_h1_bg},
"Rectangle::selection_h2": {"background_color": cl.ui_docs_catalog_bg},
"Rectangle::selection_h2:hovered": {"background_color": 0xFF4A4A4E},
"Rectangle::selection_h2:pressed": {"background_color": 0xFFB98029},
"Rectangle::selection_h2:selected": {"background_color": 0xFFFCFCFC},
"Rectangle::selection_h3": {"background_color": 0xFFE3E3E3},
"Rectangle::selection_h3:hovered": {"background_color": 0xFFD6D6D6},
"Rectangle::table": {"background_color": 0x0, "border_color": 0xFFCCCCCC, "border_width": 0.25},
"ScrollingFrame::canvas": {"background_color": cl.ui_docs_bg},
"Triangle::default": {"background_color": 0xFF00FF00, "border_color": 0xFFFFFFFF, "border_width": 1},
"Triangle::orientation": {"background_color": 0xFF444444, "border_color": 0xFFFFFFFF, "border_width": 3},
"VStack::layout": {"margin": 50},
"VStack::layout_md": {"margin": 1},
})
return style
def build_window(self, title):
"""Caled to load the extension"""
self._window = ui.Window(title, width=1000, height=600, dockPreference=ui.DockPreference.LEFT_BOTTOM)
# Populate UI once the window is visible
self._window.frame.set_build_fn(self.build_window_content)
# Dock it to the same space where Layers is docked
if ui.Workspace.get_window("Content"):
self._window.deferred_dock_in("Content")
def rebuild(self):
"""Rebuild all the content"""
self._window.frame.rebuild()
def build_window_content(self):
global_style = self.get_style()
with ui.HStack():
# Side panel with the table of contents
with ui.ScrollingFrame(
width=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.ZStack(height=0):
ui.Rectangle(style={"background_color": 0xFF313134})
with ui.VStack(style=global_style, height=0):
# Omniverse logo and version
with ui.ZStack():
ui.Rectangle(style={"background_color": 0xFF000000})
with ui.VStack(style=global_style, height=0):
ui.Image(height=250, alignment=ui.Alignment.CENTER, name="omniverse_image")
# Cut the end of the version. It's enough to print:
# "Omniverse Version: 103.0+master..."
text = f"Omniverse Version: {self.omniverse_version}"
if len(text) > 32:
text = text[:32] + "..."
ui.Label(
text,
alignment=ui.Alignment.CENTER,
name="omniverse_version",
tooltip=self.omniverse_version,
# elided_text=True,
content_clipping=True,
)
# The table of contents
with ui.VStack():
for entry in self.index_list:
if len(entry) == 1:
# If entry has nothing, it's a h1 title
ui.Label(entry[0], name="index_h1")
else:
# Otherwise it's h2 title and it has h3 subtitles
title = entry[0]
sub_titles = entry[2]
if len(entry) < 4:
entry.append(None)
entry.append(None)
# Draw h2 title
stack = ui.ZStack()
entry[3] = stack
with stack:
ui.Rectangle(
name="selection_h2",
mouse_pressed_fn=lambda x, y, b, a, e=entry: self.show_a_doc(e),
)
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack(width=0):
ui.Spacer()
ui.Image(name="index_h2", width=10, height=10)
ui.Spacer()
ui.Label(title, name="index_h2")
# Draw h3 titles, they appear only if h2 is selected
stack = ui.VStack(visible=False)
entry[4] = stack
with stack:
for sub in sub_titles:
with ui.ZStack():
ui.Rectangle(
name="selection_h3",
mouse_pressed_fn=lambda x, y, b, a, e=entry, n=sub: self.show_a_doc(
e, n
),
)
ui.Label(sub, name="index_h3")
ui.Label("WINDOW EXAMPLES", name="index_h1")
with ui.VStack():
for entry in self._window_list:
with ui.ZStack():
ui.Rectangle(
name="selection_h2",
mouse_pressed_fn=lambda x, y, b, a, n=entry[0], w=entry[1]: self._show_a_window(
n, w
),
)
with ui.HStack():
ui.Spacer(width=20)
ui.Label(entry[0], name="index_h2")
ui.Spacer(height=10)
# The document
if self.vertical_scrollbar_on:
vertical_scrollbar_policy = ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON
else:
vertical_scrollbar_policy = ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF
self._doc_scrolling_frame = ui.ScrollingFrame(
style=global_style,
name="canvas",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=vertical_scrollbar_policy,
)
self._add_all_docs()
def clean_entries(self):
"""Should be called when the extesion is reloaded to destroy the items, that can't be auto destroyed."""
for entry in self.index_list:
if len(entry) > 1 and entry[1]:
entry[1].clean()
def shutdown(self):
"""Should be called when the extesion us unloaded"""
# Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it
# automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But
# we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it
# will fire warning that texture is not destroyed.
for page in self._mvd_pages:
page.destroy()
self._mvd_pages = []
self.clean_entries()
self._window = None
def show_a_doc(self, entry, navigate_to=None):
""" show a single doc """
# Unselect/uncheck everything on the side panel
for index_entry in self.index_list:
if len(index_entry) == 5:
_, _, _, item, sub_items = index_entry
item.selected = False
sub_items.visible = False
self.clean_entries()
# Select and show the given title
_, doc, _, item, sub_items = entry
item.selected = True
sub_items.visible = True
if isinstance(doc, MdDoc):
style = "layout_md"
else:
style = "layout"
with self._doc_scrolling_frame: # The page itself
with ui.VStack(height=0, spacing=20, name=style):
doc.create_doc(navigate_to)
if not navigate_to:
# Scroll up if there is nothing to jump to because scrolling frame remembers the scrolling position of
# the previous page
self._doc_scrolling_frame.scroll_y = 0
def _show_a_window(self, name, window_class):
""" window an example window """
if name not in self._example_windows:
self._example_windows[name] = window_class.build_window()
self._example_windows[name].visible = True
def _add_all_docs(self):
"""The body of the document"""
self.clean_entries()
with self._doc_scrolling_frame: # The page itself
with ui.VStack(height=0, spacing=20, name="layout"):
self._section_title("What is Omni::UI?")
self._text(
"Omni::UI is Omniverse's UI toolkit for creating beautiful and flexible graphical user interfaces "
"in the Kit extensions. Omni::UI provides the basic types necessary to create rich extensions with "
"a fluid and dynamic user interface in Omniverse Kit. It gives a layout system and includes "
"widgets for creating visual components, receiving user input, and creating data models. It allows "
"user interface components to be built around their behavior and enables a declarative flavor of "
"describing the layout of the application. Omni::UI gives a very flexible styling system that "
"allows for deep customizing of the final look of the application."
)
for entry in self.index_list:
if len(entry) > 1 and entry[1] is not None:
entry[1].create_doc()
| 20,840 | Python | 46.151584 | 120 | 0.518042 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/workspace_doc.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.
#
"""The documentation for Workspaces"""
from omni import ui
from .doc_page import DocPage
import json
SPACING = 5
class WorkspaceDoc(DocPage):
"""document Workspace class"""
def _undock(self, selection):
if not selection:
return
for item in selection:
item.window.undock()
def _dock(self, left, right, position):
if not left or not right:
return
target = right[0].window
for item in left:
item.window.dock_in(target, position)
def _left(self, selection):
if not selection:
return
for item in selection:
item.window.position_x -= 100
def _right(self, selection):
if not selection:
return
for item in selection:
item.window.position_x += 100
def _set_visibility(self, selection, visible):
if not selection:
return
for item in selection:
if visible is not None:
item.window.visible = visible
else:
item.window.visible = not item.window.visible
def _dock_reorder(self, selection):
if not selection:
return
docking_groups = [ui.Workspace.get_docked_neighbours(item.window) for item in selection]
for group in docking_groups:
# Reverse order
for i, window in enumerate(reversed(group)):
window.dock_order = i
def _tabs(self, selection, visible):
if not selection:
return
for item in selection:
item.window.dock_tab_bar_visible = visible
def _focus(self, selection):
if not selection:
return
for item in selection:
item.window.focus()
break
def create_doc(self, navigate_to=None):
self._section_title("Workspace")
self._caption("Controlling Windows", navigate_to)
class WindowItem(ui.AbstractItem):
def __init__(self, window):
super().__init__()
# Don't keep the window because it prevents the window from closing.
self._window_title = window.title
self.title_model = ui.SimpleStringModel(self._window_title)
self.type_model = ui.SimpleStringModel(type(window).__name__)
@property
def window(self):
return ui.Workspace.get_window(self._window_title)
class WindowModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._root = ui.SimpleStringModel("Windows")
self.update()
def update(self):
self._children = [WindowItem(i) for i in ui.Workspace.get_windows()]
self._item_changed(None)
def get_item_children(self, item):
if item is not None:
return []
return self._children
def get_item_value_model_count(self, item):
return 2
def get_item_value_model(self, item, column_id):
if item is None:
return self._root
if column_id == 0:
return item.title_model
if column_id == 1:
return item.type_model
self._window_model = WindowModel()
self._tree_left = None
self._tree_right = None
with ui.VStack(style=self._style_system):
ui.Button("Refresh", clicked_fn=lambda: self._window_model.update())
with ui.HStack():
ui.Button("Clear", clicked_fn=ui.Workspace.clear)
ui.Button("Focus", clicked_fn=lambda: self._focus(self._tree_left.selection))
with ui.HStack():
ui.Button("Visibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, True))
ui.Button("Invisibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, False))
ui.Button("Toggle Visibility", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, None))
with ui.HStack():
ui.Button(
"Dock Right",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.RIGHT
),
)
ui.Button(
"Dock Left",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.LEFT
),
)
ui.Button(
"Dock Top",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.TOP
),
)
ui.Button(
"Dock Bottom",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.BOTTOM
),
)
ui.Button(
"Dock Same",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.SAME
),
)
ui.Button("Undock", clicked_fn=lambda: self._undock(self._tree_left.selection))
with ui.HStack():
ui.Button("Move Left", clicked_fn=lambda: self._left(self._tree_left.selection))
ui.Button("MoveRight", clicked_fn=lambda: self._right(self._tree_left.selection))
with ui.HStack():
ui.Button(
"Reverse Docking Tabs of Neighbours",
clicked_fn=lambda: self._dock_reorder(self._tree_left.selection),
)
ui.Button("Hide Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, False))
ui.Button("Show Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, True))
with ui.HStack(height=400):
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._tree_left = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80])
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._tree_right = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80])
self._caption("Capture Layout", navigate_to)
def generate(label):
dump = ui.Workspace.dump_workspace()
label.text = json.dumps(dump, sort_keys=True, indent=4)
def restore(label):
dump = label.text
ui.Workspace.restore_workspace(json.loads(dump))
with ui.HStack(style=self._style_system):
ui.Button("Generate", clicked_fn=lambda: generate(self._label))
ui.Button("Restore", clicked_fn=lambda: restore(self._label))
self._label = self._code("Press Generate to dump layout")
# some padding at the bottom
ui.Spacer(height=100)
| 8,098 | Python | 35.813636 | 120 | 0.551988 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/menu_bar_doc.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.
#
"""The documentation for the MenuBar"""
from omni import ui
from .doc_page import DocPage
SPACING = 5
class MenuBarDoc(DocPage):
""" document MenuBar classes"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._window_menu_example = None
def create_and_show_window_with_menu(self):
if not self._window_menu_example:
self._window_menu_example = ui.Window(
"Window Menu Example",
width=300,
height=300,
flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_BACKGROUND,
)
menu_bar = self._window_menu_example.menu_bar
with menu_bar:
with ui.Menu("File"):
ui.MenuItem("Load")
ui.MenuItem("Save")
ui.MenuItem("Export")
with ui.Menu("Window"):
ui.MenuItem("Hide")
with self._window_menu_example.frame:
with ui.VStack():
ui.Button("This Window has a Menu")
def show_hide_menu(menubar):
menubar.visible = not menubar.visible
ui.Button("Click here to show/hide Menu", clicked_fn=lambda m=menu_bar: show_hide_menu(m))
def add_menu(menubar):
with menubar:
with ui.Menu("New Menu"):
ui.MenuItem("I don't do anything")
ui.Button("Add New Menu", clicked_fn=lambda m=menu_bar: add_menu(m))
self._window_menu_example.visible = True
def create_doc(self, navigate_to=None):
self._section_title("MenuBar")
self._text(
"All the Windows in Omni.UI can have a MenuBar. To add a MenuBar to your window add this flag to your "
"constructor - omni.ui.Window(flags=ui.WINDOW_FLAGS_MENU_BAR). The MenuBar object can then be accessed "
"through the menu_bar read-only property on your window\n"
"A MenuBar is a container so it is built like a Frame or Stack but only takes Menu objects as children. "
"You can leverage the 'priority' property on the Menu to order them. They will automatically be sorted "
"when they are added, but if you change the priority of an item then you need to explicitly call sort()."
)
self._caption("MenuBar", navigate_to)
self._text("This class is used to construct a MenuBar for the Window")
with ui.HStack(width=0):
ui.Button("window with MenuBar Example", width=180, clicked_fn=self.create_and_show_window_with_menu)
ui.Label("this populates the menuBar", name="text", width=180, style={"margin_width": 10})
| 3,237 | Python | 41.051948 | 117 | 0.599629 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/checkbox_doc.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.
#
"""The documentation for CheckBox"""
from omni import ui
from .doc_page import DocPage
SPACING = 5
class CheckBoxDoc(DocPage):
""" document for CheckBox"""
def create_doc(self, navigate_to=None):
self._section_title("CheckBox")
self._text(
"A CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are "
"typically used to represent features in an application that can be enabled or disabled without affecting "
"others."
)
self._text(
"The checkbox is implemented using the model-delegate-view pattern. The model is the central component of this "
"system. It is the application's dynamic data structure independent of the widget. It directly manages the "
"data, logic, and rules of the checkbox. If the model is not specified, the simple one is created "
"automatically when the object is constructed."
)
self._text(
"In the following example, the models of two checkboxes are connected, and if one checkbox is changed, it "
"makes another checkbox be changed as well."
)
with ui.HStack(width=0, spacing=SPACING):
# Create two checkboxes
first = ui.CheckBox()
second = ui.CheckBox()
# Connect one to another
first.model.add_value_changed_fn(lambda a, b=second: b.model.set_value(not a.get_value_as_bool()))
second.model.add_value_changed_fn(lambda a, b=first: b.model.set_value(not a.get_value_as_bool()))
# Set the first one to True
first.model.set_value(True)
self._text("One of two")
self._code(
"""
# Create two checkboxes
first = ui.CheckBox()
second = ui.CheckBox()
# Connect one to another
first.model.add_value_changed_fn(
lambda a, b=second: b.model.set_value(not a.get_value_as_bool()))
second.model.add_value_changed_fn(
lambda a, b=first: b.model.set_value(not a.get_value_as_bool()))
"""
)
self._text("In the following example, that is a bit more complicated, only one checkbox can be enabled.")
with ui.HStack(width=0, spacing=SPACING):
# Create two checkboxes
first = ui.CheckBox()
second = ui.CheckBox()
third = ui.CheckBox()
def like_radio(model, first, second):
"""Turn on the model and turn off two checkboxes"""
if model.get_value_as_bool():
model.set_value(True)
first.model.set_value(False)
second.model.set_value(False)
# Connect one to another
first.model.add_value_changed_fn(lambda a, b=second, c=third: like_radio(a, b, c))
second.model.add_value_changed_fn(lambda a, b=first, c=third: like_radio(a, b, c))
third.model.add_value_changed_fn(lambda a, b=first, c=second: like_radio(a, b, c))
# Set the first one to True
first.model.set_value(True)
self._text("Almost like radio box")
self._code(
"""
# Create two checkboxes
first = ui.CheckBox()
second = ui.CheckBox()
third = ui.CheckBox()
def like_radio(model, first, second):
'''Turn on the model and turn off two checkboxes'''
if model.get_value_as_bool():
model.set_value(True)
first.model.set_value(False)
second.model.set_value(False)
# Connect one to another
first.model.add_value_changed_fn(
lambda a, b=second, c=third: like_radio(a, b, c))
second.model.add_value_changed_fn(
lambda a, b=first, c=third: like_radio(a, b, c))
third.model.add_value_changed_fn(
lambda a, b=first, c=second: like_radio(a, b, c))
"""
)
with ui.HStack(width=0, spacing=SPACING):
ui.CheckBox(enabled=False).model.set_value(True)
ui.CheckBox(enabled=False)
self._text("Disabled")
self._code(
"""
ui.CheckBox(enabled=False).model.set_value(True)
ui.CheckBox(enabled=False)
"""
)
ui.Spacer(height=10)
| 4,949 | Python | 36.786259 | 124 | 0.578299 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/combobox_doc.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.
#
"""The documentation for ComboBox"""
from omni import ui
from .doc_page import DocPage
class ComboBoxDoc(DocPage):
""" document for ComboBox"""
def create_doc(self, navigate_to=None):
self._section_title("ComboBox")
self._text("The ComboBox widget is a combined button and a drop-down list.")
self._text(
"A combo box is a selection widget that displays the current item and can pop up a list of selectable "
"items."
)
self._exec_code(
"""
ui.ComboBox(1, "Option 1", "Option 2", "Option 3")
"""
)
self._text("The following example demonstrates how to add items to the combo box.")
self._exec_code(
"""
editable_combo = ui.ComboBox()
ui.Button(
"Add item to combo",
clicked_fn=lambda m=editable_combo.model: m.append_child_item(
None, ui.SimpleStringModel("Hello World")),
)
"""
)
self._text("The minimal model implementation. It requires to hold the value models and reimplement two methods.")
self._exec_code(
"""
class MinimalItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = ui.SimpleStringModel(text)
class MinimalModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(
lambda a: self._item_changed(None))
self._items = [
MinimalItem(text)
for text in ["Option 1", "Option 2"]
]
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
self._minimal_model = MinimalModel()
ui.ComboBox(self._minimal_model, style={"font_size": 22})
"""
)
self._text(
"The example of communication between widgets. Type anything in the field and it will appear in the combo "
"box."
)
self._exec_code(
"""
editable_combo = None
class StringModel(ui.SimpleStringModel):
'''
String Model activated when editing is finished.
Adds item to combo box.
'''
def __init__(self):
super().__init__("")
def end_edit(self):
combo_model = editable_combo.model
# Get all the options ad list of strings
all_options = [
combo_model.get_item_value_model(child).as_string
for child in combo_model.get_item_children()
]
# Get the current string of this model
fieldString = self.as_string
if fieldString:
if fieldString in all_options:
index = all_options.index(fieldString)
else:
# It's a new string in the combo box
combo_model.append_child_item(
None,
ui.SimpleStringModel(fieldString)
)
index = len(all_options)
combo_model.get_item_value_model().set_value(index)
self._field_model = StringModel()
def combo_changed(combo_model, item):
all_options = [
combo_model.get_item_value_model(child).as_string
for child in combo_model.get_item_children()
]
current_index = combo_model.get_item_value_model().as_int
self._field_model.as_string = all_options[current_index]
with ui.HStack():
ui.StringField(self._field_model)
editable_combo = ui.ComboBox(width=0, arrow_only=True)
editable_combo.model.add_item_changed_fn(combo_changed)
"""
)
ui.Spacer(height=10)
# TODO omni.ui: restore functionality for Kit Next
if True:
return
self._text("The USD example. It tracks the stage cameras and can assign the current camera.")
self._exec_code(
"""
class CamerasItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
class CamerasModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
# Omniverse interfaces
self._viewport = omni.kit.viewport.utility.get_active_viewport()
self._stage_update = \\
omni.stageupdate.get_stage_update_interface()
self._usd_context = omni.usd.get_context()
self._stage_subscription = \\
self._stage_update.create_stage_update_node(
"CamerasModel",
None,
None,
None,
self._on_prim_created,
None,
self._on_prim_removed
)
# The list of the cameras is here
self._cameras = []
# The current index of the editable_combo box
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(
self._current_index_changed)
# Iterate the stage and get all the cameras
stage = self._usd_context.get_stage()
for prim in Usd.PrimRange(stage.GetPseudoRoot()):
if prim.IsA(UsdGeom.Camera):
self._cameras.append(
CamerasItem(
ui.SimpleStringModel(
prim.GetPath().pathString)))
def get_item_children(self, item):
return self._cameras
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def _on_prim_created(self, path):
self._cameras.append(
CamerasItem(ui.SimpleStringModel(path)))
self._item_changed(None)
def _on_prim_removed(self, path):
cameras = [cam.model.as_string for cam in self._cameras]
if path in cameras:
index = cameras.index(path)
del self._cameras[index]
self._current_index.as_int = 0
self._item_changed(None)
def _current_index_changed(self, model):
index = model.as_int
self.self._viewport.camera_path = self._cameras[index].model.as_string
self._item_changed(None)
self._combo_model = CamerasModel()
ui.ComboBox(self._combo_model)
"""
)
| 7,786 | Python | 34.076576 | 121 | 0.509504 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/slider_doc.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.
#
"""The documentation for Sliders"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import re
SPACING = 5
class SliderDoc(DocPage):
""" document for Slider"""
def create_doc(self, navigate_to=None):
self._section_title("Drag & Slider")
self._text(
"There are 2 main kind of Sliders, <Type>Slider and <Type>Drag. The Sliders are more like traditionalal "
"slider that can be drag and snap where you click, the value can be shown on the slider or not but can not "
"be edited directly by double clicking"
)
self._text(
"The Drags are more like Field in the way that they behave like a Field, you can double clic to edit the "
"value but they also have a mean to be 'Dragged' to increase / decrease the value"
)
self._text(
"They currently support minimal styling, simple background color (background_color) and text color (color)."
)
self._caption("FloatSlider", navigate_to)
def build_slider_table(label, slider_command):
def mystrip(line: str, number: int) -> str:
"""Remove `number` spaces from the begin of the line"""
n = 0
l = len(line)
while n < number and n < l and line[n] == " ":
n += 1
return line[n:]
# Remove whitespaces from the command but keep the newline symbols
code = "\n".join(mystrip(line, 16) for line in slider_command.split("\n") if line)
with ui.HStack():
with ui.ZStack(width=130):
ui.Rectangle(name="table")
ui.Label(label, name="text", alignment=ui.Alignment.RIGHT, style={"margin": SPACING})
with ui.ZStack():
ui.Rectangle(name="table")
with ui.HStack(name="margin", style={"HStack::margin": {"margin": SPACING / 2}}, spacing=SPACING):
exec(code)
with ui.ZStack(width=ui.Fraction(2)):
ui.Rectangle(name="table")
with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING / 2}}):
ui.Rectangle(name="code")
ui.Label(code, name="code")
with ui.VStack():
build_slider_table(
"Default",
"""
ui.FloatSlider()
""",
)
build_slider_table(
"Min/Max",
"""
ui.FloatSlider(min=0, max=10)
""",
)
build_slider_table(
"Hard Min/Max",
"""
model = ui.SimpleFloatModel(1.0, min=0, max=100)
ui.FloatSlider(model, min=0, max=10)
""",
)
build_slider_table(
"With Style",
"""
ui.FloatSlider(
min=-180,
max=180,
style={
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl("#BBBBBB"),
"color": cl.black
}
)
""",
)
build_slider_table(
"Transparent bg",
"""
ui.FloatSlider(
min=-180,
max=180,
style={
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl.transparent,
"color": cl.black,
"font_size":20.0
}
)
""",
)
build_slider_table(
"different slider color",
"""
ui.FloatSlider(
min=0,
max=1,
style={
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl.transparent,
"color": cl.black,
"font_size":20.0,
"secondary_color": cl.red,
"secondary_selected_color": cl("#FF00FF")
}
)
""",
)
build_slider_table(
"Field & Slider",
"""
field = ui.FloatField(height=15, width=50)
ui.FloatSlider(
min=0,
max=20,
step=.1,
model=field.model,
style={"color":cl.transparent}
)
# default value
field.model.set_value(12.0)
""",
)
build_slider_table(
"Filled Mode Slider",
"""
ui.FloatSlider(
height=20,
style={"background_color": cl("#DDDDDD"),
"secondary_color": cl("#AAAAAA"),
"color": cl("#111111")}
).model.set_value(0.5)
""",
)
build_slider_table(
"Rounded Slider",
"""
ui.FloatSlider(
height=20,
style={"border_radius": 20,
"background_color": cl.black,
"secondary_color": cl("#DDDDDD"),
"color": cl("#AAAAAA")}
).model.set_value(0.5)
""",
)
build_slider_table(
"Slider Step",
"""
slider = ui.FloatSlider(
step=0.25,
height=0,
style={"border_radius": 20,
"background_color": cl.black,
"secondary_color": cl("#DDDDDD"),
"color": cl("#AAAAAA")})
slider.model.set_value(0.5)
""",
)
build_slider_table(
"Handle Step",
"""
slider = ui.FloatSlider(
step=0.2,
height=0,
style={"draw_mode": ui.SliderDrawMode.HANDLE})
slider.model.set_value(0.4)
""",
)
self._caption("IntSlider", navigate_to)
with ui.VStack():
build_slider_table(
"Default",
"""
ui.IntSlider()
""",
)
build_slider_table(
"Min/Max",
"""
ui.IntSlider(min=0, max=20)
""",
)
build_slider_table(
"With Style",
"""
ui.IntSlider(
min=0,
max=20,
style={
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl("#BBFFBB"),
"color": cl("#FF00FF"),
"font_size": 14.0
}
)
""",
)
self._caption("FloatDrag", navigate_to)
with ui.VStack():
build_slider_table("Default", "ui.FloatDrag()")
build_slider_table("Min/Max", "ui.FloatDrag(min=-10, max=10, step=0.01)")
self._caption("IntDrag", navigate_to)
with ui.VStack():
build_slider_table("Default", "ui.IntDrag()")
build_slider_table("Min/Max", "ui.IntDrag(min=0, max=50)")
ui.Spacer(height=10)
| 8,360 | Python | 33.407407 | 120 | 0.417105 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/length_doc.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.
#
"""The documentation for Length"""
from omni import ui
from .doc_page import DocPage
SPACING = 5
class LengthDoc(DocPage):
""" document for Length classes"""
def create_doc(self, navigate_to=None):
self._section_title("Lengths")
self._text(
"The Framework UI offers several different units for expressing length: Pixel, Percent and Fraction."
)
self._text("There is no restriction on which units can be used where.")
self._caption("Pixel", navigate_to)
self._text("Pixel is the size in pixels and scaled with the HiDPI scale factor.")
with ui.HStack():
ui.Button("40px", width=ui.Pixel(40))
ui.Button("60px", width=ui.Pixel(60))
ui.Button("100px", width=100)
ui.Button("120px", width=120)
ui.Button("150px", width=150)
self._code(
"""
with ui.HStack():
ui.Button("40px", width=ui.Pixel(40))
ui.Button("60px", width=ui.Pixel(60))
ui.Button("100px", width=100)
ui.Button("120px", width=120)
ui.Button("150px", width=150)
"""
)
self._caption("Percent", navigate_to)
self._text("Percent and Fraction units make it possible to specify sizes relative to the parent size.")
self._text("Percent is 1/100th of the parent size.")
with ui.HStack():
ui.Button("5%", width=ui.Percent(5))
ui.Button("10%", width=ui.Percent(10))
ui.Button("15%", width=ui.Percent(15))
ui.Button("20%", width=ui.Percent(20))
ui.Button("25%", width=ui.Percent(25))
self._code(
"""
with ui.HStack():
ui.Button("5%", width=ui.Percent(5))
ui.Button("10%", width=ui.Percent(10))
ui.Button("15%", width=ui.Percent(15))
ui.Button("20%", width=ui.Percent(20))
ui.Button("25%", width=ui.Percent(25))
"""
)
self._caption("Fraction", navigate_to)
self._text(
"Fraction length is made to take the available space of the parent widget and then divide it among all the "
"child widgets with Fraction length in proportion to their Fraction factor."
)
with ui.HStack():
ui.Button("One", width=ui.Fraction(1))
ui.Button("Two", width=ui.Fraction(2))
ui.Button("Three", width=ui.Fraction(3))
ui.Button("Four", width=ui.Fraction(4))
ui.Button("Five", width=ui.Fraction(5))
self._code(
"""
with ui.HStack():
ui.Button("One", width=ui.Fraction(1))
ui.Button("Two", width=ui.Fraction(2))
ui.Button("Three", width=ui.Fraction(3))
ui.Button("Four", width=ui.Fraction(4))
ui.Button("Five", width=ui.Fraction(5))
"""
)
ui.Spacer(height=10)
| 3,405 | Python | 34.479166 | 120 | 0.576799 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/shape_doc.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.
#
"""The documentation for Shapes"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import inspect
SPACING = 5
def editable_curve():
with ui.ZStack(height=400):
# The Bezier tangents
tangents = [(50, 50), (-50, -50)]
# Four draggable rectangles that represent the control points
placer1 = ui.Placer(draggable=True, offset_x=0, offset_y=0)
with placer1:
rect1 = ui.Rectangle(width=20, height=20)
placer2 = ui.Placer(draggable=True, offset_x=50, offset_y=50)
with placer2:
rect2 = ui.Rectangle(width=20, height=20)
placer3 = ui.Placer(draggable=True, offset_x=100, offset_y=100)
with placer3:
rect3 = ui.Rectangle(width=20, height=20)
placer4 = ui.Placer(draggable=True, offset_x=150, offset_y=150)
with placer4:
rect4 = ui.Rectangle(width=20, height=20)
# The bezier curve
curve = ui.FreeBezierCurve(rect1, rect4)
curve.start_tangent_width = ui.Pixel(tangents[0][0])
curve.start_tangent_height = ui.Pixel(tangents[0][1])
curve.end_tangent_width = ui.Pixel(tangents[1][0])
curve.end_tangent_height = ui.Pixel(tangents[1][1])
# The logic of moving the control points
def left_moved(_):
x = placer1.offset_x
y = placer1.offset_y
tangent = tangents[0]
placer2.offset_x = x + tangent[0]
placer2.offset_y = y + tangent[1]
def right_moved(_):
x = placer4.offset_x
y = placer4.offset_y
tangent = tangents[1]
placer3.offset_x = x + tangent[0]
placer3.offset_y = y + tangent[1]
def left_tangent_moved(_):
x1 = placer1.offset_x
y1 = placer1.offset_y
x2 = placer2.offset_x
y2 = placer2.offset_y
tangent = (x2 - x1, y2 - y1)
tangents[0] = tangent
curve.start_tangent_width = ui.Pixel(tangent[0])
curve.start_tangent_height = ui.Pixel(tangent[1])
def right_tangent_moved(_):
x1 = placer4.offset_x
y1 = placer4.offset_y
x2 = placer3.offset_x
y2 = placer3.offset_y
tangent = (x2 - x1, y2 - y1)
tangents[1] = tangent
curve.end_tangent_width = ui.Pixel(tangent[0])
curve.end_tangent_height = ui.Pixel(tangent[1])
# Callback for moving the control points
placer1.set_offset_x_changed_fn(left_moved)
placer1.set_offset_y_changed_fn(left_moved)
placer2.set_offset_x_changed_fn(left_tangent_moved)
placer2.set_offset_y_changed_fn(left_tangent_moved)
placer3.set_offset_x_changed_fn(right_tangent_moved)
placer3.set_offset_y_changed_fn(right_tangent_moved)
placer4.set_offset_x_changed_fn(right_moved)
placer4.set_offset_y_changed_fn(right_moved)
def editable_rect():
with ui.ZStack(height=200):
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Circle(width=10, height=10, name="default")
with ui.Placer(draggable=True, offset_x=150, offset_y=150):
control2 = ui.Circle(width=10, height=10, name="default")
# The rectangle that fits to the control points
ui.FreeRectangle(control1, control2)
class ShapeDoc(DocPage):
""" document for Shapes"""
def create_doc(self, navigate_to=None):
""" descriptions for the shapes widgets"""
self._section_title("Shape")
self._text("Shape enable you to build custom widget with specific look")
self._text("There are many shape you can use, Rectangle, Circle, Triangle, Line, etc")
self._text(
"In most case those Shape will fit into the Widget size and scale accoringly to the layout they are in "
"For some of them you can fix the size to enable to have more precise control over they size"
)
self._caption("Rectangle", navigate_to)
self._text(
"You can use Rectable to draw rectangle shape, you can have backgroundColor, borderColor, "
"borderWidth, border_radius. mixed it with other controls using ZStack to create advance look"
)
with ui.VStack():
self._shape_table(f"""ui.Rectangle(name="default")""", "(Default) The rectangle is scaled to fit")
self._shape_table(
"""ui.Rectangle(
style={"background_color": cl("#888888"),
"border_color": cl("#222222"),
"border_width": 2.0,
"border_radius": 5.0} )""",
"this rectangle use its own style to control colors and shape",
)
self._shape_table(
"""ui.Rectangle( width=20, height=20,
style={"background_color": cl("#888888"),
"border_color": cl("#222222")} )""",
"using fixed width and height",
)
self._shape_table(
"""with ui.ZStack(height=20):
ui.Rectangle(height=20,
style={"background_color": cl("#888888"),
"border_color": cl("#111111"),
"border_width": .5,
"border_radius": 8.0} )
with ui.HStack():
ui.Spacer(width=10)
ui.Image(
"resources/icons/Cloud.png",
width=20,
height=20
)
ui.Label(
"Search Field",
style={"color": cl("#DDDDDD")}
)""",
"Compose with ZStack for advanced control",
)
self._text("Support for specific Rounded Corner")
corner_flags = {
"NONE": ui.CornerFlag.NONE,
"TOP_LEFT": ui.CornerFlag.TOP_LEFT,
"TOP_RIGHT": ui.CornerFlag.TOP_RIGHT,
"BOTTOM_LEFT": ui.CornerFlag.BOTTOM_LEFT,
"BOTTOM_RIGHT": ui.CornerFlag.BOTTOM_RIGHT,
"TOP": ui.CornerFlag.TOP,
"BOTTOM": ui.CornerFlag.BOTTOM,
"LEFT": ui.CornerFlag.LEFT,
"RIGHT": ui.CornerFlag.RIGHT,
"ALL": ui.CornerFlag.ALL,
}
with ui.ScrollingFrame(
height=100,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in corner_flags.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": SPACING * 2}}):
ui.Rectangle(
style={"background_color": cl("#AA4444"), "border_radius": 20.0, "corner_flag": value}
)
ui.Spacer(height=10)
ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER)
self._caption("Circle", navigate_to)
self._text("You can use Circle to draw circular shape, you can have backgroundColor, borderColor, borderWidth")
with ui.VStack():
self._shape_table(
f"""ui.Circle(name="default")""", "(Default) The circle is scaled to fit, the alignment is centered"
)
self._shape_table(
f"""ui.Circle(name="default")""", "This circle, is scaled to Fit too with the Row 100 height", 100
)
self._shape_table(
f"""ui.Circle(
name="blue",
radius=20,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.LEFT_CENTER)""",
"This circle has a fixed radius of 20, the alignment is LEFT_CENTER",
)
self._shape_table(
f"""ui.Circle(
name="red",
radius=10,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.RIGHT_CENTER)""",
"This circle has a fixed radius of 10, the alignment is RIGHT_CENTER",
)
self._shape_table(
"""ui.Circle(
style={"background_color": cl("#00FFFF"),},
size_policy=ui.CircleSizePolicy.STRETCH,
alignment=ui.Alignment.CENTER_TOP)""",
"This circle has a radius to fill the bound, with an alignment is CENTER_TOP",
)
self._shape_table(
"""ui.Circle(
style={"background_color": cl.green,
"border_color": cl.blue,
"border_width": 5},
radius=10,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.CENTER_BOTTOM)""",
"This circle has a fixed radius of 5, the alignment is CENTER_BOTTOM, and a custom style ",
)
self._text("Supported Alignment value for the Circle")
alignments = {
"CENTER": ui.Alignment.CENTER,
"LEFT_TOP": ui.Alignment.LEFT_TOP,
"LEFT_CENTER": ui.Alignment.LEFT_CENTER,
"LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM,
"CENTER_TOP": ui.Alignment.CENTER_TOP,
"CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM,
"RIGHT_TOP": ui.Alignment.RIGHT_TOP,
"RIGHT_CENTER": ui.Alignment.RIGHT_CENTER,
"RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM,
}
with ui.ScrollingFrame(
height=150,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2):
with ui.ZStack():
ui.Rectangle(name="table")
ui.Circle(
radius=10,
size_policy=ui.CircleSizePolicy.FIXED,
name="orientation",
alignment=value,
style={"background_color": cl("#AA4444")},
)
ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER)
self._caption("Triangle", navigate_to)
self._text(
"You can use Triangle to draw Triangle shape, you can have backgroundColor, borderColor, borderWidth"
)
with ui.VStack():
self._shape_table(
f"""ui.Triangle(name="default")""",
"(Default) The triange is scaled to fit, base on the left and tip on the center right",
100,
)
self._shape_table(
"""ui.Triangle(
style={"border_color": cl.black,
"border_width": 2},
alignment=ui.Alignment.CENTER_TOP)""",
"Default triange with custom color and border",
100,
)
self._text("the Alignment define where is the Tip of the Triangle, base will be at the oposite side")
alignments = {
"LEFT_TOP": ui.Alignment.LEFT_TOP,
"LEFT_CENTER": ui.Alignment.LEFT_CENTER,
"LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM,
"CENTER_TOP": ui.Alignment.CENTER_TOP,
"CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM,
"RIGHT_TOP": ui.Alignment.RIGHT_TOP,
"RIGHT_CENTER": ui.Alignment.RIGHT_CENTER,
"RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM,
}
colors = [cl.red, cl("#FFFF00"), cl("#FF00FF"), cl("#FF0FF0"), cl.green, cl("#F00FFF"), cl("#FFF000"), cl("#AA3333")]
index = 0
with ui.ScrollingFrame(
height=100,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2):
color = colors[index]
index = index + 1
ui.Triangle(name="orientation", alignment=value, style={"background_color": color})
ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER)
self._caption("Line", navigate_to)
self._text("You can use Line to draw Line shape, you can use color, border_width")
with ui.VStack():
self._shape_table(
f"""ui.Line(name="default")""",
"(Default) The Line is scaled to fit, base on the left and tip on the center right",
100,
)
self._shape_table(
"""ui.Line(name="default",
alignment=ui.Alignment.H_CENTER,
style={"border_width":1, "color": cl.blue})""",
"The Line is scaled to fit, centered top to bottom, color red and line width 1",
100,
)
self._shape_table(
"""ui.Line(name="default",
alignment=ui.Alignment.LEFT,
style={"border_width":5, "color": cl("#880088")})""",
"The Line is scaled to fit, Aligned Left , color purple and line width 5",
100,
)
self._text("the Alignment define where is the line is in the Widget, always fit")
alignments = {
"LEFT": ui.Alignment.LEFT,
"RIGHT": ui.Alignment.RIGHT,
"H_CENTER": ui.Alignment.H_CENTER,
"TOP": ui.Alignment.TOP,
"BOTTOM": ui.Alignment.BOTTOM,
"V_CENTER": ui.Alignment.V_CENTER,
}
with ui.ScrollingFrame(
height=100,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack(height=100):
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2):
ui.Line(name="demo", alignment=value)
ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER)
self._caption("FreeRectangle", navigate_to)
self._text(
"The free widget is the widget that is independent of the layout. It means it can be stuck to other "
"widgets."
)
editable_rect()
self._code(inspect.getsource(editable_rect).split("\n", 1)[-1])
self._caption("FreeBezierCurve", navigate_to)
self._text("Bezier curves are used to model smooth curves that can be scaled infinitely.")
self._text(
"FreeBezierCurve is using two widgets to get the position of the curve ends. It means it's possible to "
"stick the curve to the layout's widgets, and the curve will follow the changes of the layout "
"automatically."
)
editable_curve()
self._code(inspect.getsource(editable_curve).split("\n", 1)[-1])
ui.Spacer(height=10)
| 16,893 | Python | 41.661616 | 125 | 0.524063 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/scrolling_frame_doc.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.
#
"""The documentation for Scrolling Frame"""
from omni import ui
from .doc_page import DocPage
SPACING = 5
class ScrollingFrameDoc(DocPage):
""" document for Menu"""
def create_doc(self, navigate_to=None):
self._section_title("ScrollingFrame")
self._text(
"The ScrollingFrame class provides the ability to scroll onto another widget. ScrollingFrame is used to "
"display the contents of a child widget within a frame. If the widget exceeds the size of the frame, the "
"frame can provide scroll bars so that the entire area of the child widget can be viewed."
)
with ui.HStack(style=self._style_system):
left_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with left_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Left {i}")
right_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with right_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Right {i}")
# Synchronize the scroll position of two frames
def set_scroll_y(frame, y):
frame.scroll_y = y
left_frame.set_scroll_y_changed_fn(lambda y, frame=right_frame: set_scroll_y(frame, y))
right_frame.set_scroll_y_changed_fn(lambda y, frame=left_frame: set_scroll_y(frame, y))
self._code(
"""
with ui.HStack(style=style_system):
left_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with left_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Left {i}")
right_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with right_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Right {i}")
# Synchronize the scroll position of two frames
def set_scroll_y(frame, y):
frame.scroll_y = y
left_frame.set_scroll_y_changed_fn(
lambda y, frame=right_frame: set_scroll_y(frame, y))
right_frame.set_scroll_y_changed_fn(
lambda y, frame=left_frame: set_scroll_y(frame, y)
"""
)
ui.Spacer(height=10)
| 3,595 | Python | 38.086956 | 118 | 0.596106 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/treeview_doc.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.
#
"""The documentation for Widget"""
from .doc_page import DocPage
from pathlib import Path
import asyncio
import omni.ui as ui
import time
class TreeViewDoc(DocPage):
"""Document for TreeView"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._selection = None
self._model = None
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
# Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it
# automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But
# we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it
# will fire warning that texture is not destroyed.
if self._selection:
self._selection._stage_event_sub = None
self._selection._tree_view = None
self._selection = None
if self._model:
self._model.stage_subscription = None
self._model = None
self._command_model = None
self._list_model = None
self._name_value_model = None
self._name_value_delegate = None
def create_doc(self, navigate_to=None):
self._section_title("TreeView")
self._text(
"TreeView is a widget that presents a hierarchical view of information. Each item can have a number of "
"subitems. An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if "
"any exist, and collapsed to hide subitems."
)
self._text(
"TreeView can be used in file manager applications, where it allows the user to navigate the file system "
"directories. They are also used to present hierarchical data, such as the scene object hierarchy."
)
self._text(
"TreeView uses a model-delegate-view pattern to manage the relationship between data and the way it is presented. "
"The separation of functionality gives developers greater flexibility to customize the presentation of "
"items and provides a standard interface to allow a wide range of data sources to be used with other "
"widgets."
)
self._text("The following example demonstrates how to make a single level tree appear like a simple list.")
class CommandItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
class CommandModel(ui.AbstractItemModel):
"""
Represents the list of commands registered in Kit.
It is used to make a single level tree appear like a simple list.
"""
def __init__(self):
super().__init__()
self._commands = []
try:
import omni.kit.commands
except ModuleNotFoundError:
return
omni.kit.commands.subscribe_on_change(self._commands_changed)
self._commands_changed()
def _commands_changed(self):
"""Called by subscribe_on_change"""
self._commands = []
import omni.kit.commands
for cmd_list in omni.kit.commands.get_commands().values():
for k in cmd_list.values():
self._commands.append(CommandItem(k.__name__))
self._item_changed(None)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._commands
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
if item and isinstance(item, CommandItem):
return item.name_model
with ui.ScrollingFrame(
height=400,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._command_model = CommandModel()
tree_view = ui.TreeView(
self._command_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}
)
self._text("The following example demonstrates reordering with drag and drop.")
class ListItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
def __repr__(self):
return f'"{self.name_model.as_string}"'
class ListModel(ui.AbstractItemModel):
"""
Represents the model for lists. It's very easy to initialize it
with any string list:
string_list = ["Hello", "World"]
model = ListModel(*string_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
self._children = [ListItem(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
class ListModelWithReordering(ListModel):
"""
Represents the model for the list with the ability to reorder the
list with drag and drop.
"""
def __init__(self, *args):
super().__init__(*args)
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
# As we don't do Drag and Drop to the operating system, we return the string.
return item.name_model.as_string
def drop_accepted(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called to highlight target when drag and drop."""
# If target_item is None, it's the drop to root. Since it's
# list model, we support reorganizetion of root only and we
# don't want to create tree.
return not target_item and drop_location >= 0
def drop(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called when dropping something to the item."""
try:
source_id = self._children.index(source)
except ValueError:
# Not in the list. This is the source from another model.
return
if source_id == drop_location:
# Nothing to do
return
self._children.remove(source)
if drop_location > len(self._children):
# Drop it to the end
self._children.append(source)
else:
if source_id < drop_location:
# Becase when we removed source, the array became shorter
drop_location = drop_location - 1
self._children.insert(drop_location, source)
self._item_changed(None)
with ui.ScrollingFrame(
height=400,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._list_model = ListModelWithReordering("Simplest", "List", "Model", "With", "Reordering")
tree_view = ui.TreeView(
self._list_model,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
drop_between_items=True,
)
self._text("The following example demonstrates the ability to edit TreeView items.")
class FloatModel(ui.AbstractValueModel):
"""An example of custom float model that can be used for formatted string output"""
def __init__(self, value: float):
super().__init__()
self._value = value
def get_value_as_float(self):
"""Reimplemented get float"""
return self._value or 0.0
def get_value_as_string(self):
"""Reimplemented get string"""
# This string gors to the field.
if self._value is None:
return ""
# General format. This prints the number as a fixed-point
# number, unless the number is too large, in which case it
# switches to 'e' exponent notation.
return "{0:g}".format(self._value)
def set_value(self, value):
"""Reimplemented set"""
try:
value = float(value)
except ValueError:
value = None
if value != self._value:
# Tell the widget that the model is changed
self._value = value
self._value_changed()
class NameValueItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text, value):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.value_model = FloatModel(value)
def __repr__(self):
return f'"{self.name_model.as_string} {self.value_model.as_string}"'
class NameValueModel(ui.AbstractItemModel):
"""
Represents the model for name-value table. It's very easy to initialize it
with any string-float list:
my_list = ["Hello", 1.0, "World", 2.0]
model = NameValueModel(*my_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
# ["Hello", 1.0, "World", 2.0"] -> [("Hello", 1.0), ("World", 2.0)]
regrouped = zip(*(iter(args),) * 2)
self._children = [NameValueItem(*t) for t in regrouped]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 2
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel for the first column
and SimpleFloatModel for the second column.
"""
return item.value_model if column_id == 1 else item.name_model
class EditableDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def __init__(self):
super().__init__()
self.subscription = None
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
stack = ui.ZStack(height=20)
with stack:
value_model = model.get_item_value_model(item, column_id)
label = ui.Label(value_model.as_string)
if column_id == 1:
field = ui.FloatField(value_model, visible=False)
else:
field = ui.StringField(value_model, visible=False)
# Start editing when double clicked
stack.set_mouse_double_clicked_fn(lambda x, y, b, m, f=field, l=label: self.on_double_click(b, f, l))
def on_double_click(self, button, field, label):
"""Called when the user double-clicked the item in TreeView"""
if button != 0:
return
# Make Field visible when double clicked
field.visible = True
field.focus_keyboard()
# When editing is finished (enter pressed of mouse clicked outside of the viewport)
self.subscription = field.model.subscribe_end_edit_fn(
lambda m, f=field, l=label: self.on_end_edit(m, f, l)
)
def on_end_edit(self, model, field, label):
"""Called when the user is editing the item and pressed Enter or clicked outside of the item"""
field.visible = False
label.text = model.as_string
self.subscription = None
with ui.ScrollingFrame(
height=400,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
style={"Field": {"background_color": 0xFF000000}},
):
self._name_value_model = NameValueModel("First", 0.2, "Second", 0.3, "Last", 0.4)
self._name_value_delegate = EditableDelegate()
tree_view = ui.TreeView(
self._name_value_model,
delegate=self._name_value_delegate,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
)
class AsyncQueryModel(ListModel):
"""
This is an example of async filling the TreeView model. It's
collecting only as many as it's possible of USD prims for 0.016s
and waits for the next frame, so the UI is not locked even if the
USD Stage is extremely big.
"""
def __init__(self):
super().__init__()
self._stop_event = None
def destroy(self):
self.stop()
def stop(self):
"""Stop traversing the stage"""
if self._stop_event:
self._stop_event.set()
def reset(self):
"""Traverse the stage and keep materials"""
self.stop()
self._stop_event = asyncio.Event()
self._children.clear()
self._item_changed(None)
asyncio.ensure_future(self.__get_all(self._stop_event))
def __push_collected(self, collected):
"""Add given array to the model"""
for c in collected:
self._children.append(c)
self._item_changed(None)
async def __get_all(self, stop_event):
"""Traverse the stage portion at time, so it doesn't freeze"""
stop_event.clear()
start_time = time.time()
# The widget will be updated not faster than 60 times a second
update_every = 1.0 / 60.0
import omni.usd
from pxr import Usd
from pxr import UsdShade
context = omni.usd.get_context()
stage = context.get_stage()
if not stage:
return
# Buffer to keep the portion of the items before sending to the
# widget
collected = []
for p in stage.Traverse(
Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded)
):
if stop_event.is_set():
break
if p.IsA(UsdShade.Material):
# Collect materials only
collected.append(ListItem(str(p.GetPath())))
elapsed_time = time.time()
# Loop some amount of time so fps will be about 60FPS
if elapsed_time - start_time > update_every:
start_time = elapsed_time
# Append the portion and update the widget
if collected:
self.__push_collected(collected)
collected = []
# Wait one frame to let other tasks go
await omni.kit.app.get_app().next_update_async()
self.__push_collected(collected)
try:
import omni.usd
from pxr import Usd
usd_available = True
except ModuleNotFoundError:
usd_available = False
if usd_available:
self._text(
"This is an example of async filling the TreeView model. It's collecting only as many as it's possible "
"of USD prims for 0.016s and waits for the next frame, so the UI is not locked even if the USD Stage "
"is extremely big."
)
with ui.ScrollingFrame(
height=400,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
style={"Field": {"background_color": 0xFF000000}},
):
self._async_query_model = AsyncQueryModel()
ui.TreeView(
self._async_query_model,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
)
self._loaded_label = ui.Label("Press Button to Load Materials", name="text")
with ui.HStack():
ui.Button("Traverse All", clicked_fn=self._async_query_model.reset)
ui.Button("Stop Traversing", clicked_fn=self._async_query_model.stop)
def _item_changed(model, item):
if item is None:
count = len(model._children)
self._loaded_label.text = f"{count} Materials Traversed"
self._async_query_sub = self._async_query_model.subscribe_item_changed_fn(_item_changed)
self._text("For the example code please see the following file:")
current_file_name = Path(__file__).resolve()
self._code(f"{current_file_name}", elided_text=True)
ui.Spacer(height=10)
| 20,987 | Python | 39.130019 | 127 | 0.532377 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/dnd_doc.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.
#
"""The documentation of the omni.ui aka UI Framework"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import inspect
def simple_dnd():
def drag(url):
"""Called for the drag operation. Returns drag data."""
return url
def drop_accept(url):
"""Called to check the drag data is acceptable."""
return True
def drop(widget, event):
"""Called when dropping the data."""
widget.source_url = event.mime_data
def drag_area(url):
"""Create a draggable image."""
image = ui.Image(url, width=64, height=64)
image.set_drag_fn(lambda: drag(url))
def drop_area():
"""A drop area that shows image when drop."""
with ui.ZStack(width=64, height=64):
ui.Rectangle()
image = ui.Image()
image.set_accept_drop_fn(drop_accept)
image.set_drop_fn(lambda a, w=image: drop(w, a))
with ui.HStack():
drag_area("resources/icons/Nav_Flymode.png")
drag_area("resources/icons/Move_64.png")
ui.Spacer(width=64)
drop_area()
def complex_dnd():
def drag(url):
# Draw the image and the image name in the drag tooltip
with ui.VStack():
ui.Image(url, width=32, height=32)
ui.Label(url)
return url
def drop_accept(url, ext):
# Accept drops of specific extension only
return url.endswith(ext)
def drop(widget, event):
widget.source_url = event.mime_data
def drag_area(url):
image = ui.Image(url, width=64, height=64)
image.set_drag_fn(lambda: drag(url))
def drop_area(ext):
# If drop is acceptable, the rectangle is blue
style = {}
style["Rectangle"] = {"background_color": cl("#999999")}
style["Rectangle:drop"] = {"background_color": cl("#004499")}
stack = ui.ZStack(width=64, height=64)
with stack:
ui.Rectangle(style=style)
ui.Label(f"Accepts {ext}")
image = ui.Image(style={"margin": 2})
stack.set_accept_drop_fn(lambda d, e=ext: drop_accept(d, e))
stack.set_drop_fn(lambda a, w=image: drop(w, a))
with ui.HStack():
drag_area("resources/icons/sound.png")
drag_area("resources/icons/stage.png")
drag_area("resources/glyphs/menu_audio.svg")
drag_area("resources/glyphs/menu_camera.svg")
ui.Spacer(width=64)
drop_area(".png")
ui.Spacer(width=64)
drop_area(".svg")
class DNDDoc(DocPage):
"""The document for Drag and Drop"""
def create_doc(self, navigate_to=None):
self._section_title("Drag and Drop")
self._caption("Minimal Example", navigate_to)
self._text(
"Omni::UI includes methods to perform Drag and Drop operations quickly. Drag and Drop with Omni::UI is "
"straightforward."
)
self._text(
"A drag and drop operation consists of three parts: the drag, accept the drop, and the drop. For drag, "
"Widget has a single callback drag_fn. By adding this function to a widget, you set the callback attached "
"to the drag operation. The function should return the string data to drag."
)
self._text(
"To accept the drop Widget has a callback accept_drop_fn. It's called when the mouse enters the widget "
"area. It takes the drag string data and should return either the widget can accept this data for the "
"drop."
)
self._text(
"For the drop part, Widget has a callback drop_fn. With this method, we specify if Widget accepts drops. "
"And it's called when the user drops the string data to the widget."
)
simple_dnd()
self._code(inspect.getsource(simple_dnd).split("\n", 1)[-1])
self._caption("Styling and Tooltips", navigate_to)
self._text("It's possible to customize the drag tooltip with creating widgets in drag_fn.")
self._text(
"To show the drop widget accepts drops visually, there is a style 'drop', and it's propagated to the "
"children widgets."
)
complex_dnd()
self._code(inspect.getsource(complex_dnd).split("\n", 1)[-1])
ui.Spacer(height=10)
| 4,786 | Python | 32.711267 | 119 | 0.616172 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/web_doc.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.
#
"""The documentation for Web features such as WebViewWidget implementations"""
from .doc_page import DocPage
from typing import List
import json
import omni.kit.widget.webview as webview
import omni.ui as ui
_BASE_STYLE = {
"WebViewWidget": {"border_width": 0.5, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D},
"Label": {"color": 0xFF000000, "margin": 5.0},
"CheckBox": {"margin": 5.0},
}
class WebViewWidgetDoc(DocPage):
""" Document for WebViewWidget"""
def __init__(self):
self._sections = [
("Displaying an url", self.create_displaying_an_url),
("Styling", self.create_styling),
("Content loading", self.create_content_loading),
("Non-opaque contents", self.create_non_opaque_contents),
("Communication", self.create_js_host_communication),
("Web page debugging", self.create_web_page_debugging),
]
def get_sections(self) -> List[str]:
return [t for (t, _) in self._sections]
def create_doc(self, navigate_to=None):
self._section_title("WebViewWidget")
for (title, create_func) in self._sections:
self._caption(title, navigate_to)
create_func()
def create_displaying_an_url(self):
self._text(
"""The WebViewWidget type displays web pages.
The url can be loaded with 'load_url()'.
The load progress can be observed with 'loading_changed_fn' and 'progress_changed_fn' as well as the WebViewWidget properties 'loading' and 'progress'.
"""
)
with ui.VStack(style=_BASE_STYLE):
loading_label = ui.Label("Load label")
def update_progress(progress: float):
loading_label.text = f"Loading {(progress * 100.0):.0f}% ..."
def update_loading(loading: bool):
if not loading:
loading_label.text = "Loading done."
web_view = webview.WebViewWidget(
width=ui.Percent(100),
height=ui.Pixel(500),
loading_changed_fn=update_loading,
progress_changed_fn=update_progress,
)
urls = ["https://www.nvidia.com", "https://news.ycombinator.com", "http://google.com"]
web_view.load_url(urls[0])
def change_url(model, _item):
url = urls[model.get_item_value_model().as_int]
web_view.load_url(url)
url_selector = ui.ComboBox(0, *urls)
url_selector.model.add_item_changed_fn(change_url)
def create_styling(self):
self._text(
"""The WebViewWidget can be styled normally.
Here we create a web view with rounded corners and wider borders.
In this example, we also use 'url' constructor property to start the load."""
)
style = {
"WebViewWidget": {
"border_width": 3,
"border_radius": 7,
"margin": 5.0,
"padding": 5.0,
"border_color": 0xFFFD761D,
}
}
with ui.VStack(style=_BASE_STYLE):
webview.WebViewWidget(width=ui.Percent(100), height=ui.Pixel(500), url="https://www.google.com")
def create_content_loading(self):
self._text(
"""The WebViewWidget can be populated with static html with the 'html' constructor property.
In this case, the 'url' property describes the base url of the document."""
)
style = {"WebViewWidget": {"border_width": 0.5, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D}}
with ui.VStack(style=style):
webview.WebViewWidget(
width=ui.Percent(100),
height=ui.Pixel(500),
html='<body><h1>Hello from web page</h1><p>This is web content. Here\'s a link <a href="http://wwf.org">into the wild.</a></p></body>',
url="http://example.com/content_loading",
)
def create_non_opaque_contents(self):
self._text(
"""The WebViewWidget can be marked non-opaque so transparent or translucent contents work.
The magenta circles are omni.ui widgets and can be seen beneath and on top of the WebViewWidget.
The web page is marked as transparent with 'contents_is_opaque=False' and then with HTML body css property 'background: transparent'.
"""
)
html = """<body style="background: transparent">
<h3 style="background: rgba(255, 0, 0, 0.4)">Web page input</h3>
<input type="text" value="..text 1.." /> <br/>
<input type="text" value="..text 2.." style="background: rgba(255,255,255,0.5)"/> <br/>
<input type="text" value="..text 3.." /> <br/>
<input type="text" value="..text 4.." style="background: rgba(255,255,255,0.5)"/> <br/>
<input type="text" value="..text last.." /> <br/>
</body>
"""
with ui.VStack(style=_BASE_STYLE):
ui.Circle(
radius=100,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.LEFT_BOTTOM,
style={"background_color": 0xDDFF00AA},
)
webview.WebViewWidget(
width=ui.Percent(100),
height=ui.Pixel(200),
contents_is_opaque=False,
html=html,
url="http://example.com/non_opaque_contents",
style={"background_color": 0},
)
ui.Circle(
radius=100,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.LEFT_TOP,
style={"background_color": 0xDDFFAAAA},
)
def create_js_host_communication(self):
self._text(
"""The WebViewWidget can control the JavaScript application by using WebViewWidget.evaluate_javascript.
The JavaScript application can send data to the host application by using window.nvwebview.messageHandlers.<name>.postMessage("msg").
"""
)
html = """<body>
<script>
function sendToHost() {
var v = document.getElementById("toHost");
window.nvwebview.messageHandlers.hostApp.postMessage(v.value);
}
function receiveFromHost(data)
{
document.getElementById('fromHost').value = data;
}
</script>
<h3>From JS application to host application</h3>
Text to send: <input id="toHost" type="text" value="Hello from "JS" application" size="75" /> <br/>
<input type="button" value="Send message to host application" onclick="javascript: sendToHost();" /> <br/>
<h3>From host application to JS application</h3>
<input id="fromHost" type="text" value="Message from host application comes here" readonly size="75"/> <br/>
</body>
"""
message_to_send = 'Hello from "host" application \U0001f600.'
webview_widget = None
message_from_js_label = None
send_to_js_button = None
with ui.VStack(style=_BASE_STYLE):
send_to_js_button = ui.Button("Send hello to JS application", width=0)
message_from_js_label = ui.Label("Message from JS application comes here")
webview_widget = webview.WebViewWidget(width=ui.Percent(100), height=ui.Pixel(300))
def send_to_js():
webview_widget.evaluate_javascript(f"receiveFromHost({json.dumps(message_to_send)})")
send_to_js_button.set_clicked_fn(send_to_js)
def update_message_from_js_label(msg: str):
message_from_js_label.text = msg
webview_widget.set_user_script_message_handler_fn("hostApp", update_message_from_js_label)
webview_widget.load_html_from_url(html, "https://example.com/js_host_communication")
def create_web_page_debugging(self):
self._text(
"""The WebViewWidget.set_remote_web_page_debugging_enabled(true) can be used to enable Chrome Web Inspector debugging for all the WebViewWidget instances.
Enable the web page debugging below. Using the desktop Chrome browser, navigate to chrome://inspect to see list of WebViewWidget instances in the process.
"""
)
webview.WebViewWidget.set_remote_web_page_debugging_enabled(False)
checkbox = None
def update_remote_debugging(value_model):
webview.WebViewWidget.set_remote_web_page_debugging_enabled(value_model.get_value_as_bool())
with ui.HStack(style=_BASE_STYLE):
ui.Label("Remote web page debugging enabled", width=0, style={"color": 0xFF000000})
checkbox = ui.CheckBox()
checkbox.model.add_value_changed_fn(update_remote_debugging)
with ui.VStack():
ui.Spacer()
ui.Spacer()
| 9,073 | Python | 39.150442 | 166 | 0.616665 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/attribute_editor_demo.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.
#
"""an example of creating a custom attribute Editor window"""
from omni import ui
from pathlib import Path
ICON_PATH = Path(__file__).parent.parent.joinpath("icons")
LIGHT_WINDOW_STYLE = {
# main frame style
"ScrollingFrame::canvas": {"background_color": 0xFFCACACA},
"Frame::main_frame": {"background_color": 0xFFCACACA},
# title bar style
"Label::title": {"color": 0xFF777777, "font_size": 16.0},
"Rectangle::titleBar": {"background_color": 0xFFCACACA},
"Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0},
"Triangle::timeArrows": {"background_color": 0xFFCACACA},
"Label::timeLabel": {"color": 0xFFDDDDDD, "font_size": 16.0},
# custom widget slider
"Rectangle::sunStudySliderBackground": {
"background_color": 0xFFBBBBBB,
"border_color": 0xFF888888,
"border_width": 1.0,
"border_radius": 10.0,
},
"Rectangle::sunStudySliderForground": {"background_color": 0xFF888888},
"Circle::slider": {"background_color": 0xFFBBBBBB},
"Circle::slider:hovered": {"background_color": 0xFFCCCCCC},
"Circle::slider:pressed": {"background_color": 0xFFAAAAAA},
"Triangle::selector": {"background_color": 0xFF888888},
"Triangle::selector:hovered": {"background_color": 0xFF999999},
"Triangle::selector:pressed": {"background_color": 0xFF777777},
# toolbar
"Triangle::play_button": {"background_color": 0xFF6E6E6E},
}
KIT_GREEN = 0xFF8A8777
LABEL_PADDING = 120
DARK_WINDOW_STYLE = {
"Window": {"background_color": 0xFF444444},
"Button": {"background_color": 0xFF292929, "margin": 3, "padding": 3, "border_radius": 2},
"Button.Label": {"color": 0xFFCCCCCC},
"Button:hovered": {"background_color": 0xFF9E9E9E},
"Button:pressed": {"background_color": 0xC22A8778},
"VStack::main_v_stack": {"secondary_color": 0x0, "margin_width": 10, "margin_height": 0},
"VStack::frame_v_stack": {"margin_width": 15},
"Rectangle::frame_background": {"background_color": 0xFF343432, "border_radius": 5},
"Field::models": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 4.0},
"Frame": {"background_color": 0xFFAAAAAA},
"Label::transform": {"font_size": 12, "color": 0xFF8A8777},
"Circle::transform": {"background_color": 0x558A8777},
"Field::transform": {
"background_color": 0xFF23211F,
"border_radius": 3,
"corner_flag": ui.CornerFlag.RIGHT,
"font_size": 12,
},
"Slider::transform": {
"background_color": 0xFF23211F,
"border_radius": 3,
"draw_mode": ui.SliderDrawMode.DRAG,
"corner_flag": ui.CornerFlag.RIGHT,
"font_size": 14,
},
"Label::transform_label": {"font_size": 12, "color": 0xFFDDDDDD},
"Label": {"font_size": 12, "color": 0xFF8A8777},
"Label::label": {"font_size": 14, "color": 0xFF8A8777},
"Label::title": {"font_size": 14, "color": 0xFFAAAAAA},
"Triangle::title": {"background_color": 0xFFAAAAAA},
"ComboBox::path": {"font_size": 12, "secondary_color": 0xFF23211F, "color": 0xFFAAAAAA},
"ComboBox::choices": {
"font_size": 12,
"color": 0xFFAAAAAA,
"background_color": 0xFF23211F,
"secondary_color": 0xFF23211F,
},
"ComboBox:hovered:choices": {"background_color": 0xFF33312F, "secondary_color": 0xFF33312F},
"Slider::value_less": {
"font_size": 12,
"color": 0x0,
"border_radius": 5,
"background_color": 0xFF23211F,
"secondary_color": KIT_GREEN,
"border_color": 0xFFAAFFFF,
"border_width": 0,
},
"Slider::value": {
"font_size": 14,
"color": 0xFFAAAAAA,
"border_radius": 5,
"background_color": 0xFF23211F,
"secondary_color": KIT_GREEN,
},
"Rectangle::add": {"background_color": 0xFF23211F},
"Rectangle:hovered:add": {"background_color": 0xFF73414F},
"CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F},
"CheckBox::whiteCheck": {"font_size": 10, "background_color": 0xFFDDDDDD, "color": 0xFF23211F},
"Slider::colorField": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFF8A8777},
# Frame
"CollapsableFrame::standard_collapsable": {
"background_color": 0xFF343432,
"secondary_color": 0xFF343432,
"font_size": 16,
"border_radius": 2.0,
"border_color": 0x0,
"border_width": 0,
},
"CollapsableFrame:hovered:standard_collapsable": {"secondary_color": 0xFFFBF1E5},
"CollapsableFrame:pressed:standard_collapsable": {"secondary_color": 0xFFF7E4CC},
}
CollapsableFrame_style = {
"CollapsableFrame": {
"background_color": 0xFF343432,
"secondary_color": 0xFF343432,
"color": 0xFFAAAAAA,
"border_radius": 4.0,
"border_color": 0x0,
"border_width": 0,
"font_size": 14,
"padding": 0,
},
"HStack::header": {"margin": 5},
"CollapsableFrame:hovered": {"secondary_color": 0xFF3A3A3A},
"CollapsableFrame:pressed": {"secondary_color": 0xFF343432},
}
class AttributeEditorWindow:
""" example of an Attribute Editor Window using Omni::UI """
def __init__(self):
self._editor_window = None
self._window_Frame = None
def set_style_light(self, button):
""" """
self._window_Frame.set_style(LIGHT_WINDOW_STYLE)
def set_style_dark(self, button):
""" """
self._window_Frame.set_style(DARK_WINDOW_STYLE)
def shutdown(self):
"""Should be called when the extesion us unloaded"""
# Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it
# automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But
# we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it
# will fire warning that texture is not destroyed.
self._editor_window = None
def _create_object_selection_frame(self):
with ui.Frame():
with ui.ZStack():
ui.Rectangle(name="frame_background")
with ui.VStack(spacing=5, name="this", style={"VStack::this": {"margin": 5, "margin_width": 15}}):
with ui.HStack(height=0):
ui.StringField(name="models").model.set_value("(9 models selected)")
with ui.VStack(width=0, height=0):
ui.Spacer(width=0, height=3)
ui.Image(
"resources/glyphs/lock_open.svg",
width=25,
height=12,
style={"color": KIT_GREEN, "marging_width": 5},
)
ui.Spacer(width=0)
with ui.VStack(width=0, height=0):
ui.Spacer(width=0, height=3)
ui.Image("resources/glyphs/settings.svg", width=25, height=12, style={"color": KIT_GREEN})
ui.Spacer(width=0)
with ui.HStack(height=0):
with ui.ZStack(width=60):
ui.Image(f"{ICON_PATH}/Add.svg", width=60, height=30)
with ui.HStack(name="this", style={"HStack::this": {"margin_height": 0}}):
ui.Spacer(width=15)
ui.Label("Add", style={"font_size": 16, "color": 0xFFAAAAAA, "margin_width": 10})
ui.Spacer(width=50)
with ui.ZStack():
ui.Rectangle(style={"background_color": 0xFF23211F, "border_radius": 4.0})
with ui.HStack():
with ui.VStack(width=0):
ui.Spacer(width=0)
ui.Image("resources/glyphs/sync.svg", width=25, height=12)
ui.Spacer(width=0)
ui.StringField(name="models").model.set_value("Search")
def _create_control_state(self, state=0):
control_type = [
f"{ICON_PATH}/Expression.svg",
f"{ICON_PATH}/Mute Channel.svg",
f"{ICON_PATH}/mixed properties.svg",
f"{ICON_PATH}/Default value.svg",
f"{ICON_PATH}/Changed value.svg",
f"{ICON_PATH}/Animation Curve.svg",
f"{ICON_PATH}/Animation Key.svg",
]
if state == 0:
ui.Circle(name="transform", width=20, radius=3.5, size_policy=ui.CircleSizePolicy.FIXED)
else:
with ui.VStack(width=0):
ui.Spacer()
ui.Image(control_type[state - 1], width=20, height=12)
ui.Spacer()
def _create_checkbox_control(self, name, value, label_width=100, line_width=ui.Fraction(1)):
with ui.HStack():
ui.Label(name, name="label", width=0)
ui.Spacer(width=10)
ui.Line(style={"color": 0x338A8777}, width=line_width)
ui.Spacer(width=5)
with ui.VStack(width=10):
ui.Spacer()
ui.CheckBox(width=10, height=0, name="greenCheck").model.set_value(value)
ui.Spacer()
self._create_control_state(0)
def _create_path_combo(self, name, paths):
with ui.HStack():
ui.Label(name, name="label", width=LABEL_PADDING)
with ui.ZStack():
ui.StringField(name="models").model.set_value(paths)
with ui.HStack():
ui.Spacer()
ui.Circle(width=10, height=20, style={"background_color": 0xFF555555})
ui.ComboBox(0, paths, paths, name="path", width=0, height=0, arrow_only=True)
ui.Spacer(width=5)
ui.Image("resources/icons/folder.png", width=15)
ui.Spacer(width=5)
ui.Image("resources/icons/find.png", width=15)
self._create_control_state(2)
def _build_transform_frame(self):
# Transform Frame
with ui.CollapsableFrame(title="Transform", style=CollapsableFrame_style):
with ui.VStack(spacing=8, name="frame_v_stack"):
ui.Spacer(height=0)
components = ["Position", "Rotation", "Scale"]
for component in components:
with ui.HStack():
with ui.HStack(width=LABEL_PADDING):
ui.Label(component, name="transform", width=50)
self._create_control_state()
ui.Spacer()
# Field (X)
all_axis = ["X", "Y", "Z"]
colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F}
for axis in all_axis:
with ui.HStack():
with ui.ZStack(width=15):
ui.Rectangle(
width=15,
height=20,
style={
"background_color": colors[axis],
"border_radius": 3,
"corner_flag": ui.CornerFlag.LEFT,
},
)
ui.Label(axis, name="transform_label", alignment=ui.Alignment.CENTER)
ui.FloatDrag(name="transform", min=-1000000, max=1000000, step=0.01)
self._create_control_state(0)
ui.Spacer(height=0)
def _build_checked_header(self, collapsed, title):
triangle_alignment = ui.Alignment.RIGHT_CENTER
if not collapsed:
triangle_alignment = ui.Alignment.CENTER_BOTTOM
with ui.HStack(style={"HStack": {"margin_width": 15, "margin_height": 5}}):
with ui.VStack(width=20):
ui.Spacer()
ui.Triangle(
alignment=triangle_alignment,
name="title",
width=8,
height=8,
style={"background_color": 0xFFCCCCCC},
)
ui.Spacer()
ui.Label(title, name="title", width=0)
ui.Spacer()
ui.CheckBox(width=10, name="whiteCheck").model.set_value(True)
self._create_control_state()
def _build_custom_callapsable_frame(self):
with ui.CollapsableFrame(
title="Light Property", style=CollapsableFrame_style, build_header_fn=self._build_checked_header
):
with ui.VStack(spacing=12, name="frame_v_stack"):
ui.Spacer(height=5)
with ui.HStack():
ui.Label("Slider", name="label", width=LABEL_PADDING)
ui.IntSlider(name="value_less", min=0, max=100, usingGauge=True).model.set_value(30)
self._create_control_state()
self._create_checkbox_control("Great UI", True)
self._create_checkbox_control("Hard To Build", False)
self._create_checkbox_control("Support very very very long checkbox label", True)
ui.Spacer(height=0)
def _build_dropdown_frame(self):
with ui.Frame():
with ui.ZStack():
ui.Rectangle(name="frame_background")
with ui.VStack(height=0, spacing=10, name="frame_v_stack"):
ui.Spacer(height=5)
for index in range(3):
with ui.HStack():
ui.Label("Drop Down", name="label", width=LABEL_PADDING)
ui.ComboBox(0, "Choice 1", "Choice 2", "Choice 3", height=10, name="choices")
self._create_control_state()
self._create_checkbox_control("Check Box", False)
ui.Spacer(height=0)
def _build_scale_and_bias_frame(self):
with ui.CollapsableFrame(title="Scale And Bias Output", collapsed=False, style=CollapsableFrame_style):
with ui.VStack(name="frame_v_stack"):
with ui.HStack():
ui.Spacer(width=100)
ui.Label("Scale", name="label", alignment=ui.Alignment.CENTER)
ui.Spacer(width=10)
ui.Label("Bias", name="label", alignment=ui.Alignment.CENTER)
with ui.VStack(spacing=8):
colors = ["Red", "Green", "Blue", "Alpha"]
for color in colors:
with ui.HStack():
ui.Label(color, name="label", width=LABEL_PADDING)
ui.FloatSlider(name="value", min=0, max=2).model.set_value(1.0)
self._create_control_state(6)
ui.Spacer(width=20)
ui.FloatSlider(name="value", min=-1.0, max=1.0).model.set_value(0.0)
state = None
if color == "Red":
state = 2
elif color == "Blue":
state = 5
else:
state = 3
self._create_control_state(state)
ui.Spacer(height=0)
ui.Spacer(height=5)
with ui.VStack(spacing=14):
self._create_checkbox_control("Warp to Output Range", True)
ui.Line(style={"color": KIT_GREEN})
self._create_checkbox_control("Border Color", True)
self._create_checkbox_control("Zero Alpha Border", False)
with ui.HStack():
self._create_checkbox_control("Cutout Alpha", False, label_width=20, line_width=20)
self._create_checkbox_control("Scale Alpha For Mi Pmap Coverage", True)
self._create_checkbox_control("Border Color", True)
ui.Spacer(height=0)
def _build_color_picker_frame(self):
def color_drag(args):
with ui.HStack(spacing=2):
color_model = ui.MultiFloatDragField(
args[0], args[1], args[2], width=200, h_spacing=5, name="colorField"
).model
ui.ColorWidget(color_model, width=10, height=10)
def color4_drag(args):
with ui.HStack(spacing=2):
color_model = ui.MultiFloatDragField(
args[0],
args[1],
args[2],
args[3],
width=200,
h_spacing=5,
style={"color": 0xFFAAAAAA, "background_color": 0xFF000000, "draw_mode": ui.SliderDrawMode.HANDLE},
).model
ui.ColorWidget(color_model, width=10, height=10)
with ui.CollapsableFrame(title="Color Controls", collapsed=False, style=CollapsableFrame_style):
with ui.VStack(name="frame_v_stack"):
with ui.VStack(spacing=8):
colors = [("Red", [1.0, 0.0, 0.0]), ("Green", [0.0, 1.0, 0.0]), ("Blue", [0.0, 0.0, 1.0])]
for color in colors:
with ui.HStack():
ui.Label(color[0], name="label", width=LABEL_PADDING)
if len(color[1]) == 4:
color4_drag(color[1])
else:
color_drag(color[1])
self._create_control_state(0)
ui.Line(style={"color": 0x338A8777})
color = ("RGBA", [1.0, 0.0, 1.0, 0.5])
with ui.HStack():
ui.Label(color[0], name="label", width=LABEL_PADDING)
color4_drag(color[1])
self._create_control_state(0)
ui.Spacer(height=0)
def _build_frame_with_radio_button(self):
with ui.CollapsableFrame(title="Compression Quality", collapsed=False, style=CollapsableFrame_style):
with ui.VStack(spacing=8, name="frame_v_stack"):
ui.Spacer(height=5)
with ui.HStack():
with ui.VStack(width=LABEL_PADDING):
ui.Label(" Select One...", name="label", width=100, height=0)
ui.Spacer(width=100)
with ui.VStack(spacing=10):
values = ["Faster", "Normal", "Production", "Highest"]
for value in values:
with ui.HStack():
with ui.ZStack(width=20):
outer_style = {
"border_width": 1,
"border_color": KIT_GREEN,
"background_color": 0x0,
"border_radius": 2,
}
ui.Rectangle(width=12, height=12, style=outer_style)
if value == "Faster":
outer_style = {"background_color": KIT_GREEN, "border_radius": 2}
with ui.Placer(offset_x=3, offset_y=3):
ui.Rectangle(width=10, height=10, style=outer_style)
ui.Label(value, name="label", aligment=ui.Alignment.LEFT)
ui.Spacer(height=0)
def build_window(self):
""" build the window for the Class"""
self._editor_window = ui.Window("Attribute Editor", width=450, height=800)
self._editor_window.deferred_dock_in("Layers")
self._editor_window.setPosition(0, 0)
self._editor_window.frame.set_style(DARK_WINDOW_STYLE)
with self._editor_window.frame:
with ui.VStack():
with ui.HStack(height=20):
ui.Label("Styling : ", alignment=ui.Alignment.RIGHT_CENTER)
ui.Button("Light Mode", clicked_fn=lambda b=None: self.set_style_light(b))
ui.Button("Dark Mode", clicked_fn=lambda b=None: self.set_style_dark(b))
ui.Spacer()
ui.Spacer(height=10)
self._window_Frame = ui.ScrollingFrame(
name="canvas",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
)
with self._window_Frame:
with ui.VStack(height=0, name="main_v_stack", spacing=6):
# create object selection Frame
self._create_object_selection_frame()
# create build transform Frame
self._build_transform_frame()
# DropDown Frame
self._build_dropdown_frame()
# Custom Collapsable Frame
self._build_custom_callapsable_frame()
# Custom Collapsable Frame
with ui.CollapsableFrame(title="Files", style=CollapsableFrame_style):
with ui.VStack(spacing=10, name="frame_v_stack"):
ui.Spacer(height=0)
self._create_path_combo("UI Path", "omni:/Project/Cool_ui.usd")
self._create_path_combo("Texture Path", "omni:/Project/cool_texture.png")
ui.Spacer(height=0)
# Custom Collapsable Frame
with ui.CollapsableFrame(title="Images Options", collapsed=True, style=CollapsableFrame_style):
with ui.VStack(spacing=10, name="frame_v_stack"):
self._create_path_combo("Images Path", "omni:/Library/Images/")
ui.Spacer(height=0)
# Custom Collapsable Frame
self._build_frame_with_radio_button()
# Scale And Bias
self._build_scale_and_bias_frame()
# Color Pickrs
self._build_color_picker_frame()
return self._editor_window
| 23,430 | Python | 45.582505 | 119 | 0.509902 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/progressbar_doc.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.
#
"""The documentation for ProgressBar"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
SPACING = 5
class CustomProgressValueModel(ui.AbstractValueModel):
"""An example of custom float model that can be used for progress bar"""
def __init__(self, value: float):
super().__init__()
self._value = value
def set_value(self, value):
"""Reimplemented set"""
try:
value = float(value)
except ValueError:
value = None
if value != self._value:
# Tell the widget that the model is changed
self._value = value
self._value_changed()
def get_value_as_float(self):
return self._value
def get_value_as_string(self):
return "Custom Overlay"
class ProgressBarDoc(DocPage):
""" document for ProgressBar"""
def create_doc(self, navigate_to=None):
self._section_title("ProgressBar")
self._text("A progressbar is widget that indicates the progress of an operation.")
self._text("In the following example, it shows how to use progress bar and override the overlay text.")
with ui.VStack(spacing=SPACING):
# Create progressbars
first = ui.ProgressBar()
# Range is [0.0, 1.0]
first.model.set_value(0.5)
second = ui.ProgressBar()
second.model.set_value(1.0)
# Overrides the overlay of progressbar
model = CustomProgressValueModel(0.8)
third = ui.ProgressBar(model)
third.model.set_value(0.1)
# Styling its color
fourth = ui.ProgressBar(style={"color": cl("#0000DD")})
fourth.model.set_value(0.3)
# Styling its border width
ui.ProgressBar(style={"border_width": 2, "color": cl("#0000DD")}).model.set_value(0.7)
# Styling its border radius
ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000DD")}).model.set_value(0.6)
# Styling its background color
ui.ProgressBar(style={"border_radius": 100, "background_color": cl("#0000DD")}).model.set_value(0.6)
# Styling the text color
ui.ProgressBar(style={"border_radius": 100, "secondary_color": cl("#00DDDD")}).model.set_value(0.6)
# Two progress bars in a row with padding
with ui.HStack():
ui.ProgressBar(style={"color": cl("#0000DD"), "padding": 100}).model.set_value(1.0)
ui.ProgressBar().model.set_value(0.0)
self._code(
"""
# Create progressbars
first = ui.ProgressBar()
# Range is [0.0, 1.0]
first.model.set_value(0.5)
second = ui.ProgressBar()
second.model.set_value(1.0)
# Overrides the overlay of progressbar
model = CustomProgressValueModel(0.8)
third = ui.ProgressBar(model)
third.model.set_value(0.1)
# Styling its color
fourth = ui.ProgressBar(style={"color": cl("#0000DD")})
fourth.model.set_value(0.3)
# Styling its border width
ui.ProgressBar(style={"border_width": 2, "color": cl("#0000DD")}).model.set_value(0.7)
# Styling its border radius
ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000DD")}).model.set_value(0.6)
# Styling its background color
ui.ProgressBar(style={"border_radius": 100, "background_color": cl("#0000DD")}).model.set_value(0.6)
# Styling the text color
ui.ProgressBar(style={"border_radius": 100, "secondary_color": cl("#00DDDD")}).model.set_value(0.6)
# Two progress bars in a row with padding
with ui.HStack():
ui.ProgressBar(style={"color": cl("#0000DD"), "padding": 100}).model.set_value(1.0)
ui.ProgressBar().model.set_value(0.0)
"""
)
ui.Spacer(height=10)
| 4,492 | Python | 34.377952 | 112 | 0.592164 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/menu_doc.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.
#
"""The documentation for Menu"""
from omni import ui
from .doc_page import DocPage
class MenuDoc(DocPage):
""" document for Menu"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._context_menu = ui.Menu(
"Context menu",
name="this",
style={
"Menu": {"background_color": 0xFFAA0000, "color": 0xFFFFFFFF, "background_selected_color": 0xFF00AA00},
"MenuItem": {"color": 0xFFFFFFFF, "background_selected_color": 0xFF00AA00},
"Separator": {"color": 0xFFFFFFFF},
},
)
self._pushed_menu = ui.Menu(
"Pushed menu",
style={
"Menu": {"background_color": 0xFF000000, "color": 0xFFFFFFFF, "background_selected_color": 0xFFAAAAAA},
"MenuItem": {"color": 0xFFFFFFFF, "background_selected_color": 0xFFAAAAAA},
},
)
def _show_context_menu(self, x, y, button, modifier):
"""The context menu example"""
# Display context menu only if the right button is pressed
if button != 1:
return
# Reset the previous context popup
self._context_menu.clear()
with self._context_menu:
ui.MenuItem("Delete Shot")
ui.Separator()
ui.MenuItem("Attach Selected Camera")
with ui.Menu("Sub-menu"):
ui.MenuItem("One")
ui.MenuItem("Two")
ui.MenuItem("Three")
ui.Separator()
ui.MenuItem("Four")
with ui.Menu("Five"):
ui.MenuItem("Six")
ui.MenuItem("Seven")
# Show it
self._context_menu.show()
def _show_pushed_menu(self, x, y, button, modifier, widget):
"""The Pushed menu example"""
# Display context menu only if the left mouse button is pressed
if button != 0:
return
# Reset the previous context popup
self._pushed_menu.clear()
with self._pushed_menu:
ui.MenuItem("Camera 1")
ui.MenuItem("Camera 2")
ui.MenuItem("Camera 3")
ui.Separator()
with ui.Menu("More Cameras"):
ui.MenuItem("This Menu is Pushed")
ui.MenuItem("and Aligned with a widget")
# Show it
self._pushed_menu.show_at(
(int)(widget.screen_position_x), (int)(widget.screen_position_y + widget.computed_content_height)
)
def create_doc(self, navigate_to=None):
self._section_title("Menu")
self._text(
"The Menu class provides a menu widget for use in menu bars, context menus, and other popup menus. It can "
"be either a pull-down menu in a menu bar or a standalone context menu. Pull-down menus are shown by the "
"menu bar when the user clicks on the respective item. Context menus are usually invoked by some special "
"keyboard key or by right-clicking."
)
with ui.HStack(style=self._style_system):
ui.Button("Right click to context menu", width=0, mouse_pressed_fn=self._show_context_menu)
self._code(
"""
def _on_startup(self):
....
with ui.HStack(style=style_system):
ui.Button(
"Right click to context menu",
width=0,
mouse_pressed_fn=self._show_context_menu
)
....
def _show_context_menu(self, x, y, button, modifier):
# Display context menu only if the right button is pressed
if button != 1:
return
# Reset the previous context popup
self._context_menu.clear()
with self._context_menu:
with ui.Menu("Sub-menu"):
ui.MenuItem("One")
ui.MenuItem("Two")
ui.MenuItem("Three")
ui.MenuItem("Four")
with ui.Menu("Five"):
ui.MenuItem("Six")
ui.MenuItem("Seven")
ui.MenuItem("Delete Shot")
ui.MenuItem("Attach Selected Camera")
"""
)
with ui.HStack(style=self._style_system):
bt = ui.Button("Pushed Button Menu", width=0, style={"background_color": 0xFF000000, "color": 0xFFFFFFFF})
bt.set_mouse_pressed_fn(lambda x, y, b, m, widget=bt: self._show_pushed_menu(x, y, b, m, widget))
ui.Spacer(height=100)
| 5,068 | Python | 36 | 119 | 0.547948 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/md_doc.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .doc_page import DocPage
from omni.kit.documentation.builder import DocumentationBuilderMd
from omni.kit.documentation.builder import DocumentationBuilderPage
class MdDoc(DocPage):
def __init__(self, extension_path, md: DocumentationBuilderMd):
super().__init__(extension_path)
self.__md = md
self.__page = None
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
if self.__page:
self.__page.destroy()
self.__page = None
def create_doc(self, navigate_to=None):
"""Issue the UI"""
self.__page = DocumentationBuilderPage(self.__md, navigate_to)
| 1,108 | Python | 35.966665 | 76 | 0.710289 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/abstract_model_doc.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.
#
"""The documentation for Abstract Model """
from omni import ui
from pxr import UsdGeom
import omni.kit.commands
import omni.usd
from .doc_page import DocPage
SPACING = 5
class VisibilityWatchModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the visibility of the selection"""
def __init__(self):
super(VisibilityWatchModel, self).__init__()
self._usd_context = omni.usd.get_context()
self._selection = None
self._events = None
self._stage_event_sub = None
if self._usd_context is not None:
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="omni.example.ui abstract model stage update"
)
self.prim = None
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
self._usd_context = None
self._selection = None
self._events = None
self._stage_event_sub = None
self.prim = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
# When TC runs tests, it's possible that stage is None
if selection and stage:
self.prim = stage.GetPrimAtPath(selection[0])
# Say to the widgets that the model value is changed
self._value_changed()
def get_value_as_bool(self):
"""Reimplemented get bool"""
if self.prim:
if self.prim.HasAttribute(UsdGeom.Tokens.visibility):
attribute = self.prim.GetAttribute(UsdGeom.Tokens.visibility)
if attribute:
return attribute.Get() == UsdGeom.Tokens.inherited
def set_value(self, value):
"""Reimplemented set bool"""
if self.prim:
omni.kit.commands.execute("ToggleVisibilitySelectedPrims", selected_paths=[self.prim.GetPath()])
# Say to the widgets that the model value is changed
self._value_changed()
class AbstractModelDoc(DocPage):
""" document for CheckBox"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._visibility_model = VisibilityWatchModel()
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
# Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it
# automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But
# we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it
# will fire warning that texture is not destroyed.
if self._visibility_model:
self._visibility_model.clean()
self._visibility_model = None
def create_doc(self, navigate_to=None):
self._section_title("AbstractValueModel")
self._text(
"The AbstractValueModel class provides an abstract interface for the model that holds a single value. It's "
"a central component of the model-delegate-view pattern used in many widgets like CheckBox, StringField(TODO), "
"Slider(TODO), RadioBox(TODO). It's a dynamic data structure independent of the widget implementation. And "
"it holds the data, logic, and rules of the widgets and defines the standard interface that widgets must "
"use to be able to interoperate with the data model. It is not supposed to be instantiated directly. "
"Instead, the user should subclass it to create new models."
)
self._text(
"In the next example, AbstractValueModel class is reimplemented to provide control over the visibility of "
"the selected object."
)
with ui.HStack(width=0, spacing=SPACING):
ui.CheckBox(self._visibility_model)
self._text("Visibility of Selected Prim")
self._code(
"""
class VisibilityWatchModel(ui.AbstractValueModel):
'''
The value model that is reimplemented in Python
to watch the visibility of the selection.
'''
def __init__(self):
super(VisibilityWatchModel, self).__init__()
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = \\
self._events.create_subscription_to_pop(
self._on_stage_event, name="omni.example.ui visibilitywatch stage update")
self.prim = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
if selection and stage:
self.prim = stage.GetPrimAtPath(selection[0])
# Say to the widgets that the model value is changed
self._value_changed()
def get_value_as_bool(self):
'''Reimplemented get bool'''
if self.prim:
attribute = \\
UsdGeom.Imageable(self.prim).GetVisibilityAttr()
inherited = \\
attribute.Get() == UsdGeom.Tokens.inherited
return inherited if attribute else False
def set_value(self, value):
'''Reimplemented set bool'''
if self.prim:
omni.kit.commands.execute(
"ToggleVisibilitySelectedPrims",
selected_paths=[self.prim.GetPath()])
# Say to the widgets that the model value is changed
self._value_changed()
"""
)
ui.Spacer(height=10)
| 6,940 | Python | 41.32317 | 124 | 0.610375 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/field_doc.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.
#
"""The documentation for Field """
from .doc_page import DocPage
from omni import ui
import inspect
SPACING = 5
def field_callbacks():
def on_value(label):
label.text = "Value is changed"
def on_begin(label):
label.text = "Editing is started"
def on_end(label):
label.text = "Editing is finished"
label = ui.Label("Nothing happened", name="text")
model = ui.StringField().model
model.add_value_changed_fn(lambda m, l=label: on_value(l))
model.add_begin_edit_fn(lambda m, l=label: on_begin(l))
model.add_end_edit_fn(lambda m, l=label: on_end(l))
def multiline_field():
initial_text = inspect.getsource(field_callbacks)
model = ui.SimpleStringModel(initial_text)
field = ui.StringField(model, multiline=True)
class FieldDoc(DocPage):
""" document for Field"""
def create_doc(self, navigate_to=None):
self._section_title("Field")
self._caption("StringField", navigate_to)
self._text(
"The StringField widget is a one-line text editor. A field allows the user to enter and edit a single line "
"of plain text. It's implemented using the model-delegate-view pattern and uses AbstractValueModel as the central "
"component of the system."
)
self._text("The following example demonstrates the way how to connect a StringField and a Label.")
field_style = {
"Field": {
"background_color": 0xFFFFFFFF,
"background_selected_color": 0xFFD77800,
"border_color": 0xFF444444,
"border_radius": 1,
"border_width": 0.5,
"color": 0xFF444444,
"font_size": 16.0,
},
"Field:hovered": {"border_color": 0xFF000000},
"Field:pressed": {"background_color": 0xFFFFFFFF, "border_color": 0xFF995400, "border_width": 0.75},
}
def setText(label, text):
"""Sets text on the label"""
# This function exists because lambda cannot contain assignment
label.text = f"You wrote '{text}'"
with ui.HStack():
field = ui.StringField(style=field_style)
ui.Spacer(width=SPACING)
label = ui.Label("", name="text")
field.model.add_value_changed_fn(lambda m, label=label: setText(label, m.get_value_as_string()))
self._code(
"""
def setText(label, text):
'''Sets text on the label'''
# This function exists because lambda cannot contain assignment
label.text = f"You wrote '{text}'"
with ui.HStack():
field = ui.StringField(style=field_style)
label = ui.Label("")
field.model.add_value_changed_fn(
lambda m, label=label: setText(label, m.get_value_as_string()))
"""
)
self._text(
"The following example demonstrates that the model decides the content of the field. The field can have "
"only one of two options, either 'True' or 'False' because the model supports only those two possibilities."
)
with ui.HStack():
checkbox = ui.CheckBox(width=0)
field = ui.StringField()
field.model = checkbox.model
self._code(
"""
with ui.HStack():
checkbox = ui.CheckBox(width=0)
field = ui.StringField()
field.model = checkbox.model
"""
)
self._text(
"In this example, the field can have anything because the model accepts any string, but the model returns "
"bool for checkbox, and the checkbox is off when the string is empty or 'False'."
)
with ui.HStack():
checkbox = ui.CheckBox(width=0)
field = ui.StringField()
checkbox.model = field.model
self._code(
"""
with ui.HStack():
checkbox = ui.CheckBox(width=0)
field = ui.StringField()
checkbox.model = field.model
"""
)
self._caption("FloatField and IntField", navigate_to)
self._text(
"There are fields for string, float and int models. The following example shows how they interact with "
"each other:"
)
self._text("All three fields share the same SimpleFloatModel:")
with ui.HStack():
self._text("FloatField")
self._text("IntField")
self._text("StringField")
with ui.HStack():
left = ui.FloatField()
center = ui.IntField()
right = ui.StringField()
center.model = left.model
right.model = left.model
self._text("All three fields share the same SimpleIntModel:")
with ui.HStack():
self._text("FloatField")
self._text("IntField")
self._text("StringField")
with ui.HStack():
left = ui.FloatField()
center = ui.IntField()
right = ui.StringField()
left.model = center.model
right.model = center.model
self._text("All three fields share the same SimpleStringModel:")
with ui.HStack():
self._text("FloatField")
self._text("IntField")
self._text("StringField")
with ui.HStack():
left = ui.FloatField()
center = ui.IntField()
right = ui.StringField()
left.model = right.model
center.model = right.model
self._text(
"The widget doesn't keep the data due to the model-delegate-view pattern. However, there are two ways to track the "
"state of the widget. It's possible to reimplement AbstractValueModel, for details see the chapter "
"`AbstractValueModel`. The second way is using the callbacks of the model. This is a minimal example "
"of callbacks."
)
field_callbacks()
self._code(inspect.getsource(field_callbacks).split("\n", 1)[-1])
self._caption("Multiline StringField", navigate_to)
self._text(
"Property `multiline` of `StringField` allows to press enter and create a new line. It's possible to "
"finish editing with Ctrl-Enter."
)
with ui.Frame(style=field_style, height=300):
multiline_field()
self._code(inspect.getsource(multiline_field).split("\n", 1)[-1])
ui.Spacer(height=10)
| 7,030 | Python | 34.155 | 128 | 0.582077 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/multifield_doc.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.
#
"""The documentation for Shapes"""
from omni import ui
from .doc_page import DocPage
import inspect
import omni.usd
from .colorwidget_doc import USDColorModel
SPACING = 5
def simplest_field():
ui.MultiIntField(0, 0, 0, 0)
def simplest_drag():
ui.MultiFloatDragField(0.0, 0.0, 0.0, 0.0)
def matrix_field():
args = [1.0 if i % 5 == 0 else 0.0 for i in range(16)]
ui.MultiFloatField(*args, width=ui.Percent(50), h_spacing=5, v_spacing=2)
def usd_field():
with ui.HStack(spacing=SPACING):
model = USDColorModel()
ui.ColorWidget(model, width=0)
ui.MultiFloatField(model)
def usd_drag():
with ui.HStack(spacing=SPACING):
model = USDColorModel()
ui.ColorWidget(model, width=0)
ui.MultiFloatDragField(model, min=0.0, max=2.0)
class MultiFieldDoc(DocPage):
"""Document for MultiField"""
def create_doc(self, navigate_to=None):
"""Descriptions for MultiField"""
self._section_title("MultiField")
self._text(
"MultiField widget groups are the widgets that have multiple similar widgets to represent each item in the "
"model. It's handy to use them for arrays and multi-component data like float3, matrix, and color."
)
simplest_field()
self._code(inspect.getsource(simplest_field).split("\n", 1)[-1])
simplest_drag()
self._code(inspect.getsource(simplest_drag).split("\n", 1)[-1])
matrix_field()
self._code(inspect.getsource(matrix_field).split("\n", 1)[-1])
# TODO omni.ui: restore functionality for Kit Next
if False:
usd_field()
self._code(inspect.getsource(usd_field).split("\n", 1)[-1])
usd_drag()
self._code(inspect.getsource(usd_drag).split("\n", 1)[-1])
| 2,255 | Python | 28.68421 | 120 | 0.659867 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/colorwidget_doc.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.
#
"""The documentation for ColorWidget"""
from .doc_page import DocPage
from omni import ui
from pxr import Gf
from pxr import UsdGeom
from typing import Any
import inspect
import omni.kit.commands
import omni.usd
import weakref
SPACING = 5
class SetDisplayColorCommand(omni.kit.commands.Command):
"""
Change prim display color undoable **Command**. Unlike ChangePropertyCommand, it can undo property creation.
Args:
gprim (Gprim): Prim to change display color on.
value: Value to change to.
value: Value to undo to.
"""
def __init__(self, gprim: UsdGeom.Gprim, color: Any, prev: Any):
self._gprim = gprim
self._color = color
self._prev = prev
def do(self):
color_attr = self._gprim.CreateDisplayColorAttr()
color_attr.Set([self._color])
def undo(self):
color_attr = self._gprim.GetDisplayColorAttr()
if self._prev is None:
color_attr.Clear()
else:
color_attr.Set([self._prev])
class FloatModel(ui.SimpleFloatModel):
def __init__(self, parent):
super().__init__()
self._parent = weakref.ref(parent)
def begin_edit(self):
parent = self._parent()
parent.begin_edit(None)
def end_edit(self):
parent = self._parent()
parent.end_edit(None)
class USDColorItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
class USDColorModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
self._items = [USDColorItem(FloatModel(self)) for i in range(3)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
# Omniverse contexts
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="omni.example.ui colorwidget stage update"
)
# Privates
self._subscription = None
self._gprim = None
self._prev_color = None
self._edit_mode_counter = 0
def _on_stage_event(self, event):
"""Called with subscription to pop"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
"""Called when the user changes the selection"""
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
self._subscription = None
self._gprim = None
# When TC runs tests, it's possible that stage is None
if selection and stage:
self._gprim = UsdGeom.Gprim.Get(stage, selection[0])
if self._gprim:
color_attr = self._gprim.GetDisplayColorAttr()
usd_watcher = omni.usd.get_watcher()
self._subscription = usd_watcher.subscribe_to_change_info_path(
color_attr.GetPath(), self._on_usd_changed
)
# Change the widget color
self._on_usd_changed()
def _on_value_changed(self, item):
"""Called when the submodel is chaged"""
if not self._gprim:
return
if self._edit_mode_counter > 0:
# Change USD only if we are in the edit mode.
color_attr = self._gprim.CreateDisplayColorAttr()
color = Gf.Vec3f(
self._items[0].model.get_value_as_float(),
self._items[1].model.get_value_as_float(),
self._items[2].model.get_value_as_float(),
)
color_attr.Set([color])
self._item_changed(item)
def _on_usd_changed(self, path=None):
"""Called with UsdWatcher when something in USD is changed"""
color = self._get_current_color() or Gf.Vec3f(0.0)
for i in range(len(self._items)):
self._items[i].model.set_value(color[i])
def _get_current_color(self):
"""Returns color of the current object"""
if self._gprim:
color_attr = self._gprim.GetDisplayColorAttr()
if color_attr:
color_array = color_attr.Get()
if color_array:
return color_array[0]
def get_item_children(self, item):
"""Reimplemented from the base class"""
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
if self._edit_mode_counter == 0:
self._prev_color = self._get_current_color()
self._edit_mode_counter += 1
def end_edit(self, item):
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
self._edit_mode_counter -= 1
if not self._gprim or self._edit_mode_counter > 0:
return
color = Gf.Vec3f(
self._items[0].model.get_value_as_float(),
self._items[1].model.get_value_as_float(),
self._items[2].model.get_value_as_float(),
)
omni.kit.commands.execute("SetDisplayColor", gprim=self._gprim, color=color, prev=self._prev_color)
def color_field():
with ui.HStack(spacing=SPACING):
color_model = ui.ColorWidget(width=0, height=0).model
for item in color_model.get_item_children():
component = color_model.get_item_value_model(item)
ui.FloatField(component)
def color_drag():
with ui.HStack(spacing=SPACING):
color_model = ui.ColorWidget(0.125, 0.25, 0.5, width=0, height=0).model
for item in color_model.get_item_children():
component = color_model.get_item_value_model(item)
ui.FloatDrag(component)
def color_combo():
with ui.HStack(spacing=SPACING):
color_model = ui.ColorWidget(width=0, height=0).model
ui.ComboBox(color_model)
def two_usd_color_boxes():
with ui.HStack(spacing=SPACING):
ui.ColorWidget(USDColorModel(), width=0)
ui.Label("First ColorWidget", name="text")
with ui.HStack(spacing=SPACING):
ui.ColorWidget(USDColorModel(), width=0)
ui.Label("Second ColorWidget has independed model", name="text")
class ColorWidgetDoc(DocPage):
"""Document for ColorWidget"""
def create_doc(self, navigate_to=None):
self._section_title("ColorWidget")
self._text(
"The ColorWidget widget is a button that displays the color from the item model and can open a picker "
"window. The color dialog's function is to allow users to choose colors."
)
self._text("Fields connected to the color model")
color_field()
self._code(inspect.getsource(color_field).split("\n", 1)[-1])
self._text("Drags connected to the color model")
color_drag()
self._code(inspect.getsource(color_drag).split("\n", 1)[-1])
self._text("ComboBox connected to the color model.")
color_combo()
self._code(inspect.getsource(color_combo).split("\n", 1)[-1])
# TODO omni.ui: restore functionality for Kit Next
if False:
self._text("Two different models that watch USD Stage. Undo/Redo example.")
two_usd_color_boxes()
with ui.ScrollingFrame(height=250, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON):
self._code(
inspect.getsource(FloatModel)
+ "\n"
+ inspect.getsource(USDColorItem)
+ "\n"
+ inspect.getsource(USDColorModel)
+ "\n"
+ inspect.getsource(two_usd_color_boxes)
)
ui.Spacer(height=20)
| 8,824 | Python | 31.806691 | 115 | 0.600748 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/widget_doc.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.
#
"""The documentation for Widget"""
from .doc_page import DocPage
from omni import ui
from omni.ui import color as cl
from pathlib import Path
import inspect
import random
SPACING = 5
def tooltip_fixed_position():
ui.Button("Fixed-position Tooltip", width=200, tooltip="Hello World", tooltip_offset_y=22)
def tooltip_random_position():
button = ui.Button("Random-position Tooltip", width=200, tooltip_offset_y=22)
def create_tooltip(button=button):
button.tooltip_offset_x = random.randint(0, 200)
ui.Label("Hello World")
button.set_tooltip_fn(create_tooltip)
def image_button():
style = {
"Button": {"stack_direction": ui.Direction.TOP_TO_BOTTOM},
"Button.Image": {
"color": cl("#99CCFF"),
"image_url": "resources/icons/Learn_128.png",
"alignment": ui.Alignment.CENTER,
},
"Button.Label": {"alignment": ui.Alignment.CENTER},
}
def direction(model, button, style=style):
value = model.get_item_value_model().get_value_as_int()
direction = (
ui.Direction.TOP_TO_BOTTOM,
ui.Direction.BOTTOM_TO_TOP,
ui.Direction.LEFT_TO_RIGHT,
ui.Direction.RIGHT_TO_LEFT,
ui.Direction.BACK_TO_FRONT,
ui.Direction.FRONT_TO_BACK,
)[value]
style["Button"]["stack_direction"] = direction
button.set_style(style)
def align(model, button, image, style=style):
value = model.get_item_value_model().get_value_as_int()
alignment = (
ui.Alignment.LEFT_TOP,
ui.Alignment.LEFT_CENTER,
ui.Alignment.LEFT_BOTTOM,
ui.Alignment.CENTER_TOP,
ui.Alignment.CENTER,
ui.Alignment.CENTER_BOTTOM,
ui.Alignment.RIGHT_TOP,
ui.Alignment.RIGHT_CENTER,
ui.Alignment.RIGHT_BOTTOM,
)[value]
if image:
style["Button.Image"]["alignment"] = alignment
else:
style["Button.Label"]["alignment"] = alignment
button.set_style(style)
def layout(model, button, padding, style=style):
padding = "padding" if padding else "margin"
style["Button"][padding] = model.get_value_as_float()
button.set_style(style)
def spacing(model, button):
button.spacing = model.get_value_as_float()
button = ui.Button("Label", style=style, width=64, height=64)
with ui.HStack(width=ui.Percent(50)):
ui.Label('"Button": {"stack_direction"}', name="text")
options = (
0,
"TOP_TO_BOTTOM",
"BOTTOM_TO_TOP",
"LEFT_TO_RIGHT",
"RIGHT_TO_LEFT",
"BACK_TO_FRONT",
"FRONT_TO_BACK",
)
model = ui.ComboBox(*options).model
model.add_item_changed_fn(lambda m, i, b=button: direction(m, b))
alignment = (
4,
"LEFT_TOP",
"LEFT_CENTER",
"LEFT_BOTTOM",
"CENTER_TOP",
"CENTER",
"CENTER_BOTTOM",
"RIGHT_TOP",
"RIGHT_CENTER",
"RIGHT_BOTTOM",
)
with ui.HStack(width=ui.Percent(50)):
ui.Label('"Button.Image": {"alignment"}', name="text")
model = ui.ComboBox(*alignment).model
model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 1))
with ui.HStack(width=ui.Percent(50)):
ui.Label('"Button.Label": {"alignment"}', name="text")
model = ui.ComboBox(*alignment).model
model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 0))
with ui.HStack(width=ui.Percent(50)):
ui.Label("padding", name="text")
model = ui.FloatSlider(min=0, max=500).model
model.add_value_changed_fn(lambda m, b=button: layout(m, b, 1))
with ui.HStack(width=ui.Percent(50)):
ui.Label("margin", name="text")
model = ui.FloatSlider(min=0, max=500).model
model.add_value_changed_fn(lambda m, b=button: layout(m, b, 0))
with ui.HStack(width=ui.Percent(50)):
ui.Label("Button.spacing", name="text")
model = ui.FloatSlider(min=0, max=50).model
model.add_value_changed_fn(lambda m, b=button: spacing(m, b))
class WidgetDoc(DocPage):
""" document for Widget"""
def radio_button(self):
style = {
"": {"background_color": cl.transparent, "image_url": f"{self._extension_path}/icons/radio_off.svg"},
":checked": {"image_url": f"{self._extension_path}/icons/radio_on.svg"},
}
collection = ui.RadioCollection()
for i in range(5):
with ui.HStack(style=style):
ui.RadioButton(radio_collection=collection, width=30, height=30)
ui.Label(f"Option {i}", name="text")
ui.IntSlider(collection.model, min=0, max=4)
def create_doc(self, navigate_to=None):
self._section_title("Widgets")
self._text(
"The widget provides all the base functionality for most ui elements" "There is a lot of default feature "
)
self._caption("Button", navigate_to)
self._text(
"The Button widget provides a command button. The command button, is perhaps the most commonly used widget "
"in any graphical user interface. Click a button to execute a command. It is rectangular and typically "
"displays a text label describing its action."
)
def make_longer_text(button):
"""Set the text of the button longer"""
button.text = "Longer " + button.text
def make_shorter_text(button):
"""Set the text of the button shorter"""
splitted = button.text.split(" ", 1)
button.text = splitted[1] if len(splitted) > 1 else splitted[0]
with ui.HStack(style=self._style_system):
btn_with_text = ui.Button("Text", width=0)
ui.Button("Press me", width=0, clicked_fn=lambda b=btn_with_text: make_longer_text(b))
btn_with_text.set_clicked_fn(lambda b=btn_with_text: make_shorter_text(b))
self._code(
"""
def make_longer_text(button):
'''Set the text of the button longer'''
button.text = "Longer " + button.text
def make_shorter_text(button):
'''Set the text of the button shorter'''
splitted = button.text.split(" ", 1)
button.text = \\
splitted[1] if len(splitted) > 1 else splitted[0]
with ui.HStack(style=style_system):
btn_with_text = ui.Button("Text", width=0)
ui.Button(
"Press me",
width=0,
clicked_fn=lambda b=btn_with_text: make_longer_text(b)
)
btn_with_text.set_clicked_fn(
lambda b=btn_with_text: make_shorter_text(b))
"""
)
image_button()
self._code(inspect.getsource(image_button).split("\n", 1)[-1])
self._caption("RadioButton", navigate_to)
self._text(
"RadioButton is the widget that allows the user to choose only one of a predefined set of mutually "
"exclusive options."
)
self._text(
"RadioButtons are arranged in collections of two or more with the class RadioGroup, which is the central "
"component of the system and controls the behavior of all the RadioButtons in the collection."
)
self.radio_button()
self._code(inspect.getsource(self.radio_button).split("\n", 1)[-1])
self._caption("Label", navigate_to)
self._text(
"Labels are used everywhere in omni.ui. They are text-only objects, and don't have a background color"
"But you can control the color, font_size and alignment in the styling."
)
self._exec_code(
"""
ui.Label("this is a simple label", style={"color": cl.black})
"""
)
self._exec_code(
"""
ui.Label("label with aligment", style={"color": cl.black}, alignment=ui.Alignment.CENTER)
"""
)
self._exec_code(
"""
label_style = {"Label": {"font_size": 16, "color": cl.blue, "alignment":ui.Alignment.RIGHT }}
ui.Label("Label with style", style=label_style)
"""
)
self._exec_code(
"""
ui.Label(
"Label can be elided: Lorem ipsum dolor "
"sit amet, consectetur adipiscing elit, sed do "
"eiusmod tempor incididunt ut labore et dolore "
"magna aliqua. Ut enim ad minim veniam, quis "
"nostrud exercitation ullamco laboris nisi ut "
"aliquip ex ea commodo consequat. Duis aute irure "
"dolor in reprehenderit in voluptate velit esse "
"cillum dolore eu fugiat nulla pariatur. Excepteur "
"sint occaecat cupidatat non proident, sunt in "
"culpa qui officia deserunt mollit anim id est "
"laborum.",
style={"color":cl.black},
elided_text=True,
)
"""
)
self._caption("Tooltip", navigate_to)
self._text(
"All Widget can be augmented with a tooltip, it can take 2 forms, either a simple ui.Label or a callback"
"when using the callback, tooltip_fn= or widget.set_tooltip_fn() you can create virtually any widget for "
"the tooltip"
)
self._exec_code(
"""
tooltip_style = {
"Tooltip": {"background_color": cl("#DDDD00"), "color": cl("#333333"), "margin_width": 3 ,
"margin_height": 2 , "border_width":3, "border_color": cl.red }}
ui.Button("Simple Label Tooltip", name="tooltip", width=200,
tooltip=" I am a text ToolTip ", style=tooltip_style)
"""
)
self._exec_code(
"""
def create_tooltip():
with ui.VStack(width=200, style=tooltip_style):
with ui.HStack():
ui.Label("Fancy tooltip", width=150)
ui.IntField().model.set_value(12)
ui.Line(height=2, style={"color": cl.white})
with ui.HStack():
ui.Label("Anything is possible", width=150)
ui.StringField().model.set_value("you bet")
image_source = "resources/desktop-icons/omniverse_512.png"
ui.Image(
image_source,
width=200,
height=200,
alignment=ui.Alignment.CENTER,
style={"margin": 0},
)
tooltip_style = {
"Tooltip": {"background_color": cl("#444444"), "border_width":2, "border_radius":5},
}
ui.Button("Callback function Tooltip", width=200, style=tooltip_style, tooltip_fn=create_tooltip)
"""
)
tooltip_fixed_position()
self._code(inspect.getsource(tooltip_fixed_position).split("\n", 1)[-1])
tooltip_random_position()
self._code(inspect.getsource(tooltip_random_position).split("\n", 1)[-1])
ui.Spacer(height=50)
self._caption("Debug Color", navigate_to)
self._text("All Widget can be styled to use a debug color that enable you to visualize their frame")
self._exec_code(
"""
style = {"background_color": cl("#DDDD00"),
"color": cl("#333333"),
"debug_color": cl("#FF000022") }
ui.Label("Label with Debug", width=200, style=style)
"""
)
self._exec_code(
"""
style = {":hovered": {"debug_color": cl("#00FFFF22") },
"Label": {"padding": 3,
"background_color": cl("#DDDD00"),
"color": cl("#333333"),
"debug_color": cl("#0000FF22") }}
with ui.HStack(width=500, style=style):
ui.Label("Label 1", width=50)
ui.Label("Label 2")
ui.Label("Label 3",
width=100,
alignment=ui.Alignment.CENTER)
ui.Spacer()
ui.Label("Label 3", width=50)
"""
)
self._caption("Font", navigate_to)
self._text(
"It's possible to set the font of the label using styles. The style key 'font' should point to the font "
"file, which allows packaging of the font to the extension. We support both TTF and OTF formats. "
"All text-based widgets support custom fonts."
)
self._exec_code(
"""
ui.Label(
"The quick brown fox jumps over the lazy dog",
style={
"font_size": 55,
"font": "${fonts}/OpenSans-SemiBold.ttf",
"alignment": ui.Alignment.CENTER
},
word_wrap=True,
)
"""
)
ui.Spacer(height=10)
| 13,547 | Python | 34.465968 | 120 | 0.552668 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/plot_doc.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.
#
"""The documentation for Menu"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import math
class PlotDoc(DocPage):
""" document for Plot"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._data = []
for i in range(360):
self._data.append(math.cos(math.radians(i)))
def create_doc(self, navigate_to=None):
self._section_title("Plot")
self._text("The Plot class displayes a line or histogram image.")
self._text("The data of image is specified as a data array or a provider function.")
ui.Plot(ui.Type.LINE, -1.0, 1.0, *self._data, width=360, height=100, style={"color": cl.red})
self._code(
"""
self._data = []
for i in range(360):
self._data.append(math.cos(math.radians(i)))
ui.Plot(ui.Type.LINE, -1.0, 1.0, *self._data, width=360, height=100, style={"color": cl.red})
"""
)
plot = ui.Plot(
ui.Type.HISTOGRAM,
-1.0,
1.0,
self._on_data_provider,
360,
width=360,
height=100,
style={"color": cl.blue},
)
plot.value_stride = 6
self._code(
"""
def _on_data_provider(self, index):
return math.sin(math.radians(index))
plot = ui.Plot(ui.Type.HISTOGRAM, -1.0, 1.0, self._on_data_provider, 360, width=360, height=100, style={"color": cl.blue})
plot.value_stride = 6
"""
)
ui.Spacer(height=100)
def _on_data_provider(self, index):
return math.sin(math.radians(index))
| 2,140 | Python | 29.585714 | 130 | 0.590187 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/styling_doc.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.
#
"""The documentation for Styling"""
from .doc_page import DocPage
from functools import partial
from omni import ui
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import inspect
SPACING = 5
def named_shades():
def set_color(color):
cl.example_color = color
def set_width(value):
fl.example_width = value
cl.example_color = cl.green
fl.example_width = 1.0
with ui.HStack(height=100, spacing=5):
with ui.ZStack():
ui.Rectangle(
style={
"background_color": cl.shade(
"aqua",
orange=cl.orange,
another=cl.example_color,
transparent=cl.transparent,
black=cl.black,
),
"border_width": fl.shade(1, orange=4, another=8),
"border_radius": fl.one,
"border_color": cl.black,
},
)
ui.Label(
"ui.Rectangle(\n"
"\tstyle={\n"
'\t\t"background_color":\n'
"\t\t\tcl.shade(\n"
'\t\t\t\t"aqua",\n'
"\t\t\t\torange=cl(1, 0.5, 0),\n"
"\t\t\t\tanother=cl.example_color),\n"
'\t\t"border_width":\n'
"\t\t\tfl.shade(1, orange=4, another=8)})",
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.ZStack():
ui.Rectangle(
style={
"background_color": cl.example_color,
"border_width": fl.example_width,
"border_radius": fl.one,
"border_color": cl.black,
}
)
ui.Label(
"ui.Rectangle(\n"
"\tstyle={\n"
'\t\t"background_color": cl.example_color,\n'
'\t\t"border_width": fl.example_width)})',
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.HStack():
ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, ""))
ui.Button('ui.set_shade("orange")', clicked_fn=partial(ui.set_shade, "orange"))
ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another"))
with ui.HStack():
ui.Button("fl.example_width = 1", clicked_fn=partial(set_width, 1))
ui.Button("fl.example_width = 4", clicked_fn=partial(set_width, 4))
with ui.HStack():
ui.Button('cl.example_color = "green"', clicked_fn=partial(set_color, "green"))
ui.Button("cl.example_color = cl(0.8)", clicked_fn=partial(set_color, cl(0.8)))
def url_shades():
def set_url(url_path: str):
url.example_url = url_path
walk = "resources/icons/Nav_Walkmode.png"
fly = "resources/icons/Nav_Flymode.png"
url.example_url = walk
with ui.HStack(height=100, spacing=5):
with ui.ZStack():
ui.Image(style={"image_url": url.example_url})
ui.Label(
'ui.Image(\n\tstyle={"image_url": cl.example_url})\n',
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.ZStack():
ui.ImageWithProvider(
style={
"image_url": url.shade(
"resources/icons/Move_local_64.png",
another="resources/icons/Move_64.png",
orange="resources/icons/Rotate_local_64.png",
)
}
)
ui.Label(
"ui.ImageWithProvider(\n"
"\tstyle={\n"
'\t\t"image_url":\n'
"\t\t\tst.shade(\n"
'\t\t\t\t"Move_local_64.png",\n'
'\t\t\t\tanother="Move_64.png")})\n',
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.HStack():
ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, ""))
ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another"))
with ui.HStack():
ui.Button("url.example_url = Nav_Walkmode.png", clicked_fn=partial(set_url, walk))
ui.Button("url.example_url = Nav_Flymode.png", clicked_fn=partial(set_url, fly))
def font_size():
def value_changed(label, value):
label.style = {"color": ui.color(0), "font_size": value.as_float}
slider = ui.FloatSlider(min=1.0, max=150.0)
slider.model.as_float = 10.0
label = ui.Label("Omniverse", style={"color": ui.color(0), "font_size": 7.0})
slider.model.add_value_changed_fn(partial(value_changed, label))
class StylingDoc(DocPage):
""" document for Styling workflow"""
def create_doc(self, navigate_to=None):
self._section_title("Styling")
self._caption("The Style Sheet Syntax", navigate_to)
self._text(
"OMNI.UI Style Sheet rules are almost identical to those of HTML CSS. Style sheets consist of a sequence "
"of style rules. A style rule is made up of a selector and a declaration. The selector specifies which "
"widgets are affected by the rule; the declaration specifies which properties should be set on the widget. "
"For example:"
)
with ui.VStack(width=0, style={"Button": {"background_color": cl("#097EFF")}}):
ui.Button("Style Example")
self._code(
"""
with ui.VStack(width=0, style={"Button": {"background_color": cl("#097EFF")}}):
ui.Button("Style Example")
"""
)
self._text(
'In the above style rule, Button is the selector, and { "background_color": cl("#097EFF") } is the '
"declaration. The rule specifies that Button should use blue as its background color."
)
with ui.VStack():
self._table("Selector", "Example", "Explanation", cl.black)
self._table("Type Selector", "Button", "Matches instances of Button.")
self._table(
"Name Selector", "Button::okButton", "Matches all Button instances whose object name is okButton."
)
self._table(
"State Selector",
"Button:hovered",
"Matches all Button instances whose state is hovered. It means the mouse should be in the widget area. "
"Pseudo-states appear at the end of the selector, with a colon (:) in between. The supported states are "
"hovered and pressed.",
)
self._text("It's possible to omit the selector and override the property in all the widget types:")
with ui.VStack(width=0, style={"background_color": cl("#097EFF")}):
ui.Button("Style Example")
self._code(
"""
with ui.VStack(width=0, style={"background_color": cl("#097EFF")}):
ui.Button("Style Example")
"""
)
self._text(
"The difference with the previous button is that all the colors, including pressed color and hovered "
"color, are overridden."
)
style1 = {
"Button": {"border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0},
"Button::one": {
"background_color": cl("#097EFF"),
"background_gradient_color": cl("#6DB2FA"),
"border_color": cl("#1D76FD"),
},
"Button.Label::one": {"color": cl.white},
"Button::one:hovered": {"background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF")},
"Button::one:pressed": {"background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF")},
"Button::two": {"background_color": cl.white, "border_color": cl("#B1B1B1")},
"Button.Label::two": {"color": cl("#272727")},
"Button::three:hovered": {
"background_color": cl("#006EFF"),
"background_gradient_color": cl("#5AAEFF"),
"border_color": cl("#1D76FD"),
},
"Button::four:pressed": {
"background_color": cl("#6DB2FA"),
"background_gradient_color": cl("#097EFF"),
"border_color": cl("#1D76FD"),
},
}
with ui.HStack(style=style1):
ui.Button("One", name="one")
ui.Button("Two", name="two")
ui.Button("Three", name="three")
ui.Button("Four", name="four")
ui.Button("Five", name="five")
self._code(
"""
style1 = {
"Button": {
"border_width": 0.5,
"border_radius": 0.0,
"margin": 5.0,
"padding": 5.0
},
"Button::one": {
"background_color": cl("#097EFF"),
"background_gradient_color": cl("#6DB2FA"),
"border_color": cl("#1D76FD"),
},
"Button.Label::one": {
"color": cl.white,
},
"Button::one:hovered": {
"background_color": cl("#006EFF"),
"background_gradient_color": cl("#5AAEFF")
},
"Button::one:pressed": {
"background_color": cl("#6DB2FA"),
"background_gradient_color": cl("#097EFF")
},
"Button::two": {
"background_color": cl.white,
"border_color": cl("#B1B1B1")
},
"Button.Label::two": {
"color": cl("#272727")
},
"Button::three:hovered": {
"background_color": cl("#006EFF"),
"background_gradient_color": cl("#5AAEFF"),
"border_color": cl("#1D76FD"),
},
"Button::four:pressed": {
"background_color": cl("#6DB2FA"),
"background_gradient_color": cl("#097EFF"),
"border_color": cl("#1D76FD"),
},
}
with ui.HStack(style=style1):
ui.Button("One", name="one")
ui.Button("Two", name="two")
ui.Button("Three", name="three")
ui.Button("Four", name="four")
ui.Button("Five", name="five")
"""
)
self._text(
"It's possible to assign any style override to any level of the widget. It can be assigned to both parents "
"and children at the same time."
)
with ui.HStack(style=self._style_system):
ui.Button("One")
ui.Button("Two", style={"color": cl("#AAAAAA")})
ui.Button("Three", style={"background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA")})
ui.Button(
"Four", style={":hovered": {"background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF")}}
)
ui.Button(
"Five",
style={"Button:pressed": {"background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF")}},
)
self._code(
"""
style_system = {
"Button": {
"background_color": cl("#E1E1E1"),
"border_color": cl("#ADADAD"),
"border_width": 0.5,
"border_radius": 0.0,
"margin": 5.0,
"padding": 5.0,
},
"Button.Label": {
"color": cl.black,
},
"Button:hovered": {
"background_color": cl("#E5F1FB"),
"border_color": cl("#0078D7")
},
"Button:pressed": {
"background_color": cl("#CCE4F7"),
"border_color": cl("#005499"),
"border_width": 1.0
},
}
with ui.HStack(style=style_system):
ui.Button("One")
ui.Button("Two", style={"color": cl("#AAAAAA")})
ui.Button("Three", style={
"background_color": cl("#097EFF"),
"background_gradient_color": cl("#6DB2FA")}
)
ui.Button(
"Four", style={
":hovered": {
"background_color": cl("#006EFF"),
"background_gradient_color": cl("#5AAEFF")
}
}
)
ui.Button(
"Five",
style={
"Button:pressed": {
"background_color": cl("#6DB2FA"),
"background_gradient_color": cl("#097EFF")
}
},
)
"""
)
self._caption("Color Syntax", navigate_to)
self._text(
"There are many ways that colors can be described with omni.ui.color. If alpha is not specified, it is assumed to be 255 or 1.0."
)
self._code(
"""
from omni.ui import color as cl
cl("#CCCCCC") # RGB
cl("#CCCCCCFF") # RGBA
cl(128, 128, 128) # RGB
cl(0.5, 0.5, 0.5) # RGB
cl(128, 128, 128, 255) # RGBA
cl(0.5, 0.5, 0.5, 1.0) # RGBA
cl(128) # RGB all the same
cl(0.5) # RGB all the same
cl.blue
"""
)
self._text(
"Note: You may see something like this syntax in older code, but that syntax is not suggested anymore:"
)
self._code('"background_color": 0xFF886644 # Same as cl("#446688FF")')
self._text(
"Because of the way bytes are packed with little-endian format in that syntax, the color components appear to be backwards (ABGR). "
"Going forward only omni.ui.color syntax should be used."
)
self._caption("Shades", navigate_to)
self._text(
"Shades are used to have multiple named color palettes with the ability to runtime switch. The shade can "
"be defined with the following code:"
)
self._code('cl.shade(cl("#0066FF"), red=cl.red, green=cl("#00FF66"))')
self._text(
"It can be assigned to the color style. It's possible to switch the color with the following command "
"globally:"
)
self._code('cl.set_shade("red")')
named_shades()
self._code(inspect.getsource(named_shades).split("\n", 1)[-1])
self._caption("URL Shades", navigate_to)
self._text("It's also possible to use shades for specifying shortcuts to the images and style-based paths.")
url_shades()
self._code(inspect.getsource(url_shades).split("\n", 1)[-1])
self._caption("Font Size", navigate_to)
self._text("It's possible to set the font size with the style:")
font_size()
self._code(inspect.getsource(font_size).split("\n", 1)[-1])
ui.Spacer(height=10)
| 15,870 | Python | 35.823666 | 144 | 0.497669 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/custom_window_example.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.
#
"""an example of creating a custom with shapes and drags window"""
# TODO : This need clean up for full documentation
from omni import ui
EXTENSION_NAME = "Brick Demo Window"
LIGHT_WINDOW_STYLE = {
# main frame style
"ScrollingFrame::canvas": {"background_color": 0xFFCACACA},
"Frame::main_frame": {"background_color": 0xFFCACACA},
# title bar style
"Label::title": {"color": 0xFF777777, "font_size": 16.0},
"Rectangle::titleBar": {"background_color": 0xFFCACACA},
"Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0},
"Triangle::timeArrows": {"background_color": 0xFFCACACA},
"Label::timeLabel": {"color": 0xFFDDDDDD, "font_size": 16.0},
# custom widget slider
"Rectangle::sunStudySliderBackground": {
"background_color": 0xFFBBBBBB,
"border_color": 0xFF888888,
"border_width": 1.0,
"border_radius": 10.0,
},
"Rectangle::sunStudySliderForground": {"background_color": 0xFF888888},
"Circle::slider": {"background_color": 0xFFBBBBBB},
"Circle::slider:hovered": {"background_color": 0xFFCCCCCC},
"Circle::slider:pressed": {"background_color": 0xFFAAAAAA},
"Triangle::selector": {"background_color": 0xFF888888},
"Triangle::selector:hovered": {"background_color": 0xFF999999},
"Triangle::selector:pressed": {"background_color": 0xFF777777},
# toolbar
"Triangle::play_button": {"background_color": 0xFF6E6E6E},
}
DARK_WINDOW_STYLE = {
# main frame style
"ScrollingFrame::canvas": {"background_color": 0xFF454545},
"Frame::main_frame": {"background_color": 0xFF454545},
# title bar style
"Label::title": {"color": 0xFF777777, "font_size": 16.0},
"Rectangle::titleBar": {"background_color": 0xFF454545},
"Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0},
"Triangle::timeArrows": {"background_color": 0xFF454545},
"Label::timeLabel": {"color": 0xFF454545, "font_size": 16.0},
# custom widget slider
"Rectangle::sunStudySliderBackground": {
"background_color": 0xFF666666,
"border_color": 0xFF333333,
"border_width": 1.0,
"border_radius": 10.0,
},
"Rectangle::sunStudySliderForground": {"background_color": 0xFF333333},
"Circle::slider": {"background_color": 0xFF888888},
"Triangle::selector": {"background_color": 0xFF888888},
# toolbar
"Triangle::play_button": {"background_color": 0xFF6E6E6E},
}
class BrickSunStudyWindow:
""" example of sun study window using Omni::UI """
def __init__(self):
self._is_playing = False
self._window_Frame = None
self._time_selector_left_spacer = None
self._slider_spacer = None
self._slider_spacer_width = [200]
self._start_time_offset = [200]
self._start_time_label = None
self._start_time = "8:00 AM"
self._end_time_offset = [600]
self._end_time_label = None
self._end_time = "6:00 PM"
self._time_of_day_offset = [200]
self._mouse_press_position = [0, 0]
def _play_pause_fn(self, x, y):
""" """
self._is_playing = not self._is_playing
self._play_button.visible = not self._is_playing
self._pause_button.visible = self._is_playing
def _on_object_mouse_pressed(self, position, x, y):
position[0] = x
position[1] = y
def on_placer_mouse_moved_both(self, placer, offset, position, x, y):
# TODO: DPI is the problem we need to solve
offset[0] += x - position[0]
offset[1] += y - position[1]
placer.offset_x = max(offset[0], 0)
placer.offset_y = offset[1]
self._on_object_mouse_pressed(position, x, y)
def on_time_placer_mouse_moved_X(self, placer, offset, position, x, y):
# TODO: DPI is the problem we need to solve
offset[0] += x - position[0]
offset[0] = max(offset[0], 0)
placer.offset_x = offset[0]
# this is not very correct but serve ok for this demo
hours = int(offset[0] / 800 * 24)
time = "AM"
if hours > 12:
hours = hours - 12
time = "PM"
self._current_time_label.text = f"{hours}:00 {time}"
self._on_object_mouse_pressed(position, x, 0)
def on_start_placer_mouse_moved_X(self, placer, offset, position, x, y):
# TODO: DPI is the problem we need to solve
offset[0] += x - position[0]
offset[0] = max(offset[0], 0)
placer.offset_x = offset[0]
self._time_range_placer.offset_x = offset[0] + 50
self._time_range_rectangle.width = ui.Pixel(self._end_time_offset[0] - self._start_time_offset[0] + 3)
# this is not very correct but serve ok for this demo
hours = int(offset[0] / 800 * 24)
time = "AM"
if hours > 12:
hours = hours - 12
time = "PM"
self._start_time_label.text = f"{hours}:00 {time}"
self._on_object_mouse_pressed(position, x, 0)
def on_end_placer_mouse_moved_X(self, placer, offset, position, x, y):
# TODO: DPI is the problem we need to solve
offset[0] += x - position[0]
offset[0] = max(offset[0], 0)
placer.offset_x = offset[0]
self._time_range_rectangle.width = ui.Pixel(self._end_time_offset[0] - self._start_time_offset[0] + 3)
# this is not very correct but serve ok for this demo
hours = int(offset[0] / 800 * 24)
time = "AM"
if hours > 12:
hours = hours - 12
time = "PM"
self._end_time_label.text = f"{hours}:00 {time}"
self._on_object_mouse_pressed(position, x, 0)
def set_style_light(self, button):
""" """
self._window_Frame.set_style(LIGHT_WINDOW_STYLE)
def set_style_dark(self, button):
""" """
self._window_Frame.set_style(DARK_WINDOW_STYLE)
def _build_title_bar(self):
""" return the title bar stack"""
with ui.VStack():
with ui.ZStack(height=30):
ui.Rectangle(name="titleBar")
# Title Bar
with ui.HStack():
ui.Spacer(width=10, height=0)
with ui.VStack(width=0):
ui.Spacer(width=0, height=8)
ui.Label("Sun Study", name="title", width=0, alignment=ui.Alignment.LEFT)
ui.Spacer(width=0, height=ui.Fraction(1))
ui.Spacer(width=ui.Fraction(1))
with ui.VStack(width=0):
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer(width=10, height=0)
ui.Image("resources/icons/[email protected]", width=20, height=20)
ui.Spacer(width=10)
ui.Image("resources/icons/[email protected]", width=20, height=20)
ui.Spacer(width=5)
ui.Spacer(height=5)
# Shadow
ui.Image("resources/icons/TitleBarShadow_wAlpha_v2.png", fill_policy=ui.FillPolicy.STRETCH, height=20)
def _build_time_arrow(self, arrowAlignment):
with ui.VStack(width=0): # remove spacer with Fraction Padding
ui.Spacer()
ui.Triangle(name="timeArrows", width=12, height=12, alignment=arrowAlignment)
ui.Spacer()
def _build_start_time_selector(self):
""" """
selector_placer = ui.Placer(offset_x=self._start_time_offset[0])
with selector_placer:
with ui.VStack(
width=80,
mouse_pressed_fn=lambda x, y, b, a, c=self._mouse_press_position: self._on_object_mouse_pressed(
c, x, y
),
mouse_moved_fn=lambda x, y, b, a: self.on_start_placer_mouse_moved_X(
selector_placer, self._start_time_offset, self._mouse_press_position, x, y
),
opaque_for_mouse_events=True,
): # SELECTOR START
self._start_time_selector_stack = ui.ZStack()
with self._start_time_selector_stack:
ui.Rectangle(height=25, name="timeSelection")
with ui.HStack(height=25): # remove spacer with Padding
ui.Spacer(width=5)
self._build_time_arrow(ui.Alignment.LEFT_CENTER)
ui.Spacer(width=5)
self._start_time_label = ui.Label(
self._start_time, name="timeLabel", alignment=ui.Alignment.RIGHT_CENTER
)
ui.Spacer(width=5)
with ui.HStack(height=20): # Selector tip, Spacer will be removed wiht Padding
ui.Spacer()
def show_hide_start_time_selector():
self._start_time_selector_stack.visible = not self._start_time_selector_stack.visible
ui.Triangle(
width=10,
height=17,
name="selector",
alignment=ui.Alignment.CENTER_BOTTOM,
mouse_pressed_fn=lambda x, y, b, a: show_hide_start_time_selector(),
)
ui.Spacer()
def _build_end_time_selector(self):
self._end_time_placer = ui.Placer(offset_x=self._end_time_offset[0])
with self._end_time_placer:
with ui.VStack(
width=80,
mouse_pressed_fn=lambda x, y, b, a: self._on_object_mouse_pressed(
self._mouse_press_position, x, y
),
mouse_moved_fn=lambda x, y, b, a: self.on_end_placer_mouse_moved_X(
self._end_time_placer, self._end_time_offset, self._mouse_press_position, x, y
),
opaque_for_mouse_events=True,
): # SELECTOR END
self._end_time_selector_stack = ui.ZStack()
with self._end_time_selector_stack:
ui.Rectangle(height=25, name="timeSelection")
with ui.HStack(height=25):
ui.Spacer(width=5)
self._end_time_label = ui.Label(
self._end_time, name="timeLabel", widthalignment=ui.Alignment.RIGHT_CENTER
)
ui.Spacer(width=5)
self._build_time_arrow(ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=5)
def show_hide_end_time_selector():
self._end_time_selector_stack.visible = not self._end_time_selector_stack.visible
with ui.HStack(height=20):
ui.Spacer()
ui.Triangle(
width=10,
height=17,
name="selector",
alignment=ui.Alignment.CENTER_BOTTOM,
mouse_pressed_fn=lambda x, y, b, a: show_hide_end_time_selector(),
)
ui.Spacer()
def _build_central_slider(self):
""" """
# custom slider Widget
with ui.VStack(height=70):
ui.Spacer(height=40)
with ui.HStack():
with ui.ZStack(height=20):
ui.Rectangle(name="sunStudySliderBackground")
self._time_range_placer = ui.Placer(offset_x=self._start_time_offset[0])
with self._time_range_placer:
self._time_range_rectangle = ui.Rectangle(name="sunStudySliderForground", width=500, height=30)
circle_placer = ui.Placer(offset_x=self._time_of_day_offset[0])
with circle_placer:
ui.Circle(
name="slider",
width=30,
height=30,
radius=10,
mouse_pressed_fn=lambda x, y, b, a: self._on_object_mouse_pressed(
self._mouse_press_position, x, y
),
mouse_moved_fn=lambda x, y, b, a: self.on_time_placer_mouse_moved_X(
circle_placer, self._time_of_day_offset, self._mouse_press_position, x, y
),
opaque_for_mouse_events=True,
)
def _build_custom_slider(self):
""" return the slider stack"""
side_padding = 50
with ui.HStack(height=70):
ui.Spacer(width=side_padding) # from Padding (will be removed by Padding on the HStack)
with ui.ZStack():
self._build_central_slider()
# Selectors
with ui.ZStack(height=40): # Selector Height
self._build_start_time_selector()
self._build_end_time_selector()
ui.Spacer(width=side_padding)
def _build_control_bar(self):
""" """
with ui.HStack(height=40):
ui.Spacer(width=50)
ui.Image("resources/icons/[email protected]", width=25)
ui.Spacer(width=10)
ui.Image("resources/icons/[email protected]", width=20)
ui.Spacer(width=10)
ui.Image("resources/icons/[email protected]", width=20)
ui.Spacer(width=ui.Fraction(2))
# with ui.ZStack():
self._play_button = ui.Image(
"resources/icons/[email protected]",
height=30,
width=30,
mouse_pressed_fn=lambda x, y, button, modifier: self._play_pause_fn(x, y),
)
self._pause_button = ui.Image(
"resources/icons/[email protected]",
height=30,
width=30,
mouse_pressed_fn=lambda x, y, button, modifier: self._play_pause_fn(x, y),
)
self._pause_button.visible = False
ui.Spacer(width=ui.Fraction(1))
with ui.HStack(width=120):
self._current_time_label = ui.Label("9:30 AM", name="title")
ui.Label(" October 21, 2019", name="title")
ui.Spacer(width=30)
def build_window(self):
""" build the window for the Class"""
self._window = ui.Window("Brick Sun Study", width=800, height=250, flags=ui.WINDOW_FLAGS_NO_TITLE_BAR)
with self._window.frame:
with ui.VStack():
with ui.HStack(height=20):
ui.Label("Styling : ", alignment=ui.Alignment.RIGHT_CENTER)
ui.Button("Light Mode", clicked_fn=lambda b=None: self.set_style_light(b))
ui.Button("Dark Mode", clicked_fn=lambda b=None: self.set_style_dark(b))
ui.Spacer()
ui.Spacer(height=10)
self._window_Frame = ui.ScrollingFrame(
style=LIGHT_WINDOW_STYLE,
name="canvas",
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
)
with self._window_Frame:
with ui.VStack(height=0):
# Build the toolbar for the window
self._build_title_bar()
ui.Spacer(height=10)
# build the custom slider
self._build_custom_slider()
ui.Spacer(height=10)
self._build_control_bar()
# botton Padding
ui.Spacer(height=10)
return self._window
| 16,391 | Python | 40.498734 | 119 | 0.532426 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/window_doc.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.
#
"""The documentation for Windows"""
from .doc_page import DocPage
from omni import ui
from omni.ui import color as cl
import inspect
import json
import carb.settings
SPACING = 5
def popup_example(self):
class StrModel(ui.AbstractValueModel):
def __init__(self, **kwargs):
super().__init__()
self.__str = ""
self.__parent = None
self.__window = None
self.__frame = None
self.__tooltips = ["Hello", "World", "Hello World"]
self.__kwargs = kwargs
def set_parent(self, parent):
self.__parent = parent
def set_value(self, value):
self.__str = str(value)
self._value_changed()
self._set_tips()
def get_value_as_string(self):
return self.__str
def begin_edit(self):
if self.__window and self.__window.visible:
return
# Create and show the window with field and list of tips
self.__window = ui.Window("0", **self.__kwargs)
with self.__window.frame:
with ui.VStack(width=0, height=0):
width = self.__parent.computed_content_width
# Field with the same model
field = ui.StringField(self, width=width)
field.focus_keyboard()
self.__frame = ui.Frame()
self.__window.position_x = self.__parent.screen_position_x
self.__window.position_y = self.__parent.screen_position_y
self._set_tips()
def _set_tips(self):
"""Generates list of tips"""
if not self.__frame:
return
found = False
with self.__frame:
with ui.VStack():
for t in self.__tooltips:
if self.__str and self.__str in t:
ui.Button(t)
found = True
if not found:
for t in self.__tooltips:
ui.Button(t)
def destroy(self):
self.__parent = None
self.__frame = None
self.__window = None
window_args = {
"flags": ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
"auto_resize": True,
"padding_x": 0,
"padding_y": 0,
}
self._model = StrModel(**window_args)
self._field = ui.StringField(self._model)
self._model.set_parent(self._field)
class WindowDoc(DocPage):
""" document Windows classes"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._window_example = None
self._modal_window_example = None
self._no_close_window_example = None
self._style_window_example = None
self._simple_toolbar = None
self._rotating_toolbar = None
self._toolbar_rotation = ui.DockPosition.BOTTOM
self._modal_test = []
self._model = None
def clean(self):
self._model = None
def build_toolbar(self):
"""Caled to load the extension"""
def top_toolbar_changeAxis(frame, axis):
with frame:
stack = None
if axis == ui.ToolBarAxis.X:
stack = ui.HStack(spacing=15, height=24)
else:
stack = ui.VStack(spacing=15, height=24)
with stack:
ui.Spacer()
ui.Image("resources/icons/Select_model_64.png", width=24, height=24)
ui.Image("resources/icons/Move_64.png", width=24, height=24)
ui.Image("resources/icons/Rotate_global.png", width=24, height=24)
ui.Image("resources/icons/Scale_64.png", width=24, height=24)
ui.Image("resources/icons/Snap_64.png", width=24, height=24)
ui.Spacer()
self._top_toolbar = ui.ToolBar("UI ToolBar", noTabBar=False, padding_x=0, padding_y=0)
self._top_toolbar.set_axis_changed_fn(
lambda axis, frame=self._top_toolbar.frame: top_toolbar_changeAxis(frame, axis)
)
top_toolbar_changeAxis(self._top_toolbar.frame, ui.ToolBarAxis.X)
self._right_toolbar = ui.ToolBar("Right Size ToolBar", noTabBar=True, padding_x=5, padding_y=0)
with self._right_toolbar.frame:
with ui.VStack(spacing=15, width=25):
ui.Spacer(height=1)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/SunStudy_64.png", width=20, height=20)
ui.Spacer()
self._left_toolbar = ui.ToolBar("Left Size ToolBar", noTabBar=True, padding_x=5, padding_y=0)
with self._left_toolbar.frame:
with ui.VStack(spacing=0):
ui.Spacer(height=10)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Spacer()
self._bottom_toolbar = ui.ToolBar("Bottom ToolBar", noTabBar=True, padding_x=0, padding_y=0)
with self._bottom_toolbar.frame:
with ui.HStack(height=18):
ui.Spacer()
with ui.ZStack(width=200, height=15):
ui.Rectangle(
width=120,
style={"background_color": cl("#809EAB"), "corner_flag": ui.CornerFlag.LEFT, "border_radius": 2},
)
ui.Rectangle(
width=200,
style={
"background_color": cl.transparent,
"border_color": cl("#222222"),
"border_width": 1.0,
"border_radius": 2,
},
)
ui.Label("FPS 30", style={"color": cl.white, "margin_width": 10, "font_size": 8})
ui.Spacer()
self._bottom_toolbar.dock_in_window("Viewport", ui.DockPosition.BOTTOM)
self._top_toolbar.dock_in_window("Viewport", ui.DockPosition.TOP)
self._left_toolbar.dock_in_window("Viewport", ui.DockPosition.LEFT)
self._right_toolbar.dock_in_window("Viewport", ui.DockPosition.RIGHT)
# TODO omni.ui: restore functionality for Kit Next
self._settings = carb.settings.get_settings()
self._settings.set("/app/docks/autoHideTabBar", True)
self._settings.set("/app/docks/noWindowMenuButton", False)
self._settings.set("app/window/showStatusBar", False)
self._settings.set("app/window/showStatusBar", False)
self._settings.set("/app/viewport/showSettingsMenu", True)
self._settings.set("/app/viewport/showCameraMenu", False)
self._settings.set("/app/viewport/showRendererMenu", True)
self._settings.set("/app/viewport/showHideMenu", True)
self._settings.set("/app/viewport/showLayerMenu", False)
def create_and_show_window(self):
if not self._window_example:
self._window_example = ui.Window("Example Window", width=300, height=300)
button_size = None
button_dock = None
with self._window_example.frame:
with ui.VStack():
ui.Button("click me")
button_size = ui.Button("")
def move_me(window):
window.setPosition(200, 200)
def size_me(window):
window.width = 300
window.height = 300
ui.Button("move to 200,200", clicked_fn=lambda w=self._window_example: move_me(w))
ui.Button("set size 300,300", clicked_fn=lambda w=self._window_example: size_me(w))
button_dock = ui.Button("Undocked")
def update_button(window, button):
computed_width = (int)(button.computed_width)
computed_height = (int)(button.computed_height)
button.text = (
"Window size is {:.1f} x {:.1f}\n".format(window.width, window.height)
+ "Window position is {:.1f} x {:.1f}\n".format(window.position_x, window.position_y)
+ "Button size is {:.1f} x {:.1f}".format(computed_width, computed_height)
)
def update_docking(docked, button):
button.text = "Docked" if docked else "Undocked"
for fn in [
self._window_example.set_width_changed_fn,
self._window_example.set_height_changed_fn,
self._window_example.set_position_x_changed_fn,
self._window_example.set_position_y_changed_fn,
]:
fn(lambda value, b=button_size, w=self._window_example: update_button(w, b))
self._window_example.set_docked_changed_fn(lambda value, b=button_dock: update_docking(value, b))
self._window_example.visible = True
def close_modal_window_me(self):
if self._modal_window_example:
self._modal_window_example.visible = False
def create_and_show_modal_window(self):
if not self._modal_window_example:
window_flags = ui.WINDOW_FLAGS_NO_RESIZE
window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR
window_flags |= ui.WINDOW_FLAGS_MODAL
self._modal_window_example = ui.Window("Example Modal Window", width=200, height=200, flags=window_flags)
with self._modal_window_example.frame:
with ui.VStack():
ui.Button("I am Modal")
ui.Button("You Can't Click outsite ")
ui.Button("click here to close me", height=100, clicked_fn=self.close_modal_window_me)
self._modal_window_example.visible = True
def create_and_show_window_no_close(self):
if not self._no_close_window_example:
window_flags = ui.WINDOW_FLAGS_NO_CLOSE
self._no_close_window_example = ui.Window(
"Example Modal Window",
width=400,
height=200,
flags=window_flags,
visibility_changed_fn=self._update_window_visible,
)
with self._no_close_window_example.frame:
with ui.VStack():
ui.Button("I dont have Close button")
ui.Button("my Size is 400x200 ")
def close_me(window):
if window:
window.visible = False
ui.Button(
"click here to close me",
height=100,
clicked_fn=lambda w=self._no_close_window_example: close_me(w),
)
self._no_close_window_example.visible = True
def create_styled_window(self):
if not self._style_window_example:
self._style_window_example = ui.Window("Styled Window Example", width=300, height=300)
self._style_window_example.frame.set_style(
{
"Window": {
"background_color": cl.blue,
"border_radius": 10,
"border_width": 5,
"border_color": cl.red,
}
}
)
with self._style_window_example.frame:
with ui.VStack():
ui.Button("I am a Styled Window")
ui.Spacer(height=10)
ui.Button(
"""Style is attached to 'Window'
{"Window": {"background_color": cl.blue,
"border_radius": 10,
"border_width": 5,
"border_color": cl.red}""",
height=200,
)
self._style_window_example.visible = True
def _update_window_visible(self, value):
self._window_checkbox.model.set_value(value)
def create_simple_toolbar(self):
if self._simple_toolbar:
self._simple_toolbar.visible = not self._simple_toolbar.visible
else:
self._simple_toolbar = ui.ToolBar("simple toolbar", noTabBar=True)
with self._simple_toolbar.frame:
with ui.HStack(spacing=15, height=28):
ui.Spacer()
ui.Image("resources/icons/Select_model_64.png", width=24, height=24)
ui.Image("resources/icons/Move_64.png", width=24, height=24)
ui.Image("resources/icons/Rotate_global.png", width=24, height=24)
ui.Image("resources/icons/Scale_64.png", width=24, height=24)
ui.Image("resources/icons/Snap_64.png", width=24, height=24)
ui.Spacer()
self._simple_toolbar.dock_in_window("Viewport", ui.DockPosition.TOP)
self._simple_toolbar.frame.set_style({"Window": {"background_color": cl("#DDDDDD")}})
def create_rotating_toolbar(self):
if not self._rotating_toolbar:
def toolbar_changeAxis(frame, axis):
with frame:
stack = None
if axis == ui.ToolBarAxis.X:
stack = ui.HStack(spacing=15, height=30)
else:
stack = ui.VStack(spacing=15, width=30)
with stack:
ui.Spacer()
ui.Image("resources/icons/Select_model_64.png", width=24, height=24)
ui.Image("resources/icons/Move_64.png", width=24, height=24)
ui.Image("resources/icons/Rotate_global.png", width=24, height=24)
ui.Image("resources/icons/Scale_64.png", width=24, height=24)
ui.Image("resources/icons/Snap_64.png", width=24, height=24)
ui.Spacer()
self._rotating_toolbar = ui.ToolBar("Rotating ToolBar", noTabBar=False, padding_x=5, padding_y=5, margin=5)
self._rotating_toolbar.set_axis_changed_fn(
lambda axis, frame=self._rotating_toolbar.frame: toolbar_changeAxis(frame, axis)
)
toolbar_changeAxis(self._rotating_toolbar.frame, ui.ToolBarAxis.X)
if self._toolbar_rotation == ui.DockPosition.RIGHT:
self._toolbar_rotation = ui.DockPosition.BOTTOM
else:
self._toolbar_rotation = ui.DockPosition.RIGHT
self._rotating_toolbar.dock_in_window("Viewport", self._toolbar_rotation)
def create_doc(self, navigate_to=None):
self._section_title("Windows")
self._text(
"With omni ui you can create a varierty of Window type and style"
" the main Window type are floating window that can optionally be docked into the Main Window.\n"
"There are also other type of window like ToolBar, DialogBox, Etc that you can use"
)
self._caption("Window", navigate_to)
self._text("This class is used to construct a regular Window")
with ui.ScrollingFrame(height=350, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF):
with ui.VStack(height=0):
with ui.HStack(width=0):
ui.Button("click for window Example", width=180, clicked_fn=self.create_and_show_window)
ui.Label("this create a regular Window", name="text", width=180, style={"margin_width": 10})
ui.Label(
"""
ui.Window("Example Window",
position_x=100,
position_y=100)""",
name="text",
)
with ui.HStack(width=0):
ui.Button("Window without close", width=180, clicked_fn=self.create_and_show_window_no_close)
self._window_checkbox = ui.CheckBox(style={"margin": 5})
# this Tie the window visibility with the checkox
def update_check_box(value, self):
self._no_close_window_example.visible = value
self._window_checkbox.model.add_value_changed_fn(
lambda a, this=self: update_check_box(a.get_value_as_bool(), self)
)
ui.Label("this create a regular Window", name="text", width=150, style={"margin_width": 10})
ui.Label('ui.Window("Example Window", )', name="text")
# Modal example is off because there are few issue but this MR need to go in
with ui.HStack(width=0):
ui.Button("click for Custom Window", width=180, clicked_fn=self.create_and_show_modal_window)
ui.Label("this create a custom Window", name="text", width=180, style={"margin_width": 10})
ui.Label(
"window_flags = ui.WINDOW_FLAGS_NO_COLLAPSE\n"
"window_flags |= ui.WINDOW_FLAGS_NO_RESIZE\n"
"window_flags |= ui.WINDOW_FLAGS_NO_CLOSE\n"
"window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR\n"
"window_flags |= ui.WINDOW_FLAGS_NO_TITLE_BAR\n\n"
"ui.Window('Example Window', flags=window_flags",
name="text",
)
with ui.HStack(width=0):
ui.Button("click for Styled Window", width=180, clicked_fn=self.create_styled_window)
ui.Spacer(width=20)
ui.Label(
"""
self._style_window_example = ui.Window("Styled Window Example", width=300, height=300)
self._style_window_example.frame.set_style({"Window": {"background_color": cl.blue,
"border_radius": 10,
"border_width": 5,
"border_color": cl.red})
with self._style_window_example.frame:
with ui.VStack():
ui.Button("I am a Styled Window")
ui.Button("Style is attached to 'Window'", height=200)""",
name="text",
)
self._text("All the Window Flags")
self._text(
""" WINDOW_FLAGS_NONE
WINDOW_FLAGS_NO_TITLE_BAR
WINDOW_FLAGS_NO_RESIZE
WINDOW_FLAGS_NO_MOVE
WINDOW_FLAGS_NO_SCROLLBAR
WINDOW_FLAGS_NO_COLLAPSE
WINDOW_FLAGS_NO_SAVED_SETTINGS
WINDOW_FLAGS_SHOW_HORIZONTAL_SCROLLBAR
WINDOW_FLAGS_FORCE_VERTICAL_SCROLLBAR
WINDOW_FLAGS_FORCE_HORIZONTAL_SCROLLBAR
WINDOW_FLAGS_NO_FOCUS_ON_APPEARING
WINDOW_FLAGS_NO_CLOSE
"""
)
self._text("Available Window Properties, call can be used in the constructor")
self._text(
""" title : set the title for the window
visible: set the window to be visible or not
frame: read only property to get the frame of the window
padding_x: padding on the window around the Frame
padding_y: padding on the window around the Frame
flags: the window flags, not that you can pass then on the constructor but also change them after !
"""
)
self._caption("ToolBar", navigate_to)
with ui.ScrollingFrame(height=60, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF):
with ui.VStack(height=0):
with ui.HStack(width=0):
ui.Button("ToolBar Example", width=180, clicked_fn=self.create_simple_toolbar)
ui.Label("this create a ToolBar Docked at the top", name="text", width=280)
ui.Label("""ui.ToolBar("Awesome ToolBar", noTabBar=True)""", name="text")
with ui.HStack(width=0):
ui.Button("Axis changing ToolBar Example", width=180, clicked_fn=self.create_rotating_toolbar)
ui.Label("see how the orientation of the toolbar can change", name="text", width=280)
ui.Label("""ui.ToolBar("Awesome ToolBar")""", name="text")
self._text(
"This file contain a very complete example of many type of toolbar\n" "location is " + __file__ + "\n"
)
self._caption("Multiple Modal Windows", navigate_to)
self._text(
"Omni::UI supports the conception of multiple modal windows. When the new modal window is created, it "
"makes other modal windows inactive. And when it's destroyed, the previous modal window becomes active, "
"blocking all other windows."
)
ui.Button("Multiple Modal Windows", clicked_fn=self._on_modal_in_modal_clicked)
self._caption("Overlay Other Windows", navigate_to)
self._text(
"When creating two windows with the same title, only one window will be displayed, and it will contain "
"the widgets from both windows. This ability allows for overlaying omni.ui Widgets to any ImGui window. "
"For example, it's possible to add a button to the viewport with creating a new window with the title "
'"Viewport".'
)
def overlay_viewport(self):
self._overlay_window = None
def create_overlay_window(self):
if self._overlay_window:
self._overlay_window = None
else:
self._overlay_window = ui.Window("Viewport")
with self._overlay_window.frame:
with ui.HStack():
ui.Spacer()
ui.Label("Hello World", width=0)
ui.Spacer()
self._overaly_button = ui.Button(
"Create or Remove Viewport Label",
style=self._style_system,
clicked_fn=lambda: create_overlay_window(self),
)
overlay_viewport(self)
self._code(inspect.getsource(overlay_viewport).split("\n", 1)[-1])
self._caption("Workspace", navigate_to)
class WindowItem(ui.AbstractItem):
def __init__(self, window):
super().__init__()
# Don't keep the window because it prevents the window from closing.
self._window_title = window.title
self.title_model = ui.SimpleStringModel(self._window_title)
self.type_model = ui.SimpleStringModel(type(window).__name__)
@property
def window(self):
return ui.Workspace.get_window(self._window_title)
class WindowModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._root = ui.SimpleStringModel("Windows")
self.update()
def update(self):
self._children = [WindowItem(i) for i in ui.Workspace.get_windows()]
self._item_changed(None)
def get_item_children(self, item):
if item is not None:
return []
return self._children
def get_item_value_model_count(self, item):
return 2
def get_item_value_model(self, item, column_id):
if item is None:
return self._root
if column_id == 0:
return item.title_model
if column_id == 1:
return item.type_model
self._window_model = WindowModel()
self._tree_left = None
self._tree_right = None
with ui.VStack(style=self._style_system):
ui.Button("Refresh", clicked_fn=lambda: self._window_model.update())
with ui.HStack():
ui.Button("Clear", clicked_fn=ui.Workspace.clear)
ui.Button("Focus", clicked_fn=lambda: self._focus(self._tree_left.selection))
with ui.HStack():
ui.Button("Visibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, True))
ui.Button("Invisibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, False))
ui.Button("Toggle Visibility", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, None))
with ui.HStack():
ui.Button(
"Dock Right",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.RIGHT
),
)
ui.Button(
"Dock Left",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.LEFT
),
)
ui.Button(
"Dock Top",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.TOP
),
)
ui.Button(
"Dock Bottom",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.BOTTOM
),
)
ui.Button(
"Dock Same",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.SAME
),
)
ui.Button("Undock", clicked_fn=lambda: self._undock(self._tree_left.selection))
with ui.HStack():
ui.Button("Move Left", clicked_fn=lambda: self._left(self._tree_left.selection))
ui.Button("MoveRight", clicked_fn=lambda: self._right(self._tree_left.selection))
with ui.HStack():
ui.Button(
"Reverse Docking Tabs of Neighbours",
clicked_fn=lambda: self._dock_reorder(self._tree_left.selection),
)
ui.Button("Hide Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, False))
ui.Button("Show Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, True))
with ui.HStack(height=400):
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._tree_left = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80])
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._tree_right = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80])
self._caption("Popup", navigate_to)
self._text(
"The Popup window is a window that disappears when the user clicks outside of the window. To create a popup "
"window, it's necessary to use the flag ui.WINDOW_FLAGS_POPUP. It's very useful for creating a menu with "
"custom widgets inside."
)
self._text("Start typing for popup")
popup_example(self)
self._code(inspect.getsource(popup_example).split("\n", 1)[-1])
# some padding at the bottom
ui.Spacer(height=100)
def _undock(self, selection):
if not selection:
return
for item in selection:
item.window.undock()
def _dock(self, left, right, position):
if not left or not right:
return
target = right[0].window
for item in left:
item.window.dock_in(target, position)
def _left(self, selection):
if not selection:
return
for item in selection:
item.window.position_x -= 100
def _right(self, selection):
if not selection:
return
for item in selection:
item.window.position_x += 100
def _set_visibility(self, selection, visible):
if not selection:
return
for item in selection:
if visible is not None:
item.window.visible = visible
else:
item.window.visible = not item.window.visible
def _dock_reorder(self, selection):
if not selection:
return
docking_groups = [ui.Workspace.get_docked_neighbours(item.window) for item in selection]
for group in docking_groups:
# Reverse order
for i, window in enumerate(reversed(group)):
window.dock_order = i
def _on_modal_in_modal_clicked(self):
def close_me(id):
self._modal_test[id].visible = False
def put_on_front(id):
if not self._modal_test[id]:
return
self._modal_test[id].set_top_modal()
def toggle(id):
if not self._modal_test[id]:
return
self._modal_test[id].visible = not self._modal_test[id].visible
window_id = len(self._modal_test)
prev_id = max(0, window_id - 1)
window_flags = ui.WINDOW_FLAGS_NO_RESIZE
window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR
window_flags |= ui.WINDOW_FLAGS_MODAL
modal_window = ui.Window(f"Modal Window #{window_id}", width=200, height=200, flags=window_flags)
self._modal_test.append(modal_window)
with modal_window.frame:
with ui.VStack(height=0):
ui.Label(f"This is the window #{window_id}")
ui.Button("One Modal More", clicked_fn=self._on_modal_in_modal_clicked)
ui.Button(f"Bring #{prev_id} To Top", clicked_fn=lambda id=prev_id: put_on_front(id))
ui.Button(f"Toggle visibility of #{prev_id}", clicked_fn=lambda id=prev_id: toggle(id))
ui.Button("Close", clicked_fn=lambda id=window_id: close_me(id))
| 31,379 | Python | 40.618037 | 121 | 0.541445 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/image_doc.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.
#
"""The documentation for Images"""
from omni import ui
from .doc_page import DocPage
import inspect
SPACING = 5
def image_hot_switch():
styles = [
{
"": {"image_url": "resources/icons/Nav_Walkmode.png"},
":hovered": {"image_url": "resources/icons/Nav_Flymode.png"},
},
{
"": {"image_url": "resources/icons/Move_local_64.png"},
":hovered": {"image_url": "resources/icons/Move_64.png"},
},
{
"": {"image_url": "resources/icons/Rotate_local_64.png"},
":hovered": {"image_url": "resources/icons/Rotate_global.png"},
},
]
def set_image(model, image):
value = model.get_item_value_model().get_value_as_int()
image.set_style(styles[value])
image = ui.Image(width=64, height=64, style=styles[0])
with ui.HStack(width=ui.Percent(50)):
ui.Label("Select a texture to display", name="text")
model = ui.ComboBox(0, "Navigation", "Move", "Rotate").model
model.add_item_changed_fn(lambda m, i, im=image: set_image(m, im))
class ImageDoc(DocPage):
""" document for Image"""
def create_doc(self, navigate_to=None):
self._section_title("Image")
self._text("The Image type displays an image.")
self._text("The source of the image is specified as a URL using the source property.")
self._text(
"By default, specifying the width and height of the item causes the image to be scaled to that size. This "
"behavior can be changed by setting the fill_mode property, allowing the image to be stretched or scaled "
"instead. The property alignment controls where to align the scaled image."
)
code_width = 320
image_source = "resources/desktop-icons/omniverse_512.png"
with ui.VStack():
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.STRETCH)""",
"(Default) The image is scaled to fit, the alignment is ignored",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.LEFT_CENTER)""",
"The image is scaled uniformly to fit without cropping and aligned to the left",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.CENTER)""",
"The image is scaled uniformly to fit without cropping and aligned to the center",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.RIGHT_CENTER)""",
"The image is scaled uniformly to fit without croppingt and aligned to right",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
alignment=ui.Alignment.CENTER_TOP)""",
"The image is scaled uniformly to fill, cropping if necessary and aligned to the top",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
alignment=ui.Alignment.CENTER)""",
"The image is scaled uniformly to fill, cropping if necessary and centered",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
alignment=ui.Alignment.CENTER_BOTTOM)""",
"The image is scaled uniformly to fill, cropping if necessary and aligned to the bottom",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.CENTER,
style={{'border_radius': 10}})""",
"The image has rounded corners",
code_width=code_width,
)
ui.Spacer(height=20)
ui.Line()
ui.Spacer(height=10)
self._text("The Image can use style image_url")
ui.Spacer(height=10)
ui.Line()
ui.Spacer(height=20)
code_width = 470
self._image_table(
f"""ui.Image(style={{'image_url': 'resources/desktop-icons/omniverse_128.png'}})""",
"The image has a styled URL",
code_width=code_width,
)
self._image_table(
f"""with ui.HStack(spacing =5,
style={{"Image":{{'image_url': 'resources/desktop-icons/omniverse_128.png'}}}}):
ui.Image()
ui.Image()
ui.Image()
""",
"The image has a styled URL",
code_width=code_width,
)
self._image_table(
f"""ui.Image(style={{
'image_url': 'resources/desktop-icons/omniverse_128.png',
'alignment': ui.Alignment.RIGHT_CENTER}})""",
"The image has styled Alignment",
code_width=code_width,
)
self._image_table(
f"""ui.Image(style={{
'image_url': 'resources/desktop-icons/omniverse_256.png',
'fill_policy': ui.FillPolicy.PRESERVE_ASPECT_CROP,
'alignment': ui.Alignment.RIGHT_CENTER}})""",
"The image has styled fill_policy",
code_width=code_width,
)
self._text(
"It's possible to set a different image per style state. And switch them depending on the mouse hovering, "
"selection state, etc."
)
image_hot_switch()
self._code(inspect.getsource(image_hot_switch).split("\n", 1)[-1])
ui.Spacer(height=10)
| 7,160 | Python | 39.005586 | 119 | 0.525978 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/layout_doc.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.
#
"""The documentation for Layouts"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import inspect
import asyncio
import omni.kit.app
SPACING = 5
def collapsable_simple():
with ui.CollapsableFrame("Header"):
with ui.VStack(height=0):
ui.Button("Hello World")
ui.Button("Hello World")
def collapsable_custom(style_system):
def custom_header(collapsed, title):
with ui.HStack(style=style_system):
with ui.ZStack(width=30):
ui.Circle(name="title")
with ui.HStack():
ui.Spacer()
align = ui.Alignment.V_CENTER
ui.Line(name="title", width=6, alignment=align)
ui.Spacer()
if collapsed:
with ui.VStack():
ui.Spacer()
align = ui.Alignment.H_CENTER
ui.Line(name="title", height=6, alignment=align)
ui.Spacer()
ui.Label(title, name="title")
style = {
"CollapsableFrame": {
"background_color": cl.transparent,
"secondary_color": cl.transparent,
"border_radius": 0,
"border_color": cl("#B2B2B2"),
"border_width": 0.5,
},
"CollapsableFrame:hovered": {"secondary_color": cl("#E5F1FB")},
"CollapsableFrame:pressed": {"secondary_color": cl("#CCE4F7")},
"Label::title": {"color": cl.black},
"Circle::title": {
"color": cl.black,
"background_color": cl.transparent,
"border_color": cl("#B2B2B2"),
"border_width": 0.75,
},
"Line::title": {"color": cl("#666666"), "border_width": 1},
}
style.update(style_system)
with ui.CollapsableFrame("Header", build_header_fn=custom_header, style=style):
with ui.VStack(height=0):
ui.Button("Hello World")
ui.Button("Hello World")
def collapsable_layout(style_system):
style = {
"CollapsableFrame": {
"border_color": cl("#005B96"),
"border_radius": 4,
"border_width": 2,
"padding": 0,
"margin": 0,
}
}
frame = ui.CollapsableFrame("Header", style=style)
with frame:
with ui.VStack(height=0):
ui.Button("Hello World")
ui.Button("Hello World")
def set_style(field, model, style=style, frame=frame):
frame_style = style["CollapsableFrame"]
frame_style[field] = model.get_value_as_float()
frame.set_style(style)
with ui.HStack():
ui.Label("Padding:", width=ui.Percent(10), name="text")
model = ui.FloatSlider(min=0, max=50).model
model.add_value_changed_fn(lambda m: set_style("padding", m))
with ui.HStack():
ui.Label("Margin:", width=ui.Percent(10), name="text")
model = ui.FloatSlider(min=0, max=50).model
model.add_value_changed_fn(lambda m: set_style("margin", m))
def direction():
def rotate(dirs, stack, label):
dirs[0] = (dirs[0] + 1) % len(dirs[1])
stack.direction = dirs[1][dirs[0]]
label.text = str(stack.direction)
dirs = [
0,
[
ui.Direction.LEFT_TO_RIGHT,
ui.Direction.RIGHT_TO_LEFT,
ui.Direction.TOP_TO_BOTTOM,
ui.Direction.BOTTOM_TO_TOP,
],
]
stack = ui.Stack(ui.Direction.LEFT_TO_RIGHT, width=0, height=0)
with stack:
for name in ["One", "Two", "Three", "Four"]:
ui.Button(name)
with ui.HStack():
with ui.HStack():
ui.Label("Current direcion is ", name="text", width=0)
label = ui.Label("", name="text")
button = ui.Button("Change")
button.set_clicked_fn(lambda d=dirs, s=stack, l=label: rotate(d, s, l))
rotate(dirs, stack, label)
def recreate(self):
self._recreate_ui = ui.Frame(height=40)
def changed(model, recreate_ui=self._recreate_ui):
with recreate_ui:
with ui.HStack():
for i in range(model.get_value_as_int()):
ui.Button(f"Button #{i}")
model = ui.IntDrag(min=0, max=10).model
self._sub_recreate = model.subscribe_value_changed_fn(changed)
def clipping(self):
self._clipping_frame = ui.Frame()
with self._clipping_frame:
ui.Button("Hello World")
def set_width(model):
self._clipping_frame.width = ui.Pixel(model.as_float)
def set_height(model):
self._clipping_frame.height = ui.Pixel(model.as_float)
def set_hclipping(model):
self._clipping_frame.horizontal_clipping = model.as_bool
def set_vclipping(model):
self._clipping_frame.horizontal_clipping = model.as_bool
width = ui.FloatDrag(min=50, max=1000).model
height = ui.FloatDrag(min=50, max=1000).model
hclipping = ui.ToolButton(text="HClipping").model
vclipping = ui.ToolButton(text="VClipping").model
self._width = width.subscribe_value_changed_fn(set_width)
self._height = height.subscribe_value_changed_fn(set_height)
self._hclipping = hclipping.subscribe_value_changed_fn(set_hclipping)
self._vclipping = vclipping.subscribe_value_changed_fn(set_vclipping)
width.set_value(100)
height.set_value(100)
def visibility():
def invisible(button):
button.visible = False
def visible(buttons):
for button in buttons:
button.visible = True
buttons = []
with ui.HStack():
for n in ["One", "Two", "Three", "Four", "Five"]:
button = ui.Button(n, width=0)
button.set_clicked_fn(lambda b=button: invisible(b))
buttons.append(button)
ui.Spacer()
button = ui.Button("Visible all", width=0)
button.set_clicked_fn(lambda b=buttons: visible(b))
def vgrid():
with ui.ScrollingFrame(
height=425,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
with ui.VGrid(column_width=100, row_height=100):
for i in range(100):
with ui.ZStack():
ui.Rectangle(
style={
"border_color": cl.black,
"background_color": cl.white,
"border_width": 1,
"margin": 0,
}
)
ui.Label(f"{i}", style={"margin": 5})
def hgrid():
with ui.ScrollingFrame(
height=425,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.HGrid(column_width=100, row_height=100):
for i in range(100):
with ui.ZStack():
ui.Rectangle(
style={
"border_color": cl.black,
"background_color": cl.white,
"border_width": 1,
"margin": 0,
}
)
ui.Label(f"{i}", style={"margin": 5})
def placer_track(self, id):
# Initial size
BEGIN = 50 + 100 * id
END = 120 + 100 * id
HANDLE_WIDTH = 10
class EditScope:
"""The class to avoid circular event calling"""
def __init__(self):
self.active = False
def __enter__(self):
self.active = True
def __exit__(self, type, value, traceback):
self.active = False
def __bool__(self):
return not self.active
class DoLater:
"""A helper to collect data and process it one frame later"""
def __init__(self):
self.__task = None
self.__data = []
def do(self, data):
# Collect data
self.__data.append(data)
# Update in the next frame. We need it because we want to accumulate the affected prims
if self.__task is None or self.__task.done():
self.__task = asyncio.ensure_future(self.__delayed_do())
async def __delayed_do(self):
# Wait one frame
await omni.kit.app.get_app().next_update_async()
print(f"In the previous frame the user clicked the rectangles: {self.__data}")
self.__data.clear()
self.edit = EditScope()
self.dolater = DoLater()
def start_moved(start, body, end):
if not self.edit:
# Something already edits it
return
with self.edit:
body.offset_x = start.offset_x
rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH)
def body_moved(start, body, end, rect):
if not self.edit:
# Something already edits it
return
with self.edit:
start.offset_x = body.offset_x
end.offset_x = body.offset_x + rect.width.value - HANDLE_WIDTH
def end_moved(start, body, end, rect):
if not self.edit:
# Something already edits it
return
with self.edit:
body.offset_x = start.offset_x
rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH)
with ui.ZStack(height=30):
# Body
body = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN)
with body:
rect = ui.Rectangle(width=END - BEGIN + HANDLE_WIDTH)
rect.set_mouse_pressed_fn(lambda x, y, b, m, id=id: self.dolater.do(id))
# Left handle
start = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN)
with start:
ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")})
# Right handle
end = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=END)
with end:
ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")})
# Connect them together
start.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end: start_moved(s, b, e))
body.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: body_moved(s, b, e, r))
end.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: end_moved(s, b, e, r))
def placer_percents(self):
# The size of the rectangle
SIZE = 20.0
with ui.ZStack(height=300):
# Background
ui.Rectangle(style={"background_color": cl("#999999")})
# Small rectangle
p = ui.Percent(50)
placer = ui.Placer(draggable=True, offset_x=p, offset_y=p)
with placer:
ui.Rectangle(width=SIZE, height=SIZE)
def clamp_x(offset):
if offset.value < 0:
placer.offset_x = ui.Percent(0)
max_per = 100.0 - SIZE / placer.computed_width * 100.0
if offset.value > max_per:
placer.offset_x = ui.Percent(max_per)
def clamp_y(offset):
if offset.value < 0:
placer.offset_y = ui.Percent(0)
max_per = 100.0 - SIZE / placer.computed_height * 100.0
if offset.value > max_per:
placer.offset_y = ui.Percent(max_per)
# Calbacks
placer.set_offset_x_changed_fn(clamp_x)
placer.set_offset_y_changed_fn(clamp_y)
class LayoutDoc(DocPage):
""" document Layout classes"""
def create_doc(self, navigate_to=None):
self._section_title("Layout")
self._text("We have three main components: VStack, HStack, and ZStack.")
self._caption("HStack", navigate_to)
self._text("This class is used to construct horizontal layout objects.")
with ui.HStack():
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
self._text("The simplest use of the class is like this:")
self._code(
"""
with ui.HStack():
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
"""
)
self._caption("VStack", navigate_to)
self._text("The VStack class lines up widgets vertically.")
with ui.VStack(width=100.0):
with ui.VStack():
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
self._text("The simplest use of the class is like this:")
self._code(
"""
with ui.VStack():
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
"""
)
self._caption("ZStack", navigate_to)
self._text("A view that overlays its children, aligning them on top of each other.")
with ui.VStack(width=100.0):
with ui.ZStack():
ui.Button("Very Long Text to See How Big it Can Be", height=0)
ui.Button("Another\nMultiline\nButton", width=0)
self._code(
"""
with ui.ZStack():
ui.Button("Very Long Text to See How Big it Can Be", height=0)
ui.Button("Another\\nMultiline\\nButton", width=0)
"""
)
self._caption("Spacing", navigate_to)
self._text("Spacing is a non-stretchable space in pixels between child items of the layout.")
def set_spacing(stack, spacing):
stack.spacing = spacing
spacing_stack = ui.HStack(style={"margin": 0})
with spacing_stack:
for name in ["One", "Two", "Three", "Four"]:
ui.Button(name)
with ui.HStack(spacing=SPACING):
with ui.HStack(width=100):
ui.Spacer()
ui.Label("spacing", width=0, name="text")
with ui.HStack(width=ui.Percent(20)):
field = ui.FloatField(width=50)
slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent})
# Link them together
slider.model = field.model
slider.model.add_value_changed_fn(lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float()))
self._code(
"""
def set_spacing(stack, spacing):
stack.spacing = spacing
ui.Spacer(height=SPACING)
spacing_stack = ui.HStack(style={"margin": 0})
with spacing_stack:
for name in ["One", "Two", "Three", "Four"]:
ui.Button(name)
ui.Spacer(height=SPACING)
with ui.HStack(spacing=SPACING):
with ui.HStack(width=100):
ui.Spacer()
ui.Label("spacing", width=0, name="text")
with ui.HStack(width=ui.Percent(20)):
field = ui.FloatField(width=50)
slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent})
# Link them together
slider.model = field.model
slider.model.add_value_changed_fn(
lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float()))
"""
)
self._caption("VGrid", navigate_to)
self._text(
"Grid is a container that arranges its child views in a grid. The grid vertical/horizontal direction is "
"the direction the grid size growing with creating more children."
)
self._text("It has two modes for cell width.")
self._text(" - If the user set column_count, the column width is computed from the grid width.")
self._text(" - If the user sets column_width, the column count is computed.")
self._text("It also has two modes for height.")
self._text(
" - If the user sets row_height, VGrid uses it to set the height for all the cells. It's the fast mode "
"because it's considered that the cell height never changes. VGrid easily predict which cells are visible."
)
self._text(
" - If the user sets nothing, VGrid computes the size of the children. This mode is slower than the "
"previous one, but the advantage is that all the rows can be different custom sizes. VGrid still draws "
"only visible items, but to predict it, it uses cache, which can be big if VGrid has hundreds of "
"thousands of items."
)
vgrid()
self._code(inspect.getsource(vgrid).split("\n", 1)[-1])
self._caption("HGrid", navigate_to)
self._text("HGrid works exactly like VGrid, but with swapped width and height..")
hgrid()
self._code(inspect.getsource(hgrid).split("\n", 1)[-1])
self._caption("Frame", navigate_to)
self._text(
"Frame is a container that can keep only one child. Each child added to Frame overrides the previous one. "
"This feature is used for creating dynamic layouts. The whole layout can be easily recreated with a "
"simple callback. In the following example, the buttons are recreated each time the slider changes."
)
recreate(self)
self._code(inspect.getsource(recreate).split("\n", 1)[-1])
self._text(
"Another feature of Frame is the ability to clip its child. When the content of Frame is bigger than "
"Frame itself, the exceeding part is not drawn if the clipping is on."
)
clipping(self)
self._code(inspect.getsource(clipping).split("\n", 1)[-1])
self._caption("CollapsableFrame", navigate_to)
self._text(
"CollapsableFrame is a frame widget that can hide or show its content. It has two states expanded and "
"collapsed. When it's collapsed, it looks like a button. If it's expanded, it looks like a button and a "
"frame with the content. It's handy to group properties, and temporarily hide them to get more space for "
"something else."
)
collapsable_simple()
self._code(inspect.getsource(collapsable_simple).split("\n", 1)[-1])
self._text("It's possible to use a custom header.")
collapsable_custom(self._style_system)
self._code(inspect.getsource(collapsable_custom).split("\n", 1)[-1])
self._text("The next example demonstrates how padding and margin work in the collapsable frame.")
collapsable_layout(self._style_system)
self._code(inspect.getsource(collapsable_layout).split("\n", 1)[-1])
self._caption("Examples", navigate_to)
with ui.VStack(style=self._style_system):
for i in range(2):
with ui.HStack():
ui.Spacer(width=50)
with ui.VStack(height=0):
ui.Button("Left {}".format(i), height=0)
ui.Button("Vertical {}".format(i), height=50)
with ui.HStack(width=ui.Fraction(2)):
ui.Button("Right {}".format(i))
ui.Button("Horizontal {}".format(i), width=ui.Fraction(2))
ui.Spacer(width=50)
self._code(
"""
with ui.VStack():
for i in range(2):
with ui.HStack():
ui.Spacer()
with ui.VStack(height=0):
ui.Button("Left {}".format(i), height=0)
ui.Button("Vertical {}".format(i), height=50)
with ui.HStack(width=ui.Fraction(2)):
ui.Button("Right {}".format(i))
ui.Button("Horizontal {}".format(i), width=ui.Fraction(2))
ui.Spacer()
"""
)
self._caption("Placer", navigate_to)
self._text(
"Enable you to place a widget presisely with offset. Placer's property `draggable` allows changing "
"the position of the child widget with dragging it with the mouse."
)
with ui.ScrollingFrame(
height=170,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.ZStack():
with ui.HStack():
for index in range(60):
ui.Line(width=10, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.LEFT)
with ui.VStack():
ui.Line(
height=10,
width=600,
style={"color": cl.black, "border_width": 0.5},
alignment=ui.Alignment.TOP,
)
for index in range(15):
ui.Line(
height=10,
width=600,
style={"color": cl.black, "border_width": 0.5},
alignment=ui.Alignment.TOP,
)
ui.Line(
height=10,
width=600,
style={"color": cl.black, "border_width": 0.5},
alignment=ui.Alignment.TOP,
)
with ui.Placer(offset_x=100, offset_y=10):
ui.Button("moved 100px in X, and 10px in Y", width=0, height=20, name="placed")
with ui.Placer(offset_x=200, offset_y=50):
ui.Button("moved 200px X , and 50 Y", width=0, height=0)
def set_text(widget, text):
widget.text = text
with ui.Placer(draggable=True, offset_x=300, offset_y=100):
ui.Circle(radius=50, width=50, height=50, size_policy=ui.CircleSizePolicy.STRETCH, name="placed")
placer = ui.Placer(draggable=True, drag_axis=ui.Axis.Y, offset_x=400, offset_y=120)
with placer:
with ui.ZStack(width=150, height=40):
ui.Rectangle(name="placed")
with ui.HStack(spacing=5):
ui.Circle(
radius=3,
width=15,
size_policy=ui.CircleSizePolicy.FIXED,
style={"background_color": cl.white},
)
ui.Label("UP / Down", style={"color": cl.white, "font_size": 16.0})
offset_label = ui.Label("120", style={"color": cl.white})
placer.set_offset_y_changed_fn(lambda o: set_text(offset_label, str(o)))
self._code(
"""
with ui.Placer(
draggable=True, offset_x=300, offset_y=100):
ui.Circle(
radius=50,
width=50,
height=50,
size_policy=ui.CircleSizePolicy.STRETCH,
name="placed"
)
placer = ui.Placer(
draggable=True,
drag_axis=ui.Axis.Y,
offset_x=400,
offset_y=120)
with placer:
with ui.ZStack(
width=150,
height=40,
):
ui.Rectangle(name="placed")
with ui.HStack(spacing=5):
ui.Circle(
radius=3,
width=15,
size_policy=ui.CircleSizePolicy.FIXED,
style={"background_color": cl.white},
)
ui.Label(
"UP / Down",
style={
"color": cl.white,
"font_size": 16.0
}
)
offset_label = ui.Label(
"120", style={"color": cl.white})
placer.set_offset_y_changed_fn(
lambda o: set_text(offset_label, str(o)))
"""
)
self._text(
"The following example shows the way to interact between three Placers to create a resizable rectangle. "
"The rectangle can be moved on X-axis and can be resized with small side handles."
)
self._text(
"When multiple widgets fire the callbacks simultaneously, it's possible to collect the event data and "
"process them one frame later using asyncio."
)
with ui.ZStack():
placer_track(self, 0)
placer_track(self, 1)
self._code(inspect.getsource(placer_track).split("\n", 1)[-1])
self._text(
"It's possible to set `offset_x` and `offset_y` in percents. It allows stacking the children to the "
"proportions of the parent widget. If the parent size is changed, then the offset is updated accordingly."
)
placer_percents(self)
self._code(inspect.getsource(placer_percents).split("\n", 1)[-1])
self._caption("Visibility", navigate_to)
self._text(
"This property holds whether the widget is visible. Invisible widget is not rendered, and it doesn't take "
"part in the layout. The layout skips it."
)
self._text("In the following example click the button to hide it.")
visibility()
self._code(inspect.getsource(visibility).split("\n", 1)[-1])
self._caption("Direction", navigate_to)
self._text(
"It's possible to determine the direction of a stack with the property direction. The stack is able to "
"change its direction dynamically."
)
direction()
self._code(inspect.getsource(direction).split("\n", 1)[-1])
ui.Spacer(height=50)
| 26,307 | Python | 34.647696 | 119 | 0.541415 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/canvas_frame_doc.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.
#
"""The documentation for Scrolling Frame"""
from omni import ui
from .doc_page import DocPage
import inspect
SPACING = 5
TEXT = (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
)
def simple_canvasframe():
IMAGE = "resources/icons/ov_logo_square.png"
with ui.CanvasFrame(height=256):
with ui.VStack(height=0, spacing=10):
ui.Label(TEXT, name="text", word_wrap=True)
ui.Button("Button")
ui.Image(IMAGE, width=128, height=128)
class CanvasFrameDoc(DocPage):
""" document for Menu"""
def create_doc(self, navigate_to=None):
self._section_title("CanvasFrame")
self._text(
"CanvasFrame is the widget that allows the user to pan and zoom its children with a mouse. It has the layout "
"that can be infinitely moved in any direction."
)
with ui.Frame(style=self._style_system):
simple_canvasframe()
self._code(inspect.getsource(simple_canvasframe).split("\n", 1)[-1])
ui.Spacer(height=10)
| 1,903 | Python | 35.615384 | 122 | 0.705202 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/doc_page.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.
#
"""The documentation of the omni.ui aka UI Framework"""
# Add imports here that are needed in the _exec_code calls.
from omni import ui
from omni.ui import color as cl
import omni.usd
from pxr import Usd
from pxr import UsdGeom
import subprocess
import sys
SPACING = 5
class DocPage:
"""The Demo extension"""
def __init__(self, extension_path):
self._extension_path = extension_path
self._style_system = {
"Button": {
"background_color": 0xFFE1E1E1,
"border_color": 0xFFADADAD,
"border_width": 0.5,
"border_radius": 0.0,
"margin": 5.0,
"padding": 5.0,
},
"Button.Label": {"color": 0xFF000000},
"Button:hovered": {"background_color": 0xFFFBF1E5, "border_color": 0xFFD77800},
"Button:pressed": {"background_color": 0xFFF7E4CC, "border_color": 0xFF995400, "border_width": 1.0},
}
self._copy_context_menu = ui.Menu("Copy Context menu", name="this")
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
pass
def _show_copy_menu(self, x, y, button, modifier, text):
"""The context menu to copy the text"""
# Display context menu only if the right button is pressed
if button != 1:
return
def copy_text(text_value):
# we need to find a cross plartform way currently Window Only
subprocess.run(["clip.exe"], input=text_value.strip().encode("utf-8"), check=True)
# Reset the previous context popup
self._copy_context_menu.clear()
with self._copy_context_menu:
ui.MenuItem("Copy Code", triggered_fn=lambda t=text: copy_text(t))
# Show it
self._copy_context_menu.show()
def create_doc(self, navigate_to=None):
"""
Class should overide this methods.
Args:
navigate_to: The chapter it's necessary to navigate the scrollbar.
"""
pass
def _text(self, text):
"""Create a formated paragraph of the text"""
ui.Label(text, name="text", word_wrap=True, skip_draw_when_clipped=True)
def _section_title(self, text):
"""Create a title separator"""
with ui.ZStack():
ui.Rectangle(name="section")
ui.Label(text, name="section", alignment=ui.Alignment.CENTER)
def _caption(self, text, navigate_to=None):
"""Create a formated heading"""
with ui.ZStack():
background = ui.Rectangle(name="caption")
if navigate_to == text:
background.scroll_here_y(0.0)
ui.Label(text, name="caption", alignment=ui.Alignment.LEFT_CENTER)
def _code(self, text, elided_text=False):
"""Create a code snippet"""
stack = ui.ZStack()
with stack:
ui.Rectangle(name="code")
label = ui.Label(text, name="code", skip_draw_when_clipped=True, elided_text=elided_text)
if not sys.platform == "linux":
stack.set_mouse_pressed_fn(lambda x, y, b, m, text=text: self._show_copy_menu(x, y, b, m, text))
return label
def _exec_code(self, code):
"""Execute the code and create a snippet"""
# Python magic to capture output of exec
locals_from_execution = {}
exec(f"class Execution():\n def __init__(self):\n{code}", None, locals_from_execution)
self._first = locals_from_execution["Execution"]()
self._code(code)
def _image_table(self, code, description, description_width=ui.Fraction(1), code_width=ui.Fraction(1)):
"""Create a row of the table that demostrates images"""
# TODO: We need to use style padding instead of thousands of spacers
with ui.HStack():
with ui.ZStack(width=140):
ui.Rectangle(name="table")
with ui.HStack():
ui.Spacer(width=SPACING / 2)
with ui.VStack():
ui.Spacer(height=SPACING / 2)
# Execute the provided code
exec(code)
ui.Spacer(height=SPACING / 2)
ui.Spacer(width=SPACING / 2)
with ui.ZStack(width=description_width):
ui.Rectangle(name="table")
with ui.HStack():
ui.Spacer(width=SPACING / 2)
ui.Label(description, style={"margin": 5}, name="text", word_wrap=True)
ui.Spacer(width=SPACING / 2)
with ui.ZStack(width=code_width):
ui.Rectangle(name="table")
with ui.HStack():
ui.Spacer(width=SPACING / 2)
with ui.VStack():
ui.Spacer(height=SPACING / 2)
with ui.ZStack():
ui.Rectangle(name="code")
ui.Label(f"\n\t{code}\n\n", name="code")
ui.Spacer(height=SPACING / 2)
ui.Spacer(width=SPACING / 2)
def _shape_table(self, code, description, row_height=0):
"""Create a row of the table that demostrates images"""
# TODO: We need to use style padding instead of thousands of spacers
with ui.HStack(height=row_height):
with ui.ZStack():
ui.Rectangle(name="table")
# Execute the provided code
with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING * 2}}):
ui.Rectangle(name="code")
exec(code)
with ui.ZStack(width=ui.Fraction(2)):
ui.Rectangle(name="table")
ui.Label(description, name="text", style={"margin": SPACING}, word_wrap=True)
with ui.ZStack(width=300):
ui.Rectangle(name="table")
with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING / 2}}):
ui.Rectangle(name="code")
ui.Label(f"\n\t{code}\n\n", name="code")
def _table(self, selector, example, explanatoin, color=None):
"""Create a one row of a table"""
localStyle = {}
if color is not None:
localStyle = {"color": color}
# TODO: We need to use style padding instead of thousands of spacers
with ui.HStack(height=0, style=localStyle):
with ui.ZStack(width=100):
ui.Rectangle(name="table")
with ui.HStack(height=0):
ui.Spacer(width=SPACING)
ui.Label(selector, name="text")
ui.Spacer(width=SPACING)
with ui.ZStack(width=120):
ui.Rectangle(name="table")
with ui.HStack(height=0):
ui.Spacer(width=SPACING)
ui.Label(example, name="text")
ui.Spacer(width=SPACING)
with ui.ZStack():
ui.Rectangle(name="table")
with ui.HStack(height=0):
ui.Spacer(width=SPACING)
ui.Label(explanatoin, name="text", word_wrap=True)
ui.Spacer(width=SPACING)
| 7,721 | Python | 39.857143 | 112 | 0.553685 |
omniverse-code/kit/exts/omni.example.ui/docs/treeview.md | # TreeView
## Selection
## Drag-and-drop
| 44 | Markdown | 5.428571 | 16 | 0.636364 |
omniverse-code/kit/exts/omni.example.ui/docs/model.md | # Model
The central component of the TreeView widget. It is the application's dynamic
data structure, independent of the user interface, and it directly manages the
nested data. It follows the Model-Dlegate-View pattern closely. It's abstract,
and it defines the standard interface to be able to interoperate with the
components of the model-view architecture. It is not supposed to be instantiated
directly. Instead, the user should subclass it to create a new model.
The item model doesn't return the data itself. Instead, it returns the value
model that can contain any data type and supports callbacks. Thus, the model
client can track the changes in both the item model and any value it holds.
The item model can get both the value model and the nested items from any item.
Therefore, the model is flexible to represent anything from color to complicated
tree-table construction.
## Item
Item is the object that is associated with the data entity of the model.
The item should be created and stored by the model implementation. And can
contain any data in it. Another option would be to use it as a raw pointer to
the data. In any case, it's the choice of the model how to manage this class.
## Hierarchial Model
Usually, the model is a hierarchical system where the item can have any number
of child items. The model can be populated at the moment the user expands the
item to save resources. The following example demonstrates that the model can be
infinitely long.
```execute 200
class Item(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.children = None
class Model(ui.AbstractItemModel):
def __init__(self, *args):
super().__init__()
self._children = [Item(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
if not item.children:
item.children = [Item(f"Child #{i}") for i in range(5)]
return item.children
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._model = Model("Root", "Items")
ui.TreeView(self._model, root_visible=False, style={"margin": 0.5})
```
## Nested Model
Since the model doesn't keep any data and serves as an API protocol, sometimes
it's very helpful to merge multiple models into one single model. The parent
model should redirect the calls to the children.
In the following example, three different models are merged into one.
```execute 200
class Item(ui.AbstractItem):
def __init__(self, text, name, d=5):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.children = [Item(f"Child {name}{i}", name, d - 1) for i in range(d)]
class Model(ui.AbstractItemModel):
def __init__(self, name):
super().__init__()
self._children = [Item(f"Model {name}", name)]
def get_item_children(self, item):
return item.children if item else self._children
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
return item.name_model
class NestedItem(ui.AbstractItem):
def __init__(self, source_item, source_model):
super().__init__()
self.source = source_item
self.model = source_model
self.children = None
class NestedModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
models = [Model("A"), Model("B"), Model("C")]
self.children = [
NestedItem(i, m) for m in models for i in m.get_item_children(None)]
def get_item_children(self, item):
if item is None:
return self.children
if item.children is None:
m = item.model
item.children = [
NestedItem(i, m) for i in m.get_item_children(item.source)]
return item.children
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
return item.model.get_item_value_model(item.source, column_id)
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._model = NestedModel()
ui.TreeView(self._model, root_visible=False, style={"margin": 0.5})
```
## Drag and Drop
### Drag
If the model has the item to drag, the method `get_drag_mime_data` should be
reimplemented. This method should return the string with the drag and drop
payload. This data can be dropped to any model or to any `omni.ui` widget that
accepts this data.
```
def get_drag_mime_data(self, item):
```
### Drop
The model supports drag and drop. The drag source can be an item from any model
or any draggable data from omni.ui. When the cursor with draggable data enters
the area of the model's item, the method `drop_accepted` is called where the
model needs to decide if the data is compatible with the model. If the model can
accept the drop, it should return `True`. After that if the user drops the data
to the item, the method `drop` will be called.
```
def drop_accepted(self, target_item, source):
```
```
def drop(self, target_item, source):
```
```execute 200
class Item(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
def __repr__(self):
return self.name_model.as_string
class Model(ui.AbstractItemModel):
def __init__(self, label, *args):
super().__init__()
self._children = [Item(t) for t in args]
self._label = label
def get_item_children(self, item):
if item is not None:
return []
return self._children
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
return item.name_model
def get_drag_mime_data(self, item):
"""Returns data for be able to drop this item somewhere"""
return item.name_model.as_string
def drop_accepted(self, target_item, source):
"""Return true to accept the current drop"""
# Accept anything
return True
def drop(self, target_item, source):
"""Called when the user releases the mouse"""
# Change text on the label
self._label.text = f"Dropped {source} to {target_item}"
label = ui.Label("Drop something to the following TreeView")
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._model = Model(label, *[f"Item #{i}" for i in range(50)])
ui.TreeView(self._model, root_visible=False, style={"margin": 0.5})
```
| 7,577 | Markdown | 31.805195 | 81 | 0.671902 |
omniverse-code/kit/exts/omni.example.ui/docs/CHANGELOG.md | # Changelog
The documentation for omni.example.ui
## [1.2.3] - 2023-01-27
### Fixed
- Fixed config. Removed "omni.example.ui.tests"
## [1.2.2] - 2022-10-18
### Added
- A note about color syntax
### Changed
- Old hex color syntax to new omni.ui.color syntax
## [1.2.1] - 2022-06-27
### Added
- A small note about fonts
## [1.2.0] - 2021-12-17
### Added
- Dependency to `omni.kit.documentation.builder` to show md files
- Model-Delegate-View docs
## [1.1.1] - 2021-12-06
### Fixed
- The bug in the logo alignment
- Removed a warning of AbstractValueModel
### Changed
- Color scheme
| 586 | Markdown | 18.566666 | 65 | 0.672355 |
omniverse-code/kit/exts/omni.example.ui/docs/overview.md | # Overview
MDV (Model-Delegate-View) is a pattern commonly used in `omni.ui` to implement
user interfaces with data-controlling logic. It highlights a separation between
the data and the display logic. This separation of concepts provides for better
maintenance of the code.
It closely follows the MVC pattern with a slightly different separation of
components. Unlike MVC, the View component of MDV takes responsibility of
Controller, takes control of the layout, and routes the Delegate component that
controls the look.
The three parts of the MDV software-design pattern can be described as follows:
1. Model: The central component of the system. Manages data and logic. It
creates items that are used as pointers to the specific parts of the data
layer.
2. Delegate: Creates widgets and defines the look.
3. View: Handles layout, holds the widgets, and coordinates Model and Delegate.
## Model-Delegate-View in TreeView
TreeView is the MDV widget that takes advantage of the MDV pattern. For
simplicity, this document describes how the pattern applies to TreeView, and it
can be similarly applied to any MDV-based widget. The three parts are needed to
create a nice TreeView.

1. Model: it's necessary to reimplement the class `ui.AbstractItemModel`.
2. Delegate: it's necessary to reimplement the class `ui.AbstractItemDelegate`.
3. View: it's necessary to provide the model and the delegate components
to `ui.TreeView`. There is no way to reimplement it.
## MDV pipeline in Stage Widget
To describe the MDV pipeline in production, let's focus on the "visibility"
button of Stage Widget. Stage Widget is a part of the extension `omni.kit.widget.stage`.
It uses a model that is watching the stage, the delegate that is written to
match the design document, and a standard TreeView that coordinates the model
and the delegate.

The main idea is that the model doesn't keep the data (visibility value). The
model is an API protocol that is the bridge between UsdStage and TreeView. When
the user changes the visibility, the model changes it in UsdStage, which
triggers UsdNotice. And if something is changed in UsdStage, UsdNotice makes the
model dirty. When TreeView recognizes the model is dirty, it calls the delegate
to recreate the specific piece of layout. And the delegate creates a new widget
and queries the model for visibility, and the model queries it from UsdStage.
| 2,458 | Markdown | 42.910714 | 88 | 0.78926 |
omniverse-code/kit/exts/omni.example.ui/docs/delegate.md | # Delegate
Delegate is the representation layer. Delegate is called by the view to create a
specific piece of the user interface. TreeView calls the delegate to create the
widgets for the header and per item in the column.
To
## Item

Each row in TreeView is the representation of the model's item.
## Column

Each model's item can have multiple data fields. To display them, TreeView uses
columns.
## Level

The level is the number of parent items for the given item.
## Branch Widget Header

The branch is the widget that makes TreeView expand or collapse the current
item.
## Example
To reimplement a delegate, it's necessary to reimplement the following methods
of `ui.AbstractItemDelegate`:
```
def build_branch(self, model, item, column_id, level, expanded):
```
```
def build_widget(self, model, item, column_id, level, expanded):
```
```
def build_header(self, column_id):
```
```execute 200
##
class Item(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.children = None
class Model(ui.AbstractItemModel):
def __init__(self, *args):
super().__init__()
self._children = [Item(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
if not item.children:
item.children = [Item(f"Child #{i}") for i in range(5)]
return item.children
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
##
class Delegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
# Offset depents on level
text = " " * (level + 1)
# > and v symbols depending on the expanded state
if expanded:
text += "v "
else:
text += "> "
ui.Label(text, height=22, alignment=ui.Alignment.CENTER, tooltip="Branch")
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
ui.Label(
model.get_item_value_model(item, column_id).as_string,
tooltip="Widget"
)
def build_header(self, column_id):
"""Build the header"""
ui.Label("Header", tooltip="Header", height=25)
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._model = Model("Root", "Items")
self._delegate = Delegate()
ui.TreeView(
self._model, delegate=self._delegate, root_visible=False, header_visible=True
)
```
| 3,476 | Markdown | 25.746154 | 85 | 0.638953 |
omniverse-code/kit/exts/omni.kit.window.commands/config/extension.toml | [package]
version = "0.2.4"
category = "Core"
authors = ["NVIDIA"]
title = "Commands Utils"
description="Commands history viewer, commands execution script generator and registered commands viewer"
repository = ""
keywords = ["kit", "commands"]
changelog = "docs/CHANGELOG.md"
[dependencies]
"omni.kit.clipboard" = {}
"omni.kit.commands" = {}
"omni.kit.pip_archive" = {}
"omni.ui" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.kit.window.commands"
[settings]
exts."omni.kit.window.commands".windowOpenByDefault = false
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture"
]
| 715 | TOML | 19.457142 | 105 | 0.678322 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/main.py | from collections import defaultdict
from inspect import isclass
from functools import partial
import omni.kit.commands
import omni.kit.undo
from omni import ui
from .history import HistoryModel, HistoryDelegate, MainItem
from .search import SearchModel, SearchDelegate, CommandItem, Columns
class Window:
def __init__(self, title, menu_path):
self._menu_path = menu_path
self._win_history = ui.Window(title, width=700, height=500)
self._win_history.set_visibility_changed_fn(self._on_visibility_changed)
self._win_search = None
self._search_frame = None
self._doc_frame = None
self._history_delegate = HistoryDelegate()
self._search_delegate = SearchDelegate()
self._build_ui()
omni.kit.commands.subscribe_on_change(self._update_ui)
self._update_ui()
def on_shutdown(self):
self._win_history = None
self._win_search = None
self._search_frame = None
self._doc_frame = None
self._history_delegate = None
self._search_delegate = None
omni.kit.commands.unsubscribe_on_change(self._update_ui)
def show(self):
self._win_history.visible = True
self._win_history.focus()
def hide(self):
self._win_history.visible = False
if self._win_search is not None:
self._win_search.visible = False
def _on_visibility_changed(self, visible):
if not visible:
omni.kit.ui.get_editor_menu().set_value(self._menu_path, False)
if self._win_search is not None:
self._win_search.visible = False
def _build_ui(self):
with self._win_history.frame:
with ui.VStack():
with ui.HStack(height=20):
ui.Button("Clear history", width=60, clicked_fn=self._clear_history)
ui.Button("Search commands", width=60, clicked_fn=self._show_registered)
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="TreeView",
):
self._history_model = HistoryModel()
self._history_tree_view = ui.TreeView(
self._history_model,
delegate=self._history_delegate,
root_visible=False,
style={"TreeView.Item::error": {"color": 0xFF0000BB}},
column_widths=[ui.Fraction(1)],
)
self._history_tree_view.set_mouse_double_clicked_fn(self._on_double_click)
with ui.HStack(height=20):
ui.Label("Generate script to clipboard from:", width=0)
ui.Button("Top-level commands", width=60, clicked_fn=partial(self._copy_to_clipboard, False))
ui.Button("Selected commands", width=60, clicked_fn=partial(self._copy_to_clipboard, True))
def _on_double_click(self, x, y, b, m):
if len(self._history_tree_view.selection) <= 0:
return
item = self._history_tree_view.selection[0]
if isinstance(item, MainItem):
self._history_tree_view.set_expanded(item, not self._history_tree_view.is_expanded(item), False)
def _copy_to_clipboard(self, only_selected):
omni.kit.clipboard.copy(self._generate_command_script(only_selected))
def _clear_history(self):
omni.kit.undo.clear_history()
self._history_model._commands_changed()
def _show_registered(self):
if self._win_search is None:
self._win_search = ui.Window(
"Search Commands", width=700, height=500, dockPreference=ui.DockPreference.MAIN
)
with self._win_search.frame:
with ui.VStack():
with ui.HStack(height=20):
ui.Label("Find: ", width=0)
self._search_field = ui.StringField()
self._search_field.model.add_value_changed_fn(lambda _: self._refresh_list())
with ui.HStack(height=300):
self._search_frame = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="TreeView",
)
with self._search_frame:
self._search_tree_model = SearchModel()
self._search_tree_view = ui.TreeView(
self._search_tree_model,
delegate=self._search_delegate,
selection_changed_fn=self._on_selection_changed,
root_visible=False,
header_visible=True,
columns_resizable=True,
column_widths=[x.width for x in Columns.ORDER],
)
self._doc_frame = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
)
self._refresh_list()
self._win_search.visible = True
self._win_search.focus()
def _on_selection_changed(self, selected_items):
with self._doc_frame:
with ui.VStack(height=40):
for item in selected_items:
if isinstance(item, CommandItem):
ui.Label(f"{item.command_model.as_string}{item.class_sig}", height=30)
ui.Label(f"Documentation:", height=30)
if item.doc is None or item.doc == omni.kit.commands.Command.__doc__:
ui.Label("\n\t<None>")
else:
ui.Label(item.doc.strip())
def _update_ui(self):
self._history_model._commands_changed()
self._refresh_list() # TODO: check if this is called too much
def _refresh_list(self):
if self._search_frame is None:
return
search_str = self._search_field.model.get_value_as_string().lower().strip()
self._search_tree_model._clear_commands()
commands = omni.kit.commands.get_commands()
for cmd_list in commands.values():
for command in cmd_list.values():
if search_str == "" or command.__name__.lower().find(search_str) != -1:
if self._search_tree_model:
class_sig = omni.kit.commands.get_command_class_signature(command.__name__)
self._search_tree_model._add_command(CommandItem(command, class_sig))
self._search_tree_view.clear_selection()
self._search_tree_model._commands_changed()
def _generate_command_script(self, only_selected):
history = omni.kit.undo.get_history().values()
imports = "import omni.kit.commands\n"
code_str = ""
arg_imports = defaultdict(set)
def parse_module_name(name):
if name == "builtins":
return
nonlocal imports
lst = name.split(".")
if len(lst) == 1:
imports += "import " + name + "\n"
else:
arg_imports[lst[0]].add(".".join(lst[1:]))
def arg_import(val):
if isclass(val):
parse_module_name(val.__module__)
else:
parse_module_name(val.__class__.__module__)
return val
def gen_cmd_str(cmd):
if len(cmd.kwargs.items()) > 0:
args = ",\n\t".join(["{}={!r}".format(k, arg_import(v)) for k, v in cmd.kwargs.items()])
return f"\nomni.kit.commands.execute('{cmd.name}',\n\t{args})\n"
else:
return f"\nomni.kit.commands.execute('{cmd.name}')\n"
# generate a script executing top-level commands or all selected commands
if only_selected:
for item in self._history_tree_view.selection:
if isinstance(item, MainItem):
code_str += gen_cmd_str(item._data)
else:
for cmd in history:
if cmd.level == 0:
code_str += gen_cmd_str(cmd)
for k, v in arg_imports.items():
imports += f"from {k} import " + ", ".join(v) + "\n"
return imports + code_str
| 8,837 | Python | 41.085714 | 113 | 0.539097 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/search.py | import inspect
from pathlib import Path
import carb.settings
import omni.ext
import omni.kit.app
from omni import ui
class SearchModel(ui.AbstractItemModel):
"""
Represents the list of commands registered in Kit.
It is used to make a single level tree appear like a simple list.
"""
def __init__(self):
super().__init__()
self._commands = []
def _clear_commands(self):
self._commands = []
def _commands_changed(self):
self._item_changed(None)
def _add_command(self, item):
if item and isinstance(item, CommandItem):
self._commands.append(item)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is None:
return self._commands
return item.children
def get_item_value_model_count(self, item):
"""The number of columns"""
return Columns.get_count()
def get_item_value_model(self, item, column_id):
"""Return value model."""
if item and isinstance(item, CommandItem):
return Columns.get_model(item, column_id)
class SearchDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
self._icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons")
self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
# Read all the svg files in the directory
self._icons = {icon.stem: icon for icon in self._icon_path.joinpath(self._style).glob("*.svg")}
def build_widget(self, model, item, column_id, level, expanded):
value_model = model.get_item_value_model(item, column_id)
text = value_model.as_string
ui.Label(text, style_type_name_override="TreeView.Item")
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=16 * (level + 2), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.Image(
str(self._icons.get(image_name)), width=10, height=10, style_type_name_override="TreeView.Item"
)
ui.Spacer(width=4)
def build_header(self, column_id):
label = Columns.get_label(column_id)
ui.Label(label, height=30, width=20)
class CommandItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, command, class_sig):
super().__init__()
self.command_model = ui.SimpleStringModel(command.__name__)
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = manager.get_extension_id_by_module(command.__module__)
ext_name = omni.ext.get_extension_name(ext_id) if ext_id else "Unknown"
self.extension_model = ui.SimpleStringModel(ext_name)
self.undo_model = ui.SimpleBoolModel(hasattr(command, "undo") and inspect.isfunction(command.undo))
self.doc = command.__doc__ or (command.__init__ is not None and command.__init__.__doc__)
self.class_sig = class_sig
self.children = []
# uncomment these lines if child items are needed later on
# if doc is not None:
# self.children.append(CommandChildItem(doc))
class CommandChildItem(CommandItem):
def __init__(self, arg):
super().__init__(str(arg))
self.children = []
class Columns:
"""
Store UI info about the columns in one place so it's easier to keep in
"""
class ColumnData:
def __init__(self, label, column, width, attrib_name):
self.label = label
self.column = column
self.width = width
self.attrib_name = attrib_name
Command = ColumnData("Command", 0, ui.Fraction(1), "command_model")
Extension = ColumnData("Extension", 1, ui.Pixel(200), "extension_model")
CanUndo = ColumnData("Can Undo", 2, ui.Pixel(80), "undo_model")
ORDER = [Command, Extension, CanUndo]
@classmethod
def get_count(cls):
return len(cls.ORDER)
@classmethod
def get_label(cls, index):
return cls.ORDER[index].label
@classmethod
def get_model(cls, entry: CommandItem, index):
return getattr(entry, cls.ORDER[index].attrib_name)
| 4,521 | Python | 33.519084 | 119 | 0.610263 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/extension.py | import carb.settings
import omni.ext
import omni.kit.ui
from .main import Window
EXTENSION_NAME = "Commands"
class Extension(omni.ext.IExt):
def on_startup(self):
self._menu_path = f"Window/{EXTENSION_NAME}"
self._window = None
open_by_default = carb.settings.get_settings().get("exts/omni.kit.window.commands/windowOpenByDefault")
self._menu = omni.kit.ui.get_editor_menu().add_item(
self._menu_path, self._on_menu_click, True, value=open_by_default
)
if open_by_default:
self._on_menu_click(None, True)
def on_shutdown(self):
if self._window is not None:
self._window.on_shutdown()
self._menu = None
self._window = None
def _on_menu_click(self, menu, toggled):
if toggled:
if self._window is None:
self._window = Window(EXTENSION_NAME, self._menu_path)
else:
self._window.show()
else:
if self._window is not None:
self._window.hide()
| 1,062 | Python | 28.527777 | 111 | 0.582863 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/history.py | from pathlib import Path
import carb.settings
from omni import ui
import omni.kit.undo
class HistoryData:
def __init__(self):
self._data = omni.kit.undo.get_history()
if len(self._data):
self._curr = next(iter(self._data))
self._last = next(reversed(self._data))
else:
self._curr = 0
self._last = -1
def is_not_empty(self):
return self._curr <= self._last
def get_next(self):
self._curr += 1
return self._data[self._curr - 1]
def is_next_lower(self, level):
return self._data[self._curr].level > level
class HistoryModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._root = MainItem(None, HistoryData())
def _commands_changed(self):
self._root = MainItem(None, HistoryData())
self._item_changed(None)
def get_item_children(self, item):
if item is None:
return self._root.children
return item.children
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
if column_id == 0:
return item.name_model
class HistoryDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
self._icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons")
self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
# Read all the svg files in the directory
self._icons = {icon.stem: icon for icon in self._icon_path.joinpath(self._style).glob("*.svg")}
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
value_model = model.get_item_value_model(item, column_id)
# call out commands that had errors
text = value_model.as_string
name = ""
if hasattr(item, "_data") and hasattr(item._data, "error") and item._data.error:
text = "[ERROR] " + text
name = "error"
ui.Label(text, name=name, style_type_name_override="TreeView.Item")
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=16 * (level + 2), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.Image(
str(self._icons.get(image_name)), width=10, height=10, style_type_name_override="TreeView.Item"
)
ui.Spacer(width=4)
def build_header(self, column_id):
pass
class MainItem(ui.AbstractItem):
def __init__(self, command_data, history):
super().__init__()
self._data = command_data
if command_data is None:
self._create_root(history)
else:
self._create_node(history)
def _create_root(self, history):
self.children = []
while history.is_not_empty():
self.children.append(MainItem(history.get_next(), history))
def _create_node(self, history):
self.name_model = ui.SimpleStringModel(self._data.name)
self.children = [ParamItem(arg, val) for arg, val in self._data.kwargs.items()]
while history.is_not_empty() and history.is_next_lower(self._data.level):
next_command = history.get_next()
self.children.append(MainItem(next_command, history))
class ParamItem(ui.AbstractItem):
def __init__(self, arg, val):
super().__init__()
self.name_model = ui.SimpleStringModel(str(arg) + "=" + str(val))
self.children = []
| 3,889 | Python | 32.534482 | 119 | 0.580869 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/tests/test_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 omni.kit.test
import re
from pathlib import Path
import omni.kit.app
import omni.kit.commands
import omni.kit.undo
from omni.kit.window.commands import Window
from omni.ui.tests.test_base import OmniUiTest
_result = []
class TestAppendCommand(omni.kit.commands.Command):
def __init__(self, x, y):
self._x = x
self._y = y
def do(self):
global _result
_result.append(self._x)
_result.append(self._y)
def undo(self):
global _result
del _result[-1]
del _result[-1]
class TestCommandsWindow(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute()
# make sure we are starting from a clean state
omni.kit.undo.clear_stack()
# Register all commands
omni.kit.commands.register(TestAppendCommand)
# After running each test
async def tearDown(self):
# Unregister all commands
omni.kit.commands.unregister(TestAppendCommand)
await super().tearDown()
async def test_simple_command(self):
window = await self.create_test_window(1000, 600)
with window.frame:
win = Window("Commands", "Commands")
win.show()
global _result
# Execute and undo
_result = []
omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertListEqual(_result, [1, 2])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
script = """import omni.kit.commands
omni.kit.commands.execute('TestAppend',
x=1,
y=2)
omni.kit.commands.execute('Undo')"""
result = win._generate_command_script(False)
# strip all whitespaces to ease our comparison
s = re.sub("[\s+]", "", script)
r = re.sub("[\s+]", "", result)
# test script
self.assertEqual(s, r)
for i in range(50):
await omni.kit.app.get_app().next_update_async()
# test image
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="test_simple_command.png", use_log=False
)
| 2,862 | Python | 28.822916 | 110 | 0.620196 |
omniverse-code/kit/exts/omni.kit.window.commands/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.2.4] - 2022-11-17
### Changes
- Switched out pyperclip for linux-friendly copy & paste
## [0.2.3] - 2022-09-22
### Fixes
- Make test pass again by allowing more time for SVG load.
## [0.2.2] - 2022-06-07
### Fixes
- Get extension name from the extension manager.
## [0.2.1] - 2022-05-09
### Changes
- Added tests
## [0.2.0] - 2021-12-16
### Changes
- New TreeView for the search window that provide more details
## [0.1.1] - 2021-02-10
### Changes
- Updated StyleUI handling
## [0.1.0] - 2020-07-30
### Added
- initial implementation
| 641 | Markdown | 19.062499 | 80 | 0.656786 |
omniverse-code/kit/exts/omni.kit.window.commands/docs/index.rst | omni.kit.window.commands
###########################
* Commands history view.
* Script generator for the execution of top-level or selected commands.
* Full-text search in names of all currently registered commands.
.. toctree::
:maxdepth: 1
CHANGELOG | 272 | reStructuredText | 23.81818 | 75 | 0.647059 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/renderer_capture/__init__.py | from omni.kit.renderer_capture import *
| 40 | Python | 19.49999 | 39 | 0.8 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/scripts/extension.py | import carb.settings
import omni.ext
import omni.kit.renderer_capture
class Extension(omni.ext.IExt):
def __init__(self):
omni.ext.IExt.__init__(self)
pass
def on_startup(self):
self._settings = carb.settings.get_settings()
self._settings.set_default_bool("/exts/omni.kit.renderer.capture/autostartCapture", True)
self._autostart = self._settings.get("/exts/omni.kit.renderer.capture/autostartCapture")
if self._autostart:
self._renderer_capture = omni.kit.renderer_capture.acquire_renderer_capture_interface()
self._renderer_capture.startup()
def on_shutdown(self):
if self._autostart:
self._renderer_capture.shutdown()
self._renderer_capture = None
| 772 | Python | 31.208332 | 99 | 0.65544 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/tests/__init__.py | from .test_renderer_capture import *
| 37 | Python | 17.999991 | 36 | 0.783784 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/tests/test_renderer_capture.py | import os
import sys
import inspect
import pathlib
import importlib
import carb
import carb.dictionary
import carb.settings
import carb.tokens
import omni.appwindow
import omni.kit.app
import omni.kit.test
import omni.kit.renderer.bind
import omni.kit.renderer_capture
import omni.kit.renderer_capture_test
OUTPUTS_DIR = omni.kit.test.get_test_output_path()
USE_TUPLES = True
# Ancient hack coming from dark times
SET_ALPHA_TO_1_SETTING_PATH = "/app/captureFrame/setAlphaTo1"
class RendererCaptureTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.acquire_dictionary_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
self._renderer_capture = omni.kit.renderer_capture.acquire_renderer_capture_interface()
self._renderer_capture_test = omni.kit.renderer_capture_test.acquire_renderer_capture_test_interface()
self._renderer.startup()
self._renderer_capture.startup()
self._renderer_capture_test.startup()
def __test_name(self) -> str:
return f"{self.__class__.__name__}.{inspect.stack()[1][3]}"
async def tearDown(self):
self._renderer_capture_test.shutdown()
self._renderer_capture.shutdown()
self._renderer.shutdown()
self._renderer_capture_test = None
self._renderer_capture = None
self._renderer = None
self._app_window_factory = None
self._settings = None
def _create_and_attach_window(self, w, h, window_type):
app_window = self._app_window_factory.create_window_by_type(window_type)
app_window.startup_with_desc(
title="Renderer capture test OS window",
width=w,
height=h,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=1.0
)
self._app_window_factory.set_default_window(app_window)
self._renderer.attach_app_window(app_window)
return app_window
def _detach_and_destroy_window(self, app_window):
self._app_window_factory.set_default_window(None)
self._renderer.detach_app_window(app_window)
app_window.shutdown()
def _capture_callback(self, buf, buf_size, w, h, fmt):
if USE_TUPLES:
self._captured_buffer = omni.kit.renderer_capture.convert_raw_bytes_to_rgba_tuples(buf, buf_size, w, h, fmt)
else:
self._captured_buffer = omni.kit.renderer_capture.convert_raw_bytes_to_list(buf, buf_size, w, h, fmt)
self._captured_buffer_w = w
self._captured_buffer_h = h
self._captured_buffer_fmt = fmt
def _get_pil_image_from_captured_data(self):
from PIL import Image
image = Image.new('RGBA', [self._captured_buffer_w, self._captured_buffer_h])
if USE_TUPLES:
image.putdata(self._captured_buffer)
else:
buf_channel_it = iter(self._captured_buffer)
captured_buffer_tuples = list(zip(buf_channel_it, buf_channel_it, buf_channel_it, buf_channel_it))
image.putdata(captured_buffer_tuples)
return image
def _get_pil_image_size_data(self, path):
from PIL import Image
image = Image.open(path)
image_data = list(image.getdata())
image_w, image_h = image.size
image.close()
return image_w, image_h, image_data
def _disable_alpha_to_1(self):
self._settings.set_default(SET_ALPHA_TO_1_SETTING_PATH, False)
self._setAlphaTo1 = self._settings.get(SET_ALPHA_TO_1_SETTING_PATH)
self._settings.set(SET_ALPHA_TO_1_SETTING_PATH, False)
def _restore_alpha_to_1(self):
self._settings.set(SET_ALPHA_TO_1_SETTING_PATH, self._setAlphaTo1)
async def test_0001_capture_swapchain_to_file(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 8
TEST_IMG_H = 8
TEST_COLOR = (255, 0, 0, 255)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0002_capture_swapchain_callback(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 16
TEST_IMG_H = 16
TEST_COLOR = (0, 255, 255, 255)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain_callback(self._capture_callback, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image = self._get_pil_image_from_captured_data()
image.save(TEST_IMG_PATH)
self.assertEqual(self._captured_buffer_w, TEST_IMG_W)
self.assertEqual(self._captured_buffer_h, TEST_IMG_H)
if USE_TUPLES:
self.assertEqual(self._captured_buffer[0], TEST_COLOR)
else:
self.assertEqual(self._captured_buffer[0], TEST_COLOR[0])
self.assertEqual(self._captured_buffer[1], TEST_COLOR[1])
self.assertEqual(self._captured_buffer[2], TEST_COLOR[2])
self.assertEqual(self._captured_buffer[3], TEST_COLOR[3])
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0003_capture_texture_to_file(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 4
TEST_IMG_H = 4
TEST_COLOR = (255, 255, 0, 255)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
texture = self._renderer_capture_test.create_solid_color_texture(test_color_unit, TEST_IMG_W, TEST_IMG_H)
self._renderer_capture.capture_next_frame_texture(TEST_IMG_PATH, texture)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0004_capture_texture_callback(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 6
TEST_IMG_H = 6
TEST_COLOR = (255, 0, 255, 255)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
texture = self._renderer_capture_test.create_solid_color_texture(test_color_unit, TEST_IMG_W, TEST_IMG_H)
self._renderer_capture.capture_next_frame_texture_callback(self._capture_callback, texture)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image = self._get_pil_image_from_captured_data()
image.save(TEST_IMG_PATH)
self.assertEqual(self._captured_buffer_w, TEST_IMG_W)
self.assertEqual(self._captured_buffer_h, TEST_IMG_H)
if USE_TUPLES:
self.assertEqual(self._captured_buffer[0], TEST_COLOR)
else:
self.assertEqual(self._captured_buffer[0], TEST_COLOR[0])
self.assertEqual(self._captured_buffer[1], TEST_COLOR[1])
self.assertEqual(self._captured_buffer[2], TEST_COLOR[2])
self.assertEqual(self._captured_buffer[3], TEST_COLOR[3])
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0005_capture_rp_resource_to_file(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 5
TEST_IMG_H = 5
TEST_COLOR = (0, 255, 0, 255)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
rp_resource = self._renderer_capture_test.create_solid_color_rp_resource(test_color_unit, TEST_IMG_W, TEST_IMG_H)
self._renderer_capture.capture_next_frame_rp_resource(TEST_IMG_PATH, rp_resource)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0006_capture_rp_resource_callback(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 6
TEST_IMG_H = 6
TEST_COLOR = (0, 0, 255, 255)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
rp_resource = self._renderer_capture_test.create_solid_color_rp_resource(test_color_unit, TEST_IMG_W, TEST_IMG_H)
self._renderer_capture.capture_next_frame_rp_resource_callback(self._capture_callback, rp_resource)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image = self._get_pil_image_from_captured_data()
image.save(TEST_IMG_PATH)
self.assertEqual(self._captured_buffer_w, TEST_IMG_W)
self.assertEqual(self._captured_buffer_h, TEST_IMG_H)
if USE_TUPLES:
self.assertEqual(self._captured_buffer[0], TEST_COLOR)
else:
self.assertEqual(self._captured_buffer[0], TEST_COLOR[0])
self.assertEqual(self._captured_buffer[1], TEST_COLOR[1])
self.assertEqual(self._captured_buffer[2], TEST_COLOR[2])
self.assertEqual(self._captured_buffer[3], TEST_COLOR[3])
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0007_capture_os_swapchain_to_file(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 256
TEST_IMG_H = 32
TEST_COLOR = (255, 128, 0, 255)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.OS)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0008_capture_transparent_swapchain_to_file(self):
self._disable_alpha_to_1()
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 8
TEST_IMG_H = 8
TEST_COLOR = (255, 0, 0, 0)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._detach_and_destroy_window(app_window)
app_window = None
self._restore_alpha_to_1()
async def test_0009_capture_transparent_swapchain_callback(self):
self._disable_alpha_to_1()
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 16
TEST_IMG_H = 16
TEST_COLOR = (0, 255, 255, 0)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain_callback(self._capture_callback, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image = self._get_pil_image_from_captured_data()
image.save(TEST_IMG_PATH)
self.assertEqual(self._captured_buffer_w, TEST_IMG_W)
self.assertEqual(self._captured_buffer_h, TEST_IMG_H)
if USE_TUPLES:
self.assertEqual(self._captured_buffer[0], TEST_COLOR)
else:
self.assertEqual(self._captured_buffer[0], TEST_COLOR[0])
self.assertEqual(self._captured_buffer[1], TEST_COLOR[1])
self.assertEqual(self._captured_buffer[2], TEST_COLOR[2])
self.assertEqual(self._captured_buffer[3], TEST_COLOR[3])
self._detach_and_destroy_window(app_window)
app_window = None
self._restore_alpha_to_1()
async def __test_capture_rp_resource_with_format(self, format_desc_item):
test_name = self.__test_name()
TEST_IMG_PATH_NOEXT = os.path.join(OUTPUTS_DIR, test_name)
TEST_IMG_W = 15
TEST_IMG_H = 15
TEST_COLOR = (12.34, 34.56, 67.89, 128.0)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
files = {}
format_desc_item["format"] = "exr"
rp_resource = self._renderer_capture_test.create_solid_color_rp_resource_hdr(TEST_COLOR, TEST_IMG_W, TEST_IMG_H)
async def capture():
filename = TEST_IMG_PATH_NOEXT + "_" + format_desc_item["compression"] + ".exr"
files[format_desc_item["compression"]] = filename
self._renderer_capture.capture_next_frame_rp_resource_to_file(filename, rp_resource, None, format_desc_item)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
format_desc_item["compression"] = "none"
await capture()
format_desc_item["compression"] = "rle"
await capture()
format_desc_item["compression"] = "b44"
await capture()
file_sizes = {}
for file_key, file_path in files.items():
file_sizes[file_key] = os.path.getsize(file_path)
self.assertNotEqual(file_sizes["none"], file_sizes["rle"])
self.assertNotEqual(file_sizes["none"], file_sizes["b44"])
self.assertNotEqual(file_sizes["rle"], file_sizes["b44"])
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0010_capture_rp_resource_hdr_to_file_carb_dict(self):
format_desc_item = self._dict.create_item(None, "", carb.dictionary.ItemType.DICTIONARY)
await self.__test_capture_rp_resource_with_format(format_desc_item)
async def test_0010_capture_rp_resource_hdr_to_file_py_dict(self):
format_desc_item = {}
await self.__test_capture_rp_resource_with_format(format_desc_item)
| 17,721 | Python | 39.277273 | 121 | 0.639806 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture_test/__init__.py | import functools
from ._renderer_capture_test import *
# Cached interface instance pointer
@functools.lru_cache()
def get_renderer_capture_test_interface() -> IRendererCaptureTest:
if not hasattr(get_renderer_capture_test_interface, "renderer_capture_test"):
get_renderer_capture_test_interface.renderer_capture_test = acquire_renderer_capture_test_interface()
return get_renderer_capture_test_interface.renderer_capture_test
| 444 | Python | 39.454542 | 109 | 0.783784 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture/_renderer_capture.pyi | from __future__ import annotations
import omni.kit.renderer_capture._renderer_capture
import typing
import omni.appwindow._appwindow
import omni.gpu_foundation_factory._gpu_foundation_factory
__all__ = [
"IRendererCapture",
"Metadata",
"acquire_renderer_capture_interface",
"convert_raw_bytes_to_list",
"convert_raw_bytes_to_rgba_tuples"
]
class IRendererCapture():
def capture_next_frame_rp_resource(self, filepath: str, resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture RTX resource manager RpResource and save to a file.
"""
def capture_next_frame_rp_resource_callback(self, callback: typing.Callable[[capsule, int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture RTX resource manager RpResource and trigger a callback when capture buffer is available.
"""
def capture_next_frame_rp_resource_list_callback(self, callback: typing.Callable[[typing.List[int], int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture RTX resource manager RpResource and trigger a callback when capture buffer is available.
"""
def capture_next_frame_rp_resource_to_file(self, filepath: str, resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, format_desc: object = None, metadata: Metadata = None) -> None:
"""
Request capture RTX resource manager RpResource and save to a file.
"""
def capture_next_frame_swapchain(self, filepath: str, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture swapchain and save to a file.
"""
def capture_next_frame_swapchain_callback(self, callback: typing.Callable[[capsule, int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture swapchain and trigger a callback when capture buffer is available.
"""
def capture_next_frame_swapchain_to_file(self, filepath: str, app_window: omni.appwindow._appwindow.IAppWindow = None, format_desc: object = None, metadata: Metadata = None) -> None:
"""
Request capture swapchain and save to a file.
"""
def capture_next_frame_texture(self, filepath: str, texture: omni.gpu_foundation_factory._gpu_foundation_factory.Texture = None, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture texture and save to a file.
"""
def capture_next_frame_texture_callback(self, callback: typing.Callable[[capsule, int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], texture: omni.gpu_foundation_factory._gpu_foundation_factory.Texture = None, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture texture and trigger a callback when capture buffer is available.
"""
def capture_next_frame_texture_to_file(self, filepath: str, texture: omni.gpu_foundation_factory._gpu_foundation_factory.Texture = None, app_window: omni.appwindow._appwindow.IAppWindow = None, format_desc: object = None, metadata: Metadata = None) -> None:
"""
Request capture texture and save to a file.
"""
def capture_next_frame_using_render_product(self, viewport_handle: int, filepath: str, render_product: str) -> None:
"""
Request capture of all resources in render product
"""
def request_callback_memory_ownership(self) -> bool:
"""
Request memory ownership of a buffer passed into callback. Should be called from within a callback.
"""
def set_capture_sync(self, sync: bool, app_window: omni.appwindow._appwindow.IAppWindow = None) -> bool:
"""
Set synchronous capture mode.
"""
def shutdown(self) -> bool:
"""
Internal function. Shuts down capture interface.
"""
def start_frame_updates(self, app_window: omni.appwindow._appwindow.IAppWindow = None) -> bool:
"""
Starts per frame updates to collect capturing related data during each frame, such as FPS.
"""
def startup(self) -> bool:
"""
Internal function. Starts up capture interface.
"""
def wait_async_capture(self, app_window: omni.appwindow._appwindow.IAppWindow = None) -> None:
"""
Wait for asynchronous capture to complete.
"""
pass
class Metadata():
pass
def acquire_renderer_capture_interface(*args, **kwargs) -> typing.Any:
pass
def convert_raw_bytes_to_list(arg0: capsule, arg1: int, arg2: int, arg3: int, arg4: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat) -> typing.List[int]:
pass
def convert_raw_bytes_to_rgba_tuples(arg0: capsule, arg1: int, arg2: int, arg3: int, arg4: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat) -> typing.List[tuple]:
pass
| 5,729 | unknown | 59.957446 | 361 | 0.692617 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture/__init__.py | from ._renderer_capture import *
| 33 | Python | 15.999992 | 32 | 0.757576 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTextureToLinearArray.rst | .. _omni_syntheticdata_SdTextureToLinearArray_1:
.. _omni_syntheticdata_SdTextureToLinearArray:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Texture To Linear Array
:keywords: lang-en omnigraph node internal syntheticdata sd-texture-to-linear-array
Sd Texture To Linear Array
==========================
.. <description>
SyntheticData node to copy the input texture into a linear array buffer
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:cudaMipmappedArray", "``uint64``", "Pointer to the CUDA Mipmapped Array", "0"
"inputs:format", "``uint64``", "Format", "0"
"inputs:height", "``uint``", "Height", "0"
"inputs:hydraTime", "``double``", "Hydra time in stage", "0.0"
"inputs:mipCount", "``uint``", "Mip Count", "0"
"inputs:outputHeight", "``uint``", "Requested output height", "0"
"inputs:outputWidth", "``uint``", "Requested output width", "0"
"inputs:simTime", "``double``", "Simulation time", "0.0"
"inputs:stream", "``uint64``", "Pointer to the CUDA Stream", "0"
"inputs:width", "``uint``", "Width", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:data", "``float[4][]``", "Buffer array data", "[]"
"outputs:height", "``uint``", "Buffer array height", "None"
"outputs:hydraTime", "``double``", "Hydra time in stage", "None"
"outputs:simTime", "``double``", "Simulation time", "None"
"outputs:stream", "``uint64``", "Pointer to the CUDA Stream", "None"
"outputs:width", "``uint``", "Buffer array width", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTextureToLinearArray"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"Categories", "internal"
"Generated Class Name", "OgnSdTextureToLinearArrayDatabase"
"Python Module", "omni.syntheticdata"
| 2,479 | reStructuredText | 29.617284 | 99 | 0.578459 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdLinearArrayToTexture.rst | .. _omni_syntheticdata_SdLinearArrayToTexture_1:
.. _omni_syntheticdata_SdLinearArrayToTexture:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Linear Array To Texture
:keywords: lang-en omnigraph node graph:action syntheticdata sd-linear-array-to-texture
Sd Linear Array To Texture
==========================
.. <description>
Synthetic Data node to copy the input buffer array into a texture for visualization
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:data", "``float[4][]``", "Buffer array data", "[]"
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:height", "``uint``", "Buffer array height", "0"
"inputs:sdDisplayCudaMipmappedArray", "``uint64``", "Visualization texture CUDA mipmapped array pointer", "0"
"inputs:sdDisplayFormat", "``uint64``", "Visualization texture format", "0"
"inputs:sdDisplayHeight", "``uint``", "Visualization texture Height", "0"
"inputs:sdDisplayStream", "``uint64``", "Visualization texture CUDA stream pointer", "0"
"inputs:sdDisplayWidth", "``uint``", "Visualization texture width", "0"
"inputs:stream", "``uint64``", "Pointer to the CUDA Stream", "0"
"inputs:width", "``uint``", "Buffer array width", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:cudaPtr", "``uint64``", "Display texture CUDA pointer", "None"
"Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None"
"outputs:format", "``uint64``", "Display texture format", "None"
"outputs:handlePtr", "``uint64``", "Display texture handle reference", "None"
"outputs:height", "``uint``", "Display texture height", "None"
"outputs:stream", "``uint64``", "Output texture CUDA stream pointer", "None"
"outputs:width", "``uint``", "Display texture width", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdLinearArrayToTexture"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"Categories", "graph:action"
"Generated Class Name", "OgnSdLinearArrayToTextureDatabase"
"Python Module", "omni.syntheticdata"
| 2,767 | reStructuredText | 32.756097 | 113 | 0.606072 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdSemanticFilter.rst | .. _omni_syntheticdata_SdSemanticFilter_1:
.. _omni_syntheticdata_SdSemanticFilter:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Semantic Filter
:keywords: lang-en omnigraph node graph:simulation syntheticdata sd-semantic-filter
Sd Semantic Filter
==================
.. <description>
Synthetic Data node to declare a semantic filter.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Dependency", "None"
"inputs:hierarchicalLabels", "``bool``", "If true the filter consider all labels in the semantic hierarchy above the prims", "False"
"inputs:matchingLabels", "``bool``", "If true output only the labels matching the filter (if false keep all labels of the matching prims)", "True"
"inputs:name", "``token``", "Filter unique identifier [if empty, use the normalized predicate as an identifier]", ""
"inputs:predicate", "``token``", "The semantic filter specification : a disjunctive normal form of semantic type and label", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:name", "``token``", "The semantic filter name identifier", ""
"outputs:predicate", "``token``", "The semantic filter predicate in normalized form", ""
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdSemanticFilter"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"Categories", "graph:simulation"
"Generated Class Name", "OgnSdSemanticFilterDatabase"
"Python Module", "omni.syntheticdata"
| 2,224 | reStructuredText | 29.479452 | 150 | 0.609712 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestStageSynchronization.rst | .. _omni_syntheticdata_SdTestStageSynchronization_1:
.. _omni_syntheticdata_SdTestStageSynchronization:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Test Stage Synchronization
:keywords: lang-en omnigraph node graph:simulation,graph:postRender,graph:action,internal:test syntheticdata sd-test-stage-synchronization
Sd Test Stage Synchronization
=============================
.. <description>
Synthetic Data node to test the pipeline stage synchronization
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "OnDemand connection : trigger", "None"
"gpuFoundations (*inputs:gpu*)", "``uint64``", "PostRender connection : pointer to shared context containing gpu foundations", "0"
"inputs:randomMaxProcessingTimeUs", "``uint``", "Maximum number of micro-seconds to randomly (uniformely) wait for in order to simulate varying workload", "0"
"inputs:randomSeed", "``uint``", "Random seed for the randomization", "0"
"inputs:renderResults", "``uint64``", "OnDemand connection : pointer to render product results", "0"
"renderProduct (*inputs:rp*)", "``uint64``", "PostRender connection : pointer to render product for this view", "0"
"inputs:swhFrameNumber", "``uint64``", "Fabric frame number", "0"
"inputs:tag", "``token``", "A tag to identify the node", ""
"inputs:traceError", "``bool``", "If true print an error message when the frame numbers are out-of-sync", "False"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "OnDemand connection : trigger", "None"
"outputs:fabricSWHFrameNumber", "``uint64``", "Fabric frame number from the fabric", "None"
"outputs:swhFrameNumber", "``uint64``", "Fabric frame number", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTestStageSynchronization"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"Categories", "graph:simulation,graph:postRender,graph:action,internal:test"
"Generated Class Name", "OgnSdTestStageSynchronizationDatabase"
"Python Module", "omni.syntheticdata"
| 2,765 | reStructuredText | 34.922077 | 162 | 0.633273 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestInstanceMapping.rst | .. _omni_syntheticdata_SdTestInstanceMapping_1:
.. _omni_syntheticdata_SdTestInstanceMapping:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Test Instance Mapping
:keywords: lang-en omnigraph node graph:simulation,graph:postRender,graph:action,internal:test syntheticdata sd-test-instance-mapping
Sd Test Instance Mapping
========================
.. <description>
Synthetic Data node to test the instance mapping pipeline
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:instanceMapPtr", "``uint64``", "Array pointer of numInstances uint16_t containing the semantic index of the instance prim first semantic prim parent", "0"
"inputs:instancePrimPathPtr", "``uint64``", "Array pointer of numInstances uint64_t containing the prim path tokens for every instance prims", "0"
"inputs:minInstanceIndex", "``uint``", "Instance index of the first instance prim in the instance arrays", "0"
"inputs:minSemanticIndex", "``uint``", "Semantic index of the first semantic prim in the semantic arrays", "0"
"inputs:numInstances", "``uint``", "Number of instances prim in the instance arrays", "0"
"inputs:numSemantics", "``uint``", "Number of semantic prim in the semantic arrays", "0"
"inputs:semanticLabelTokenPtrs", "``uint64[]``", "Array containing for every input semantic filters the corresponding array pointer of numSemantics uint64_t representing the semantic label of the semantic prim", "[]"
"inputs:semanticLocalTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from world to object space for every semantic prims", "0"
"inputs:semanticMapPtr", "``uint64``", "Array pointer of numSemantics uint16_t containing the semantic index of the semantic prim first semantic prim parent", "0"
"inputs:semanticPrimPathPtr", "``uint64``", "Array pointer of numSemantics uint32_t containing the prim part of the prim path tokens for every semantic prims", "0"
"inputs:semanticWorldTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from local to world space for every semantic entity", "0"
"inputs:stage", "``token``", "Stage in {simulation, postrender, ondemand}", ""
"inputs:swhFrameNumber", "``uint64``", "Fabric frame number", "0"
"inputs:testCaseIndex", "``int``", "Test case index", "-1"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None"
"outputs:semanticFilterPredicate", "``token``", "The semantic filter predicate : a disjunctive normal form of semantic type and label", "None"
"outputs:success", "``bool``", "Test value : false if failed", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTestInstanceMapping"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""simulation"", ""postRender"", ""onDemand""]"
"Categories", "graph:simulation,graph:postRender,graph:action,internal:test"
"Generated Class Name", "OgnSdTestInstanceMappingDatabase"
"Python Module", "omni.syntheticdata"
| 3,860 | reStructuredText | 44.964285 | 220 | 0.664508 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostSemanticBoundingBox.rst | .. _omni_syntheticdata_SdPostSemanticBoundingBox_1:
.. _omni_syntheticdata_SdPostSemanticBoundingBox:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Post Semantic Bounding Box
:keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-semantic-bounding-box
Sd Post Semantic Bounding Box
=============================
.. <description>
Synthetic Data node to compute the bounding boxes of the scene semantic entities.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0"
"inputs:instanceMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numInstances containing the instance parent semantic index", "0"
"inputs:instanceMappingInfoSDPtr", "``uint64``", "uint buffer pointer containing the following information : [numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic]", "0"
"inputs:renderProductResolution", "``int[2]``", "RenderProduct resolution", "[0, 0]"
"inputs:renderVar", "``token``", "Name of the BoundingBox RenderVar to process", ""
"renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0"
"inputs:semanticLocalTransformSDCudaPtr", "``uint64``", "cuda float44 buffer pointer of size numSemantics containing the local semantic transform", "0"
"inputs:semanticMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numSemantics containing the semantic parent semantic index", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:sdSemBBoxExtentCudaPtr", "``uint64``", "Cuda buffer containing the extent of the bounding boxes as a float4=(u_min,v_min,u_max,v_max) for 2D or a float6=(xmin,ymin,zmin,xmax,ymax,zmax) in object space for 3D", "None"
"outputs:sdSemBBoxInfosCudaPtr", "``uint64``", "Cuda buffer containing valid bounding boxes infos", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdPostSemanticBoundingBox"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""BoundingBox2DLooseSD"", ""BoundingBox2DTightSD"", ""SemanticBoundingBox2DExtentLooseSD"", ""SemanticBoundingBox2DInfosLooseSD"", ""SemanticBoundingBox2DExtentTightSD"", ""SemanticBoundingBox2DInfosTightSD"", ""BoundingBox3DSD"", ""SemanticBoundingBox3DExtentSD"", ""SemanticBoundingBox3DInfosSD""]"
"Categories", "graph:postRender,rendering"
"Generated Class Name", "OgnSdPostSemanticBoundingBoxDatabase"
"Python Module", "omni.syntheticdata"
| 3,344 | reStructuredText | 41.884615 | 318 | 0.664773 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdRenderVarPtr.rst | .. _omni_syntheticdata_SdRenderVarPtr_2:
.. _omni_syntheticdata_SdRenderVarPtr:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Render Var Ptr
:keywords: lang-en omnigraph node graph:action syntheticdata sd-render-var-ptr
Sd Render Var Ptr
=================
.. <description>
Synthetic Data node exposing the raw pointer data of a rendervar.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:renderResults", "``uint64``", "Render results pointer", "0"
"inputs:renderVar", "``token``", "Name of the renderVar", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:bufferSize", "``uint64``", "Size (in bytes) of the buffer (0 if the input is a texture)", "None"
"outputs:cudaDeviceIndex", "``int``", "Index of the device where the data lives (-1 for host data)", "-1"
"outputs:dataPtr", "``uint64``", "Pointer to the raw data (cuda device pointer or host pointer)", "0"
"Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None"
"outputs:format", "``uint64``", "Format", "None"
"outputs:height", "``uint``", "Height (0 if the input is a buffer)", "None"
"outputs:strides", "``int[2]``", "Strides (in bytes) ([0,0] if the input is a buffer)", "None"
"outputs:width", "``uint``", "Width (0 if the input is a buffer)", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdRenderVarPtr"
"Version", "2"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"Categories", "graph:action"
"Generated Class Name", "OgnSdRenderVarPtrDatabase"
"Python Module", "omni.syntheticdata"
| 2,325 | reStructuredText | 29.605263 | 109 | 0.582366 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestRenderProductCamera.rst | .. _omni_syntheticdata_SdTestRenderProductCamera_1:
.. _omni_syntheticdata_SdTestRenderProductCamera:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Test Render Product Camera
:keywords: lang-en omnigraph node graph:simulation,graph:postRender,graph:action,internal:test syntheticdata sd-test-render-product-camera
Sd Test Render Product Camera
=============================
.. <description>
Synthetic Data node to test the renderProduct camera pipeline
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:cameraApertureOffset", "``float[2]``", "Camera horizontal and vertical aperture offset", "[0.0, 0.0]"
"inputs:cameraApertureSize", "``float[2]``", "Camera horizontal and vertical aperture", "[0.0, 0.0]"
"inputs:cameraFStop", "``float``", "Camera fStop", "0.0"
"inputs:cameraFisheyeParams", "``float[]``", "Camera fisheye projection parameters", "[]"
"inputs:cameraFocalLength", "``float``", "Camera focal length", "0.0"
"inputs:cameraFocusDistance", "``float``", "Camera focus distance", "0.0"
"inputs:cameraModel", "``int``", "Camera model (pinhole or fisheye models)", "0"
"inputs:cameraNearFar", "``float[2]``", "Camera near/far clipping range", "[0.0, 0.0]"
"inputs:cameraProjection", "``matrixd[4]``", "Camera projection matrix", "[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]"
"inputs:cameraViewTransform", "``matrixd[4]``", "Camera view matrix", "[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]"
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:height", "``uint``", "Height of the frame", "0"
"inputs:metersPerSceneUnit", "``float``", "Scene units to meters scale", "0.0"
"inputs:renderProductCameraPath", "``token``", "RenderProduct camera prim path", ""
"inputs:renderProductResolution", "``int[2]``", "RenderProduct resolution", "[0, 0]"
"inputs:renderResults", "``uint64``", "OnDemand connection : pointer to render product results", "0"
"renderProduct (*inputs:rp*)", "``uint64``", "PostRender connection : pointer to render product for this view", "0"
"inputs:stage", "``token``", "Stage in {simulation, postrender, ondemand}", ""
"inputs:traceError", "``bool``", "If true print an error message when the frame numbers are out-of-sync", "False"
"inputs:width", "``uint``", "Width of the frame", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:test", "``bool``", "Test value : false if failed", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTestRenderProductCamera"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"__tokens", "[""simulation"", ""postRender"", ""onDemand""]"
"Categories", "graph:simulation,graph:postRender,graph:action,internal:test"
"Generated Class Name", "OgnSdTestRenderProductCameraDatabase"
"Python Module", "omni.syntheticdata"
| 3,613 | reStructuredText | 40.540229 | 167 | 0.606975 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdOnNewRenderProductFrame.rst | .. _omni_syntheticdata_SdOnNewRenderProductFrame_1:
.. _omni_syntheticdata_SdOnNewRenderProductFrame:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd On New Render Product Frame
:keywords: lang-en omnigraph node graph:action,flowControl syntheticdata sd-on-new-render-product-frame
Sd On New Render Product Frame
==============================
.. <description>
Synthetic Data postprocess node to execute pipeline after the NewFrame event has been received on the given renderProduct
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Received (*inputs:exec*)", "``execution``", "Executes for each newFrame event received", "None"
"inputs:renderProductDataPtrs", "``uint64[]``", "HydraRenderProduct data pointers.", "[]"
"inputs:renderProductPath", "``token``", "Path of the renderProduct to wait for being rendered", ""
"inputs:renderProductPaths", "``token[]``", "Render product path tokens.", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:cudaStream", "``uint64``", "Cuda stream", "None"
"Received (*outputs:exec*)", "``execution``", "Executes for each newFrame event received", "None"
"outputs:renderProductPath", "``token``", "Path of the renderProduct to wait for being rendered", "None"
"outputs:renderResults", "``uint64``", "Render results", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdOnNewRenderProductFrame"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnSdOnNewRenderProductFrameDatabase"
"Python Module", "omni.syntheticdata"
| 2,299 | reStructuredText | 30.506849 | 121 | 0.61592 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdFabricTimeRangeExecution.rst | .. _omni_syntheticdata_SdFabricTimeRangeExecution_1:
.. _omni_syntheticdata_SdFabricTimeRangeExecution:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Fabric Time Range Execution
:keywords: lang-en omnigraph node graph:postRender,graph:action syntheticdata sd-fabric-time-range-execution
Sd Fabric Time Range Execution
==============================
.. <description>
Read a rational time range from Fabric or RenderVars and signal its execution if the current time fall within this range. The range is [begin,end[, that is the end time does not belong to the range.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:gpu", "``uint64``", "Pointer to shared context containing gpu foundations.", "0"
"inputs:renderResults", "``uint64``", "Render results", "0"
"inputs:timeRangeBeginDenominatorToken", "``token``", "Attribute name of the range begin time denominator", "timeRangeStartDenominator"
"inputs:timeRangeBeginNumeratorToken", "``token``", "Attribute name of the range begin time numerator", "timeRangeStartNumerator"
"inputs:timeRangeEndDenominatorToken", "``token``", "Attribute name of the range end time denominator", "timeRangeEndDenominator"
"inputs:timeRangeEndNumeratorToken", "``token``", "Attribute name of the range end time numerator", "timeRangeEndNumerator"
"inputs:timeRangeName", "``token``", "Time range name used to read from the Fabric or RenderVars.", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:timeRangeBeginDenominator", "``uint64``", "Time denominator of the last time range change (begin)", "None"
"outputs:timeRangeBeginNumerator", "``int64``", "Time numerator of the last time range change (begin)", "None"
"outputs:timeRangeEndDenominator", "``uint64``", "Time denominator of the last time range change (end)", "None"
"outputs:timeRangeEndNumerator", "``int64``", "Time numerator of the last time range change (end)", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdFabricTimeRangeExecution"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"Categories", "graph:postRender,graph:action"
"Generated Class Name", "OgnSdFabricTimeRangeExecutionDatabase"
"Python Module", "omni.syntheticdata"
| 3,037 | reStructuredText | 37.948717 | 198 | 0.650971 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdRenderVarDisplayTexture.rst | .. _omni_syntheticdata_SdRenderVarDisplayTexture_2:
.. _omni_syntheticdata_SdRenderVarDisplayTexture:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Render Var Display Texture
:keywords: lang-en omnigraph node graph:action,rendering,internal syntheticdata sd-render-var-display-texture
Sd Render Var Display Texture
=============================
.. <description>
Synthetic Data node to expose texture resource of a visualization render variable
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:renderResults", "``uint64``", "Render results pointer", "0"
"inputs:renderVarDisplay", "``token``", "Name of the renderVar", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:cudaPtr", "``uint64``", "Display texture CUDA pointer", "None"
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:format", "``uint64``", "Display texture format", "None"
"outputs:height", "``uint``", "Display texture height", "None"
"outputs:referenceTimeDenominator", "``uint64``", "Reference time represented as a rational number : denominator", "None"
"outputs:referenceTimeNumerator", "``int64``", "Reference time represented as a rational number : numerator", "None"
"outputs:rpResourcePtr", "``uint64``", "Display texture RpResource pointer", "None"
"outputs:width", "``uint``", "Display texture width", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdRenderVarDisplayTexture"
"Version", "2"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"Categories", "graph:action,rendering,internal"
"Generated Class Name", "OgnSdRenderVarDisplayTextureDatabase"
"Python Module", "omni.syntheticdata"
| 2,410 | reStructuredText | 30.723684 | 125 | 0.614523 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostRenderVarTextureToBuffer.rst | .. _omni_syntheticdata_SdPostRenderVarTextureToBuffer_1:
.. _omni_syntheticdata_SdPostRenderVarTextureToBuffer:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Post Render Var Texture To Buffer
:keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-render-var-texture-to-buffer
Sd Post Render Var Texture To Buffer
====================================
.. <description>
Expose a device renderVar buffer a texture one.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:gpu", "``uint64``", "Pointer to shared context containing gpu foundations", "0"
"inputs:renderVar", "``token``", "Name of the device renderVar to expose on the host", ""
"inputs:renderVarBufferSuffix", "``string``", "Suffix appended to the renderVar name", "buffer"
"inputs:rp", "``uint64``", "Pointer to render product for this view", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:renderVar", "``token``", "Name of the resulting renderVar on the host", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdPostRenderVarTextureToBuffer"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"Categories", "graph:postRender,rendering"
"Generated Class Name", "OgnSdPostRenderVarTextureToBufferDatabase"
"Python Module", "omni.syntheticdata"
| 2,114 | reStructuredText | 28.375 | 115 | 0.603122 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostInstanceMapping.rst | .. _omni_syntheticdata_SdPostInstanceMapping_2:
.. _omni_syntheticdata_SdPostInstanceMapping:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Post Instance Mapping
:keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-instance-mapping
Sd Post Instance Mapping
========================
.. <description>
Synthetic Data node to compute and store scene instances semantic hierarchy information
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0"
"renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0"
"inputs:semanticFilterName", "``token``", "Name of the semantic filter to apply to the semanticLabelToken", "default"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:instanceMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numInstances containing the instance parent semantic index", "None"
"outputs:instanceMappingInfoSDPtr", "``uint64``", "uint buffer pointer containing the following information : [ numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic, lastUpdateTimeNumeratorHigh, lastUpdateTimeNumeratorLow, , lastUpdateTimeDenominatorHigh, lastUpdateTimeDenominatorLow ]", "None"
"outputs:instancePrimTokenSDCudaPtr", "``uint64``", "cuda uint64_t buffer pointer of size numInstances containing the instance path token", "None"
"outputs:lastUpdateTimeDenominator", "``uint64``", "Time denominator of the last time the data has changed", "None"
"outputs:lastUpdateTimeNumerator", "``int64``", "Time numerator of the last time the data has changed", "None"
"outputs:semanticLabelTokenSDCudaPtr", "``uint64``", "cuda uint64_t buffer pointer of size numSemantics containing the semantic label token", "None"
"outputs:semanticLocalTransformSDCudaPtr", "``uint64``", "cuda float44 buffer pointer of size numSemantics containing the local semantic transform", "None"
"outputs:semanticMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numSemantics containing the semantic parent semantic index", "None"
"outputs:semanticPrimTokenSDCudaPtr", "``uint64``", "cuda uint32_t buffer pointer of size numSemantics containing the prim part of the semantic path token", "None"
"outputs:semanticWorldTransformSDCudaPtr", "``uint64``", "cuda float44 buffer pointer of size numSemantics containing the world semantic transform", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdPostInstanceMapping"
"Version", "2"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""InstanceMappingInfoSDhost"", ""SemanticMapSD"", ""SemanticMapSDhost"", ""SemanticPrimTokenSD"", ""SemanticPrimTokenSDhost"", ""InstanceMapSD"", ""InstanceMapSDhost"", ""InstancePrimTokenSD"", ""InstancePrimTokenSDhost"", ""SemanticLabelTokenSD"", ""SemanticLabelTokenSDhost"", ""SemanticLocalTransformSD"", ""SemanticLocalTransformSDhost"", ""SemanticWorldTransformSD"", ""SemanticWorldTransformSDhost""]"
"Categories", "graph:postRender,rendering"
"Generated Class Name", "OgnSdPostInstanceMappingDatabase"
"Python Module", "omni.syntheticdata"
| 4,032 | reStructuredText | 48.790123 | 425 | 0.689236 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdInstanceMapping.rst | .. _omni_syntheticdata_SdInstanceMapping_2:
.. _omni_syntheticdata_SdInstanceMapping:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Instance Mapping
:keywords: lang-en omnigraph node graph:action syntheticdata sd-instance-mapping
Sd Instance Mapping
===================
.. <description>
Synthetic Data node to expose the scene instances semantic hierarchy information
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:lazy", "``bool``", "Compute outputs only when connected to a downstream node", "True"
"inputs:renderResults", "``uint64``", "Render results pointer", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None"
"outputs:sdIMInstanceSemanticMap", "``uchar[]``", "Raw array of uint16_t of size sdIMNumInstances*sdIMMaxSemanticHierarchyDepth containing the mapping from the instances index to their inherited semantic entities", "None"
"outputs:sdIMInstanceTokens", "``token[]``", "Instance array containing the token for every instances", "None"
"outputs:sdIMLastUpdateTimeDenominator", "``uint64``", "Time denominator of the last time the data has changed", "None"
"outputs:sdIMLastUpdateTimeNumerator", "``int64``", "Time numerator of the last time the data has changed", "None"
"outputs:sdIMMaxSemanticHierarchyDepth", "``uint``", "Maximal number of semantic entities inherited by an instance", "None"
"outputs:sdIMMinInstanceIndex", "``uint``", "Instance id of the first instance in the instance arrays", "None"
"outputs:sdIMMinSemanticIndex", "``uint``", "Semantic id of the first semantic entity in the semantic arrays", "None"
"outputs:sdIMNumInstances", "``uint``", "Number of instances in the instance arrays", "None"
"outputs:sdIMNumSemanticTokens", "``uint``", "Number of semantics token including the semantic entity path, the semantic entity types and if the number of semantic types is greater than one a ", "None"
"outputs:sdIMNumSemantics", "``uint``", "Number of semantic entities in the semantic arrays", "None"
"outputs:sdIMSemanticLocalTransform", "``float[]``", "Semantic array of 4x4 float matrices containing the transform from world to local space for every semantic entity", "None"
"outputs:sdIMSemanticTokenMap", "``token[]``", "Semantic array of token of size numSemantics * numSemanticTypes containing the mapping from the semantic entities to the semantic entity path and semantic types", "None"
"outputs:sdIMSemanticWorldTransform", "``float[]``", "Semantic array of 4x4 float matrices containing the transform from local to world space for every semantic entity", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdInstanceMapping"
"Version", "2"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""InstanceMappingInfoSDhost"", ""InstanceMapSDhost"", ""SemanticLabelTokenSDhost"", ""InstancePrimTokenSDhost"", ""SemanticLocalTransformSDhost"", ""SemanticWorldTransformSDhost""]"
"Categories", "graph:action"
"Generated Class Name", "OgnSdInstanceMappingDatabase"
"Python Module", "omni.syntheticdata"
| 3,895 | reStructuredText | 45.939758 | 225 | 0.675225 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdInstanceMappingPtr.rst | .. _omni_syntheticdata_SdInstanceMappingPtr_2:
.. _omni_syntheticdata_SdInstanceMappingPtr:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Instance Mapping Ptr
:keywords: lang-en omnigraph node graph:action syntheticdata sd-instance-mapping-ptr
Sd Instance Mapping Ptr
=======================
.. <description>
Synthetic Data node to expose the scene instances semantic hierarchy information
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:cudaPtr", "``bool``", "If true, return cuda device pointer instead of host pointer", "False"
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:renderResults", "``uint64``", "Render results pointer", "0"
"inputs:semanticFilerTokens", "``token[]``", "Tokens identifying the semantic filters applied to the output semantic labels. Each token should correspond to an activated SdSemanticFilter node", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:cudaDeviceIndex", "``int``", "If the data is on the device it is the cuda index of this device otherwise it is set to -1", "-1"
"Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None"
"outputs:instanceMapPtr", "``uint64``", "Array pointer of numInstances uint16_t containing the semantic index of the instance prim first semantic prim parent", "None"
"outputs:instancePrimPathPtr", "``uint64``", "Array pointer of numInstances uint64_t containing the prim path tokens for every instance prims", "None"
"outputs:lastUpdateTimeDenominator", "``uint64``", "Time denominator of the last time the data has changed", "None"
"outputs:lastUpdateTimeNumerator", "``int64``", "Time numerator of the last time the data has changed", "None"
"outputs:minInstanceIndex", "``uint``", "Instance index of the first instance prim in the instance arrays", "None"
"outputs:minSemanticIndex", "``uint``", "Semantic index of the first semantic prim in the semantic arrays", "None"
"outputs:numInstances", "``uint``", "Number of instances prim in the instance arrays", "None"
"outputs:numSemantics", "``uint``", "Number of semantic prim in the semantic arrays", "None"
"outputs:semanticLabelTokenPtrs", "``uint64[]``", "Array containing for every input semantic filters the corresponding array pointer of numSemantics uint64_t representing the semantic label of the semantic prim", "None"
"outputs:semanticLocalTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from world to object space for every semantic prims", "None"
"outputs:semanticMapPtr", "``uint64``", "Array pointer of numSemantics uint16_t containing the semantic index of the semantic prim first semantic prim parent", "None"
"outputs:semanticPrimPathPtr", "``uint64``", "Array pointer of numSemantics uint32_t containing the prim part of the prim path tokens for every semantic prims", "None"
"outputs:semanticWorldTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from local to world space for every semantic entity", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdInstanceMappingPtr"
"Version", "2"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""InstanceMappingInfoSDhost"", ""InstancePrimTokenSDhost"", ""InstancePrimTokenSD"", ""SemanticPrimTokenSDhost"", ""SemanticPrimTokenSD"", ""InstanceMapSDhost"", ""InstanceMapSD"", ""SemanticMapSDhost"", ""SemanticMapSD"", ""SemanticWorldTransformSDhost"", ""SemanticWorldTransformSD"", ""SemanticLocalTransformSDhost"", ""SemanticLocalTransformSD"", ""SemanticLabelTokenSDhost"", ""SemanticLabelTokenSD""]"
"Categories", "graph:action"
"Generated Class Name", "OgnSdInstanceMappingPtrDatabase"
"Python Module", "omni.syntheticdata"
| 4,502 | reStructuredText | 51.97647 | 425 | 0.684363 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestSimFabricTimeRange.rst | .. _omni_syntheticdata_SdTestSimFabricTimeRange_1:
.. _omni_syntheticdata_SdTestSimFabricTimeRange:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Test Sim Fabric Time Range
:keywords: lang-en omnigraph node graph:simulation,internal,event compute-on-request syntheticdata sd-test-sim-fabric-time-range
Sd Test Sim Fabric Time Range
=============================
.. <description>
Testing node : on request write/update a Fabric time range of a given number of frames starting at the current simulation time.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:numberOfFrames", "``uint64``", "Number of frames to writes.", "0"
"inputs:timeRangeBeginDenominatorToken", "``token``", "Attribute name of the range begin time denominator", "timeRangeStartDenominator"
"inputs:timeRangeBeginNumeratorToken", "``token``", "Attribute name of the range begin time numerator", "timeRangeStartNumerator"
"inputs:timeRangeEndDenominatorToken", "``token``", "Attribute name of the range end time denominator", "timeRangeEndDenominator"
"inputs:timeRangeEndNumeratorToken", "``token``", "Attribute name of the range end time numerator", "timeRangeEndNumerator"
"inputs:timeRangeName", "``token``", "Time range name used to write to the Fabric.", "TestSimFabricTimeRangeSD"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTestSimFabricTimeRange"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""fc_exportToRingbuffer""]"
"Categories", "graph:simulation,internal,event"
"Generated Class Name", "OgnSdTestSimFabricTimeRangeDatabase"
"Python Module", "omni.syntheticdata"
| 2,437 | reStructuredText | 32.39726 | 139 | 0.639311 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostCompRenderVarTextures.rst | .. _omni_syntheticdata_SdPostCompRenderVarTextures_1:
.. _omni_syntheticdata_SdPostCompRenderVarTextures:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Post Comp Render Var Textures
:keywords: lang-en omnigraph node graph:postRender,rendering,internal syntheticdata sd-post-comp-render-var-textures
Sd Post Comp Render Var Textures
================================
.. <description>
Synthetic Data node to compose a front renderVar texture into a back renderVar texture
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:cudaPtr", "``uint64``", "Front texture CUDA pointer", "0"
"inputs:format", "``uint64``", "Front texture format", "0"
"gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0"
"inputs:height", "``uint``", "Front texture height", "0"
"inputs:mode", "``token``", "Mode : grid, line", "line"
"inputs:parameters", "``float[3]``", "Parameters", "[0, 0, 0]"
"inputs:renderVar", "``token``", "Name of the back RenderVar", "LdrColor"
"renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0"
"inputs:width", "``uint``", "Front texture width", "0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdPostCompRenderVarTextures"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""line"", ""grid""]"
"Categories", "graph:postRender,rendering,internal"
"Generated Class Name", "OgnSdPostCompRenderVarTexturesDatabase"
"Python Module", "omni.syntheticdata"
| 2,167 | reStructuredText | 31.358208 | 120 | 0.5976 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostSemantic3dBoundingBoxFilter.rst | .. _omni_syntheticdata_SdPostSemantic3dBoundingBoxFilter_1:
.. _omni_syntheticdata_SdPostSemantic3dBoundingBoxFilter:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Post Semantic3D Bounding Box Filter
:keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-semantic3d-bounding-box-filter
Sd Post Semantic3D Bounding Box Filter
======================================
.. <description>
Synthetic Data node to cull the semantic 3d bounding boxes.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0"
"inputs:instanceMappingInfoSDPtr", "``uint64``", "uint buffer pointer containing the following information : [numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic]", "0"
"inputs:metersPerSceneUnit", "``float``", "Scene units to meters scale", "0.01"
"renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0"
"inputs:sdSemBBox3dCamCornersCudaPtr", "``uint64``", "Cuda buffer containing the projection of the 3d bounding boxes on the camera plane represented as a float3=(u,v,z,a) for each bounding box corners", "0"
"inputs:sdSemBBoxInfosCudaPtr", "``uint64``", "Cuda buffer containing valid bounding boxes infos", "0"
"inputs:viewportNearFar", "``float[2]``", "near and far plane (in scene units) used to clip the 3d bounding boxes.", "[0.0, -1.0]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:sdSemBBoxInfosCudaPtr", "``uint64``", "Cuda buffer containing valid bounding boxes infos", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdPostSemantic3dBoundingBoxFilter"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""SemanticBoundingBox3DInfosSD"", ""SemanticBoundingBox3DFilterInfosSD""]"
"Categories", "graph:postRender,rendering"
"Generated Class Name", "OgnSdPostSemantic3dBoundingBoxFilterDatabase"
"Python Module", "omni.syntheticdata"
| 2,834 | reStructuredText | 36.302631 | 210 | 0.641849 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdSimInstanceMapping.rst | .. _omni_syntheticdata_SdSimInstanceMapping_1:
.. _omni_syntheticdata_SdSimInstanceMapping:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Sim Instance Mapping
:keywords: lang-en omnigraph node graph:simulation,internal syntheticdata sd-sim-instance-mapping
Sd Sim Instance Mapping
=======================
.. <description>
Synthetic Data node to update and cache the instance mapping data
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:needTransform", "``bool``", "If true compute the semantic entities world and object transforms", "True"
"inputs:semanticFilterPredicate", "``token``", "The semantic filter predicate : a disjunctive normal form of semantic type and label", "*:*"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:semanticFilterPredicate", "``token``", "The semantic filter predicate in normalized form", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdSimInstanceMapping"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"Categories", "graph:simulation,internal"
"Generated Class Name", "OgnSdSimInstanceMappingDatabase"
"Python Module", "omni.syntheticdata"
| 1,900 | reStructuredText | 26.550724 | 144 | 0.607368 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdFrameIdentifier.rst | .. _omni_syntheticdata_SdFrameIdentifier_1:
.. _omni_syntheticdata_SdFrameIdentifier:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Frame Identifier
:keywords: lang-en omnigraph node graph:postRender,graph:action syntheticdata sd-frame-identifier
Sd Frame Identifier
===================
.. <description>
Synthetic Data node to expose pipeline frame identifier.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:renderResults", "``uint64``", "Render results", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:durationDenominator", "``uint64``", "Duration denominator. Only valid if eConstantFramerateFrameNumber", "0"
"outputs:durationNumerator", "``int64``", "Duration numerator. Only valid if eConstantFramerateFrameNumber.", "0"
"Received (*outputs:exec*)", "``execution``", "Executes for each newFrame event received", "None"
"outputs:externalTimeOfSimNs", "``int64``", "External time in Ns. Only valid if eConstantFramerateFrameNumber.", "-1"
"outputs:frameNumber", "``int64``", "Frame number. Valid if eFrameNumber or eConstantFramerateFrameNumber.", "-1"
"outputs:rationalTimeOfSimDenominator", "``uint64``", "rational time of simulation denominator.", "0"
"outputs:rationalTimeOfSimNumerator", "``int64``", "rational time of simulation numerator.", "0"
"outputs:sampleTimeOffsetInSimFrames", "``uint64``", "Sample time offset. Only valid if eConstantFramerateFrameNumber.", "0"
"outputs:type", "``token``", "Type of the frame identifier.", "NoFrameNumber"
"", "*allowedTokens*", "NoFrameNumber,FrameNumber,ConstantFramerateFrameNumber", ""
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdFrameIdentifier"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"Categories", "graph:postRender,graph:action"
"Generated Class Name", "OgnSdFrameIdentifierDatabase"
"Python Module", "omni.syntheticdata"
| 2,650 | reStructuredText | 33.428571 | 128 | 0.636226 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestPrintRawArray.rst | .. _omni_syntheticdata_SdTestPrintRawArray_1:
.. _omni_syntheticdata_SdTestPrintRawArray:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Test Print Raw Array
:keywords: lang-en omnigraph node graph:action,internal:test syntheticdata sd-test-print-raw-array
Sd Test Print Raw Array
=======================
.. <description>
Synthetic Data test node printing the input linear array
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:bufferSize", "``uint``", "Size (in bytes) of the buffer (0 if the input is a texture)", "0"
"inputs:data", "``uchar[]``", "Buffer array data", "[]"
"inputs:dataFileBaseName", "``token``", "Basename of the output npy file", "/tmp/sdTestRawArray"
"inputs:elementCount", "``int``", "Number of array element", "1"
"inputs:elementType", "``token``", "Type of the array element", "uint8"
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:height", "``uint``", "Height (0 if the input is a buffer)", "0"
"inputs:mode", "``token``", "Mode in [printFormatted, printReferences, testReferences]", "printFormatted"
"inputs:randomSeed", "``int``", "Random seed", "0"
"inputs:referenceNumUniqueRandomValues", "``int``", "Number of reference unique random values to compare", "7"
"inputs:referenceSWHFrameNumbers", "``uint[]``", "Reference swhFrameNumbers relative to the first one", "[11, 17, 29]"
"inputs:referenceTolerance", "``float``", "Reference tolerance", "0.1"
"inputs:referenceValues", "``float[]``", "Reference data point values", "[]"
"inputs:swhFrameNumber", "``uint64``", "Frame number", "0"
"inputs:width", "``uint``", "Width (0 if the input is a buffer)", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None"
"outputs:swhFrameNumber", "``uint64``", "FrameNumber just rendered", "None"
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"state:initialSWHFrameNumber", "``int64``", "Initial swhFrameNumber", "-1"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTestPrintRawArray"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"__tokens", "[""uint16"", ""int16"", ""uint32"", ""int32"", ""float32"", ""token"", ""printFormatted"", ""printReferences"", ""writeToDisk""]"
"Categories", "graph:action,internal:test"
"Generated Class Name", "OgnSdTestPrintRawArrayDatabase"
"Python Module", "omni.syntheticdata"
| 3,216 | reStructuredText | 33.967391 | 146 | 0.601679 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdOnNewFrame.rst | .. _omni_syntheticdata_SdOnNewFrame_1:
.. _omni_syntheticdata_SdOnNewFrame:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd On New Frame
:keywords: lang-en omnigraph node graph:action,flowControl syntheticdata sd-on-new-frame
Sd On New Frame
===============
.. <description>
Synthetic Data postprocess node to execute pipeline after the NewFrame event has been received
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:cudaStream", "``uint64``", "Cuda stream", "None"
"outputs:exec", "``execution``", "Executes for each newFrame event received", "None"
"outputs:referenceTimeDenominator", "``uint64``", "Reference time represented as a rational number : denominator", "None"
"outputs:referenceTimeNumerator", "``int64``", "Reference time represented as a rational number : numerator", "None"
"outputs:renderProductDataPtrs", "``uint64[]``", "HydraRenderProduct data pointer.", "None"
"outputs:renderProductPaths", "``token[]``", "Render product path tokens.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdOnNewFrame"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnSdOnNewFrameDatabase"
"Python Module", "omni.syntheticdata"
| 1,904 | reStructuredText | 29.238095 | 125 | 0.612395 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestStageManipulationScenarii.rst | .. _omni_syntheticdata_SdTestStageManipulationScenarii_1:
.. _omni_syntheticdata_SdTestStageManipulationScenarii:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Test Stage Manipulation Scenarii
:keywords: lang-en omnigraph node graph:simulation,internal:test syntheticdata sd-test-stage-manipulation-scenarii
Sd Test Stage Manipulation Scenarii
===================================
.. <description>
Synthetic Data test node applying randomly some predefined stage manipulation scenarii
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:randomSeed", "``int``", "Random seed", "0"
"inputs:worldPrimPath", "``token``", "Path of the world prim : contains every modifiable prim, cannot be modified", ""
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"state:frameNumber", "``uint64``", "Current frameNumber (number of invocations)", "0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTestStageManipulationScenarii"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"Categories", "graph:simulation,internal:test"
"Generated Class Name", "OgnSdTestStageManipulationScenariiDatabase"
"Python Module", "omni.syntheticdata"
| 1,863 | reStructuredText | 26.411764 | 122 | 0.611379 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdRenderProductCamera.rst | .. _omni_syntheticdata_SdRenderProductCamera_2:
.. _omni_syntheticdata_SdRenderProductCamera:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Render Product Camera
:keywords: lang-en omnigraph node graph:postRender,graph:action syntheticdata sd-render-product-camera
Sd Render Product Camera
========================
.. <description>
Synthetic Data node to expose the camera data
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:gpu", "``uint64``", "Pointer to shared context containing gpu foundations.", "0"
"inputs:renderProductPath", "``token``", "RenderProduct prim path", ""
"inputs:renderResults", "``uint64``", "Render results", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:cameraApertureOffset", "``float[2]``", "Camera horizontal and vertical aperture offset", "None"
"outputs:cameraApertureSize", "``float[2]``", "Camera horizontal and vertical aperture", "None"
"outputs:cameraFStop", "``float``", "Camera fStop", "None"
"outputs:cameraFisheyeParams", "``float[]``", "Camera fisheye projection parameters", "None"
"outputs:cameraFocalLength", "``float``", "Camera focal length", "None"
"outputs:cameraFocusDistance", "``float``", "Camera focus distance", "None"
"outputs:cameraModel", "``int``", "Camera model (pinhole or fisheye models)", "None"
"outputs:cameraNearFar", "``float[2]``", "Camera near/far clipping range", "None"
"outputs:cameraProjection", "``matrixd[4]``", "Camera projection matrix", "None"
"outputs:cameraViewTransform", "``matrixd[4]``", "Camera view matrix", "None"
"Received (*outputs:exec*)", "``execution``", "Executes for each newFrame event received", "None"
"outputs:metersPerSceneUnit", "``float``", "Scene units to meters scale", "None"
"outputs:renderProductResolution", "``int[2]``", "RenderProduct resolution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdRenderProductCamera"
"Version", "2"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""RenderProductCameraSD""]"
"Categories", "graph:postRender,graph:action"
"Generated Class Name", "OgnSdRenderProductCameraDatabase"
"Python Module", "omni.syntheticdata"
| 2,943 | reStructuredText | 34.469879 | 108 | 0.620795 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdTestStageSynchronizationDatabase.py | """Support for simplified access to data on nodes of type omni.syntheticdata.SdTestStageSynchronization
Synthetic Data node to test the pipeline stage synchronization
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSdTestStageSynchronizationDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdTestStageSynchronization
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.exec
inputs.gpu
inputs.randomMaxProcessingTimeUs
inputs.randomSeed
inputs.renderResults
inputs.rp
inputs.swhFrameNumber
inputs.tag
inputs.traceError
Outputs:
outputs.exec
outputs.fabricSWHFrameNumber
outputs.swhFrameNumber
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:exec', 'execution', 0, None, 'OnDemand connection : trigger', {}, True, None, False, ''),
('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'PostRender connection : pointer to shared context containing gpu foundations', {}, True, 0, False, ''),
('inputs:randomMaxProcessingTimeUs', 'uint', 0, None, 'Maximum number of micro-seconds to randomly (uniformely) wait for in order to simulate varying workload', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:randomSeed', 'uint', 0, None, 'Random seed for the randomization', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:renderResults', 'uint64', 0, None, 'OnDemand connection : pointer to render product results', {}, True, 0, False, ''),
('inputs:rp', 'uint64', 0, 'renderProduct', 'PostRender connection : pointer to render product for this view', {}, True, 0, False, ''),
('inputs:swhFrameNumber', 'uint64', 0, None, 'Fabric frame number', {}, True, 0, False, ''),
('inputs:tag', 'token', 0, None, 'A tag to identify the node', {}, True, "", False, ''),
('inputs:traceError', 'bool', 0, None, 'If true print an error message when the frame numbers are out-of-sync', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('outputs:exec', 'execution', 0, None, 'OnDemand connection : trigger', {}, True, None, False, ''),
('outputs:fabricSWHFrameNumber', 'uint64', 0, None, 'Fabric frame number from the fabric', {}, True, None, False, ''),
('outputs:swhFrameNumber', 'uint64', 0, None, 'Fabric frame number', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.exec = og.AttributeRole.EXECUTION
role_data.outputs.exec = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.exec)
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gpu)
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def randomMaxProcessingTimeUs(self):
data_view = og.AttributeValueHelper(self._attributes.randomMaxProcessingTimeUs)
return data_view.get()
@randomMaxProcessingTimeUs.setter
def randomMaxProcessingTimeUs(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.randomMaxProcessingTimeUs)
data_view = og.AttributeValueHelper(self._attributes.randomMaxProcessingTimeUs)
data_view.set(value)
@property
def randomSeed(self):
data_view = og.AttributeValueHelper(self._attributes.randomSeed)
return data_view.get()
@randomSeed.setter
def randomSeed(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.randomSeed)
data_view = og.AttributeValueHelper(self._attributes.randomSeed)
data_view.set(value)
@property
def renderResults(self):
data_view = og.AttributeValueHelper(self._attributes.renderResults)
return data_view.get()
@renderResults.setter
def renderResults(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.renderResults)
data_view = og.AttributeValueHelper(self._attributes.renderResults)
data_view.set(value)
@property
def rp(self):
data_view = og.AttributeValueHelper(self._attributes.rp)
return data_view.get()
@rp.setter
def rp(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.rp)
data_view = og.AttributeValueHelper(self._attributes.rp)
data_view.set(value)
@property
def swhFrameNumber(self):
data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber)
return data_view.get()
@swhFrameNumber.setter
def swhFrameNumber(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.swhFrameNumber)
data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber)
data_view.set(value)
@property
def tag(self):
data_view = og.AttributeValueHelper(self._attributes.tag)
return data_view.get()
@tag.setter
def tag(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.tag)
data_view = og.AttributeValueHelper(self._attributes.tag)
data_view.set(value)
@property
def traceError(self):
data_view = og.AttributeValueHelper(self._attributes.traceError)
return data_view.get()
@traceError.setter
def traceError(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.traceError)
data_view = og.AttributeValueHelper(self._attributes.traceError)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def fabricSWHFrameNumber(self):
data_view = og.AttributeValueHelper(self._attributes.fabricSWHFrameNumber)
return data_view.get()
@fabricSWHFrameNumber.setter
def fabricSWHFrameNumber(self, value):
data_view = og.AttributeValueHelper(self._attributes.fabricSWHFrameNumber)
data_view.set(value)
@property
def swhFrameNumber(self):
data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber)
return data_view.get()
@swhFrameNumber.setter
def swhFrameNumber(self, value):
data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnSdTestStageSynchronizationDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSdTestStageSynchronizationDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSdTestStageSynchronizationDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 11,401 | Python | 44.067194 | 222 | 0.643277 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdFabricTimeRangeExecutionDatabase.py | """Support for simplified access to data on nodes of type omni.syntheticdata.SdFabricTimeRangeExecution
Read a rational time range from Fabric or RenderVars and signal its execution if the current time fall within this range.
The range is [begin,end[, that is the end time does not belong to the range.
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSdFabricTimeRangeExecutionDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdFabricTimeRangeExecution
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.exec
inputs.gpu
inputs.renderResults
inputs.timeRangeBeginDenominatorToken
inputs.timeRangeBeginNumeratorToken
inputs.timeRangeEndDenominatorToken
inputs.timeRangeEndNumeratorToken
inputs.timeRangeName
Outputs:
outputs.exec
outputs.timeRangeBeginDenominator
outputs.timeRangeBeginNumerator
outputs.timeRangeEndDenominator
outputs.timeRangeEndNumerator
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('inputs:gpu', 'uint64', 0, None, 'Pointer to shared context containing gpu foundations.', {}, True, 0, False, ''),
('inputs:renderResults', 'uint64', 0, None, 'Render results', {}, True, 0, False, ''),
('inputs:timeRangeBeginDenominatorToken', 'token', 0, None, 'Attribute name of the range begin time denominator', {ogn.MetadataKeys.DEFAULT: '"timeRangeStartDenominator"'}, True, "timeRangeStartDenominator", False, ''),
('inputs:timeRangeBeginNumeratorToken', 'token', 0, None, 'Attribute name of the range begin time numerator', {ogn.MetadataKeys.DEFAULT: '"timeRangeStartNumerator"'}, True, "timeRangeStartNumerator", False, ''),
('inputs:timeRangeEndDenominatorToken', 'token', 0, None, 'Attribute name of the range end time denominator', {ogn.MetadataKeys.DEFAULT: '"timeRangeEndDenominator"'}, True, "timeRangeEndDenominator", False, ''),
('inputs:timeRangeEndNumeratorToken', 'token', 0, None, 'Attribute name of the range end time numerator', {ogn.MetadataKeys.DEFAULT: '"timeRangeEndNumerator"'}, True, "timeRangeEndNumerator", False, ''),
('inputs:timeRangeName', 'token', 0, None, 'Time range name used to read from the Fabric or RenderVars.', {}, True, "", False, ''),
('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('outputs:timeRangeBeginDenominator', 'uint64', 0, None, 'Time denominator of the last time range change (begin)', {}, True, None, False, ''),
('outputs:timeRangeBeginNumerator', 'int64', 0, None, 'Time numerator of the last time range change (begin)', {}, True, None, False, ''),
('outputs:timeRangeEndDenominator', 'uint64', 0, None, 'Time denominator of the last time range change (end)', {}, True, None, False, ''),
('outputs:timeRangeEndNumerator', 'int64', 0, None, 'Time numerator of the last time range change (end)', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.exec = og.AttributeRole.EXECUTION
role_data.outputs.exec = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.exec)
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gpu)
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def renderResults(self):
data_view = og.AttributeValueHelper(self._attributes.renderResults)
return data_view.get()
@renderResults.setter
def renderResults(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.renderResults)
data_view = og.AttributeValueHelper(self._attributes.renderResults)
data_view.set(value)
@property
def timeRangeBeginDenominatorToken(self):
data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginDenominatorToken)
return data_view.get()
@timeRangeBeginDenominatorToken.setter
def timeRangeBeginDenominatorToken(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.timeRangeBeginDenominatorToken)
data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginDenominatorToken)
data_view.set(value)
@property
def timeRangeBeginNumeratorToken(self):
data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginNumeratorToken)
return data_view.get()
@timeRangeBeginNumeratorToken.setter
def timeRangeBeginNumeratorToken(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.timeRangeBeginNumeratorToken)
data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginNumeratorToken)
data_view.set(value)
@property
def timeRangeEndDenominatorToken(self):
data_view = og.AttributeValueHelper(self._attributes.timeRangeEndDenominatorToken)
return data_view.get()
@timeRangeEndDenominatorToken.setter
def timeRangeEndDenominatorToken(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.timeRangeEndDenominatorToken)
data_view = og.AttributeValueHelper(self._attributes.timeRangeEndDenominatorToken)
data_view.set(value)
@property
def timeRangeEndNumeratorToken(self):
data_view = og.AttributeValueHelper(self._attributes.timeRangeEndNumeratorToken)
return data_view.get()
@timeRangeEndNumeratorToken.setter
def timeRangeEndNumeratorToken(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.timeRangeEndNumeratorToken)
data_view = og.AttributeValueHelper(self._attributes.timeRangeEndNumeratorToken)
data_view.set(value)
@property
def timeRangeName(self):
data_view = og.AttributeValueHelper(self._attributes.timeRangeName)
return data_view.get()
@timeRangeName.setter
def timeRangeName(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.timeRangeName)
data_view = og.AttributeValueHelper(self._attributes.timeRangeName)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def timeRangeBeginDenominator(self):
data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginDenominator)
return data_view.get()
@timeRangeBeginDenominator.setter
def timeRangeBeginDenominator(self, value):
data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginDenominator)
data_view.set(value)
@property
def timeRangeBeginNumerator(self):
data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginNumerator)
return data_view.get()
@timeRangeBeginNumerator.setter
def timeRangeBeginNumerator(self, value):
data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginNumerator)
data_view.set(value)
@property
def timeRangeEndDenominator(self):
data_view = og.AttributeValueHelper(self._attributes.timeRangeEndDenominator)
return data_view.get()
@timeRangeEndDenominator.setter
def timeRangeEndDenominator(self, value):
data_view = og.AttributeValueHelper(self._attributes.timeRangeEndDenominator)
data_view.set(value)
@property
def timeRangeEndNumerator(self):
data_view = og.AttributeValueHelper(self._attributes.timeRangeEndNumerator)
return data_view.get()
@timeRangeEndNumerator.setter
def timeRangeEndNumerator(self, value):
data_view = og.AttributeValueHelper(self._attributes.timeRangeEndNumerator)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnSdFabricTimeRangeExecutionDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSdFabricTimeRangeExecutionDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSdFabricTimeRangeExecutionDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,894 | Python | 47.844697 | 227 | 0.669148 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdRenderVarDisplayTextureDatabase.py | """Support for simplified access to data on nodes of type omni.syntheticdata.SdRenderVarDisplayTexture
Synthetic Data node to expose texture resource of a visualization render variable
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSdRenderVarDisplayTextureDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdRenderVarDisplayTexture
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.exec
inputs.renderResults
inputs.renderVarDisplay
Outputs:
outputs.cudaPtr
outputs.exec
outputs.format
outputs.height
outputs.referenceTimeDenominator
outputs.referenceTimeNumerator
outputs.rpResourcePtr
outputs.width
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('inputs:renderResults', 'uint64', 0, None, 'Render results pointer', {}, True, 0, False, ''),
('inputs:renderVarDisplay', 'token', 0, None, 'Name of the renderVar', {}, True, "", False, ''),
('outputs:cudaPtr', 'uint64', 0, None, 'Display texture CUDA pointer', {}, True, None, False, ''),
('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('outputs:format', 'uint64', 0, None, 'Display texture format', {}, True, None, False, ''),
('outputs:height', 'uint', 0, None, 'Display texture height', {}, True, None, False, ''),
('outputs:referenceTimeDenominator', 'uint64', 0, None, 'Reference time represented as a rational number : denominator', {}, True, None, False, ''),
('outputs:referenceTimeNumerator', 'int64', 0, None, 'Reference time represented as a rational number : numerator', {}, True, None, False, ''),
('outputs:rpResourcePtr', 'uint64', 0, None, 'Display texture RpResource pointer', {}, True, None, False, ''),
('outputs:width', 'uint', 0, None, 'Display texture width', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.exec = og.AttributeRole.EXECUTION
role_data.outputs.exec = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.exec)
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def renderResults(self):
data_view = og.AttributeValueHelper(self._attributes.renderResults)
return data_view.get()
@renderResults.setter
def renderResults(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.renderResults)
data_view = og.AttributeValueHelper(self._attributes.renderResults)
data_view.set(value)
@property
def renderVarDisplay(self):
data_view = og.AttributeValueHelper(self._attributes.renderVarDisplay)
return data_view.get()
@renderVarDisplay.setter
def renderVarDisplay(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.renderVarDisplay)
data_view = og.AttributeValueHelper(self._attributes.renderVarDisplay)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def cudaPtr(self):
data_view = og.AttributeValueHelper(self._attributes.cudaPtr)
return data_view.get()
@cudaPtr.setter
def cudaPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.cudaPtr)
data_view.set(value)
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def format(self):
data_view = og.AttributeValueHelper(self._attributes.format)
return data_view.get()
@format.setter
def format(self, value):
data_view = og.AttributeValueHelper(self._attributes.format)
data_view.set(value)
@property
def height(self):
data_view = og.AttributeValueHelper(self._attributes.height)
return data_view.get()
@height.setter
def height(self, value):
data_view = og.AttributeValueHelper(self._attributes.height)
data_view.set(value)
@property
def referenceTimeDenominator(self):
data_view = og.AttributeValueHelper(self._attributes.referenceTimeDenominator)
return data_view.get()
@referenceTimeDenominator.setter
def referenceTimeDenominator(self, value):
data_view = og.AttributeValueHelper(self._attributes.referenceTimeDenominator)
data_view.set(value)
@property
def referenceTimeNumerator(self):
data_view = og.AttributeValueHelper(self._attributes.referenceTimeNumerator)
return data_view.get()
@referenceTimeNumerator.setter
def referenceTimeNumerator(self, value):
data_view = og.AttributeValueHelper(self._attributes.referenceTimeNumerator)
data_view.set(value)
@property
def rpResourcePtr(self):
data_view = og.AttributeValueHelper(self._attributes.rpResourcePtr)
return data_view.get()
@rpResourcePtr.setter
def rpResourcePtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.rpResourcePtr)
data_view.set(value)
@property
def width(self):
data_view = og.AttributeValueHelper(self._attributes.width)
return data_view.get()
@width.setter
def width(self, value):
data_view = og.AttributeValueHelper(self._attributes.width)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnSdRenderVarDisplayTextureDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSdRenderVarDisplayTextureDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSdRenderVarDisplayTextureDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,061 | Python | 42.938864 | 156 | 0.646158 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdPostCompRenderVarTexturesDatabase.py | """Support for simplified access to data on nodes of type omni.syntheticdata.SdPostCompRenderVarTextures
Synthetic Data node to compose a front renderVar texture into a back renderVar texture
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSdPostCompRenderVarTexturesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdPostCompRenderVarTextures
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cudaPtr
inputs.format
inputs.gpu
inputs.height
inputs.mode
inputs.parameters
inputs.renderVar
inputs.rp
inputs.width
Predefined Tokens:
tokens.line
tokens.grid
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:cudaPtr', 'uint64', 0, None, 'Front texture CUDA pointer', {}, True, 0, False, ''),
('inputs:format', 'uint64', 0, None, 'Front texture format', {}, True, 0, False, ''),
('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''),
('inputs:height', 'uint', 0, None, 'Front texture height', {}, True, 0, False, ''),
('inputs:mode', 'token', 0, None, 'Mode : grid, line', {ogn.MetadataKeys.DEFAULT: '"line"'}, True, "line", False, ''),
('inputs:parameters', 'float3', 0, None, 'Parameters', {ogn.MetadataKeys.DEFAULT: '[0, 0, 0]'}, True, [0, 0, 0], False, ''),
('inputs:renderVar', 'token', 0, None, 'Name of the back RenderVar', {ogn.MetadataKeys.DEFAULT: '"LdrColor"'}, True, "LdrColor", False, ''),
('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''),
('inputs:width', 'uint', 0, None, 'Front texture width', {}, True, 0, False, ''),
])
class tokens:
line = "line"
grid = "grid"
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def cudaPtr(self):
data_view = og.AttributeValueHelper(self._attributes.cudaPtr)
return data_view.get()
@cudaPtr.setter
def cudaPtr(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.cudaPtr)
data_view = og.AttributeValueHelper(self._attributes.cudaPtr)
data_view.set(value)
@property
def format(self):
data_view = og.AttributeValueHelper(self._attributes.format)
return data_view.get()
@format.setter
def format(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.format)
data_view = og.AttributeValueHelper(self._attributes.format)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gpu)
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def height(self):
data_view = og.AttributeValueHelper(self._attributes.height)
return data_view.get()
@height.setter
def height(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.height)
data_view = og.AttributeValueHelper(self._attributes.height)
data_view.set(value)
@property
def mode(self):
data_view = og.AttributeValueHelper(self._attributes.mode)
return data_view.get()
@mode.setter
def mode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.mode)
data_view = og.AttributeValueHelper(self._attributes.mode)
data_view.set(value)
@property
def parameters(self):
data_view = og.AttributeValueHelper(self._attributes.parameters)
return data_view.get()
@parameters.setter
def parameters(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.parameters)
data_view = og.AttributeValueHelper(self._attributes.parameters)
data_view.set(value)
@property
def renderVar(self):
data_view = og.AttributeValueHelper(self._attributes.renderVar)
return data_view.get()
@renderVar.setter
def renderVar(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.renderVar)
data_view = og.AttributeValueHelper(self._attributes.renderVar)
data_view.set(value)
@property
def rp(self):
data_view = og.AttributeValueHelper(self._attributes.rp)
return data_view.get()
@rp.setter
def rp(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.rp)
data_view = og.AttributeValueHelper(self._attributes.rp)
data_view.set(value)
@property
def width(self):
data_view = og.AttributeValueHelper(self._attributes.width)
return data_view.get()
@width.setter
def width(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.width)
data_view = og.AttributeValueHelper(self._attributes.width)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnSdPostCompRenderVarTexturesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSdPostCompRenderVarTexturesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSdPostCompRenderVarTexturesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 9,264 | Python | 41.695852 | 148 | 0.630937 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdTextureToLinearArrayDatabase.py | """Support for simplified access to data on nodes of type omni.syntheticdata.SdTextureToLinearArray
SyntheticData node to copy the input texture into a linear array buffer
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSdTextureToLinearArrayDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdTextureToLinearArray
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cudaMipmappedArray
inputs.format
inputs.height
inputs.hydraTime
inputs.mipCount
inputs.outputHeight
inputs.outputWidth
inputs.simTime
inputs.stream
inputs.width
Outputs:
outputs.data
outputs.height
outputs.hydraTime
outputs.simTime
outputs.stream
outputs.width
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:cudaMipmappedArray', 'uint64', 0, None, 'Pointer to the CUDA Mipmapped Array', {}, True, 0, False, ''),
('inputs:format', 'uint64', 0, None, 'Format', {}, True, 0, False, ''),
('inputs:height', 'uint', 0, None, 'Height', {}, True, 0, False, ''),
('inputs:hydraTime', 'double', 0, None, 'Hydra time in stage', {}, True, 0.0, False, ''),
('inputs:mipCount', 'uint', 0, None, 'Mip Count', {}, True, 0, False, ''),
('inputs:outputHeight', 'uint', 0, None, 'Requested output height', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:outputWidth', 'uint', 0, None, 'Requested output width', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:simTime', 'double', 0, None, 'Simulation time', {}, True, 0.0, False, ''),
('inputs:stream', 'uint64', 0, None, 'Pointer to the CUDA Stream', {}, True, 0, False, ''),
('inputs:width', 'uint', 0, None, 'Width', {}, True, 0, False, ''),
('outputs:data', 'float4[]', 0, None, 'Buffer array data', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda', ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:height', 'uint', 0, None, 'Buffer array height', {}, True, None, False, ''),
('outputs:hydraTime', 'double', 0, None, 'Hydra time in stage', {}, True, None, False, ''),
('outputs:simTime', 'double', 0, None, 'Simulation time', {}, True, None, False, ''),
('outputs:stream', 'uint64', 0, None, 'Pointer to the CUDA Stream', {}, True, None, False, ''),
('outputs:width', 'uint', 0, None, 'Buffer array width', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def cudaMipmappedArray(self):
data_view = og.AttributeValueHelper(self._attributes.cudaMipmappedArray)
return data_view.get()
@cudaMipmappedArray.setter
def cudaMipmappedArray(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.cudaMipmappedArray)
data_view = og.AttributeValueHelper(self._attributes.cudaMipmappedArray)
data_view.set(value)
@property
def format(self):
data_view = og.AttributeValueHelper(self._attributes.format)
return data_view.get()
@format.setter
def format(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.format)
data_view = og.AttributeValueHelper(self._attributes.format)
data_view.set(value)
@property
def height(self):
data_view = og.AttributeValueHelper(self._attributes.height)
return data_view.get()
@height.setter
def height(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.height)
data_view = og.AttributeValueHelper(self._attributes.height)
data_view.set(value)
@property
def hydraTime(self):
data_view = og.AttributeValueHelper(self._attributes.hydraTime)
return data_view.get()
@hydraTime.setter
def hydraTime(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.hydraTime)
data_view = og.AttributeValueHelper(self._attributes.hydraTime)
data_view.set(value)
@property
def mipCount(self):
data_view = og.AttributeValueHelper(self._attributes.mipCount)
return data_view.get()
@mipCount.setter
def mipCount(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.mipCount)
data_view = og.AttributeValueHelper(self._attributes.mipCount)
data_view.set(value)
@property
def outputHeight(self):
data_view = og.AttributeValueHelper(self._attributes.outputHeight)
return data_view.get()
@outputHeight.setter
def outputHeight(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.outputHeight)
data_view = og.AttributeValueHelper(self._attributes.outputHeight)
data_view.set(value)
@property
def outputWidth(self):
data_view = og.AttributeValueHelper(self._attributes.outputWidth)
return data_view.get()
@outputWidth.setter
def outputWidth(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.outputWidth)
data_view = og.AttributeValueHelper(self._attributes.outputWidth)
data_view.set(value)
@property
def simTime(self):
data_view = og.AttributeValueHelper(self._attributes.simTime)
return data_view.get()
@simTime.setter
def simTime(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.simTime)
data_view = og.AttributeValueHelper(self._attributes.simTime)
data_view.set(value)
@property
def stream(self):
data_view = og.AttributeValueHelper(self._attributes.stream)
return data_view.get()
@stream.setter
def stream(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.stream)
data_view = og.AttributeValueHelper(self._attributes.stream)
data_view.set(value)
@property
def width(self):
data_view = og.AttributeValueHelper(self._attributes.width)
return data_view.get()
@width.setter
def width(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.width)
data_view = og.AttributeValueHelper(self._attributes.width)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.data_size = 0
self._batchedWriteValues = { }
@property
def data(self):
data_view = og.AttributeValueHelper(self._attributes.data)
return data_view.get(reserved_element_count=self.data_size, on_gpu=True)
@data.setter
def data(self, value):
data_view = og.AttributeValueHelper(self._attributes.data)
data_view.set(value, on_gpu=True)
self.data_size = data_view.get_array_size()
@property
def height(self):
data_view = og.AttributeValueHelper(self._attributes.height)
return data_view.get()
@height.setter
def height(self, value):
data_view = og.AttributeValueHelper(self._attributes.height)
data_view.set(value)
@property
def hydraTime(self):
data_view = og.AttributeValueHelper(self._attributes.hydraTime)
return data_view.get()
@hydraTime.setter
def hydraTime(self, value):
data_view = og.AttributeValueHelper(self._attributes.hydraTime)
data_view.set(value)
@property
def simTime(self):
data_view = og.AttributeValueHelper(self._attributes.simTime)
return data_view.get()
@simTime.setter
def simTime(self, value):
data_view = og.AttributeValueHelper(self._attributes.simTime)
data_view.set(value)
@property
def stream(self):
data_view = og.AttributeValueHelper(self._attributes.stream)
return data_view.get()
@stream.setter
def stream(self, value):
data_view = og.AttributeValueHelper(self._attributes.stream)
data_view.set(value)
@property
def width(self):
data_view = og.AttributeValueHelper(self._attributes.width)
return data_view.get()
@width.setter
def width(self, value):
data_view = og.AttributeValueHelper(self._attributes.width)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnSdTextureToLinearArrayDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSdTextureToLinearArrayDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSdTextureToLinearArrayDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,568 | Python | 41.177852 | 160 | 0.620942 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdTestInstanceMappingDatabase.py | """Support for simplified access to data on nodes of type omni.syntheticdata.SdTestInstanceMapping
Synthetic Data node to test the instance mapping pipeline
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSdTestInstanceMappingDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdTestInstanceMapping
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.exec
inputs.instanceMapPtr
inputs.instancePrimPathPtr
inputs.minInstanceIndex
inputs.minSemanticIndex
inputs.numInstances
inputs.numSemantics
inputs.semanticLabelTokenPtrs
inputs.semanticLocalTransformPtr
inputs.semanticMapPtr
inputs.semanticPrimPathPtr
inputs.semanticWorldTransformPtr
inputs.stage
inputs.swhFrameNumber
inputs.testCaseIndex
Outputs:
outputs.exec
outputs.semanticFilterPredicate
outputs.success
Predefined Tokens:
tokens.simulation
tokens.postRender
tokens.onDemand
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('inputs:instanceMapPtr', 'uint64', 0, None, 'Array pointer of numInstances uint16_t containing the semantic index of the instance prim first semantic prim parent', {}, True, 0, False, ''),
('inputs:instancePrimPathPtr', 'uint64', 0, None, 'Array pointer of numInstances uint64_t containing the prim path tokens for every instance prims', {}, True, 0, False, ''),
('inputs:minInstanceIndex', 'uint', 0, None, 'Instance index of the first instance prim in the instance arrays', {}, True, 0, False, ''),
('inputs:minSemanticIndex', 'uint', 0, None, 'Semantic index of the first semantic prim in the semantic arrays', {}, True, 0, False, ''),
('inputs:numInstances', 'uint', 0, None, 'Number of instances prim in the instance arrays', {}, True, 0, False, ''),
('inputs:numSemantics', 'uint', 0, None, 'Number of semantic prim in the semantic arrays', {}, True, 0, False, ''),
('inputs:semanticLabelTokenPtrs', 'uint64[]', 0, None, 'Array containing for every input semantic filters the corresponding array pointer of numSemantics uint64_t representing the semantic label of the semantic prim', {}, True, [], False, ''),
('inputs:semanticLocalTransformPtr', 'uint64', 0, None, 'Array pointer of numSemantics 4x4 float matrices containing the transform from world to object space for every semantic prims', {}, True, 0, False, ''),
('inputs:semanticMapPtr', 'uint64', 0, None, 'Array pointer of numSemantics uint16_t containing the semantic index of the semantic prim first semantic prim parent', {}, True, 0, False, ''),
('inputs:semanticPrimPathPtr', 'uint64', 0, None, 'Array pointer of numSemantics uint32_t containing the prim part of the prim path tokens for every semantic prims', {}, True, 0, False, ''),
('inputs:semanticWorldTransformPtr', 'uint64', 0, None, 'Array pointer of numSemantics 4x4 float matrices containing the transform from local to world space for every semantic entity', {}, True, 0, False, ''),
('inputs:stage', 'token', 0, None, 'Stage in {simulation, postrender, ondemand}', {}, True, "", False, ''),
('inputs:swhFrameNumber', 'uint64', 0, None, 'Fabric frame number', {}, True, 0, False, ''),
('inputs:testCaseIndex', 'int', 0, None, 'Test case index', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''),
('outputs:exec', 'execution', 0, 'Received', 'Executes when the event is received', {}, True, None, False, ''),
('outputs:semanticFilterPredicate', 'token', 0, None, 'The semantic filter predicate : a disjunctive normal form of semantic type and label', {}, True, None, False, ''),
('outputs:success', 'bool', 0, None, 'Test value : false if failed', {}, True, None, False, ''),
])
class tokens:
simulation = "simulation"
postRender = "postRender"
onDemand = "onDemand"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.exec = og.AttributeRole.EXECUTION
role_data.outputs.exec = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.exec)
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def instanceMapPtr(self):
data_view = og.AttributeValueHelper(self._attributes.instanceMapPtr)
return data_view.get()
@instanceMapPtr.setter
def instanceMapPtr(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.instanceMapPtr)
data_view = og.AttributeValueHelper(self._attributes.instanceMapPtr)
data_view.set(value)
@property
def instancePrimPathPtr(self):
data_view = og.AttributeValueHelper(self._attributes.instancePrimPathPtr)
return data_view.get()
@instancePrimPathPtr.setter
def instancePrimPathPtr(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.instancePrimPathPtr)
data_view = og.AttributeValueHelper(self._attributes.instancePrimPathPtr)
data_view.set(value)
@property
def minInstanceIndex(self):
data_view = og.AttributeValueHelper(self._attributes.minInstanceIndex)
return data_view.get()
@minInstanceIndex.setter
def minInstanceIndex(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.minInstanceIndex)
data_view = og.AttributeValueHelper(self._attributes.minInstanceIndex)
data_view.set(value)
@property
def minSemanticIndex(self):
data_view = og.AttributeValueHelper(self._attributes.minSemanticIndex)
return data_view.get()
@minSemanticIndex.setter
def minSemanticIndex(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.minSemanticIndex)
data_view = og.AttributeValueHelper(self._attributes.minSemanticIndex)
data_view.set(value)
@property
def numInstances(self):
data_view = og.AttributeValueHelper(self._attributes.numInstances)
return data_view.get()
@numInstances.setter
def numInstances(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.numInstances)
data_view = og.AttributeValueHelper(self._attributes.numInstances)
data_view.set(value)
@property
def numSemantics(self):
data_view = og.AttributeValueHelper(self._attributes.numSemantics)
return data_view.get()
@numSemantics.setter
def numSemantics(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.numSemantics)
data_view = og.AttributeValueHelper(self._attributes.numSemantics)
data_view.set(value)
@property
def semanticLabelTokenPtrs(self):
data_view = og.AttributeValueHelper(self._attributes.semanticLabelTokenPtrs)
return data_view.get()
@semanticLabelTokenPtrs.setter
def semanticLabelTokenPtrs(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.semanticLabelTokenPtrs)
data_view = og.AttributeValueHelper(self._attributes.semanticLabelTokenPtrs)
data_view.set(value)
self.semanticLabelTokenPtrs_size = data_view.get_array_size()
@property
def semanticLocalTransformPtr(self):
data_view = og.AttributeValueHelper(self._attributes.semanticLocalTransformPtr)
return data_view.get()
@semanticLocalTransformPtr.setter
def semanticLocalTransformPtr(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.semanticLocalTransformPtr)
data_view = og.AttributeValueHelper(self._attributes.semanticLocalTransformPtr)
data_view.set(value)
@property
def semanticMapPtr(self):
data_view = og.AttributeValueHelper(self._attributes.semanticMapPtr)
return data_view.get()
@semanticMapPtr.setter
def semanticMapPtr(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.semanticMapPtr)
data_view = og.AttributeValueHelper(self._attributes.semanticMapPtr)
data_view.set(value)
@property
def semanticPrimPathPtr(self):
data_view = og.AttributeValueHelper(self._attributes.semanticPrimPathPtr)
return data_view.get()
@semanticPrimPathPtr.setter
def semanticPrimPathPtr(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.semanticPrimPathPtr)
data_view = og.AttributeValueHelper(self._attributes.semanticPrimPathPtr)
data_view.set(value)
@property
def semanticWorldTransformPtr(self):
data_view = og.AttributeValueHelper(self._attributes.semanticWorldTransformPtr)
return data_view.get()
@semanticWorldTransformPtr.setter
def semanticWorldTransformPtr(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.semanticWorldTransformPtr)
data_view = og.AttributeValueHelper(self._attributes.semanticWorldTransformPtr)
data_view.set(value)
@property
def stage(self):
data_view = og.AttributeValueHelper(self._attributes.stage)
return data_view.get()
@stage.setter
def stage(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.stage)
data_view = og.AttributeValueHelper(self._attributes.stage)
data_view.set(value)
@property
def swhFrameNumber(self):
data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber)
return data_view.get()
@swhFrameNumber.setter
def swhFrameNumber(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.swhFrameNumber)
data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber)
data_view.set(value)
@property
def testCaseIndex(self):
data_view = og.AttributeValueHelper(self._attributes.testCaseIndex)
return data_view.get()
@testCaseIndex.setter
def testCaseIndex(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.testCaseIndex)
data_view = og.AttributeValueHelper(self._attributes.testCaseIndex)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def semanticFilterPredicate(self):
data_view = og.AttributeValueHelper(self._attributes.semanticFilterPredicate)
return data_view.get()
@semanticFilterPredicate.setter
def semanticFilterPredicate(self, value):
data_view = og.AttributeValueHelper(self._attributes.semanticFilterPredicate)
data_view.set(value)
@property
def success(self):
data_view = og.AttributeValueHelper(self._attributes.success)
return data_view.get()
@success.setter
def success(self, value):
data_view = og.AttributeValueHelper(self._attributes.success)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnSdTestInstanceMappingDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSdTestInstanceMappingDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSdTestInstanceMappingDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 16,282 | Python | 45.65616 | 251 | 0.6525 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdFrameIdentifierDatabase.py | """Support for simplified access to data on nodes of type omni.syntheticdata.SdFrameIdentifier
Synthetic Data node to expose pipeline frame identifier.
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSdFrameIdentifierDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdFrameIdentifier
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.exec
inputs.renderResults
Outputs:
outputs.durationDenominator
outputs.durationNumerator
outputs.exec
outputs.externalTimeOfSimNs
outputs.frameNumber
outputs.rationalTimeOfSimDenominator
outputs.rationalTimeOfSimNumerator
outputs.sampleTimeOffsetInSimFrames
outputs.type
Predefined Tokens:
tokens.NoFrameNumber
tokens.FrameNumber
tokens.ConstantFramerateFrameNumber
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('inputs:renderResults', 'uint64', 0, None, 'Render results', {}, True, 0, False, ''),
('outputs:durationDenominator', 'uint64', 0, None, 'Duration denominator.\nOnly valid if eConstantFramerateFrameNumber', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:durationNumerator', 'int64', 0, None, 'Duration numerator.\nOnly valid if eConstantFramerateFrameNumber.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:exec', 'execution', 0, 'Received', 'Executes for each newFrame event received', {}, True, None, False, ''),
('outputs:externalTimeOfSimNs', 'int64', 0, None, 'External time in Ns.\nOnly valid if eConstantFramerateFrameNumber.', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''),
('outputs:frameNumber', 'int64', 0, None, 'Frame number.\nValid if eFrameNumber or eConstantFramerateFrameNumber.', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''),
('outputs:rationalTimeOfSimDenominator', 'uint64', 0, None, 'rational time of simulation denominator.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:rationalTimeOfSimNumerator', 'int64', 0, None, 'rational time of simulation numerator.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:sampleTimeOffsetInSimFrames', 'uint64', 0, None, 'Sample time offset.\nOnly valid if eConstantFramerateFrameNumber.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:type', 'token', 0, None, 'Type of the frame identifier.', {ogn.MetadataKeys.ALLOWED_TOKENS: 'NoFrameNumber,FrameNumber,ConstantFramerateFrameNumber', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '["NoFrameNumber", "FrameNumber", "ConstantFramerateFrameNumber"]', ogn.MetadataKeys.DEFAULT: '"NoFrameNumber"'}, True, "NoFrameNumber", False, ''),
])
class tokens:
NoFrameNumber = "NoFrameNumber"
FrameNumber = "FrameNumber"
ConstantFramerateFrameNumber = "ConstantFramerateFrameNumber"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.exec = og.AttributeRole.EXECUTION
role_data.outputs.exec = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.exec)
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def renderResults(self):
data_view = og.AttributeValueHelper(self._attributes.renderResults)
return data_view.get()
@renderResults.setter
def renderResults(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.renderResults)
data_view = og.AttributeValueHelper(self._attributes.renderResults)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def durationDenominator(self):
data_view = og.AttributeValueHelper(self._attributes.durationDenominator)
return data_view.get()
@durationDenominator.setter
def durationDenominator(self, value):
data_view = og.AttributeValueHelper(self._attributes.durationDenominator)
data_view.set(value)
@property
def durationNumerator(self):
data_view = og.AttributeValueHelper(self._attributes.durationNumerator)
return data_view.get()
@durationNumerator.setter
def durationNumerator(self, value):
data_view = og.AttributeValueHelper(self._attributes.durationNumerator)
data_view.set(value)
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def externalTimeOfSimNs(self):
data_view = og.AttributeValueHelper(self._attributes.externalTimeOfSimNs)
return data_view.get()
@externalTimeOfSimNs.setter
def externalTimeOfSimNs(self, value):
data_view = og.AttributeValueHelper(self._attributes.externalTimeOfSimNs)
data_view.set(value)
@property
def frameNumber(self):
data_view = og.AttributeValueHelper(self._attributes.frameNumber)
return data_view.get()
@frameNumber.setter
def frameNumber(self, value):
data_view = og.AttributeValueHelper(self._attributes.frameNumber)
data_view.set(value)
@property
def rationalTimeOfSimDenominator(self):
data_view = og.AttributeValueHelper(self._attributes.rationalTimeOfSimDenominator)
return data_view.get()
@rationalTimeOfSimDenominator.setter
def rationalTimeOfSimDenominator(self, value):
data_view = og.AttributeValueHelper(self._attributes.rationalTimeOfSimDenominator)
data_view.set(value)
@property
def rationalTimeOfSimNumerator(self):
data_view = og.AttributeValueHelper(self._attributes.rationalTimeOfSimNumerator)
return data_view.get()
@rationalTimeOfSimNumerator.setter
def rationalTimeOfSimNumerator(self, value):
data_view = og.AttributeValueHelper(self._attributes.rationalTimeOfSimNumerator)
data_view.set(value)
@property
def sampleTimeOffsetInSimFrames(self):
data_view = og.AttributeValueHelper(self._attributes.sampleTimeOffsetInSimFrames)
return data_view.get()
@sampleTimeOffsetInSimFrames.setter
def sampleTimeOffsetInSimFrames(self, value):
data_view = og.AttributeValueHelper(self._attributes.sampleTimeOffsetInSimFrames)
data_view.set(value)
@property
def type(self):
data_view = og.AttributeValueHelper(self._attributes.type)
return data_view.get()
@type.setter
def type(self, value):
data_view = og.AttributeValueHelper(self._attributes.type)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnSdFrameIdentifierDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSdFrameIdentifierDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSdFrameIdentifierDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 11,174 | Python | 46.151899 | 353 | 0.667442 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdPostInstanceMappingDatabase.py | """Support for simplified access to data on nodes of type omni.syntheticdata.SdPostInstanceMapping
Synthetic Data node to compute and store scene instances semantic hierarchy information
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSdPostInstanceMappingDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdPostInstanceMapping
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.exec
inputs.gpu
inputs.rp
inputs.semanticFilterName
Outputs:
outputs.exec
outputs.instanceMapSDCudaPtr
outputs.instanceMappingInfoSDPtr
outputs.instancePrimTokenSDCudaPtr
outputs.lastUpdateTimeDenominator
outputs.lastUpdateTimeNumerator
outputs.semanticLabelTokenSDCudaPtr
outputs.semanticLocalTransformSDCudaPtr
outputs.semanticMapSDCudaPtr
outputs.semanticPrimTokenSDCudaPtr
outputs.semanticWorldTransformSDCudaPtr
Predefined Tokens:
tokens.InstanceMappingInfoSDhost
tokens.SemanticMapSD
tokens.SemanticMapSDhost
tokens.SemanticPrimTokenSD
tokens.SemanticPrimTokenSDhost
tokens.InstanceMapSD
tokens.InstanceMapSDhost
tokens.InstancePrimTokenSD
tokens.InstancePrimTokenSDhost
tokens.SemanticLabelTokenSD
tokens.SemanticLabelTokenSDhost
tokens.SemanticLocalTransformSD
tokens.SemanticLocalTransformSDhost
tokens.SemanticWorldTransformSD
tokens.SemanticWorldTransformSDhost
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''),
('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''),
('inputs:semanticFilterName', 'token', 0, None, 'Name of the semantic filter to apply to the semanticLabelToken', {ogn.MetadataKeys.DEFAULT: '"default"'}, True, "default", False, ''),
('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('outputs:instanceMapSDCudaPtr', 'uint64', 0, None, 'cuda uint16_t buffer pointer of size numInstances containing the instance parent semantic index', {}, True, None, False, ''),
('outputs:instanceMappingInfoSDPtr', 'uint64', 0, None, 'uint buffer pointer containing the following information :\n[ numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic,\n lastUpdateTimeNumeratorHigh, lastUpdateTimeNumeratorLow, , lastUpdateTimeDenominatorHigh, lastUpdateTimeDenominatorLow ]', {}, True, None, False, ''),
('outputs:instancePrimTokenSDCudaPtr', 'uint64', 0, None, 'cuda uint64_t buffer pointer of size numInstances containing the instance path token', {}, True, None, False, ''),
('outputs:lastUpdateTimeDenominator', 'uint64', 0, None, 'Time denominator of the last time the data has changed', {}, True, None, False, ''),
('outputs:lastUpdateTimeNumerator', 'int64', 0, None, 'Time numerator of the last time the data has changed', {}, True, None, False, ''),
('outputs:semanticLabelTokenSDCudaPtr', 'uint64', 0, None, 'cuda uint64_t buffer pointer of size numSemantics containing the semantic label token', {}, True, None, False, ''),
('outputs:semanticLocalTransformSDCudaPtr', 'uint64', 0, None, 'cuda float44 buffer pointer of size numSemantics containing the local semantic transform', {}, True, None, False, ''),
('outputs:semanticMapSDCudaPtr', 'uint64', 0, None, 'cuda uint16_t buffer pointer of size numSemantics containing the semantic parent semantic index', {}, True, None, False, ''),
('outputs:semanticPrimTokenSDCudaPtr', 'uint64', 0, None, 'cuda uint32_t buffer pointer of size numSemantics containing the prim part of the semantic path token', {}, True, None, False, ''),
('outputs:semanticWorldTransformSDCudaPtr', 'uint64', 0, None, 'cuda float44 buffer pointer of size numSemantics containing the world semantic transform', {}, True, None, False, ''),
])
class tokens:
InstanceMappingInfoSDhost = "InstanceMappingInfoSDhost"
SemanticMapSD = "SemanticMapSD"
SemanticMapSDhost = "SemanticMapSDhost"
SemanticPrimTokenSD = "SemanticPrimTokenSD"
SemanticPrimTokenSDhost = "SemanticPrimTokenSDhost"
InstanceMapSD = "InstanceMapSD"
InstanceMapSDhost = "InstanceMapSDhost"
InstancePrimTokenSD = "InstancePrimTokenSD"
InstancePrimTokenSDhost = "InstancePrimTokenSDhost"
SemanticLabelTokenSD = "SemanticLabelTokenSD"
SemanticLabelTokenSDhost = "SemanticLabelTokenSDhost"
SemanticLocalTransformSD = "SemanticLocalTransformSD"
SemanticLocalTransformSDhost = "SemanticLocalTransformSDhost"
SemanticWorldTransformSD = "SemanticWorldTransformSD"
SemanticWorldTransformSDhost = "SemanticWorldTransformSDhost"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.exec = og.AttributeRole.EXECUTION
role_data.outputs.exec = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.exec)
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gpu)
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def rp(self):
data_view = og.AttributeValueHelper(self._attributes.rp)
return data_view.get()
@rp.setter
def rp(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.rp)
data_view = og.AttributeValueHelper(self._attributes.rp)
data_view.set(value)
@property
def semanticFilterName(self):
data_view = og.AttributeValueHelper(self._attributes.semanticFilterName)
return data_view.get()
@semanticFilterName.setter
def semanticFilterName(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.semanticFilterName)
data_view = og.AttributeValueHelper(self._attributes.semanticFilterName)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def instanceMapSDCudaPtr(self):
data_view = og.AttributeValueHelper(self._attributes.instanceMapSDCudaPtr)
return data_view.get()
@instanceMapSDCudaPtr.setter
def instanceMapSDCudaPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.instanceMapSDCudaPtr)
data_view.set(value)
@property
def instanceMappingInfoSDPtr(self):
data_view = og.AttributeValueHelper(self._attributes.instanceMappingInfoSDPtr)
return data_view.get()
@instanceMappingInfoSDPtr.setter
def instanceMappingInfoSDPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.instanceMappingInfoSDPtr)
data_view.set(value)
@property
def instancePrimTokenSDCudaPtr(self):
data_view = og.AttributeValueHelper(self._attributes.instancePrimTokenSDCudaPtr)
return data_view.get()
@instancePrimTokenSDCudaPtr.setter
def instancePrimTokenSDCudaPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.instancePrimTokenSDCudaPtr)
data_view.set(value)
@property
def lastUpdateTimeDenominator(self):
data_view = og.AttributeValueHelper(self._attributes.lastUpdateTimeDenominator)
return data_view.get()
@lastUpdateTimeDenominator.setter
def lastUpdateTimeDenominator(self, value):
data_view = og.AttributeValueHelper(self._attributes.lastUpdateTimeDenominator)
data_view.set(value)
@property
def lastUpdateTimeNumerator(self):
data_view = og.AttributeValueHelper(self._attributes.lastUpdateTimeNumerator)
return data_view.get()
@lastUpdateTimeNumerator.setter
def lastUpdateTimeNumerator(self, value):
data_view = og.AttributeValueHelper(self._attributes.lastUpdateTimeNumerator)
data_view.set(value)
@property
def semanticLabelTokenSDCudaPtr(self):
data_view = og.AttributeValueHelper(self._attributes.semanticLabelTokenSDCudaPtr)
return data_view.get()
@semanticLabelTokenSDCudaPtr.setter
def semanticLabelTokenSDCudaPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.semanticLabelTokenSDCudaPtr)
data_view.set(value)
@property
def semanticLocalTransformSDCudaPtr(self):
data_view = og.AttributeValueHelper(self._attributes.semanticLocalTransformSDCudaPtr)
return data_view.get()
@semanticLocalTransformSDCudaPtr.setter
def semanticLocalTransformSDCudaPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.semanticLocalTransformSDCudaPtr)
data_view.set(value)
@property
def semanticMapSDCudaPtr(self):
data_view = og.AttributeValueHelper(self._attributes.semanticMapSDCudaPtr)
return data_view.get()
@semanticMapSDCudaPtr.setter
def semanticMapSDCudaPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.semanticMapSDCudaPtr)
data_view.set(value)
@property
def semanticPrimTokenSDCudaPtr(self):
data_view = og.AttributeValueHelper(self._attributes.semanticPrimTokenSDCudaPtr)
return data_view.get()
@semanticPrimTokenSDCudaPtr.setter
def semanticPrimTokenSDCudaPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.semanticPrimTokenSDCudaPtr)
data_view.set(value)
@property
def semanticWorldTransformSDCudaPtr(self):
data_view = og.AttributeValueHelper(self._attributes.semanticWorldTransformSDCudaPtr)
return data_view.get()
@semanticWorldTransformSDCudaPtr.setter
def semanticWorldTransformSDCudaPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.semanticWorldTransformSDCudaPtr)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnSdPostInstanceMappingDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSdPostInstanceMappingDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSdPostInstanceMappingDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 15,172 | Python | 47.476038 | 356 | 0.679475 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/scripts/menu.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["SynthDataMenuContainer"]
from omni.kit.viewport.menubar.core import (
ComboBoxModel,
ComboBoxItem,
ComboBoxMenuDelegate,
CheckboxMenuDelegate,
IconMenuDelegate,
SliderMenuDelegate,
ViewportMenuContainer,
ViewportMenuItem,
ViewportMenuSeparator
)
from .SyntheticData import SyntheticData
from .visualizer_window import VisualizerWindow
import carb
import omni.ui as ui
from pathlib import Path
import weakref
ICON_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.syntheticdata}")).joinpath("data")
UI_STYLE = {"Menu.Item.Icon::SyntheticData": {"image_url": str(ICON_PATH.joinpath("sensor_icon.svg"))}}
class SensorAngleModel(ui.AbstractValueModel):
def __init__(self, getter, setter, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__getter = getter
self.__setter = setter
def destroy(self):
self.__getter = None
self.__setter = None
def get_value_as_float(self) -> float:
return self.__getter()
def get_value_as_int(self) -> int:
return int(self.get_value_as_float())
def set_value(self, value):
value = float(value)
if self.get_value_as_float() != value:
self.__setter(value)
self._value_changed()
class SensorVisualizationModel(ui.AbstractValueModel):
def __init__(self, sensor: str, visualizer_window, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__sensor = sensor
self.__visualizer_window = visualizer_window
def get_value_as_bool(self) -> bool:
try:
return bool(self.__sensor in self.__visualizer_window.visualization_activation)
except:
return False
def get_value_as_int(self) -> int:
return 1 if self.get_value_as_bool() else 0
def set_value(self, enabled):
enabled = bool(enabled)
if self.get_value_as_bool() != enabled:
self.__visualizer_window.on_sensor_item_clicked(enabled, self.__sensor)
self._value_changed()
def sensor(self):
return self.__sensor
class MenuContext:
def __init__(self, viewport_api):
self.__visualizer_window = VisualizerWindow(f"{viewport_api.id}", viewport_api)
self.__hide_on_click = False
self.__sensor_models = set()
def destroy(self):
self.__sensor_models = set()
self.__visualizer_window.close()
@property
def hide_on_click(self) -> bool:
return self.__hide_on_click
def add_render_settings_items(self):
render_product_combo_model = self.__visualizer_window.render_product_combo_model
if render_product_combo_model:
ViewportMenuItem(
"RenderProduct",
delegate=ComboBoxMenuDelegate(model=render_product_combo_model),
hide_on_click=self.__hide_on_click,
)
render_var_combo_model = self.__visualizer_window.render_var_combo_model
if render_var_combo_model:
ViewportMenuItem(
"RenderVar",
delegate=ComboBoxMenuDelegate(model=render_var_combo_model),
hide_on_click=self.__hide_on_click,
)
def add_angles_items(self):
render_var_combo_model = self.__visualizer_window.render_var_combo_model
if render_var_combo_model:
ViewportMenuItem(
name="Angle",
hide_on_click=self.__hide_on_click,
delegate=SliderMenuDelegate(
model=SensorAngleModel(render_var_combo_model.get_combine_angle,
render_var_combo_model.set_combine_angle),
min=-100.0,
max=100.0,
tooltip="Set Combine Angle",
),
)
ViewportMenuItem(
name="X",
hide_on_click=self.__hide_on_click,
delegate=SliderMenuDelegate(
model=SensorAngleModel(render_var_combo_model.get_combine_divide_x,
render_var_combo_model.set_combine_divide_x),
min=-100.0,
max=100.0,
tooltip="Set Combine Divide X",
),
)
ViewportMenuItem(
name="Y",
hide_on_click=self.__hide_on_click,
delegate=SliderMenuDelegate(
model=SensorAngleModel(render_var_combo_model.get_combine_divide_y,
render_var_combo_model.set_combine_divide_y),
min=-100.0,
max=100.0,
tooltip="Set Combine Divide Y",
),
)
def add_sensor_selection(self):
for sensor_label, sensor in SyntheticData.get_registered_visualization_template_names_for_display():
model = SensorVisualizationModel(sensor, self.__visualizer_window)
self.__sensor_models.add(model)
ViewportMenuItem(
name=sensor_label,
hide_on_click=self.__hide_on_click,
delegate=CheckboxMenuDelegate(model=model, tooltip=f'Enable "{sensor}" visualization')
)
if SyntheticData.get_visualization_template_name_default_activation(sensor):
model.set_value(True)
def clear_all(self, *args, **kwargs):
for smodel in self.__sensor_models:
smodel.set_value(False)
def set_as_default(self, *args, **kwargs):
for smodel in self.__sensor_models:
SyntheticData.set_visualization_template_name_default_activation(smodel.sensor(), smodel.get_value_as_bool())
def reset_to_default(self, *args, **kwargs):
default_sensors = []
for _, sensor in SyntheticData.get_registered_visualization_template_names_for_display():
if SyntheticData.get_visualization_template_name_default_activation(sensor):
default_sensors.append(sensor)
for smodel in self.__sensor_models:
smodel.set_value(smodel.sensor() in default_sensors)
def show_window(self, *args, **kwargs):
self.__visualizer_window.toggle_enable_visualization()
class SynthDataMenuContainer(ViewportMenuContainer):
def __init__(self):
super().__init__(name="SyntheticData",
visible_setting_path="/exts/omni.syntheticdata/menubar/visible",
order_setting_path="/exts/omni.syntheticdata/menubar/order",
delegate=IconMenuDelegate("SyntheticData"), # tooltip="Synthetic Data Sensors"),
style=UI_STYLE)
self.__menu_context: Dict[str, MenuContext] = {}
def __del__(self):
self.destroy()
def destroy(self):
for menu_ctx in self.__menu_context.values():
menu_ctx.destroy()
self.__menu_context = {}
super().destroy()
def build_fn(self, desc: dict):
viewport_api = desc.get("viewport_api")
if not viewport_api:
return
viewport_api_id = viewport_api.id
menu_ctx = self.__menu_context.get(viewport_api_id)
if menu_ctx:
menu_ctx.destroy()
menu_ctx = MenuContext(viewport_api)
self.__menu_context[viewport_api_id] = menu_ctx
with self:
menu_ctx.add_render_settings_items()
ViewportMenuSeparator()
menu_ctx.add_angles_items()
ViewportMenuSeparator()
menu_ctx.add_sensor_selection()
if carb.settings.get_settings().get_as_bool("/exts/omni.syntheticdata/menubar/showSensorDefaultButton"):
ViewportMenuSeparator()
ViewportMenuItem(name="Set as default", hide_on_click=menu_ctx.hide_on_click, onclick_fn=menu_ctx.set_as_default)
ViewportMenuItem(name="Reset to default", hide_on_click=menu_ctx.hide_on_click, onclick_fn=menu_ctx.reset_to_default)
ViewportMenuSeparator()
ViewportMenuItem(name="Clear All", hide_on_click=menu_ctx.hide_on_click, onclick_fn=menu_ctx.clear_all)
ViewportMenuItem(name="Show Window", hide_on_click=menu_ctx.hide_on_click, onclick_fn=menu_ctx.show_window)
super().build_fn(desc)
def clear_all(self):
for menu_ctx in self.__menu_context.values():
menu_ctx.clear_all()
| 8,981 | Python | 36.739496 | 133 | 0.595813 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/tests/pipeline/test_instance_mapping_update.py | import carb
import os.path
from pxr import Gf, UsdGeom, UsdLux, Sdf
import omni.hydratexture
import omni.kit.test
from omni.syntheticdata import SyntheticData, SyntheticDataStage
from ..utils import add_semantics
# Test the instance mapping update Fabric flag
class TestInstanceMappingUpdate(omni.kit.test.AsyncTestCase):
def __init__(self, methodName: str) -> None:
super().__init__(methodName=methodName)
# Dictionnary containing the pair (file_path , reference_data). If the reference data is None only the existence of the file is validated.
self._golden_references = {}
def _texture_render_product_path(self, hydra_texture) -> str:
'''Return a string to the UsdRender.Product used by the texture'''
render_product = hydra_texture.get_render_product_path()
if render_product and (not render_product.startswith('/')):
render_product = '/Render/RenderProduct_' + render_product
return render_product
def _assert_count_equal(self, counter_template_name, count):
count_output = SyntheticData.Get().get_node_attributes(
counter_template_name,
["outputs:count"],
self._render_product_path
)
assert "outputs:count" in count_output
assert count_output["outputs:count"] == count
def _activate_fabric_time_range(self) -> None:
sdg_iface = SyntheticData.Get()
if not sdg_iface.is_node_template_registered("TestSimFabricTimeRange"):
sdg_iface.register_node_template(
SyntheticData.NodeTemplate(
SyntheticDataStage.ON_DEMAND,
"omni.syntheticdata.SdTestSimFabricTimeRange"
),
template_name="TestSimFabricTimeRange"
)
sdg_iface.activate_node_template(
"TestSimFabricTimeRange",
attributes={"inputs:timeRangeName":"testFabricTimeRangeTrigger"}
)
if not sdg_iface.is_node_template_registered("TestPostRenderFabricTimeRange"):
sdg_iface.register_node_template(
SyntheticData.NodeTemplate(
SyntheticDataStage.POST_RENDER,
"omni.syntheticdata.SdFabricTimeRangeExecution",
[
SyntheticData.NodeConnectionTemplate(
SyntheticData.renderer_template_name(),
attributes_mapping=
{
"outputs:rp": "inputs:renderResults",
"outputs:gpu": "inputs:gpu"
}
)
]
),
template_name="TestPostRenderFabricTimeRange"
)
sdg_iface.activate_node_template(
"TestPostRenderFabricTimeRange",
0,
[self._render_product_path],
attributes={"inputs:timeRangeName":"testFabricTimeRangeTrigger"}
)
if not sdg_iface.is_node_template_registered("TestPostProcessFabricTimeRange"):
sdg_iface.register_node_template(
SyntheticData.NodeTemplate(
SyntheticDataStage.ON_DEMAND,
"omni.syntheticdata.SdFabricTimeRangeExecution",
[
SyntheticData.NodeConnectionTemplate("PostProcessDispatch"),
SyntheticData.NodeConnectionTemplate("TestPostRenderFabricTimeRange")
]
),
template_name="TestPostProcessFabricTimeRange"
)
sdg_iface.activate_node_template(
"TestPostProcessFabricTimeRange",
0,
[self._render_product_path],
attributes={"inputs:timeRangeName":"testFabricTimeRangeTrigger"}
)
if not sdg_iface.is_node_template_registered("TestPostProcessFabricTimeRangeCounter"):
sdg_iface.register_node_template(
SyntheticData.NodeTemplate(
SyntheticDataStage.ON_DEMAND,
"omni.graph.action.Counter",
[
SyntheticData.NodeConnectionTemplate(
"TestPostProcessFabricTimeRange",
attributes_mapping={"outputs:exec": "inputs:execIn"}
)
]
),
template_name="TestPostProcessFabricTimeRangeCounter"
)
sdg_iface.activate_node_template(
"TestPostProcessFabricTimeRangeCounter",
0,
[self._render_product_path]
)
def _activate_instance_mapping_update(self) -> None:
sdg_iface = SyntheticData.Get()
if not sdg_iface.is_node_template_registered("TestPostProcessInstanceMappingUpdate"):
sdg_iface.register_node_template(
SyntheticData.NodeTemplate(
SyntheticDataStage.ON_DEMAND,
"omni.syntheticdata.SdTimeChangeExecution",
[
SyntheticData.NodeConnectionTemplate("InstanceMappingPtr"),
SyntheticData.NodeConnectionTemplate("PostProcessDispatch")
]
),
template_name="TestPostProcessInstanceMappingUpdate"
)
if not sdg_iface.is_node_template_registered("TestPostProcessInstanceMappingUpdateCounter"):
sdg_iface.register_node_template(
SyntheticData.NodeTemplate(
SyntheticDataStage.ON_DEMAND,
"omni.graph.action.Counter",
[
SyntheticData.NodeConnectionTemplate(
"TestPostProcessInstanceMappingUpdate",
attributes_mapping={"outputs:exec": "inputs:execIn"}
)
]
),
template_name="TestPostProcessInstanceMappingUpdateCounter"
)
sdg_iface.activate_node_template(
"TestPostProcessInstanceMappingUpdateCounter",
0,
[self._render_product_path]
)
async def _request_fabric_time_range_trigger(self, number_of_frames=1):
sdg_iface = SyntheticData.Get()
sdg_iface.set_node_attributes("TestSimFabricTimeRange",{"inputs:numberOfFrames":number_of_frames})
sdg_iface.request_node_execution("TestSimFabricTimeRange")
await omni.kit.app.get_app().next_update_async()
async def setUp(self):
"""Called at the begining of every tests"""
self._settings = carb.settings.acquire_settings_interface()
self._hydra_texture_factory = omni.hydratexture.acquire_hydra_texture_factory_interface()
self._usd_context_name = ''
self._usd_context = omni.usd.get_context(self._usd_context_name)
await self._usd_context.new_stage_async()
# renderer
renderer = "rtx"
if renderer not in self._usd_context.get_attached_hydra_engine_names():
omni.usd.add_hydra_engine(renderer, self._usd_context)
# create the hydra textures
self._hydra_texture_0 = self._hydra_texture_factory.create_hydra_texture(
"TEX0",
1920,
1080,
self._usd_context_name,
hydra_engine_name=renderer,
is_async=self._settings.get("/app/asyncRendering")
)
self._hydra_texture_rendered_counter = 0
def on_hydra_texture_0(event: carb.events.IEvent):
self._hydra_texture_rendered_counter += 1
self._hydra_texture_rendered_counter_sub = self._hydra_texture_0.get_event_stream().create_subscription_to_push_by_type(
omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED,
on_hydra_texture_0,
name='async rendering test drawable update',
)
stage = omni.usd.get_context().get_stage()
world_prim = UsdGeom.Xform.Define(stage,"/World")
UsdGeom.Xformable(world_prim).AddTranslateOp().Set((0, 0, 0))
UsdGeom.Xformable(world_prim).AddRotateXYZOp().Set((0, 0, 0))
self._render_product_path = self._texture_render_product_path(self._hydra_texture_0)
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path)
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path)
async def tearDown(self):
"""Called at the end of every tests"""
self._hydra_texture_rendered_counter_sub = None
self._hydra_texture_0 = None
self._usd_context.close_stage()
omni.usd.release_all_hydra_engines(self._usd_context)
self._hydra_texture_factory = None
self._settings = None
wait_iterations = 6
for _ in range(wait_iterations):
await omni.kit.app.get_app().next_update_async()
async def test_case_0(self):
"""Test case 0 : no time range"""
self._activate_fabric_time_range()
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 11)
self._assert_count_equal("TestPostProcessFabricTimeRangeCounter", 0)
async def test_case_1(self):
"""Test case 1 : setup a time range of 5 frames"""
self._activate_fabric_time_range()
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path)
await self._request_fabric_time_range_trigger(5)
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 11)
self._assert_count_equal("TestPostProcessFabricTimeRangeCounter", 5)
async def test_case_2(self):
"""Test case 2 : initial instance mapping setup"""
self._activate_instance_mapping_update()
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 11)
self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 1)
async def test_case_3(self):
"""Test case 3 : setup an instance mapping with 1, 2, 3, 4 changes"""
stage = omni.usd.get_context().get_stage()
self._activate_instance_mapping_update()
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 1)
self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 1)
sphere_prim = stage.DefinePrim("/World/Sphere", "Sphere")
add_semantics(sphere_prim, "sphere")
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 3)
self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 2)
sub_sphere_prim = stage.DefinePrim("/World/Sphere/Sphere", "Sphere")
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 5)
self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 3)
add_semantics(sub_sphere_prim, "sphere")
await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 1)
self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 4) | 11,297 | Python | 45.303279 | 146 | 0.610605 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/tests/sensors/test_display_rendervar.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 os
import unittest
import omni.kit.test
from omni.kit.viewport.utility import get_active_viewport
from omni.syntheticdata import SyntheticData
# Test the semantic filter
class TestDisplayRenderVar(omni.kit.test.AsyncTestCase):
def __init__(self, methodName: str) -> None:
super().__init__(methodName=methodName)
async def setUp(self):
await omni.usd.get_context().new_stage_async()
self.render_product_path = get_active_viewport().render_product_path
await omni.kit.app.get_app().next_update_async()
async def wait_for_frames(self):
wait_iterations = 6
for _ in range(wait_iterations):
await omni.kit.app.get_app().next_update_async()
async def test_valid_ldrcolor_texture(self):
SyntheticData.Get().activate_node_template("LdrColorDisplay", 0, [self.render_product_path])
await self.wait_for_frames()
display_output_names = ["outputs:rpResourcePtr", "outputs:width", "outputs:height", "outputs:format"]
display_outputs = SyntheticData.Get().get_node_attributes("LdrColorDisplay", display_output_names, self.render_product_path)
assert(display_outputs and all(o in display_outputs for o in display_output_names) and display_outputs["outputs:rpResourcePtr"] != 0 and display_outputs["outputs:format"] == 11)
SyntheticData.Get().deactivate_node_template("LdrColorDisplay", 0, [self.render_product_path])
async def test_valid_bbox3d_texture(self):
SyntheticData.Get().activate_node_template("BoundingBox3DDisplay", 0, [self.render_product_path])
await self.wait_for_frames()
display_output_names = ["outputs:rpResourcePtr", "outputs:width", "outputs:height", "outputs:format"]
display_outputs = SyntheticData.Get().get_node_attributes("BoundingBox3DDisplay", display_output_names, self.render_product_path)
assert(display_outputs and all(o in display_outputs for o in display_output_names) and display_outputs["outputs:rpResourcePtr"] != 0 and display_outputs["outputs:format"] == 11)
SyntheticData.Get().deactivate_node_template("BoundingBox3DDisplay", 0, [self.render_product_path])
async def test_valid_cam3dpos_texture(self):
SyntheticData.Get().activate_node_template("Camera3dPositionDisplay", 0, [self.render_product_path])
await self.wait_for_frames()
display_output_names = ["outputs:rpResourcePtr", "outputs:width", "outputs:height", "outputs:format"]
display_outputs = SyntheticData.Get().get_node_attributes("Camera3dPositionDisplay", display_output_names, self.render_product_path)
assert(display_outputs and all(o in display_outputs for o in display_output_names) and display_outputs["outputs:rpResourcePtr"] != 0 and display_outputs["outputs:format"] == 11)
SyntheticData.Get().deactivate_node_template("Camera3dPositionDisplay", 0, [self.render_product_path])
| 3,130 | Python | 61.619999 | 185 | 0.720447 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/tests/sensors/test_cross_correspondence.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 os
import math
import asyncio
from PIL import Image
from time import time
from pathlib import Path
import carb
import numpy as np
from numpy.lib.arraysetops import unique
import omni.kit.test
from pxr import Gf, UsdGeom
from omni.kit.viewport.utility import get_active_viewport, next_viewport_frame_async, create_viewport_window
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import omni.syntheticdata as syn
from ..utils import add_semantics
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
TIMEOUT = 200
cameras = ["/World/Cameras/CameraFisheyeLeft", "/World/Cameras/CameraPinhole", "/World/Cameras/CameraFisheyeRight"]
# Having a test class derived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
# This test has to run last and thus it's prefixed as such to force that:
# - This is because it has to create additional viewports which makes the test
# get stuck if it's not the last one in the OV process session
class ZZHasToRunLast_TestCrossCorrespondence(omni.kit.test.AsyncTestCase):
def __init__(self, methodName: str) -> None:
super().__init__(methodName=methodName)
self.golden_image_path = Path(os.path.dirname(os.path.abspath(__file__))) / ".." / "data" / "golden"
self.output_image_path = Path(os.path.dirname(os.path.abspath(__file__))) / ".." / "data" / "output"
self.StdDevTolerance = 0.1
self.sensorViewport = None
# Before running each test
async def setUp(self):
global cameras
np.random.seed(1234)
# Load the scene
scenePath = os.path.join(FILE_DIR, "../data/scenes/cross_correspondence.usda")
await omni.usd.get_context().open_stage_async(scenePath)
await omni.kit.app.get_app().next_update_async()
# Get the main-viewport as the sensor-viewport
self.sensorViewport = get_active_viewport()
await next_viewport_frame_async(self.sensorViewport)
# Setup viewports
resolution = self.sensorViewport.resolution
viewport_windows = [None] * 2
x_pos, y_pos = 12, 75
for i in range(len(viewport_windows)):
viewport_windows[i] = create_viewport_window(width=resolution[0], height=resolution[1], position_x=x_pos, position_y=y_pos)
viewport_windows[i].width = 500
viewport_windows[i].height = 500
x_pos += 500
# Setup cameras
self.sensorViewport.camera_path = cameras[0]
for i in range(len(viewport_windows)):
viewport_windows[i].viewport_api.camera_path = cameras[i + 1]
async def test_golden_image_rt_cubemap(self):
settings = carb.settings.get_settings()
settings.set_string("/rtx/rendermode", "RaytracedLighting")
settings.set_bool("/rtx/fishEye/useCubemap", True)
await omni.kit.app.get_app().next_update_async()
# Use default viewport for sensor target as otherwise sensor enablement doesn't work
# also the test will get stuck
# Initialize Sensor
await syn.sensors.create_or_retrieve_sensor_async(
self.sensorViewport, syn._syntheticdata.SensorType.CrossCorrespondence
)
# Render one frame
await syn.sensors.next_sensor_data_async(self.sensorViewport,True)
data = syn.sensors.get_cross_correspondence(self.sensorViewport)
golden_image = np.load(self.golden_image_path / "cross_correspondence.npz")["array"]
# normalize xy (uv offset) to zw channels' value range
# x100 seems like a good number to bring uv offset to ~1
data[:, [0, 1]] *= 100
golden_image[:, [0, 1]] *= 100
std_dev = np.sqrt(np.square(data - golden_image).astype(float).mean())
if std_dev >= self.StdDevTolerance:
if not os.path.isdir(self.output_image_path):
os.mkdir(self.output_image_path)
np.savez_compressed(self.output_image_path / "cross_correspondence.npz", array=data)
golden_image = ((golden_image + 1.0) / 2) * 255
data = ((data + 1.0) / 2) * 255
Image.fromarray(golden_image.astype(np.uint8), "RGBA").save(
self.output_image_path / "cross_correspondence_golden.png"
)
Image.fromarray(data.astype(np.uint8), "RGBA").save(self.output_image_path / "cross_correspondence.png")
self.assertTrue(std_dev < self.StdDevTolerance)
async def test_golden_image_rt_non_cubemap(self):
settings = carb.settings.get_settings()
settings.set_string("/rtx/rendermode", "RaytracedLighting")
settings.set_bool("/rtx/fishEye/useCubemap", False)
await omni.kit.app.get_app().next_update_async()
# Use default viewport for sensor target as otherwise sensor enablement doesn't work
# also the test will get stuck
# Initialize Sensor
await syn.sensors.create_or_retrieve_sensor_async(
self.sensorViewport, syn._syntheticdata.SensorType.CrossCorrespondence
)
# Render one frame
await syn.sensors.next_sensor_data_async(self.sensorViewport,True)
data = syn.sensors.get_cross_correspondence(self.sensorViewport)
golden_image = np.load(self.golden_image_path / "cross_correspondence.npz")["array"]
# normalize xy (uv offset) to zw channels' value range
# x100 seems like a good number to bring uv offset to ~1
data[:, [0, 1]] *= 100
golden_image[:, [0, 1]] *= 100
std_dev = np.sqrt(np.square(data - golden_image).astype(float).mean())
if std_dev >= self.StdDevTolerance:
if not os.path.isdir(self.output_image_path):
os.mkdir(self.output_image_path)
np.savez_compressed(self.output_image_path / "cross_correspondence.npz", array=data)
golden_image = ((golden_image + 1.0) / 2) * 255
data = ((data + 1.0) / 2) * 255
Image.fromarray(golden_image.astype(np.uint8), "RGBA").save(
self.output_image_path / "cross_correspondence_golden.png"
)
Image.fromarray(data.astype(np.uint8), "RGBA").save(self.output_image_path / "cross_correspondence.png")
self.assertTrue(std_dev < self.StdDevTolerance)
async def test_golden_image_pt(self):
settings = carb.settings.get_settings()
settings.set_string("/rtx/rendermode", "PathTracing")
settings.set_int("/rtx/pathtracing/spp", 32)
settings.set_bool("/rtx/fishEye/useCubemap", False)
await omni.kit.app.get_app().next_update_async()
# Use default viewport for sensor target as otherwise sensor enablement doesn't work
# also the test will get stuck
# Initialize Sensor
await syn.sensors.create_or_retrieve_sensor_async(
self.sensorViewport, syn._syntheticdata.SensorType.CrossCorrespondence
)
# Render one frame
await syn.sensors.next_sensor_data_async(self.sensorViewport,True)
data = syn.sensors.get_cross_correspondence(self.sensorViewport)
golden_image = np.load(self.golden_image_path / "cross_correspondence.npz")["array"]
# normalize xy (uv offset) to zw channels' value range
# x100 seems like a good number to bring uv offset to ~1
data[:, [0, 1]] *= 100
golden_image[:, [0, 1]] *= 100
std_dev = np.sqrt(np.square(data - golden_image).astype(float).mean())
if std_dev >= self.StdDevTolerance:
if not os.path.isdir(self.output_image_path):
os.mkdir(self.output_image_path)
np.savez_compressed(self.output_image_path / "cross_correspondence.npz", array=data)
golden_image = ((golden_image + 1.0) / 2) * 255
data = ((data + 1.0) / 2) * 255
Image.fromarray(golden_image.astype(np.uint8), "RGBA").save(
self.output_image_path / "cross_correspondence_golden.png"
)
Image.fromarray(data.astype(np.uint8), "RGBA").save(self.output_image_path / "cross_correspondence.png")
self.assertTrue(std_dev < self.StdDevTolerance)
async def test_same_position(self):
global cameras
# Make sure our cross correspondence values converage around 0 when the target and reference cameras are
# in the same position
settings = carb.settings.get_settings()
settings.set_string("/rtx/rendermode", "PathTracing")
settings.set_int("/rtx/pathtracing/spp", 32)
settings.set_bool("/rtx/fishEye/useCubemap", False)
# Use default viewport for sensor target as otherwise sensor enablement doesn't work
# also the test will get stuck
# Move both cameras to the same position
camera_left = omni.usd.get_context().get_stage().GetPrimAtPath(cameras[0])
camera_right = omni.usd.get_context().get_stage().GetPrimAtPath(cameras[2])
UsdGeom.XformCommonAPI(camera_left).SetTranslate(Gf.Vec3d(-10, 4, 0))
UsdGeom.XformCommonAPI(camera_right).SetTranslate(Gf.Vec3d(-10, 4, 0))
await omni.kit.app.get_app().next_update_async()
# Initialize Sensor
await syn.sensors.create_or_retrieve_sensor_async(
self.sensorViewport, syn._syntheticdata.SensorType.CrossCorrespondence
)
# Render one frame
await syn.sensors.next_sensor_data_async(self.sensorViewport,True)
raw_data = syn.sensors.get_cross_correspondence(self.sensorViewport)
# Get histogram parameters
du_scale = float(raw_data.shape[1] - 1)
dv_scale = float(raw_data.shape[0] - 1)
du_img = raw_data[:, :, 0] * du_scale
dv_img = raw_data[:, :, 1] * dv_scale
# Clear all invalid pixels by setting them to 10000.0
invalid_mask = (raw_data[:, :, 2] == -1)
du_img[invalid_mask] = 10000.0
dv_img[invalid_mask] = 10000.0
# Selection mask
du_selected = (du_img >= -1.0) & (du_img < 1.0)
dv_selected = (dv_img >= -1.0) & (dv_img < 1.0)
# Calculate bins
bins = np.arange(-1.0, 1.0 + 0.1, 0.1)
# calculate histograms for cross correspondence values along eacheach axis
hist_du, edges_du = np.histogram(du_img[du_selected], bins=bins)
hist_dv, edges_dv = np.histogram(dv_img[dv_selected], bins=bins)
# ensure the (0.0, 0.0) bins contain the most values
self.assertTrue(np.argmax(hist_du) == 10)
self.assertTrue(np.argmax(hist_dv) == 10)
# After running each test
async def tearDown(self):
pass
| 10,904 | Python | 42.795181 | 141 | 0.646735 |
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/tests/sensors/test_rendervar_buff_host_ptr.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 unittest
import numpy as np
import ctypes
import omni.kit.test
from omni.gpu_foundation_factory import TextureFormat
from omni.kit.viewport.utility import get_active_viewport
from pxr import UsdGeom, UsdLux
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import omni.syntheticdata as syn
from ..utils import add_semantics
# Test the SyntheticData following nodes :
# - SdPostRenderVarTextureToBuffer : node to convert a texture device rendervar into a buffer device rendervar
# - SdPostRenderVarToHost : node to readback a device rendervar into a host rendervar
# - SdRenderVarPtr : node to expose in the action graph, raw device / host pointers on the renderVars
#
# the tests consists in pulling the ptr data and comparing it with the data ouputed by :
# - SdRenderVarToRawArray
#
class TestRenderVarBuffHostPtr(omni.kit.test.AsyncTestCase):
_tolerance = 1.1
_outputs_ptr = ["outputs:dataPtr","outputs:width","outputs:height","outputs:bufferSize","outputs:format", "outputs:strides"]
_outputs_arr = ["outputs:data","outputs:width","outputs:height","outputs:bufferSize","outputs:format"]
@staticmethod
def _texture_element_size(texture_format):
if texture_format == int(TextureFormat.RGBA16_SFLOAT):
return 8
elif texture_format == int(TextureFormat.RGBA32_SFLOAT):
return 16
elif texture_format == int(TextureFormat.R32_SFLOAT):
return 4
elif texture_format == int(TextureFormat.RGBA8_UNORM):
return 4
elif texture_format == int(TextureFormat.R32_UINT):
return 4
else:
return 0
@staticmethod
def _assert_equal_tex_infos(out_a, out_b):
assert((out_a["outputs:width"] == out_b["outputs:width"]) and
(out_a["outputs:height"] == out_b["outputs:height"]) and
(out_a["outputs:format"] == out_b["outputs:format"]))
@staticmethod
def _assert_equal_buff_infos(out_a, out_b):
assert((out_a["outputs:bufferSize"] == out_b["outputs:bufferSize"]))
@staticmethod
def _assert_equal_data(data_a, data_b):
assert(np.amax(np.square(data_a - data_b)) < TestRenderVarBuffHostPtr._tolerance)
def _get_raw_array(self, render_var):
ptr_outputs = syn.SyntheticData.Get().get_node_attributes(render_var + "ExportRawArray", TestRenderVarBuffHostPtr._outputs_arr, self.render_product)
is_texture = ptr_outputs["outputs:width"] > 0
if is_texture:
elem_size = TestRenderVarBuffHostPtr._texture_element_size(ptr_outputs["outputs:format"])
arr_shape = (ptr_outputs["outputs:height"], ptr_outputs["outputs:width"], elem_size)
ptr_outputs["outputs:data"] = ptr_outputs["outputs:data"].reshape(arr_shape)
return ptr_outputs
def _get_ptr_array(self, render_var, ptr_suffix):
ptr_outputs = syn.SyntheticData.Get().get_node_attributes(render_var + ptr_suffix, TestRenderVarBuffHostPtr._outputs_ptr, self.render_product)
c_ptr = ctypes.cast(ptr_outputs["outputs:dataPtr"],ctypes.POINTER(ctypes.c_ubyte))
is_texture = ptr_outputs["outputs:width"] > 0
if is_texture:
elem_size = TestRenderVarBuffHostPtr._texture_element_size(ptr_outputs["outputs:format"])
arr_shape = (ptr_outputs["outputs:height"], ptr_outputs["outputs:width"], elem_size)
arr_strides = ptr_outputs["outputs:strides"]
buffer_size = arr_strides[1] * arr_shape[1]
arr_strides = (arr_strides[1], arr_strides[0], 1)
data_ptr = np.ctypeslib.as_array(c_ptr,shape=(buffer_size,))
data_ptr = np.lib.stride_tricks.as_strided(data_ptr, shape=arr_shape, strides=arr_strides)
else:
data_ptr = np.ctypeslib.as_array(c_ptr,shape=(ptr_outputs["outputs:bufferSize"],))
ptr_outputs["outputs:dataPtr"] = data_ptr
return ptr_outputs
def _assert_equal_rv_ptr(self, render_var:str, ptr_suffix:str, texture=None):
arr_out = self._get_raw_array(render_var)
ptr_out = self._get_ptr_array(render_var,ptr_suffix)
if not texture is None:
if texture:
TestRenderVarBuffHostPtr._assert_equal_tex_infos(arr_out,ptr_out)
else:
TestRenderVarBuffHostPtr._assert_equal_buff_infos(arr_out,ptr_out)
TestRenderVarBuffHostPtr._assert_equal_data(arr_out["outputs:data"],ptr_out["outputs:dataPtr"])
def _assert_equal_rv_ptr_size(self, render_var:str, ptr_suffix:str, arr_size:int):
ptr_out = self._get_ptr_array(render_var,ptr_suffix)
data_ptr = ptr_out["outputs:dataPtr"]
# helper for setting the value : print the size if None
if arr_size is None:
print(f"EqualRVPtrSize : {render_var} = {data_ptr.size}")
else:
assert(data_ptr.size==arr_size)
def _assert_equal_rv_arr(self, render_var:str, ptr_suffix:str, texture=None):
arr_out_a = self._get_raw_array(render_var)
arr_out_b = self._get_raw_array(render_var+ptr_suffix)
if not texture is None:
if texture:
TestRenderVarBuffHostPtr._assert_equal_tex_infos(arr_out_a,arr_out_b)
else:
TestRenderVarBuffHostPtr._assert_equal_buff_infos(arr_out_a,arr_out_b)
TestRenderVarBuffHostPtr._assert_equal_data(
arr_out_a["outputs:data"].flatten(),arr_out_b["outputs:data"].flatten())
def _assert_executed_rv_ptr(self, render_var:str, ptr_suffix:str):
ptr_outputs = syn.SyntheticData.Get().get_node_attributes(render_var + ptr_suffix, ["outputs:exec"], self.render_product)
assert(ptr_outputs["outputs:exec"]>0)
def __init__(self, methodName: str) -> None:
super().__init__(methodName=methodName)
async def setUp(self):
await omni.usd.get_context().new_stage_async()
stage = omni.usd.get_context().get_stage()
world_prim = UsdGeom.Xform.Define(stage,"/World")
UsdGeom.Xformable(world_prim).AddTranslateOp().Set((0, 0, 0))
UsdGeom.Xformable(world_prim).AddRotateXYZOp().Set((0, 0, 0))
sphere_prim = stage.DefinePrim("/World/Sphere", "Sphere")
add_semantics(sphere_prim, "sphere")
UsdGeom.Xformable(sphere_prim).AddTranslateOp().Set((0, 0, 0))
UsdGeom.Xformable(sphere_prim).AddScaleOp().Set((77, 77, 77))
UsdGeom.Xformable(sphere_prim).AddRotateXYZOp().Set((-90, 0, 0))
sphere_prim.GetAttribute("primvars:displayColor").Set([(1, 0.3, 1)])
capsule0_prim = stage.DefinePrim("/World/Sphere/Capsule0", "Capsule")
add_semantics(capsule0_prim, "capsule0")
UsdGeom.Xformable(capsule0_prim).AddTranslateOp().Set((3, 0, 0))
UsdGeom.Xformable(capsule0_prim).AddRotateXYZOp().Set((0, 0, 0))
capsule0_prim.GetAttribute("primvars:displayColor").Set([(0.3, 1, 0)])
capsule1_prim = stage.DefinePrim("/World/Sphere/Capsule1", "Capsule")
add_semantics(capsule1_prim, "capsule1")
UsdGeom.Xformable(capsule1_prim).AddTranslateOp().Set((-3, 0, 0))
UsdGeom.Xformable(capsule1_prim).AddRotateXYZOp().Set((0, 0, 0))
capsule1_prim.GetAttribute("primvars:displayColor").Set([(0, 1, 0.3)])
capsule2_prim = stage.DefinePrim("/World/Sphere/Capsule2", "Capsule")
add_semantics(capsule2_prim, "capsule2")
UsdGeom.Xformable(capsule2_prim).AddTranslateOp().Set((0, 3, 0))
UsdGeom.Xformable(capsule2_prim).AddRotateXYZOp().Set((0, 0, 0))
capsule2_prim.GetAttribute("primvars:displayColor").Set([(0.7, 0.1, 0.4)])
capsule3_prim = stage.DefinePrim("/World/Sphere/Capsule3", "Capsule")
add_semantics(capsule3_prim, "capsule3")
UsdGeom.Xformable(capsule3_prim).AddTranslateOp().Set((0, -3, 0))
UsdGeom.Xformable(capsule3_prim).AddRotateXYZOp().Set((0, 0, 0))
capsule3_prim.GetAttribute("primvars:displayColor").Set([(0.1, 0.7, 0.4)])
spherelight = UsdLux.SphereLight.Define(stage, "/SphereLight")
spherelight.GetIntensityAttr().Set(30000)
spherelight.GetRadiusAttr().Set(30)
self.viewport = get_active_viewport()
self.render_product = self.viewport.render_product_path
await omni.kit.app.get_app().next_update_async()
async def test_host_arr(self):
render_vars = [
"BoundingBox2DLooseSD",
"SemanticLocalTransformSD"
]
for render_var in render_vars:
syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product])
syn.SyntheticData.Get().activate_node_template(render_var + "hostExportRawArray", 0, [self.render_product])
await syn.sensors.next_render_simulation_async(self.render_product, 1)
for render_var in render_vars:
self._assert_equal_rv_arr(render_var,"host", False)
async def test_host_ptr_size(self):
render_vars = {
"BoundingBox3DSD" : 576,
"BoundingBox2DLooseSD" : 144,
"SemanticLocalTransformSD" : 320,
"Camera3dPositionSD" : 14745600,
"SemanticMapSD" : 10,
"InstanceSegmentationSD" : 3686400,
"SemanticBoundingBox3DCamExtentSD" : 120,
"SemanticBoundingBox3DFilterInfosSD" : 24
}
for render_var in render_vars:
syn.SyntheticData.Get().activate_node_template(render_var + "hostPtr", 0, [self.render_product])
await syn.sensors.next_render_simulation_async(self.render_product, 1)
for render_var, arr_size in render_vars.items():
self._assert_equal_rv_ptr_size(render_var,"hostPtr", arr_size)
async def test_buff_arr(self):
render_vars = [
"Camera3dPositionSD",
"DistanceToImagePlaneSD",
]
for render_var in render_vars:
syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product])
syn.SyntheticData.Get().activate_node_template(render_var + "buffExportRawArray", 0, [self.render_product])
await syn.sensors.next_render_simulation_async(self.render_product, 1)
for render_var in render_vars:
self._assert_equal_rv_arr(render_var, "buff")
async def test_host_ptr(self):
render_vars = [
"BoundingBox2DTightSD",
"BoundingBox3DSD",
"InstanceMapSD"
]
for render_var in render_vars:
syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product])
syn.SyntheticData.Get().activate_node_template(render_var + "hostPtr", 0, [self.render_product])
await syn.sensors.next_render_simulation_async(self.render_product, 1)
for render_var in render_vars:
self._assert_equal_rv_ptr(render_var,"hostPtr",False)
self._assert_executed_rv_ptr(render_var,"hostPtr")
async def test_host_ptr_tex(self):
render_vars = [
"NormalSD",
"DistanceToCameraSD"
]
for render_var in render_vars:
syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product])
syn.SyntheticData.Get().activate_node_template(render_var + "hostPtr", 0, [self.render_product])
await syn.sensors.next_render_simulation_async(self.render_product, 1)
for render_var in render_vars:
self._assert_equal_rv_ptr(render_var,"hostPtr",True)
async def test_buff_host_ptr(self):
render_vars = [
"LdrColorSD",
"InstanceSegmentationSD",
]
for render_var in render_vars:
syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product])
syn.SyntheticData.Get().activate_node_template(render_var + "buffhostPtr", 0, [self.render_product])
await syn.sensors.next_render_simulation_async(self.render_product, 1)
for render_var in render_vars:
self._assert_equal_rv_ptr(render_var, "buffhostPtr",True)
async def test_empty_semantic_host_ptr(self):
await omni.usd.get_context().new_stage_async()
self.viewport = get_active_viewport()
self.render_product = self.viewport.render_product_path
await omni.kit.app.get_app().next_update_async()
render_vars = [
"BoundingBox2DTightSD",
"BoundingBox3DSD",
"InstanceMapSD"
]
for render_var in render_vars:
syn.SyntheticData.Get().activate_node_template(render_var + "hostPtr", 0, [self.render_product])
await syn.sensors.next_render_simulation_async(self.render_product, 1)
for render_var in render_vars:
self._assert_executed_rv_ptr(render_var,"hostPtr")
# After running each test
async def tearDown(self):
pass
| 13,257 | Python | 48.103704 | 156 | 0.646225 |
omniverse-code/kit/exts/omni.usd.schema.audio/pxr/AudioSchema/__init__.py | #!/usr/bin/env python3
#
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.log
omni.log.warn("pxr.AudioSchema is deprecated - please use pxr.OmniAudioSchema instead")
from pxr.OmniAudioSchema import *
| 597 | Python | 34.176469 | 87 | 0.80067 |
omniverse-code/kit/exts/omni.usd.schema.audio/pxr/OmniAudioSchema/_omniAudioSchema.pyi | from __future__ import annotations
import pxr.OmniAudioSchema._omniAudioSchema
import typing
import Boost.Python
import pxr.OmniAudioSchema
import pxr.Usd
import pxr.UsdGeom
__all__ = [
"Listener",
"OmniListener",
"OmniSound",
"Sound",
"Tokens"
]
class Listener(OmniListener, pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance):
@staticmethod
def Define(*args, **kwargs) -> None: ...
@staticmethod
def Get(*args, **kwargs) -> None: ...
@staticmethod
def GetSchemaAttributeNames(*args, **kwargs) -> None: ...
@staticmethod
def _GetStaticTfType(*args, **kwargs) -> None: ...
__instance_size__ = 40
pass
class OmniListener(pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance):
@staticmethod
def CreateConeAnglesAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateConeLowPassFilterAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateConeVolumesAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateOrientationFromViewAttr(*args, **kwargs) -> None: ...
@staticmethod
def Define(*args, **kwargs) -> None: ...
@staticmethod
def Get(*args, **kwargs) -> None: ...
@staticmethod
def GetConeAnglesAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetConeLowPassFilterAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetConeVolumesAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetOrientationFromViewAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetSchemaAttributeNames(*args, **kwargs) -> None: ...
@staticmethod
def _GetStaticTfType(*args, **kwargs) -> None: ...
__instance_size__ = 40
pass
class Sound(OmniSound, pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance):
@staticmethod
def Define(*args, **kwargs) -> None: ...
@staticmethod
def Get(*args, **kwargs) -> None: ...
@staticmethod
def GetSchemaAttributeNames(*args, **kwargs) -> None: ...
@staticmethod
def _GetStaticTfType(*args, **kwargs) -> None: ...
__instance_size__ = 40
pass
class OmniSound(pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance):
@staticmethod
def CreateAttenuationRangeAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateAttenuationTypeAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateAuralModeAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateConeAnglesAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateConeLowPassFilterAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateConeVolumesAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateEnableDistanceDelayAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateEnableDopplerAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateEnableInterauralDelayAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateEndTimeAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateFilePathAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateGainAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateLoopCountAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateMediaOffsetEndAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateMediaOffsetStartAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreatePriorityAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateStartTimeAttr(*args, **kwargs) -> None: ...
@staticmethod
def CreateTimeScaleAttr(*args, **kwargs) -> None: ...
@staticmethod
def Define(*args, **kwargs) -> None: ...
@staticmethod
def Get(*args, **kwargs) -> None: ...
@staticmethod
def GetAttenuationRangeAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetAttenuationTypeAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetAuralModeAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetConeAnglesAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetConeLowPassFilterAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetConeVolumesAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetEnableDistanceDelayAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetEnableDopplerAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetEnableInterauralDelayAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetEndTimeAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetFilePathAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetGainAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetLoopCountAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetMediaOffsetEndAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetMediaOffsetStartAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetPriorityAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetSchemaAttributeNames(*args, **kwargs) -> None: ...
@staticmethod
def GetStartTimeAttr(*args, **kwargs) -> None: ...
@staticmethod
def GetTimeScaleAttr(*args, **kwargs) -> None: ...
@staticmethod
def _GetStaticTfType(*args, **kwargs) -> None: ...
__instance_size__ = 40
pass
class Tokens(Boost.Python.instance):
attenuationRange = 'attenuationRange'
attenuationType = 'attenuationType'
auralMode = 'auralMode'
coneAngles = 'coneAngles'
coneLowPassFilter = 'coneLowPassFilter'
coneVolumes = 'coneVolumes'
default_ = 'default'
enableDistanceDelay = 'enableDistanceDelay'
enableDoppler = 'enableDoppler'
enableInterauralDelay = 'enableInterauralDelay'
endTime = 'endTime'
filePath = 'filePath'
gain = 'gain'
inverse = 'inverse'
linear = 'linear'
linearSquare = 'linearSquare'
loopCount = 'loopCount'
mediaOffsetEnd = 'mediaOffsetEnd'
mediaOffsetStart = 'mediaOffsetStart'
nonSpatial = 'nonSpatial'
off = 'off'
on = 'on'
orientationFromView = 'orientationFromView'
priority = 'priority'
spatial = 'spatial'
startTime = 'startTime'
timeScale = 'timeScale'
pass
__MFB_FULL_PACKAGE_NAME = 'omniAudioSchema'
| 6,388 | unknown | 34.494444 | 133 | 0.651534 |
omniverse-code/kit/exts/omni.rtx.ujitsoprocessors/omni/rtx/ujitsoprocessors/_ujitsoprocessors.pyi | """pybind11 omni.rtx.ujitsoprocessors bindings"""
from __future__ import annotations
import omni.rtx.ujitsoprocessors._ujitsoprocessors
import typing
__all__ = [
"IUJITSOProcessors",
"acquire_ujitsoprocessors_interface",
"release_ujitsoprocessors_interface"
]
class IUJITSOProcessors():
def runHTTPJobs(self, arg0: str, arg1: str) -> str: ...
pass
def acquire_ujitsoprocessors_interface(plugin_name: str = None, library_path: str = None) -> IUJITSOProcessors:
pass
def release_ujitsoprocessors_interface(arg0: IUJITSOProcessors) -> None:
pass
| 574 | unknown | 27.749999 | 111 | 0.736934 |
omniverse-code/kit/exts/omni.rtx.ujitsoprocessors/omni/rtx/ujitsoprocessors/__init__.py | from ._ujitsoprocessors import *
| 33 | Python | 15.999992 | 32 | 0.787879 |
omniverse-code/kit/exts/omni.rtx.ujitsoprocessors/omni/rtx/ujitsoprocessors/tests/__init__.py | from .test_ujitsoprocessors import *
| 37 | Python | 17.999991 | 36 | 0.810811 |
omniverse-code/kit/exts/omni.rtx.ujitsoprocessors/omni/rtx/ujitsoprocessors/tests/test_ujitsoprocessors.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
from omni.kit.test import AsyncTestCase
import pathlib
import omni.rtx.ujitsoprocessors
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent.parent.parent.parent)
except ImportError:
from . import TestRtScenegraph
TestClass = TestRtScenegraph
TEST_DIR = "."
class TestConverter(AsyncTestCase):
async def setUp(self):
self._iface = omni.rtx.ujitsoprocessors.acquire_ujitsoprocessors_interface()
async def tearDown(self):
pass
async def test_001_startstop(self):
print(self._iface.runHTTPJobs("", ""));
| 1,104 | Python | 29.694444 | 91 | 0.744565 |
omniverse-code/kit/exts/omni.kit.window.privacy/omni/kit/window/privacy/__init__.py | from .privacy_window import *
| 30 | Python | 14.499993 | 29 | 0.766667 |
omniverse-code/kit/exts/omni.kit.window.privacy/omni/kit/window/privacy/privacy_window.py | import toml
import os
import asyncio
import weakref
import carb
import carb.settings
import carb.tokens
import omni.client
import omni.kit.app
import omni.kit.ui
import omni.ext
from omni import ui
WINDOW_NAME = "About"
class PrivacyWindow:
def __init__(self, privacy_file=None):
if not privacy_file:
privacy_file = carb.tokens.get_tokens_interface().resolve("${omni_config}/privacy.toml")
privacy_data = toml.load(privacy_file) if os.path.exists(privacy_file) else {}
# NVIDIA Employee?
privacy_dict = privacy_data.get("privacy", {})
userId = privacy_dict.get("userId", None)
if not userId or not userId.endswith("@nvidia.com"):
return
# Already set?
extraDiagnosticDataOptIn = privacy_dict.get("extraDiagnosticDataOptIn", None)
if extraDiagnosticDataOptIn:
return
self._window = ui.Window(
"Privacy",
flags=ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE,
auto_resize=True,
)
def on_ok_clicked():
allow_for_public_build = self._cb.model.as_bool
carb.log_info(f"writing privacy file: '{privacy_file}'. allow_for_public_build: {allow_for_public_build}")
privacy_data.setdefault("privacy", {})["extraDiagnosticDataOptIn"] = (
"externalBuilds" if allow_for_public_build else "internalBuilds"
)
with open(privacy_file, "w") as f:
toml.dump(privacy_data, f)
self._window.visible = False
text = """
By accessing or using Omniverse Beta, you agree to share usage and performance data as well as diagnostic data, including crash data. This will help us to optimize our features, prioritize development, and make positive changes for future development.
As an NVIDIA employee, your email address will be associated with any collected diagnostic data from internal builds to help us improve Omniverse. Below, you can optionally choose to associate your email address with any collected diagnostic data from publicly available builds. Please contact us at [email protected] for any questions.
"""
with self._window.frame:
with ui.ZStack(width=0, height=0):
with ui.VStack(style={"margin": 5}, height=0):
ui.Label(text, width=600, style={"font_size": 18}, word_wrap=True)
ui.Separator()
with ui.HStack(height=0):
self._cb = ui.CheckBox(width=0, height=0)
self._cb.model.set_value(True)
ui.Label(
"Associate my @nvidia.com email address with diagnostic data from publicly available builds.'",
value=True,
style={"font_size": 16},
)
with ui.HStack(height=0):
ui.Spacer()
ui.Button("OK", width=100, clicked_fn=lambda: on_ok_clicked())
ui.Spacer()
self._window.visible = True
self.on_ok_clicked = on_ok_clicked
async def _create_window(ext_weak):
# Wait for few frames to get everything in working state first
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
if ext_weak():
ext_weak()._window = PrivacyWindow()
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
asyncio.ensure_future(_create_window(weakref.ref(self)))
def on_shutdown(self):
self._window = None
| 3,676 | Python | 37.302083 | 359 | 0.606094 |
omniverse-code/kit/exts/omni.kit.window.privacy/omni/kit/window/privacy/tests/__init__.py | from .test_window_privacy import *
| 35 | Python | 16.999992 | 34 | 0.771429 |
omniverse-code/kit/exts/omni.kit.window.privacy/omni/kit/window/privacy/tests/test_window_privacy.py | import tempfile
import toml
import omni.kit.test
import omni.kit.window.privacy
class TestPrivacyWindow(omni.kit.test.AsyncTestCase):
async def test_privacy(self):
with tempfile.TemporaryDirectory() as tmp_dir:
privacy_file = f"{tmp_dir}/privacy.toml"
def write_data(data):
with open(privacy_file, "w") as f:
toml.dump(data, f)
# NVIDIA User, first time
write_data({"privacy": {"userId": "[email protected]"}})
w = omni.kit.window.privacy.PrivacyWindow(privacy_file)
self.assertIsNotNone(w._window)
w.on_ok_clicked()
data = toml.load(privacy_file)
self.assertEqual(data["privacy"]["extraDiagnosticDataOptIn"], "externalBuilds")
# NVIDIA User, second time
w = omni.kit.window.privacy.PrivacyWindow(privacy_file)
self.assertFalse(hasattr(w, "_window"))
# NVIDIA User, first time, checkbox off
write_data({"privacy": {"userId": "[email protected]"}})
w = omni.kit.window.privacy.PrivacyWindow(privacy_file)
self.assertIsNotNone(w._window)
w._cb.model.set_value(False)
w.on_ok_clicked()
data = toml.load(privacy_file)
self.assertEqual(data["privacy"]["extraDiagnosticDataOptIn"], "internalBuilds")
# Non NVIDIA User
write_data({"privacy": {"userId": "[email protected]"}})
w = omni.kit.window.privacy.PrivacyWindow(privacy_file)
self.assertFalse(hasattr(w, "_window"))
| 1,602 | Python | 34.622221 | 91 | 0.591136 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/ext_utils.py | from __future__ import annotations
from collections import defaultdict
from contextlib import suppress
from types import ModuleType
from typing import Dict, Tuple
import fnmatch
import sys
import unittest
import carb
import omni.kit.app
from .unittests import get_tests_to_remove_from_modules
# Type for collecting module information corresponding to extensions
ModuleMap_t = Dict[str, Tuple[str, bool]]
# ==============================================================================================================
def get_module_to_extension_map() -> ModuleMap_t:
"""Returns a dictionary mapping the names of Python modules in an extension to (OwningExtension, EnabledState)
e.g. for this extension it would contain {"omni.kit.test": (["omni.kit.test", True])}
It will be expanded to include the implicit test modules added by the test management.
"""
module_map = {}
manager = omni.kit.app.get_app().get_extension_manager()
for extension in manager.fetch_extension_summaries():
ext_id = None
enabled = False
with suppress(KeyError):
if extension["enabled_version"]["enabled"]:
ext_id = extension["enabled_version"]["id"]
enabled = True
if ext_id is None:
try:
ext_id = extension["latest_version"]["id"]
except KeyError:
# Silently skip any extensions that do not have enough information to identify them
continue
ext_dict = manager.get_extension_dict(ext_id)
# Look for the defined Python modules, skipping processing of any extensions that have no Python modules
try:
module_list = ext_dict["python"]["module"]
except (KeyError, TypeError):
continue
# Walk through the list of all modules independently as there is no guarantee they are related.
for module in module_list:
# Some modules do not have names, only paths - just ignore them
with suppress(KeyError):
module_map[module["name"]] = (ext_id, enabled)
# Add the two test modules that are explicitly added by the testing system
if not module["name"].endswith(".tests"):
module_map[module["name"] + ".tests"] = (ext_id, enabled)
module_map[module["name"] + ".ogn.tests"] = (ext_id, enabled)
return module_map
# ==============================================================================================================
def extension_from_test_name(test_name: str, module_map: ModuleMap_t) -> tuple[str, bool, str, bool] | None:
"""Given a test name, return None if the extension couldn't be inferred from the name, otherwise a tuple
containing the name of the owning extension, a boolean indicating if it is currently enabled, a string
indicating in which Python module the test was found, and a boolean indicating if that module is currently
imported, or None if it was not.
Args:
test_name: Full name of the test to look up
module_map: Module to extension mapping. Passed in for sharing as it's expensive to compute.
The algorithm walks backwards from the full name to find the maximum-length Python import module known to be
part of an extension that is part of the test name. It does this because the exact import paths can be nested or
not nested. e.g. omni.kit.window.tests is not part of omni.kit.window
Extracting the extension from the test name is a little tricky but all of the information is available. Here is
how it attempts to decompose a sample test name
.. code-block:: text
omni.graph.nodes.tests.tests_for_samples.TestsForSamples.test_for_sample
+--------------+ +---+ +---------------+ +-------------+ +-------------+
Import path | | | |
Testing subdirectory | |
| | |
Test File Test Class Test Name
Each extension has a list of import paths of Python modules it explicitly defines, and in addition it will add
implicit imports for .tests and .ogn.tests submodules that are not explicitly listed in the extension dictionary.
With this structure the user could have done any of these imports:
.. code-block:: python
import omni.graph.nodes
import omni.graph.nodes.tests
import omni.graph.nodes.test_for_samples
Each nested one may or may not have been exposed by the parent so it is important to do a greedy match.
This is how the process of decoding works for this test:
.. code-block:: text
Split the test name on "."
["omni", "graph", "nodes", "tests", "tests_for_samples", "TestsForSamples", "test_for_sample"]
Starting at the entire list, recursively remove one element until a match in the module dictionary is found
Fail: "omni.graph.nodes.tests.tests_for_samples.TestsForSamples.test_for_sample"
Fail: "omni.graph.nodes.tests.tests_for_samples.TestsForSamples"
Fail: "omni.graph.nodes.tests.tests_for_samples"
Succeed: "omni.graph.nodes.tests"
If no success, of if sys.modules does not contain the found module:
Return the extension id, enabled state, and None for the module
Else:
Check the module recursively for exposed attributes with the rest of the names. In this example:
file_object = getattr(module, "tests_for_samples")
class_object = getattr(file_object, "TestsForSamples")
test_object = getattr(class_object, "test_for_sample")
If test_object is valid:
Return the extension id, enabled state, and the found module
Else:
Return the extension id, enabled state, and None for the module
"""
class_elements = test_name.split(".")
for el in range(len(class_elements), 0, -1):
check_module = ".".join(class_elements[:el])
# If the extension owned the module then process it, otherwise continue up to the parent element
try:
(ext_id, is_enabled) = module_map[check_module]
except KeyError:
continue
# The module was found in an extension definition but not imported into the Python namespace yet
try:
module = sys.modules[check_module]
except KeyError:
return (ext_id, is_enabled, check_module, False)
# This checks to make sure that the actual test is registered in the module that was found.
# e.g. if the full name is omni.graph.nodes.tests.TestStuff.test_stuff then we would expect to find
# a module named "omni.graph.nodes.tests" that contains "TestStuff", and the object "TestStuff" will
# in turn contain "test_stuff".
sub_module = module
for elem in class_elements[el:]:
sub_module = getattr(sub_module, elem, None)
if sub_module is None:
break
return (ext_id, is_enabled, module, sub_module is not None)
return None
# ==============================================================================================================
def test_only_extension_dependencies(ext_id: str) -> set[str]:
"""Returns a set of extensions with test-only dependencies on the given one.
Not currently used as dynamically enabling random extensions is not stable enough to use here yet.
"""
test_only_extensions = set() # Set of extensions that are enabled only in testing mode
manager = omni.kit.app.get_app().get_extension_manager()
ext_dict = manager.get_extension_dict(ext_id)
# Find the test-only dependencies that may also not be enabled yet
if ext_dict and "test" in ext_dict:
for test_info in ext_dict["test"]:
try:
new_extensions = test_info["dependencies"]
except (KeyError, TypeError):
new_extensions = []
for new_extension in new_extensions:
with suppress(KeyError):
test_only_extensions.add(new_extension)
return test_only_extensions
# ==============================================================================================================
def decompose_test_list(
test_list: list[str]
) -> tuple[list[unittest.TestCase], set[str], set[str], defaultdict[str, set[str]]]:
"""Read in the given log file and return the list of tests that were run, in the order in which they were run.
TODO: Move this outside the core omni.kit.test area as it requires external knowledge
If any modules containing the tests in the log are not currently available then they are reported for the user
to intervene and most likely enable the owning extensions.
Args:
test_list: List of tests to decompose and find modules and extensions for
Returns:
Tuple of (tests, not_found, extensions, modules) gleaned from the log file
tests: List of unittest.TestCase for all tests named in the log file, in the order they appeared
not_found: Name of tests whose location could not be determined, or that did not exist
extensions: Name of extensions containing modules that look like they contain tests from "not_found"
modules: Map of extension to list of modules where the extension is enabled but the module potentially
containing the tests from "not_found" has not been imported.
"""
module_map = get_module_to_extension_map()
not_found = set() # The set of full names of tests whose module was not found
# Map of enabled extensions to modules in them that contain tests in the log but which are not imported
modules_not_imported = defaultdict(set)
test_names = []
modules_found = set() # Modules matching the tests
extensions_to_enable = set()
# Walk the test list and parse out all of the test run information
for test_name in test_list:
test_info = extension_from_test_name(test_name, module_map)
if test_info is None:
not_found.add(test_name)
else:
(ext_id, ext_enabled, module, module_imported) = test_info
if ext_enabled:
if module is None:
not_found.add(test_name)
elif not module_imported:
modules_not_imported[ext_id].add(module)
else:
test_names.append(test_name)
modules_found.add(module)
else:
extensions_to_enable.add(ext_id)
# Carefully find all of the desired test cases, preserving the order in which they were encountered since that is
# a key feature of reading tests from a log
test_mapping: dict[str, unittest.TestCase] = {} # Mapping of test name onto discovered test case for running
for module in modules_found:
# Find all of the individual tests in the TestCase classes and add those that match any of the disabled patterns
# Uses get_tests_to_remove_from_modules because it considers possible tests and ogn.tests submodules
test_cases = get_tests_to_remove_from_modules([module])
for test_case in test_cases:
if test_case.id() in test_names:
test_mapping[test_case.id()] = test_case
tests: list[unittest.TestCase] = []
for test_name in test_names:
if test_name in test_mapping:
tests.append(test_mapping[test_name])
return (tests, not_found, extensions_to_enable, modules_not_imported)
# ==============================================================================================================
def find_disabled_tests() -> list[unittest.TestCase]:
"""Scan the existing tests and the extension.toml to find all tests that are currently disabled"""
manager = omni.kit.app.get_app().get_extension_manager()
# Find the per-extension list of (python_modules, disabled_patterns).
def __get_disabled_patterns() -> list[tuple[list[ModuleType], list[str]]]:
disabled_patterns = []
summaries = manager.fetch_extension_summaries()
for extension in summaries:
try:
if not extension["enabled_version"]["enabled"]:
continue
except KeyError:
carb.log_info(f"Could not find enabled state of extension {extension}")
continue
ext_id = extension["enabled_version"]["id"]
ext_dict = manager.get_extension_dict(ext_id)
# Look for the defined Python modules
modules = []
with suppress(KeyError, TypeError):
modules += [sys.modules[module_info["name"]] for module_info in ext_dict["python"]["module"]]
# Look for unreliable tests
regex_list = []
with suppress(KeyError, TypeError):
test_info = ext_dict["test"]
for test_details in test_info or []:
with suppress(KeyError):
regex_list += test_details["pythonTests"]["unreliable"]
if regex_list:
disabled_patterns.append((modules, regex_list))
return disabled_patterns
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def _match(to_match: str, pattern: str) -> bool:
"""Match that supports wildcards and '!' to invert it"""
should_match = True
if pattern.startswith("!"):
pattern = pattern[1:]
should_match = False
return should_match == fnmatch.fnmatch(to_match, pattern)
tests = []
for modules, regex_list in __get_disabled_patterns():
# Find all of the individual tests in the TestCase classes and add those that match any of the disabled patterns
# Uses get_tests_to_remove_from_modules because it considers possible tests and ogn.tests submodules
test_cases = get_tests_to_remove_from_modules(modules)
for test_case in test_cases:
for regex in regex_list:
if _match(test_case.id(), regex):
tests.append(test_case)
break
return tests
| 14,477 | Python | 46.782178 | 120 | 0.60344 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/ext_test_generator.py | # WARNING: This file/interface is likely to be removed after transition from Legacy Viewport is complete.
# Seee merge_requests/17255
__all__ = ["get_tests_to_run"]
# Rewrite a Legacy Viewport test to launch with Viewport backend only
def _get_viewport_next_test_config(test):
# Check for flag to run test only on legacy Viewport
if test.config.get("viewport_legacy_only", False):
return None
# Get the test dependencies
test_dependencies = test.config.get("dependencies", tuple())
# Check if legacy Viewport is in the test dependency list
if "omni.kit.window.viewport" not in test_dependencies:
return None
# Deep copy the config dependencies
test_dependencies = list(test_dependencies)
# Re-write any 'omni.kit.window.viewport' dependency as 'omni.kit.viewport.window'
for i in range(len(test_dependencies)):
cur_dep = test_dependencies[i]
if cur_dep == "omni.kit.window.viewport":
test_dependencies[i] = "omni.kit.viewport.window"
# Shallow copy of the config
test_config = test.config.copy()
# set the config name
test_config["name"] = "viewport_next"
# Replace the dependencies
test_config["dependencies"] = test_dependencies
# Add any additional args by deep copying the arg list
test_args = list(test.config.get("args", tuple()))
test_args.append("--/exts/omni.kit.viewport.window/startup/windowName=Viewport")
# Replace the args
test_config["args"] = test_args
# TODO: Error if legacy Viewport somehow still inserting itself into the test run
# Return the new config
return test_config
def get_tests_to_run(test, ExtTest, run_context, is_parallel_run: bool, valid: bool):
"""For a test gather all unique test-runs that should be invoked"""
# First run the additional tests, followed by the original / base-case
# No need to run additional tests of the original is not valid
if valid:
# Currently the only usage of this method is to have legacy Viewport test run against new Viewport
additional_tests = {
'viewport_next': _get_viewport_next_test_config
}
for test_name, get_config in additional_tests.items():
new_config = get_config(test)
if new_config:
yield ExtTest(
ext_id=test.ext_id,
ext_info=test.ext_info,
test_config=new_config,
test_id=f"{test.test_id}-{test_name}",
is_parallel_run=is_parallel_run,
run_context=run_context,
test_app=test.test_app,
valid=valid
)
# Run the original / base-case
yield test
| 2,762 | Python | 35.84 | 106 | 0.640116 |
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/teamcity.py | import os
import sys
import time
import pathlib
from functools import lru_cache
_quote = {"'": "|'", "|": "||", "\n": "|n", "\r": "|r", "[": "|[", "]": "|]"}
def escape_value(value):
return "".join(_quote.get(x, x) for x in value)
@lru_cache()
def is_running_in_teamcity():
return bool(os.getenv("TEAMCITY_VERSION"))
@lru_cache()
def get_teamcity_build_url() -> str:
teamcity_url = os.getenv("TEAMCITY_BUILD_URL")
if teamcity_url and not teamcity_url.startswith("http"):
teamcity_url = "https://" + teamcity_url
return teamcity_url or ""
# TeamCity Service messages documentation
# https://www.jetbrains.com/help/teamcity/service-messages.html
def teamcity_publish_artifact(artifact_path: str, stream=sys.stdout):
if not is_running_in_teamcity():
return
tc_message = f"##teamcity[publishArtifacts '{escape_value(artifact_path)}']\n"
stream.write(tc_message)
stream.flush()
def teamcity_log_fail(teamCityName, msg, stream=sys.stdout):
if not is_running_in_teamcity():
return
tc_message = f"##teamcity[testFailed name='{teamCityName}' message='{teamCityName} failed. Reason {msg}. Check artifacts for logs']\n"
stream.write(tc_message)
stream.flush()
def teamcity_test_retry_support(enabled: bool, stream=sys.stdout):
"""
With this option enabled, the successful run of a test will mute its previous failure,
which means that TeamCity will mute a test if it fails and then succeeds within the same build.
Such tests will not affect the build status.
"""
if not is_running_in_teamcity():
return
retry_support = str(bool(enabled)).lower()
tc_message = f"##teamcity[testRetrySupport enabled='{retry_support}']\n"
stream.write(tc_message)
stream.flush()
def teamcity_show_image(label: str, image_path: str, stream=sys.stdout):
if not is_running_in_teamcity():
return
tc_message = f"##teamcity[testMetadata type='image' name='{label}' value='{image_path}']\n"
stream.write(tc_message)
stream.flush()
def teamcity_publish_image_artifact(src_path: str, dest_path: str, inline_image_label: str = None, stream=sys.stdout):
if not is_running_in_teamcity():
return
tc_message = f"##teamcity[publishArtifacts '{src_path} => {dest_path}']\n"
stream.write(tc_message)
if inline_image_label:
result_path = str(pathlib.PurePath(dest_path).joinpath(os.path.basename(src_path)).as_posix())
teamcity_show_image(inline_image_label, result_path)
stream.flush()
def teamcity_message(message_name, stream=sys.stdout, **properties):
if not is_running_in_teamcity():
return
current_time = time.time()
(current_time_int, current_time_fraction) = divmod(current_time, 1)
current_time_struct = time.localtime(current_time_int)
timestamp = time.strftime("%Y-%m-%dT%H:%M:%S.", current_time_struct) + "%03d" % (int(current_time_fraction * 1000))
message = "##teamcity[%s timestamp='%s'" % (message_name, timestamp)
for k in sorted(properties.keys()):
value = properties[k]
if value is None:
continue
message += f" {k}='{escape_value(str(value))}'"
message += "]\n"
# Python may buffer it for a long time, flushing helps to see real-time result
stream.write(message)
stream.flush()
# Based on metadata message for TC:
# https://www.jetbrains.com/help/teamcity/reporting-test-metadata.html#Reporting+Additional+Test+Data
def teamcity_metadata_message(metadata_value, stream=sys.stdout, metadata_name="", metadata_testname=""):
teamcity_message(
"testMetadata",
stream=stream,
testName=metadata_testname,
name=metadata_name,
value=metadata_value,
)
def teamcity_status(text, status: str = "success", stream=sys.stdout):
teamcity_message("buildStatus", stream=stream, text=text, status=status)
| 3,924 | Python | 30.910569 | 138 | 0.667686 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.