file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/reload_widget.py | __all__ = ["build_reload_widget"]
import carb
import omni.usd
import omni.kit.app
import omni.ui as ui
import omni.kit.usd.layers as layers
import weakref
from functools import partial
from typing import Union
from .live_style import Styles
from .layer_icons import LayerIcons
from .utils import reload_outdated_layers
from omni.kit.async_engine import run_coroutine
class ReloadWidgetWrapper(ui.ZStack):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.auto_reload_menu = None
def __del__(self):
if self.auto_reload_menu:
self.auto_reload_menu.hide()
self.auto_reload_menu = None
def show_reload_menu(layer_identifier, usd_context, widget, button, global_auto):
"""Creates and shows a reload menu relative to widget position"""
layers_state = layers.get_layers_state(usd_context)
live_syncing = layers.get_live_syncing()
is_outdated = layers_state.is_layer_outdated(layer_identifier)
in_session = live_syncing.is_layer_in_live_session(layer_identifier)
def toggle_auto_reload(layer_identifier, widget):
async def toggle(layer_identifier):
is_auto = layers_state.is_auto_reload_layer(layer_identifier)
if not is_auto:
layers_state.add_auto_reload_layer(layer_identifier)
widget.set_style(Styles.RELOAD_AUTO)
button.tooltip = "Auto Reload Enabled"
else:
layers_state.remove_auto_reload_layer(layer_identifier)
widget.set_style(Styles.RELOAD_BTN)
button.tooltip = "Reload"
run_coroutine(toggle(layer_identifier))
def reload_layer(layer_identifier):
reload_outdated_layers(layer_identifier, layers_state._usd_context)
auto_reload_menu = ui.Menu("auto_reload_menu")
with auto_reload_menu:
ui.MenuItem(
"Reload Layer",
triggered_fn=lambda *args: reload_layer(layer_identifier),
enabled=is_outdated,
visible=not global_auto
)
ui.MenuItem(
"Auto Reload",
triggered_fn=lambda *args: toggle_auto_reload(layer_identifier, widget),
checkable=True,
checked=layers_state.is_auto_reload_layer(layer_identifier),
visible=not global_auto,
enabled=not in_session
)
_x = widget.screen_position_x
_y = widget.screen_position_y
_h = widget.computed_height
auto_reload_menu.show_at(_x - 95, _y + _h / 2 + 2)
return auto_reload_menu
def build_reload_widget(
layer_identifier: str,
usd_context_name_or_instance: Union[str, omni.usd.UsdContext] = None,
is_outdated=False,
is_auto=False,
global_auto=False
) -> None:
"""Builds reload widget."""
if isinstance(usd_context_name_or_instance, str):
usd_context = omni.usd.get_context(usd_context_name_or_instance)
elif isinstance(usd_context_name_or_instance, omni.usd.UsdContext):
usd_context = usd_context_name_or_instance
elif not usd_context_name_or_instance:
usd_context = omni.usd.get_context()
if not usd_context:
carb.log_error("Failed to reload layer as usd context is not invalid.")
return
reload_stack = ReloadWidgetWrapper(width=0, height=0)
if global_auto:
is_auto = global_auto
reload_stack.name = "reload-auto" if is_auto else "reload-outd" if is_outdated else "reload"
reload_stack.set_style(Styles.RELOAD_AUTO if is_auto and not is_outdated else Styles.RELOAD_OTD if is_outdated else Styles.RELOAD_BTN)
with reload_stack:
with ui.VStack(width=0, height=0):
ui.Spacer(width=22, height=12)
with ui.HStack(width=0):
ui.Spacer(width=16)
ui.Image(
LayerIcons.get("drop_down"),
width=6, height=6, alignment=ui.Alignment.RIGHT_BOTTOM,
name="drop_down"
)
ui.Image(LayerIcons.get("reload"), width=20, name="reload")
tooltip = "Auto Reload All Enabled" if global_auto else "Auto Reload Enabled" if is_auto else "Reload"
if is_outdated:
tooltip = "Reload Outdated"
reload_button = ui.InvisibleButton(width=20, tooltip=tooltip)
def on_reload_clicked(layout_weakref, x, y, b, m):
if (b == 0):
reload_outdated_layers(layer_identifier, usd_context)
return
auto_reload_menu = show_reload_menu(layer_identifier, usd_context, reload_stack, reload_button, global_auto)
if layout_weakref():
# Hold the menu handle to release it along with the stack.
layout_weakref().auto_reload_menu = auto_reload_menu
layout_weakref = weakref.ref(reload_stack)
reload_button.set_mouse_pressed_fn(partial(on_reload_clicked, layout_weakref))
return reload_stack
| 4,919 | Python | 34.142857 | 138 | 0.639561 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_start_window.py | import asyncio
import carb
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.ui as ui
import re
from .layer_icons import LayerIcons
from .utils import join_live_session, is_viewer_only_mode, get_session_list_select, SESSION_LIST_SELECT_DEFAULT_SESSION
from omni.kit.widget.prompt import PromptButtonInfo, PromptManager
from pxr import Sdf
from .live_session_model import LiveSessionModel
class LiveSessionStartWindow:
def __init__(self, layers_interface: layers.Layers, layer_identifier, prim_path):
self._window = None
self._layers_interface = layers_interface
self._base_layer_identifier = layer_identifier
self._live_prim_path = prim_path
self._buttons = []
self._existing_sessions_combo = None
self._session_name_input_field = None
self._session_name_input_hint = None
self._error_label = None
self._session_name_begin_edit_cb = None
self._session_name_end_edit_cb = None
self._session_name_edit_cb = None
self._existing_sessions_model = LiveSessionModel(self._layers_interface, layer_identifier)
self._participants_list = None
self._participants_layout = None
self._existing_sessions_model.set_user_update_callback(self._on_channel_users_update)
self._existing_sessions_model.add_value_changed(self._on_session_list_changed)
self._update_user_list_task: asyncio.Future = None
self._join_create_radios = None
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def _on_layer_event(event: carb.events.IEvent):
payload = layers.get_layer_event_payload(event)
if payload.event_type == layers.LayerEventType.LIVE_SESSION_LIST_CHANGED:
if self._base_layer_identifier not in payload.identifiers_or_spec_paths:
return
self._existing_sessions_model.refresh_sessions(force=True)
self._update_dialog_states()
self._layers_event_subscription = layers_interface.get_event_stream().create_subscription_to_pop(
_on_layer_event, name="Session Start Window Events"
)
def destroy(self):
self._layers_interface = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
self._participants_list = None
if self._window:
self._window.visible = False
self._window = None
if self._existing_sessions_model:
self._existing_sessions_model.set_user_update_callback(None)
self._existing_sessions_model.destroy()
self._existing_sessions_model = None
self._participants_layout = None
self._layers_event_subscription = None
self._existing_sessions_combo = None
self._existing_sessions_empty_hint = None
self._join_create_radios = None
self._session_name_input_hint = None
self._session_name_input_field = None
self._session_name_begin_edit_cb = None
self._session_name_end_edit_cb = None
self._session_name_edit_cb = None
self._error_label = None
if self._update_user_list_task:
try:
self._update_user_list_task.cancel()
except Exception:
pass
self._update_user_list_task = None
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
if not self._window.visible:
if self._update_user_list_task:
try:
self._update_user_list_task.cancel()
except Exception:
pass
self._update_user_list_task = None
self._existing_sessions_model.stop_channel()
def set_focus(self, join_session):
if not self._join_create_radios:
return
if join_session:
self._join_create_radios.model.set_value(0)
if get_session_list_select() == SESSION_LIST_SELECT_DEFAULT_SESSION:
self._existing_sessions_model.select_default_session()
else:
self._join_create_radios.model.set_value(1)
async def async_focus_keyboard():
await omni.kit.app.get_app().next_update_async()
self._session_name_input_field.focus_keyboard()
omni.kit.async_engine.run_coroutine(async_focus_keyboard())
def _on_channel_users_update(self):
async def _update_users():
all_users = self._existing_sessions_model.all_users
current_session = self._existing_sessions_model.current_session
if not current_session:
return
self._participants_list.clear()
with self._participants_list:
if len(all_users) > 0:
for _, user in all_users.items():
is_owner = current_session.owner == user.user_name
with ui.VStack(height=0):
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=10)
if is_owner:
ui.Label(f"{user.user_name} - {user.from_app} (owner)", style={"color": 0xFF808080})
else:
ui.Label(f"{user.user_name} - {user.from_app}", style={"color": 0xFF808080})
else:
self._build_empty_participants_list()
if not self._update_user_list_task or self._update_user_list_task.done():
self._update_user_list_task = asyncio.ensure_future(_update_users())
def _validate_session_name(self, str):
if re.match(r'^[a-zA-Z][a-zA-Z0-9-_]*$', str):
return True
return False
def _on_join_session(self, current_session):
layer_identifier = self._base_layer_identifier
layers_interface = self._layers_interface
prim_path = self._live_prim_path
return join_live_session(
layers_interface, layer_identifier, current_session, prim_path, is_viewer_only_mode()
)
def _on_ok_button_fn(self): # pragma: no cover
live_syncing = self._layers_interface.get_live_syncing()
current_option = self._join_create_radios.model.as_int
join_session = current_option == 0
if join_session:
current_session = self._existing_sessions_model.current_session
if not current_session:
self._error_label.text = "No Valid Session Selected"
self._error_label.visible = True
elif self._on_join_session(current_session):
self._error_label.text = ""
self._error_label.visible = False
self.visible = False
else:
self._error_label.text = "Failed to join session, please check console for more details."
self._error_label.visible = True
else:
session_name = self._session_name_input_field.model.get_value_as_string()
session_name = session_name.strip()
if not session_name or not self._validate_session_name(session_name):
self._update_button_status(session_name)
self._error_label.text = "Session name must be given."
self._error_label.visible = True
else:
session = live_syncing.create_live_session(layer_identifier=self._base_layer_identifier, name=session_name)
if not session:
self._error_label.text = "Failed to create session, please check console for more details."
self._error_label.visible = True
elif not self._on_join_session(session):
self._error_label.text = "Failed to join session, please check console for more details."
self._error_label.visible = True
else:
self._error_label.text = ""
self._error_label.visible = False
self.visible = False
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _build_option_checkbox(self, name, text, default_value, tooltip=""): # pragma: no cover
with ui.HStack(height=0, width=0):
checkbox = ui.CheckBox(width=20, name=name)
checkbox.model.set_value(default_value)
label = ui.Label(text, alignment=ui.Alignment.LEFT)
if tooltip:
label.set_tooltip(tooltip)
return checkbox, label
def _build_option_radio(self, collection, name, text, tooltip=""):
style = {
"": {"background_color": 0x0, "image_url": LayerIcons.get("radio_off")},
":checked": {"image_url": LayerIcons.get("radio_on")},
}
with ui.HStack(height=0, width=0):
radio = ui.RadioButton(radio_collection=collection, width=28, height=28, name=name, style=style)
ui.Spacer(width=4)
label = ui.Label(text, alignment=ui.Alignment.LEFT_CENTER)
if tooltip:
label.set_tooltip(tooltip)
return radio
def _update_button_status(self, session_name):
join_button = self._buttons[0]
if session_name and not self._validate_session_name(session_name):
if not str.isalpha(session_name[0]):
self._error_label.text = "Session name must be prefixed with letters."
else:
self._error_label.text = "Only alphanumeric letters, hyphens, or underscores are supported."
self._error_label.visible = True
join_button.enabled = False
else:
self._error_label.text = ""
self._error_label.visible = False
join_button.enabled = True
def _on_session_name_begin_edit(self, model):
self._session_name_input_hint.visible = False
session_name = model.get_value_as_string().strip()
self._update_button_status(session_name)
def _on_session_name_end_edit(self, model):
if len(model.get_value_as_string()) == 0:
self._session_name_input_hint.visible = True
session_name = model.get_value_as_string().strip()
self._update_button_status(session_name)
def _on_session_name_edit(self, model):
session_name = model.get_value_as_string().strip()
self._update_button_status(session_name)
def _update_dialog_states(self):
self._error_label.text = ""
current_option = self._join_create_radios.model.as_int
show_join_session = current_option == 0
join_button = self._buttons[0]
if show_join_session:
self._existing_sessions_combo.visible = True
self._session_name_input_field.visible = False
self._session_name_input_hint.visible = False
self._participants_layout.visible = True
self._existing_sessions_model.refresh_sessions()
if self._existing_sessions_model.empty():
self._existing_sessions_empty_hint.visible = True
else:
self._existing_sessions_empty_hint.visible = False
join_button.text = "JOIN"
else:
self._participants_layout.visible = False
self._existing_sessions_combo.visible = False
self._session_name_input_field.visible = True
self._session_name_input_hint.visible = False
self._existing_sessions_empty_hint.visible = False
self._existing_sessions_model.clear()
join_button.text = "CREATE"
new_session_name = self._existing_sessions_model.create_new_session_name()
self._session_name_input_field.model.set_value(new_session_name)
self._session_name_input_field.focus_keyboard()
def _on_radios_changed_fn(self, model):
self._update_dialog_states()
self._on_checkbox_changed_called = False
def _on_session_list_changed(self, model):
if self._participants_list:
self._participants_list.clear()
def _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window("Live Session", visible=False, height=0, auto_resize=True, dockPreference=ui.DockPreference.DISABLED)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
self._existing_sessions_model.refresh_sessions()
empty_sessions = self._existing_sessions_model.empty()
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
self._join_create_radios = ui.RadioCollection()
self._build_option_radio(self._join_create_radios, "join_session_radio_button", "Join Session")
ui.Spacer(width=20)
self._build_option_radio(self._join_create_radios, "create_session_radio_button", "Create Session")
ui.Spacer()
self._join_create_radios.model.add_value_changed_fn(lambda _: self._update_dialog_states())
ui.Spacer(width=0, height=15)
with ui.HStack(height=0):
ui.Spacer(width=20)
self._error_label = ui.Label("", name="error_label", style={"color": 0xFF0000CC}, alignment=ui.Alignment.LEFT, word_wrap=True)
ui.Spacer(width=20)
ui.Spacer(width=0, height=5)
with ui.ZStack(height=0):
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(height=0):
self._session_name_input_field = ui.StringField(
name="new_session_name_field", width=self._window.width - 40, height=0
)
self._session_name_input_hint = ui.Label(
" New Session Name", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F}
)
self._session_name_begin_edit_cb = self._session_name_input_field.model.subscribe_begin_edit_fn(
self._on_session_name_begin_edit
)
self._session_name_end_edit_cb = self._session_name_input_field.model.subscribe_end_edit_fn(
self._on_session_name_end_edit
)
self._session_name_edit_cb = self._session_name_input_field.model.subscribe_value_changed_fn(
self._on_session_name_edit
)
ui.Spacer(width=20)
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(height=0):
self._existing_sessions_combo = ui.ComboBox(
self._existing_sessions_model, width=self._window.width - 40, height=0
)
self._existing_sessions_empty_hint = ui.Label(
" No Existing Sessions", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F}
)
ui.Spacer(width=20)
ui.Spacer(width=0, height=10)
self._participants_layout = ui.VStack(height=0)
with self._participants_layout:
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.VStack(height=0, width=0):
with ui.HStack(height=0, width=0):
ui.Label("Participants: ", alignment=ui.Alignment.CENTER)
with ui.HStack():
ui.Spacer()
ui.Image(LayerIcons.get("participants"), width=28, height=28)
ui.Spacer()
ui.Spacer(width=0, height=5)
with ui.HStack(height=0):
with ui.ScrollingFrame(height=120, style={"background_color": 0xFF24211F}):
self._participants_list = ui.VStack(height=0)
with self._participants_list:
self._build_empty_participants_list()
ui.Spacer(width=20)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer(height=0)
ok_button = ui.Button("JOIN", name="confirm_button", width=120, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
cancel_button = ui.Button("CANCEL", name="cancel_button", width=120, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(ok_button)
self._buttons.append(cancel_button)
ui.Spacer(height=0, width=20)
ui.Spacer(width=0, height=20)
if empty_sessions:
self._join_create_radios.model.set_value(1)
else:
self._update_dialog_states()
def _build_empty_participants_list(self):
with ui.VStack(height=0):
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=10)
ui.Label("No users currently in session.", style={"color": 0xFF808080})
| 18,527 | Python | 44.635468 | 146 | 0.559454 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_end_window.py | import carb
import asyncio
import omni.ui as ui
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.kit.notification_manager as nm
from omni.kit.widget.prompt import PromptManager
from pxr import Sdf
from .file_picker import FilePicker, FileBrowserMode, FileBrowserSelectionType
class LiveSessionEndWindow:
def __init__(self, layers_interface: layers.Layers, layer_identifier):
self._window = None
self._live_syncing = layers_interface.get_live_syncing()
self._base_layer_identifier = layer_identifier
self._buttons = []
self._options_combo = None
self._file_picker = None
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def destroy(self):
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
if self._window:
self._window.visible = False
self._window = None
self._options_combo = None
if self._file_picker:
self._file_picker.destroy()
self._file_picker = None
async def __aenter__(self):
await self._live_syncing.broadcast_merge_started_message_async(self._base_layer_identifier)
self.visible = True
# Wait until dialog disappears
while self.visible:
await asyncio.sleep(0.1)
async def __aexit__(self, exc_type, exc, tb):
self.visible = False
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
def _on_ok_button_fn(self):
self.visible = False
if not self._live_syncing.is_layer_in_live_session(self._base_layer_identifier):
return
prompt = None
async def pre_merge(current_session):
nonlocal prompt
app = omni.kit.app.get_app()
await app.next_update_async()
await app.next_update_async()
prompt = PromptManager.post_simple_prompt(
"Merging",
"Merging live layers into base layers...",
None,
shortcut_keys=False
)
async def post_merge(success):
nonlocal prompt
if prompt:
prompt.destroy()
prompt = None
if success:
await self._live_syncing.broadcast_merge_done_message_async(
layer_identifier=self._base_layer_identifier
)
current_session = self._live_syncing.get_current_live_session(self._base_layer_identifier)
comment = self._description_field.model.get_value_as_string()
option = self._options_combo.model.get_item_value_model().as_int
if option == 1:
def save_model(file_path: str, overwrite_existing: bool):
layer = Sdf.Layer.FindOrOpen(file_path)
if not layer:
layer = Sdf.Layer.CreateNew(file_path)
if not layer:
error = f"Failed to save live changes to layer {file_path} as it's not writable."
carb.log_error(error)
nm.post_notification(error, status=nm.NotificationStatus.WARNING)
return
asyncio.ensure_future(
self._live_syncing.merge_and_stop_live_session_async(
file_path, comment, pre_merge=pre_merge, post_merge=post_merge,
layer_identifier=self._base_layer_identifier
)
)
usd_context = self._live_syncing.usd_context
stage = usd_context.get_stage()
root_layer_identifier = stage.GetRootLayer().identifier
root_layer_name = current_session.name
self._show_file_picker(save_model, root_layer_identifier, root_layer_name)
elif option == 0:
asyncio.ensure_future(
self._live_syncing.merge_and_stop_live_session_async(
comment=comment, pre_merge=pre_merge, post_merge=post_merge,
layer_identifier=self._base_layer_identifier
)
)
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _create_file_picker(self):
filter_options = [
(r"^(?=.*.usd$)((?!.*\.(sublayer)\.usd).)*$", "USD File (*.usd)"),
(r"^(?=.*.usda$)((?!.*\.(sublayer)\.usda).)*$", "USDA File (*.usda)"),
(r"^(?=.*.usdc$)((?!.*\.(sublayer)\.usdc).)*$", "USDC File (*.usdc)"),
("(.*?)", "All Files (*.*)"),
]
layer_file_picker = FilePicker(
"Save Live Changes",
FileBrowserMode.SAVE,
FileBrowserSelectionType.FILE_ONLY,
filter_options,
[".usd", ".usda", ".usdc", ".usd"],
)
return layer_file_picker
def _show_file_picker(self, file_handler, default_location=None, default_filename=None):
if not self._file_picker:
self._file_picker = self._create_file_picker()
self._file_picker.set_file_selected_fn(file_handler)
self._file_picker.show(default_location, default_filename)
def _on_description_begin_edit(self, model):
self._description_field_hint_label.visible = False
def _on_description_end_edit(self, model):
if len(model.get_value_as_string()) == 0:
self._description_field_hint_label.visible = True
def _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window("Merge Options", visible=False, height=0, dockPreference=ui.DockPreference.DISABLED)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
current_session = self._live_syncing.get_current_live_session(self._base_layer_identifier)
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
ui.Label(
"Live Session is ending.", word_wrap=True, alignment=ui.Alignment.CENTER, width=self._window.width - 80, height=0
)
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Label(
f"How do you want to merge changes from '{current_session.name}' session?",
alignment=ui.Alignment.CENTER, word_wrap=True, width=self._window.width - 80, height=0
)
ui.Spacer()
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
self._options_combo = ui.ComboBox(
0, "Merge to corresponding layers", "Merge to a new layer",
word_wrap=True, width=self._window.width - 80, height=0
)
ui.Spacer()
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(width=40)
self._checkpoint_comment_frame = ui.Frame()
with self._checkpoint_comment_frame:
with ui.VStack(height=0, spacing=5):
ui.Label("Checkpoint Description")
with ui.ZStack():
self._description_field = ui.StringField(multiline=True, height=80)
self._description_field_hint_label = ui.Label(
" Description", alignment=ui.Alignment.LEFT_TOP, style={"color": 0xFF3F3F3F}
)
self._description_begin_edit_sub = self._description_field.model.subscribe_begin_edit_fn(
self._on_description_begin_edit
)
self._description_end_edit_sub = self._description_field.model.subscribe_end_edit_fn(
self._on_description_end_edit
)
ui.Spacer(width=40)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer(height=0)
ok_button = ui.Button("CONTINUE", name="confirm_button", width=120, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
cancel_button = ui.Button("CANCEL", name="cancel_button", width=120, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(ok_button)
self._buttons.append(cancel_button)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
| 9,633 | Python | 39.649789 | 137 | 0.534517 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_style.py | class Styles:
RELOAD_BTN = None
RELOAD_AUTO = None
RELOAD_OTD = None
LIVE_TOOL_TIP = None
@staticmethod
def on_startup():
# from .layer_icons import LayerIcons as li
from omni.ui import color as cl
c_otd = cl("#eb9d00")
c_otdh = cl("#ffaa00")
c_live = cl("#76B900")
c_liveh = cl("#9bf400")
c_lived = cl("#76B900")
c_auto = cl("#34C7FF")
c_autoh = cl("#82dcff")
c_white = cl("#ffffff")
c_rel = cl("#888888")
c_relh = cl("#BBBBBB")
c_disabled = cl("#555555")
Styles.LIVE_TOOL_TIP = {"background_color": 0xEE222222, "color": 0x33333333}
Styles.LIVE_GREEN = {"color": c_live, "Tooltip": Styles.LIVE_TOOL_TIP}
Styles.LIVE_SEL = {"color": c_liveh, "Tooltip": Styles.LIVE_TOOL_TIP}
Styles.LIVE_GREEN_DARKER = {"color": c_lived, "Tooltip": Styles.LIVE_TOOL_TIP}
Styles.RELOAD_BTN = {
"color": c_rel,
":hovered": {"color": c_relh},
":pressed": {"color": c_white},
":disabled": {"color": c_disabled},
}
Styles.RELOAD_AUTO = {
"color": c_auto, "Tooltip": Styles.LIVE_TOOL_TIP,
":hovered": {"color": c_autoh},
":pressed": {"color": c_white},
":disabled": {"color": c_disabled},
}
Styles.RELOAD_OTD = {
"color": c_otd, "Tooltip": Styles.LIVE_TOOL_TIP,
":hovered": {"color": c_otdh},
":pressed": {"color": c_white},
":disabled": {"color": c_disabled},
}
| 1,602 | Python | 29.245282 | 86 | 0.500624 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_model.py | __all__ = ["LiveSessionItem", "LiveSessionModel"]
import asyncio
import omni.kit.usd.layers as layers
import omni.ui as ui
from typing import Callable
import itertools
_last_sessions = {}
class LiveSessionItem(ui.AbstractItem):
def __init__(self, session: layers.LiveSession) -> None:
super().__init__()
self._session = session
self.model = ui.SimpleStringModel(session.name)
@property
def session(self):
return self._session
def __str__(self) -> str:
return self._session.name
class LiveSessionModel(ui.AbstractItemModel):
def __init__(self, layers_interface: layers.Layers, layer_identifier, update_users=True) -> None:
super().__init__()
self._layers_interface = layers_interface
self._base_layer_identifier = layer_identifier
self._current_index = ui.SimpleIntModel()
self._current_index.set_value(-1)
id = self._current_index.add_value_changed_fn(self._value_changed_fn)
self._items = []
self._current_session = None
self._current_session_channel = None
self._channel_subscriber = None
self._join_channel_task = None
self._all_users = {}
self._user_update_callback: Callable[[], None] = None
self._all_value_changed_fns = [id]
self._update_users = update_users
self._refreshing_item = False
self._is_default_session_selected = False
def __del__(self):
self.destroy()
@property
def all_users(self):
return self._all_users
@property
def is_default_session_selected(self):
return self._is_default_session_selected
def set_user_update_callback(self, callback: Callable[[], None]):
self._user_update_callback = callback
def stop_channel(self):
self._cancel_current_task()
def _join_current_channel(self):
if not self._current_session or not self._update_users:
return
try:
# OM-108516: Make channel_manager optional
import omni.kit.collaboration.channel_manager as cm
except ImportError:
return
if not self._current_session_channel or self._current_session_channel.url != self._current_session.url:
self._cancel_current_task()
async def join_stage_async(url):
self._current_session_channel = await cm.join_channel_async(url, True)
if not self._current_session_channel:
return
self._channel_subscriber = self._current_session_channel.add_subscriber(self._on_channel_message)
self._join_channel_task = asyncio.ensure_future(join_stage_async(self._current_session.channel_url))
def _on_channel_message(self, message):
try:
# OM-108516: Make channel_manager optional
import omni.kit.collaboration.channel_manager as cm
except ImportError:
return
user = message.from_user
if message.message_type == cm.MessageType.LEFT and user.user_id in self._all_users:
self._all_users.pop(user.user_id, None)
changed = True
elif user.user_id not in self._all_users:
self._all_users[user.user_id] = user
changed = True
else:
changed = False
if changed and self._user_update_callback:
self._user_update_callback()
def _cancel_current_task(self):
if self._join_channel_task and not self._join_channel_task.done():
try:
self._join_channel_task.cancel()
except Exception:
pass
if self._current_session_channel:
self._current_session_channel.stop()
self._current_session_channel = None
self._join_channel_task = None
self._channel_subscriber = None
def add_value_changed(self, fn):
if self._current_index:
id = self._current_index.add_value_changed_fn(fn)
self._all_value_changed_fns.append(id)
def _value_changed_fn(self, model):
if self._refreshing_item:
return
global _last_sessions
index = self._current_index.as_int
if index < 0 or index >= len(self._items):
return
self._current_session = self._items[index].session
self._is_default_session_selected = (self._current_session and self._current_index.as_int == 0)
_last_sessions[self._base_layer_identifier] = self._current_session.url
self._all_users.clear()
if self._user_update_callback:
self._user_update_callback()
self._join_current_channel()
self._refreshing_item = True
self._item_changed(None)
self._refreshing_item = False
def destroy(self):
self._user_update_callback = None
self._cancel_current_task()
if self._current_index:
for fn in self._all_value_changed_fns:
self._current_index.remove_value_changed_fn(fn)
self._all_value_changed_fns.clear()
self._current_index = None
self._layers_interface = None
self._current_session = None
self._items = []
self._all_users = {}
self._layers_event_subscription = None
def clear(self):
self._items = []
self._current_session = None
self._current_index.set_value(-1)
def empty(self):
return len(self._items) == 0
def get_item_children(self, item):
return self._items
@property
def current_session(self):
return self._current_session
def refresh_sessions(self, force=False):
global _last_sessions
live_syncing = self._layers_interface.get_live_syncing()
current_live_session = live_syncing.get_current_live_session(self._base_layer_identifier)
live_sessions = live_syncing.get_all_live_sessions(self._base_layer_identifier)
live_sessions.sort(key=lambda s: s.get_last_modified_time(), reverse=True)
identifier = self._base_layer_identifier
pre_sort = []
for session in live_sessions:
if session.name == "Default":
pre_sort.insert(0, session)
else:
pre_sort.append(session)
self._items.clear()
index = 0 if live_sessions else -1
for i, session in enumerate(pre_sort):
item = LiveSessionItem(session)
if current_live_session and current_live_session.url == session.url:
index = i
elif identifier in _last_sessions and _last_sessions[identifier] == session.url:
index = i
self._items.append(item)
current_index = self._current_index.as_int
if current_index != index:
self._current_index.set_value(index)
elif force:
self._item_changed(None)
self._is_default_session_selected = (self._current_session and self._current_index.as_int == 0)
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def select_default_session(self):
live_syncing = self._layers_interface.get_live_syncing()
live_sessions = live_syncing.get_all_live_sessions(self._base_layer_identifier)
if live_sessions and self._current_index.as_int != 0:
self._current_index.set_value(0)
self._item_changed(None)
return
def create_new_session_name(self) -> str:
live_syncing = self._layers_interface.get_live_syncing()
live_sessions = live_syncing.get_all_live_sessions(self._base_layer_identifier)
# first we attempt creating a "Default" as the first new session.
default_session_name = "Default"
if not live_syncing.find_live_session_by_name(self._base_layer_identifier, default_session_name):
return default_session_name
# if there already is a `Default`, then we use <username>_01, <username>_02, ...
layers_instance = live_syncing._layers_instance
live_syncing_interface = live_syncing._live_syncing_interface
logged_user_name = live_syncing_interface.get_logged_in_user_name_for_layer(layers_instance, self._base_layer_identifier)
if "@" in logged_user_name:
logged_user_name = logged_user_name.split('@')[0]
for i in itertools.count(start=1):
user_session_name = "{}_{:02d}".format(logged_user_name, i)
if not live_syncing.find_live_session_by_name(self._base_layer_identifier, user_session_name):
return user_session_name
| 8,699 | Python | 35.708861 | 129 | 0.613174 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_camera_follower_list.py | __all__ = ["LiveSessionCameraFollowerList"]
import carb
import omni.usd
import omni.client.utils as clientutils
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
from .utils import build_live_session_user_layout
from pxr import Sdf
from omni.ui import color as cl
TOOLTIP_STYLE = {
"color": cl("#979797"),
"Tooltip": {"background_color": 0xEE222222}
}
class LiveSessionCameraFollowerList:
"""Widget to build an user list to show all followers to the specific camera."""
def __init__(self, usd_context: omni.usd.UsdContext, camera_path: Sdf.Path, **kwargs):
"""
Constructor.
Args:
usd_context (omni.usd.UsdContext): USD Context instance.
camera_path (str): Interested camera.
Kwargs:
icon_size (int): The width and height of the user icon. 16 pixel by default.
spacing (int): The horizonal spacing between two icons. 2 pixel by default.
maximum_users (int): The maximum users to show, and show others with overflow.
show_my_following_users (bool): Whether it should show the users that are following me or not.
"""
self.__icon_size = kwargs.get("icon_size", 16)
self.__spacing = kwargs.get("spacing", 2)
self.__maximum_count = kwargs.get("maximum_users", 3)
self.__show_my_following_users = kwargs.get("show_my_following_users", True)
self.__camera_path = camera_path
self.__usd_context = usd_context
self.__presence_layer = pl.get_presence_layer_interface(self.__usd_context)
self.__layers = layers.get_layers(usd_context)
self.__live_syncing = layers.get_live_syncing()
self.__layers_event_subscriptions = []
self.__main_layout: ui.HStack = ui.HStack(width=0, height=0)
self.__all_user_layouts = {}
self.__initialize()
self.__overflow = False
self.__overflow_button = None
@property
def layout(self) -> ui.HStack:
return self.__main_layout
def empty(self):
return len(self.__all_user_layouts) == 0
def track_camera(self, camera_path: Sdf.Path):
"""Switches the camera path to listen to."""
if self.__camera_path != camera_path:
self.__camera_path = camera_path
self.__initialize()
def __initialize(self):
layer_identifier = self.__usd_context.get_stage_url()
if self.__camera_path and not clientutils.is_local_url(layer_identifier):
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED
]:
layers_event_subscription = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event,
name=f"omni.kit.widget.live_session_management.LiveSessionCameraFollowerList {str(event)}"
)
self.__layers_event_subscriptions.append(layers_event_subscription)
else:
self.__layers_event_subscriptions = []
self.__build_ui()
def __build_ui(self):
# Destroyed
if not self.__main_layout:
return
self.__main_layout.clear()
self.__all_user_layouts.clear()
self.__overflow = False
self.__overflow_button = None
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session or not self.__camera_path:
return
with self.__main_layout:
for peer_user in current_live_session.peer_users:
self.__add_user(current_live_session, peer_user.user_id, False)
if self.__overflow:
break
if self.empty():
self.__main_layout.visible = False
else:
self.__main_layout.visible = True
def __build_tooltip(self): # pragma: no cover
live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
if not live_session:
return
with ui.VStack():
with ui.HStack(style={"color": cl("#757575")}):
ui.Spacer()
title_label = ui.Label(
"Following by 0 Users", style={"font_size": 12}, width=0
)
ui.Spacer()
ui.Spacer(height=0)
ui.Separator(style={"color": cl("#4f4f4f")})
ui.Spacer(height=4)
valid_users = 0
for user in live_session.peer_users:
if not self.__show_my_following_users:
following_user_id = self.__presence_layer.get_following_user_id(user.user_id)
if following_user_id == live_session.logged_user_id:
continue
bound_camera_prim = self.__presence_layer.get_bound_camera_prim(user.user_id)
if not bound_camera_prim or bound_camera_prim.GetPath() != self.__camera_path:
continue
valid_users += 1
item_title = f"{user.user_name} ({user.from_app})"
with ui.HStack():
build_live_session_user_layout(user, self.__icon_size, "")
ui.Spacer(width=4)
ui.Label(item_title, style={"font_size": 14})
ui.Spacer(height=2)
title_label.text = f"Following by {valid_users} Users"
@carb.profiler.profile
def __add_user(self, current_live_session, user_id, add_child=False):
bound_camera_prim = self.__presence_layer.get_bound_camera_prim(user_id)
if not bound_camera_prim:
return False
if bound_camera_prim.GetPath() == self.__camera_path:
user_info = current_live_session.get_peer_user_info(user_id)
if not user_info:
return False
if not self.__show_my_following_users:
following_user_id = self.__presence_layer.get_following_user_id(user_id)
if following_user_id == current_live_session.logged_user_id:
return False
if user_id not in self.__all_user_layouts:
current_count = len(self.__all_user_layouts)
if current_count > self.__maximum_count or self.__overflow:
# OMFP-2909: Refresh overflow button to rebuild tooltip.
if self.__overflow and self.__overflow_button:
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
return True
elif current_count == self.__maximum_count:
self.__overflow = True
layout = ui.HStack(width=0)
with layout:
ui.Spacer(width=4)
with ui.ZStack():
ui.Label("...", style={"font_size": 16}, aligment=ui.Alignment.V_CENTER)
self.__overflow_button = ui.InvisibleButton(style=TOOLTIP_STYLE)
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
if add_child:
self.__main_layout.add_child(layout)
else:
if self.empty():
spacer = 0
else:
spacer = self.__spacing
layout = self.__build_user_layout(user_info, spacer)
if add_child:
self.__main_layout.add_child(layout)
self.__main_layout.visible = True
self.__all_user_layouts[user_id] = layout
return True
return False
@carb.profiler.profile
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
stage_url = self.__usd_context.get_stage_url()
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if stage_url not in payload.identifiers_or_spec_paths:
return
self.__build_ui()
elif (
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED or
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT
):
if stage_url != payload.layer_identifier:
return
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session:
self.__build_ui()
return
user_id = payload.user_id
if payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
user = self.__all_user_layouts.pop(user_id, None)
if user:
# FIXME: omni.ui does not support to remove single child.
self.__build_ui()
else:
self.__add_user(current_live_session, user_id, True)
else:
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session:
return
payload = pl.get_presence_layer_event_payload(event)
if not payload or not payload.event_type:
return
if payload.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED:
changed_user_ids = payload.changed_user_ids
needs_rebuild = False
for user_id in changed_user_ids:
if not self.__add_user(current_live_session, user_id, True):
# It's not bound to this camera already.
needs_rebuild = user_id in self.__all_user_layouts
break
if needs_rebuild:
self.__build_ui()
def destroy(self): # pragma: no cover
self.__main_layout = None
self.__layers_event_subscriptions = []
self.__layers = None
self.__live_syncing = None
self.__all_user_layouts.clear()
self.__overflow_button = None
def __build_user_layout(self, user_info: layers.LiveSessionUser, spacing=2):
tooltip = f"{user_info.user_name} ({user_info.from_app})"
layout = ui.HStack()
with layout:
ui.Spacer(width=spacing)
build_live_session_user_layout(user_info, self.__icon_size, tooltip)
return layout
| 10,669 | Python | 39.264151 | 112 | 0.556472 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/filebrowser/__init__.py | from .app_filebrowser import FileBrowserUI, FileBrowserSelectionType, FileBrowserMode | 85 | Python | 84.999915 | 85 | 0.894118 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/filebrowser/app_filebrowser.py | import asyncio
import re
import omni.client
import omni.client.utils as clientutils
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.widget.filebrowser import FileBrowserItem
from typing import Iterable, Tuple, Union
class FileBrowserSelectionType:
FILE_ONLY = 0
DIRECTORY_ONLY = 1
ALL = 2
class FileBrowserMode:
OPEN = 0
SAVE = 1
class FileBrowserUI:
def __init__(self, title, mode, selection_type, filter_options, **kwargs):
if mode == FileBrowserMode.OPEN:
confirm_text = "Open"
else:
confirm_text = "Save"
self._file_picker = FilePickerApp(title, confirm_text, selection_type, filter_options, **kwargs)
def set_current_directory(self, dir):
self._file_picker.set_current_directory(dir)
def set_current_filename(self, filename):
self._file_picker.set_current_filename(filename)
def get_current_filename(self):
return self._file_picker.get_current_filename()
def open(self, select_fn, cancel_fn):
self._file_picker.set_custom_fn(select_fn, cancel_fn)
self._file_picker.show_dialog()
def destroy(self):
self._file_picker.set_custom_fn(None, None)
self._file_picker = None
def hide(self):
self._file_picker.hide_dialog()
class FilePickerApp:
"""
Standalone app to demonstrate the use of the FilePicker dialog.
Args:
title (str): Title of the window.
apply_button_name (str): Name of the confirm button.
selection_type (FileBrowserSelectionType): The file type that confirm event will respond to.
item_filter_options (list): Array of filter options. Element of array
is a tuple that first element of this tuple is the regex string for filtering,
and second element of this tuple is the descriptions, like ("*.*", "All Files").
By default, it will list all files.
kwargs: additional keyword arguments to be passed to FilePickerDialog.
"""
def __init__(
self,
title: str,
apply_button_name: str,
selection_type: FileBrowserSelectionType = FileBrowserSelectionType.ALL,
item_filter_options: Iterable[Tuple[Union[re.Pattern, str], str]] = ((
re.compile(".*"), "All Files (*.*)")),
**kwargs,
):
self._title = title
self._filepicker = None
self._selection_type = selection_type
self._custom_select_fn = None
self._custom_cancel_fn = None
self._apply_button_name = apply_button_name
self._filter_regexes = []
self._filter_descriptions = []
self._current_directory = None
for regex, desc in item_filter_options:
if not isinstance(regex, re.Pattern):
regex = re.compile(regex, re.IGNORECASE)
self._filter_regexes.append(regex)
self._filter_descriptions.append(desc)
self._build_ui(**kwargs)
def set_custom_fn(self, select_fn, cancel_fn):
self._custom_select_fn = select_fn
self._custom_cancel_fn = cancel_fn
def show_dialog(self):
self._filepicker.show(self._current_directory)
self._current_directory = None
def hide_dialog(self):
self._filepicker.hide()
def set_current_directory(self, dir: str):
self._current_directory = dir
if not self._current_directory.endswith("/"):
self._current_directory += "/"
def set_current_filename(self, filename: str):
self._filepicker.set_filename(filename)
def get_current_filename(self):
return self._filepicker.get_filename()
def _build_ui(self, **kwargs):
on_click_open = lambda f, d: asyncio.ensure_future(self._on_click_open(f, d))
on_click_cancel = lambda f, d: asyncio.ensure_future(self._on_click_cancel(f, d))
# Create the dialog
self._filepicker = FilePickerDialog(
self._title,
allow_multi_selection=False,
apply_button_label=self._apply_button_name,
click_apply_handler=on_click_open,
click_cancel_handler=on_click_cancel,
item_filter_options=self._filter_descriptions,
item_filter_fn=lambda item: self._on_filter_item(item),
error_handler=lambda m: self._on_error(m),
**kwargs,
)
# Start off hidden
self.hide_dialog()
def _on_filter_item(self, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if self._filepicker.current_filter_option >= len(self._filter_regexes):
return False
regex = self._filter_regexes[self._filepicker.current_filter_option]
if regex.match(item.path):
return True
else:
return False
def _on_error(self, msg: str):
"""
Demonstrates error handling. Instead of just printing to the shell, the App can
display the error message to a console window.
"""
print(msg)
async def _on_click_open(self, filename: str, dirname: str):
"""
The meat of the App is done in this callback when the user clicks 'Accept'. This is
a potentially costly operation so we implement it as an async operation. The inputs
are the filename and directory name. Together they form the fullpath to the selected
file.
"""
dirname = dirname.strip()
if dirname and not dirname.endswith("/"):
dirname += "/"
fullpath = clientutils.make_absolute_url_if_possible(dirname, filename)
result, entry = omni.client.stat(fullpath)
if result == omni.client.Result.OK and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
is_folder = True
else:
is_folder = False
if not is_folder and self._selection_type == FileBrowserSelectionType.DIRECTORY_ONLY:
return
self.hide_dialog()
await omni.kit.app.get_app().next_update_async()
if self._custom_select_fn:
self._custom_select_fn(fullpath, self._filepicker.current_filter_option)
async def _on_click_cancel(self, filename: str, dirname: str):
"""
This function is called when the user clicks 'Cancel'.
"""
self.hide_dialog()
await omni.kit.app.get_app().next_update_async()
if self._custom_cancel_fn:
self._custom_cancel_fn()
| 6,490 | Python | 33.343915 | 104 | 0.623729 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/tests/mock_utils.py | import carb
import asyncio
import os
import functools
import uuid
import omni.usd
import omni.client
import omni.kit.usd.layers as layers
from typing import Callable, Awaitable
from omni.kit.collaboration.channel_manager.types import PeerUser
from omni.kit.usd.layers import LayersState, LiveSyncing, LiveSession
from ..live_session_model import LiveSessionModel
from ..file_picker import FilePicker
from omni.kit.usd.layers._omni_kit_usd_layers import IWorkflowLiveSyncing
from unittest.mock import Mock, MagicMock
from pxr import Sdf, Usd
_mock_sdf_save_layer_api = None
_mock_layer_states_get_all_outdated_layer_identifiers_api = None
_mock_live_session_model_all_users_api = None
_mock_live_syncing_merge_and_stop_live_session_async_api = None
_mock_filepicker_show_api = None
_mock_filepicker_set_file_selected_fn_api = None
_mock_outdated_layers = []
file_save_handler = None
merge_and_stop_live_session_async_called = False
def append_outdated_layers(layer_id):
global _mock_outdated_layers
_mock_outdated_layers.append(layer_id)
def clear_outdated_layers():
global _mock_outdated_layers
_mock_outdated_layers = []
def get_merge_and_stop_live_session_async_called():
global merge_and_stop_live_session_async_called
return merge_and_stop_live_session_async_called
def _start_mock_api_for_live_session_management():
carb.log_info("Start mock api for live session management...")
def __mock_sdf_save_layer(force):
pass
global _mock_sdf_save_layer_api
_mock_sdf_save_layer_api = Sdf.Layer.Save
Sdf.Layer.Save = Mock(side_effect=__mock_sdf_save_layer)
def __mock_layer_states_get_all_outdated_layer_identifiers_():
global _mock_outdated_layers
return _mock_outdated_layers
global _mock_layer_states_get_all_outdated_layer_identifiers_api
_mock_layer_states_get_all_outdated_layer_identifiers_api = LayersState.get_all_outdated_layer_identifiers
LayersState.get_all_outdated_layer_identifiers = Mock(side_effect=__mock_layer_states_get_all_outdated_layer_identifiers_)
global _mock_live_session_model_all_users_api
_mock_live_session_model_all_users_api = LiveSessionModel.all_users
LiveSessionModel.all_users = {f"user_{i}": PeerUser(f"user_{i}", f"user_{i}", "Kit") for i in range(3)}
async def __mock_live_syncing_merge_and_stop_live_session_async(
self, target_layer: str = None, comment="",
pre_merge: Callable[[LiveSession], Awaitable] = None,
post_merge: Callable[[bool], Awaitable] = None,
layer_identifier: str = None
) -> bool:
global merge_and_stop_live_session_async_called
merge_and_stop_live_session_async_called = True
return True
global _mock_live_syncing_merge_and_stop_live_session_async_api
_mock_live_syncing_merge_and_stop_live_session_async_api = LiveSyncing.merge_and_stop_live_session_async
LiveSyncing.merge_and_stop_live_session_async = Mock(side_effect=__mock_live_syncing_merge_and_stop_live_session_async)
def __mock_filepicker_show(dummy1, dummy2):
global file_save_handler
if file_save_handler:
file_save_handler(dummy1, False)
global _mock_filepicker_show_api
_mock_filepicker_show_api = FilePicker.show
FilePicker.show = Mock(side_effect=__mock_filepicker_show)
def __mock_filepicker_set_file_selected_fn(fn):
global file_save_handler
file_save_handler = fn
global _mock_filepicker_set_file_selected_fn_api
_mock_filepicker_set_file_selected_fn_api = FilePicker.set_file_selected_fn
FilePicker.set_file_selected_fn = Mock(side_effect=__mock_filepicker_set_file_selected_fn)
def _end_mock_api_for_live_session_management():
carb.log_info("Start mock api for live session management...")
global _mock_sdf_save_layer_api
Sdf.Layer.Save = _mock_sdf_save_layer_api
_mock_sdf_save_layer_api = None
global _mock_layer_states_get_all_outdated_layer_identifiers_api
LayersState.get_all_outdated_layer_identifiers = _mock_layer_states_get_all_outdated_layer_identifiers_api
_mock_layer_states_get_all_outdated_layer_identifiers_api = None
global _mock_live_session_model_all_users_api
LiveSessionModel.all_users = _mock_live_session_model_all_users_api
_mock_live_session_model_all_users_api = None
global _mock_live_syncing_merge_and_stop_live_session_async_api
LiveSyncing.merge_and_stop_live_session_async = _mock_live_syncing_merge_and_stop_live_session_async_api
_mock_live_syncing_merge_and_stop_live_session_async_api = None
global _mock_filepicker_show_api
FilePicker.show = _mock_filepicker_show_api
_mock_filepicker_show_api = None
global _mock_filepicker_set_file_selected_fn_api
FilePicker.set_file_selected_fn = _mock_filepicker_set_file_selected_fn_api
_mock_filepicker_set_file_selected_fn_api = None
global merge_and_stop_live_session_async_called
merge_and_stop_live_session_async_called = False
def MockApiForLiveSessionManagement(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
func = args[0]
args = args[1:]
else:
func = None
def wrapper(func):
@functools.wraps(func)
def wrapper_api(*args, **kwargs):
try:
_start_mock_api_for_live_session_management()
return func(*args, **kwargs)
finally:
_end_mock_api_for_live_session_management()
@functools.wraps(func)
async def wrapper_api_async(*args, **kwargs):
try:
_start_mock_api_for_live_session_management()
return await func(*args, **kwargs)
finally:
_end_mock_api_for_live_session_management()
if asyncio.iscoroutinefunction(func):
return wrapper_api_async
else:
return wrapper_api
if func:
return wrapper(func)
else:
return wrapper
| 5,995 | Python | 37.435897 | 126 | 0.69975 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/tests/__init__.py | from .test_live_session_management import * | 43 | Python | 42.999957 | 43 | 0.813953 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/tests/test_live_session_management.py | import os
import carb
import omni.usd
import omni.kit.ui_test as ui_test
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.timeline.live_session
import omni.kit.collaboration.presence_layer as pl
import omni.kit.collaboration.presence_layer.utils as pl_utils
import unittest
import tempfile
import random
import uuid
from omni.kit.test import AsyncTestCase
from omni.kit.window.preferences import register_page, unregister_page
from pxr import Sdf, Usd
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi, join_new_simulated_user, quit_simulated_user, forbid_session_merge
from ..extension import LiveSessionWidgetExtension, stop_or_show_live_session_widget
from ..live_session_camera_follower_list import LiveSessionCameraFollowerList
from ..live_session_user_list import LiveSessionUserList
from ..file_picker import FilePicker, FileBrowserMode, FileBrowserSelectionType
from ..live_session_preferences import LiveSessionPreferences
from ..reload_widget import build_reload_widget
from ..live_session_start_window import LiveSessionStartWindow
from .mock_utils import (
MockApiForLiveSessionManagement,
append_outdated_layers,
clear_outdated_layers,
get_merge_and_stop_live_session_async_called
)
TEST_URL = "omniverse://__omni.kit.widget.live_session_management__/tests/"
LIVE_SESSION_CONFIRM_BUTTON_PATH = "Live Session//Frame/**/Button[*].name=='confirm_button'"
LIVE_SESSION_CANCEL_BUTTON_PATH = "Live Session//Frame/**/Button[*].name=='cancel_button'"
LEAVE_SESSION_CONFIRM_BUTTON_PATH = "Leave Session//Frame/**/Button[*].name=='confirm_button'"
JOIN_LIVE_SESSION_WITH_LINK_CANCEL_BUTTON_PATH = "JOIN LIVE SESSION WITH LINK//Frame/**/Button[*].name=='cancel_button'"
SHARE_LIVE_SESSION_LINK_COMBO_BOX_PATH = "SHARE LIVE SESSION LINK//Frame/**/ComboBox[0]"
SHARE_LIVE_SESSION_LINK_CONFIRM_BUTTON_PATH = "SHARE LIVE SESSION LINK//Frame/**/InvisibleButton[*].name=='confirm_button'"
MERGE_OPTIONS_CONFIRM_BUTTON_PATH = "Merge Options//Frame/**/Button[*].name=='confirm_button'"
MERGE_OPTIONS_COMBO_BOX_PATH = "Merge Options//Frame/**/ComboBox[0]"
MERGE_PROMPT_LEAVE_BUTTON_PATH = "Permission Denied//Frame/**/Button[*].name=='confirm_button'"
QUICK_JOIN_ENABLED = "/exts/omni.kit.widget.live_session_management/quick_join_enabled"
def _menu_items_as_string_list(items):
return [i.text for i in items]
def _find_menu_item(items, text):
for i in items:
if i.text == text:
return i
return None
def enable_server_tests():
settings = carb.settings.get_settings()
return True or settings.get_as_bool("/exts/omni.kit.widget.live_session_management/enable_server_tests")
class TestLiveSessionManagement(AsyncTestCase):
def get_live_syncing(self):
usd_context = omni.usd.get_context()
self.assertIsNotNone(layers.get_layers(usd_context))
self.assertIsNotNone(layers.get_layers(usd_context).get_live_syncing())
return layers.get_layers(usd_context).get_live_syncing()
async def setUp(self):
self._instance = LiveSessionWidgetExtension.get_instance()
self.assertIsNotNone(self._instance)
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
pass
async def _close_case(self):
if omni.usd.get_context().get_stage():
live_syncing = self.get_live_syncing()
if live_syncing:
if live_syncing.is_stage_in_live_session():
await self._leave_current_session()
live_syncing.stop_all_live_sessions()
await omni.usd.get_context().close_stage_async()
await ui_test.human_delay(6)
async def _click_menu_item(self, item, right_click=False):
offset = ui_test.Vec2(5, 5)
pos = ui_test.Vec2(item.screen_position_x, item.screen_position_y) + offset
await ui_test.emulate_mouse_move(pos, 4)
await ui_test.human_delay(6)
await ui_test.emulate_mouse_click(right_click=right_click)
await ui_test.human_delay(6)
async def _create_test_usd(self, filename = 'test'):
await omni.client.delete_async(TEST_URL)
stage_url = TEST_URL + f"{filename}.usd"
layer = Sdf.Layer.CreateNew(stage_url)
stage = Usd.Stage.Open(layer.identifier)
self.assertIsNotNone(stage)
return stage
async def _create_test_sublayer_usd(self, filename = 'sublayer'):
layer_url = TEST_URL + f"{filename}.usd"
layer = Sdf.Layer.CreateNew(layer_url)
return layer
async def _expand_live_session_menu(self,
layer_identifier: str=None,
quick_join: str=None):
stop_or_show_live_session_widget(layer_identifier=layer_identifier, quick_join=quick_join)
await ui_test.human_delay(6)
menu = self._instance._live_session_menu
self.assertIsNotNone(menu)
items = ui.Inspector.get_children(menu)
await ui_test.human_delay(6)
return items
def _get_current_menu_item_string_list(self):
menu = ui.Menu.get_current()
self.assertIsNotNone(menu)
items = ui.Inspector.get_children(menu)
return _menu_items_as_string_list(items)
async def _click_on_current_menu(self, text: str):
menu = ui.Menu.get_current()
self.assertIsNotNone(menu)
items = ui.Inspector.get_children(menu)
item_str_list = self._get_current_menu_item_string_list()
self.assertIn(text, item_str_list)
item = _find_menu_item(items, text)
self.assertIsNotNone(item)
await self._click_menu_item(item)
await ui_test.human_delay(6)
async def _click_live_session_menu_item(self,
text: str, layer_identifier = None,
quick_join: str = None):
items = await self._expand_live_session_menu(layer_identifier, quick_join)
self.assertTrue(len(items) > 0)
item_str_list = _menu_items_as_string_list(items)
self.assertIn(text, item_str_list)
item = _find_menu_item(items, text)
self.assertIsNotNone(item)
await self._click_menu_item(item)
await ui_test.human_delay(6)
@MockLiveSyncingApi
async def test_create_session_dialog(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._click_live_session_menu_item("Create Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
cancal_button = ui_test.find(LIVE_SESSION_CANCEL_BUTTON_PATH)
self.assertIsNotNone(cancal_button)
await cancal_button.click()
await self._close_case()
async def _create_session(self, session_name: str=None):
await self._click_live_session_menu_item("Create Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
if session_name:
name_field = ui_test.find("Live Session//Frame/**/StringField[0]")
self.assertIsNotNone(name_field)
name_field.model.set_value(session_name)
ok_button = ui_test.find(LIVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
async def _create_session_then_leave(self, session_name: str):
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
await self._create_session(session_name)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._leave_current_session()
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
async def _leave_current_session(self):
await self._click_live_session_menu_item("Leave Session")
if ui_test.find("Leave Session"):
button = ui_test.find(LEAVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(button)
await button.click()
await ui_test.human_delay(6)
@MockLiveSyncingApi
async def test_create_session(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
self.get_live_syncing().stop_all_live_sessions()
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
await self._close_case()
@MockLiveSyncingApi
async def test_leave_session(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._close_case()
@MockLiveSyncingApi
async def test_join_session(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session_then_leave("test")
await self._click_live_session_menu_item("Join Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
ok_button = ui_test.find(LIVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._close_case()
@MockLiveSyncingApi
@MockApiForLiveSessionManagement
async def test_join_session_participants(self):
stage = await self._create_test_usd("test")
await omni.usd.get_context().attach_stage_async(stage)
live_session_start_window = LiveSessionStartWindow(layers.get_layers(),
stage.GetRootLayer().identifier,
None)
await self._create_session("test")
live_session_start_window.visible = True
live_session_start_window.set_focus(True)
await ui_test.human_delay(6)
live_session_start_window.visible = False
await self._close_case()
@MockLiveSyncingApi
async def test_join_session_quick(self):
settings = carb.settings.get_settings()
before = settings.get_as_bool(QUICK_JOIN_ENABLED)
settings.set(QUICK_JOIN_ENABLED, True)
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session_then_leave("test")
await self._expand_live_session_menu(quick_join="test")
self.assertEqual("test", self.get_live_syncing().get_current_live_session().name)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
settings.set(QUICK_JOIN_ENABLED, before)
await self._close_case()
@MockLiveSyncingApi
async def test_join_session_quick_create(self):
settings = carb.settings.get_settings()
before = settings.get_as_bool(QUICK_JOIN_ENABLED)
settings.set(QUICK_JOIN_ENABLED, True)
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._expand_live_session_menu(quick_join="test")
self.assertEqual("test", self.get_live_syncing().get_current_live_session().name)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
settings.set(QUICK_JOIN_ENABLED, before)
await self._close_case()
@MockLiveSyncingApi
async def test_join_session_options(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session_then_leave(None)
await self._create_session_then_leave(None)
for i in range(3):
await self._create_session_then_leave(f"test_{i}")
await self._click_live_session_menu_item("Join Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
combo_box = ui_test.find("Live Session//Frame/**/ComboBox[0]")
items = combo_box.model.get_item_children(None)
names = [i.session.name for i in items]
carb.log_warn(names)
self.assertIn("Default", names)
self.assertIn("simulated_user_name___01", names)
for i in range(3):
self.assertIn(f"test_{i}", names)
index_of_second_test_usd = names.index('test_1')
self.assertTrue(index_of_second_test_usd > -1)
combo_box.model.get_item_value_model(None, 0).set_value(index_of_second_test_usd)
await ui_test.human_delay(6)
ok_button = ui_test.find(LIVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
self.assertEqual("test_1", self.get_live_syncing().get_current_live_session().name)
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_join_with_session_link_without_stage(self):
self.assertIsNone(stop_or_show_live_session_widget())
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_join_with_session_link_dialog(self):
await omni.usd.get_context().new_stage_async()
await self._click_live_session_menu_item("Join With Session Link")
frame = ui_test.find("JOIN LIVE SESSION WITH LINK")
self.assertIsNotNone(frame)
cancal_button = ui_test.find(JOIN_LIVE_SESSION_WITH_LINK_CANCEL_BUTTON_PATH)
self.assertIsNotNone(cancal_button)
await cancal_button.click()
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_copy_session_link(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
layer = stage.GetRootLayer()
await self._click_live_session_menu_item("Copy Session Link", layer.identifier)
current_session = self.get_live_syncing().get_current_live_session()
live_session_link = omni.kit.clipboard.paste()
self.assertEqual(live_session_link, current_session.shared_link)
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_share_session_link(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
for i in range(3):
await self._create_session_then_leave(f"test_{i}")
await self._click_live_session_menu_item("Share Session Link")
frame = ui_test.find("SHARE LIVE SESSION LINK")
self.assertIsNotNone(frame)
combo_box = ui_test.find(SHARE_LIVE_SESSION_LINK_COMBO_BOX_PATH)
items = combo_box.model.get_item_children(None)
names = [i.session.name for i in items]
index_of_second_test_usd = -1
for i in range(3):
self.assertIn(f"test_{i}", names)
if names[i] == "test_1":
index_of_second_test_usd = i
self.assertTrue(index_of_second_test_usd > -1)
combo_box.model.get_item_value_model(None, 0).set_value(index_of_second_test_usd)
await ui_test.human_delay(6)
confirm_button = ui_test.find(SHARE_LIVE_SESSION_LINK_CONFIRM_BUTTON_PATH)
await confirm_button.click()
live_session_link = omni.kit.clipboard.paste()
self.assertEqual(live_session_link, items[index_of_second_test_usd].session.shared_link)
await self._close_case()
def _create_test_camera(self, name: str='camera'):
camera_path = f"/{name}"
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Camera", prim_path=camera_path)
return Sdf.Path(camera_path)
async def _setup_camera_follower_list(self, camera_path, maximum_users=3):
camera = omni.usd.get_context().get_stage().GetPrimAtPath(camera_path)
self.assertIsNotNone(camera)
return LiveSessionCameraFollowerList(omni.usd.get_context(), camera_path, maximum_users=maximum_users)
@MockLiveSyncingApi
async def test_live_session_camera_follower_list(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
camera_path = self._create_test_camera()
camera_follower_list = await self._setup_camera_follower_list(camera_path)
await self._close_case()
async def _bound_camera(self, shared_stage: Usd.Stage, user_id: str, camera_path: Sdf.Path):
if not camera_path:
camera_path = Sdf.Path.emptyPath
camera_path = Sdf.Path(camera_path)
bound_camera_property_path = pl_utils.get_bound_camera_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
builtin_camera_name = pl_utils.is_local_builtin_camera(camera_path)
if not builtin_camera_name:
property_spec.default = str(camera_path)
else:
property_spec.default = builtin_camera_name
if builtin_camera_name:
persp_camera = pl_utils.get_user_shared_root_path(user_id).AppendChild(builtin_camera_name)
camera_prim = shared_stage.DefinePrim(persp_camera, "Camera")
await ui_test.human_delay(12)
def _get_shared_stage(self, current_session: layers.LiveSession):
shared_data_stage_url = current_session.url + "/shared_data/users.live"
layer = Sdf.Layer.FindOrOpen(shared_data_stage_url)
if not layer:
layer = Sdf.Layer.CreateNew(shared_data_stage_url)
return Usd.Stage.Open(layer)
async def _follow_user(
self, shared_stage: Usd.Stage, user_id: str, following_user_id: str
):
following_user_property_path = pl_utils.get_following_user_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), following_user_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = following_user_id
await ui_test.human_delay(6)
def _create_shared_stage(self):
current_session = self.get_live_syncing().get_current_live_session()
self.assertIsNotNone(current_session)
shared_stage = self._get_shared_stage(current_session)
self.assertIsNotNone(shared_stage)
return shared_stage
def _create_users(self, count):
return [f"user_{i}" for i in range(count)]
@MockLiveSyncingApi
async def test_live_session_camera_follower_list_user_join(self):
stage = await self._create_test_usd("test_camera")
usd_context = omni.usd.get_context()
presence_layer = pl.get_presence_layer_interface(usd_context)
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test_camera")
stage_url = usd_context.get_stage_url()
presence_layer = pl.get_presence_layer_interface(usd_context)
shared_stage = self._create_shared_stage()
camera_path = self._create_test_camera()
camera_follower_list = await self._setup_camera_follower_list(camera_path)
user_list = LiveSessionUserList(usd_context, stage_url)
users = self._create_users(3)
await self._bound_camera(shared_stage, users[0], camera_path)
for user_id in users:
join_new_simulated_user(user_id, user_id)
await ui_test.human_delay(6)
self.assertIsNotNone(presence_layer.get_bound_camera_prim(users[0]))
user_0 = self._get_user_in_session(users[0])
user_list._LiveSessionUserList__on_follow_user(
0.0,
0.0,
int(carb.input.MouseInput.LEFT_BUTTON),
None,
user_0
)
await ui_test.human_delay(6)
async def right_click_on(user):
user_list._LiveSessionUserList__on_mouse_clicked(
0.0,
0.0,
int(carb.input.MouseInput.RIGHT_BUTTON),
None,
user
)
await ui_test.human_delay(6)
timeline_session = omni.timeline.live_session.get_timeline_session()
self.assertFalse(timeline_session.is_presenter(user_0))
await right_click_on(user_0)
await self._click_on_current_menu("Set as Timeline Presenter")
self.assertTrue(timeline_session.is_presenter(user_0))
await right_click_on(user_0)
await self._click_on_current_menu("Withdraw Timeline Presenter")
self.assertFalse(timeline_session.is_presenter(user_0))
self.assertEqual(users[0], presence_layer.get_following_user_id())
await ui_test.human_delay(600)
for user_id in users:
quit_simulated_user(user_id)
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_live_session_camera_follower_list_bound_change(self):
stage = await self._create_test_usd("test_camera")
usd_context = omni.usd.get_context()
presence_layer = pl.get_presence_layer_interface(usd_context)
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test_camera")
stage_url = usd_context.get_stage_url()
presence_layer = pl.get_presence_layer_interface(usd_context)
shared_stage = self._create_shared_stage()
camera_path_1 = self._create_test_camera("camera1")
camera_path_2 = self._create_test_camera("camera2")
camera_follower_list = await self._setup_camera_follower_list(camera_path_1)
user_list = LiveSessionUserList(usd_context, stage_url)
users = self._create_users(2)
for user_id in users:
join_new_simulated_user(user_id, user_id)
await ui_test.human_delay(6)
await self._bound_camera(shared_stage, users[0], camera_path_1)
await self._bound_camera(shared_stage, users[1], camera_path_2)
await self._bound_camera(shared_stage, users[0], camera_path_2)
await self._bound_camera(shared_stage, users[1], camera_path_1)
for user_id in users:
quit_simulated_user(user_id)
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_live_session_camera_follower_list_user_join_exceed_maximum(self):
stage = await self._create_test_usd("test_camera")
usd_context = omni.usd.get_context()
presence_layer = pl.get_presence_layer_interface(usd_context)
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test_camera")
UI_MAXIMUM_USERS = 3
stage_url = usd_context.get_stage_url()
presence_layer = pl.get_presence_layer_interface(usd_context)
shared_stage = self._create_shared_stage()
camera_path = self._create_test_camera()
camera_follower_list = await self._setup_camera_follower_list(camera_path, maximum_users=UI_MAXIMUM_USERS)
user_list = LiveSessionUserList(usd_context, stage_url)
users = self._create_users(UI_MAXIMUM_USERS + 1)
for user in users:
await self._bound_camera(shared_stage, user, camera_path)
for user_id in users:
join_new_simulated_user(user_id, user_id)
await ui_test.human_delay(6)
for user_id in users:
quit_simulated_user(user_id)
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_end_and_merge(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._click_live_session_menu_item("End and Merge")
frame = ui_test.find("Merge Options")
self.assertIsNotNone(frame)
combo = ui_test.find(MERGE_OPTIONS_COMBO_BOX_PATH)
combo.model.get_item_value_model(None, 0).set_value(0)
ok_button = ui_test.find(MERGE_OPTIONS_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
@MockApiForLiveSessionManagement
async def test_end_and_merge_save_file(self):
self.assertFalse(get_merge_and_stop_live_session_async_called())
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._click_live_session_menu_item("End and Merge")
frame = ui_test.find("Merge Options")
self.assertIsNotNone(frame)
combo = ui_test.find(MERGE_OPTIONS_COMBO_BOX_PATH)
combo.model.get_item_value_model(None, 0).set_value(1)
ok_button = ui_test.find(MERGE_OPTIONS_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
self.assertTrue(get_merge_and_stop_live_session_async_called())
await self._close_case()
@MockLiveSyncingApi
async def test_end_and_merge_without_permission(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
current_session = self.get_live_syncing().get_current_live_session()
forbid_session_merge(current_session)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._click_live_session_menu_item("End and Merge")
frame = ui_test.find("Permission Denied")
self.assertIsNotNone(frame)
ok_button = ui_test.find(MERGE_PROMPT_LEAVE_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_reload_widget_on_layer(self):
stage = await self._create_test_usd("test")
usd_context = omni.usd.get_context()
await usd_context.attach_stage_async(stage)
await self._create_session("test")
layer = stage.GetSessionLayer()
window = omni.ui.Window(title='test_reload')
with window.frame:
reload_widget = build_reload_widget(layer.identifier, usd_context, True, True, False)
self.assertIsNotNone(reload_widget)
reload_widget.visible = True
await ui_test.human_delay(10)
window.width, window.height = 50, 50
reload_button = ui_test.find("test_reload//Frame/**/InvisibleButton[0]")
self.assertIsNotNone(reload_button)
await reload_button.click(right_click=True)
await ui_test.human_delay(6)
item_str_list = self._get_current_menu_item_string_list()
self.assertIn("Auto Reload", item_str_list)
self.assertIn("Reload Layer", item_str_list)
self.assertFalse(layers.get_layers_state(usd_context).is_auto_reload_layer(layer.identifier))
await self._click_on_current_menu("Auto Reload")
self.assertTrue(layers.get_layers_state(usd_context).is_auto_reload_layer(layer.identifier))
await reload_button.click(right_click=True)
await ui_test.human_delay(6)
await self._click_on_current_menu("Auto Reload")
self.assertFalse(layers.get_layers_state(usd_context).is_auto_reload_layer(layer.identifier))
await reload_button.click()
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
@MockApiForLiveSessionManagement
async def test_reload_widget_on_outdated_layer(self):
stage = await self._create_test_usd("test")
usd_context = omni.usd.get_context()
await usd_context.attach_stage_async(stage)
await self._create_session("test")
all_layers = []
for i in range(3):
layer = await self._create_test_sublayer_usd(f"layer_{i}")
self.assertIsNotNone(layer)
all_layers.append(layer)
stage.GetRootLayer().subLayerPaths.append(layer.identifier)
window = omni.ui.Window(title='test_reload')
with window.frame:
reload_widget = build_reload_widget(all_layers[0].identifier, usd_context, True, True, False)
self.assertIsNotNone(reload_widget)
reload_widget.visible = True
await ui_test.human_delay(10)
window.width, window.height = 50, 50
reload_button = ui_test.find("test_reload//Frame/**/InvisibleButton[0]")
self.assertIsNotNone(reload_button)
layer = all_layers[0]
custom_data = layer.customLayerData
custom_data['test'] = random.randint(0, 10000000)
layer.customLayerData = custom_data
layer.Save(True)
await ui_test.human_delay(6)
append_outdated_layers(all_layers[0].identifier)
await reload_button.click()
await ui_test.human_delay(6)
clear_outdated_layers()
await self._close_case()
async def test_live_session_preferences(self):
preferences = register_page(LiveSessionPreferences())
omni.kit.window.preferences.show_preferences_window()
await ui_test.human_delay(6)
label = ui_test.find("Preferences//Frame/**/ScrollingFrame[0]/TreeView[0]/Label[*].text=='Live'")
await label.click()
await ui_test.human_delay(6)
self.assertIsNotNone(preferences._checkbox_quick_join_enabled)
self.assertIsNotNone(preferences._combobox_session_list_select)
await ui_test.human_delay(6)
omni.kit.window.preferences.hide_preferences_window()
unregister_page(preferences)
def _get_user_in_session(self, user_id):
current_session = self.get_live_syncing().get_current_live_session()
session_channel = current_session._session_channel()
return session_channel._peer_users.get(user_id, None)
@MockLiveSyncingApi
async def test_file_picker(self):
temp_dir = tempfile.TemporaryDirectory()
def file_save_handler(file_path: str, overwrite_existing: bool):
prefix = "file:/"
self.assertTrue(file_path.startswith(prefix))
nonlocal called
called = True
def file_open_handler(file_path: str, overwrite_existing: bool):
nonlocal called
called = True
filter_options = [
("(.*?)", "All Files (*.*)"),
]
FILE_PICKER_DIALOG_TITLE = "test file picker"
file_picker = FilePicker(
FILE_PICKER_DIALOG_TITLE,
FileBrowserMode.SAVE,
FileBrowserSelectionType.FILE_ONLY,
filter_options,
)
called = False
file_picker.set_file_selected_fn(file_save_handler)
file_picker.show(temp_dir.name, 'test_file_picker')
await ui_test.human_delay(6)
button = ui_test.find(f"{FILE_PICKER_DIALOG_TITLE}//Frame/**/Button[*].text=='Save'")
self.assertIsNotNone(button)
await button.click()
await ui_test.human_delay(6)
self.assertTrue(called)
file_picker = FilePicker(
FILE_PICKER_DIALOG_TITLE,
FileBrowserMode.OPEN,
FileBrowserSelectionType.FILE_ONLY,
filter_options,
)
called = False
file_picker.set_file_selected_fn(file_open_handler)
file_picker.show(temp_dir.name)
await ui_test.human_delay(6)
button = ui_test.find(f"{FILE_PICKER_DIALOG_TITLE}//Frame/**/Button[*].text=='Open'")
self.assertIsNotNone(button)
await button.click()
await ui_test.human_delay(6)
self.assertTrue(called)
| 32,194 | Python | 38.024242 | 135 | 0.647139 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/scripts/camera_properties.py | import os
import carb
import omni.ext
from typing import List
from pathlib import Path
from pxr import Kind, Sdf, Usd, UsdGeom, Vt
from omni.kit.property.usd.usd_property_widget import MultiSchemaPropertiesWidget, UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import create_primspec_token, create_primspec_float, create_primspec_bool, create_primspec_string
TEST_DATA_PATH = ""
class CameraPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from . import CameraSchemaAttributesWidget
w = p.get_window()
if w:
w.register_widget(
"prim",
"camera",
CameraSchemaAttributesWidget(
"Camera",
UsdGeom.Camera,
[],
[
"cameraProjectionType",
"fthetaWidth",
"fthetaHeight",
"fthetaCx",
"fthetaCy",
"fthetaMaxFov",
"fthetaPolyA",
"fthetaPolyB",
"fthetaPolyC",
"fthetaPolyD",
"fthetaPolyE",
"fthetaPolyF",
"p0",
"p1",
"s0",
"s1",
"s2",
"s3",
"fisheyeResolutionBudget",
"fisheyeFrontFaceResolutionScale",
"interpupillaryDistance", # Only required for 'omniDirectionalStereo'
"isLeftEye", # Only required for 'omniDirectionalStereo'
"cameraSensorType",
"sensorModelPluginName",
"sensorModelConfig",
"sensorModelSignals",
"crossCameraReferenceName"
],
[],
),
)
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "camera")
self._registered = False
class CameraSchemaAttributesWidget(MultiSchemaPropertiesWidget):
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
# custom attributes
cpt_tokens = Vt.TokenArray(9, ("pinhole", "fisheyeOrthographic", "fisheyeEquidistant", "fisheyeEquisolid", "fisheyePolynomial", "fisheyeSpherical", "fisheyeKannalaBrandtK3", "fisheyeRadTanThinPrism", "omniDirectionalStereo"))
cst_tokens = Vt.TokenArray(4, ("camera", "radar", "lidar", "rtxsensor"))
self.add_custom_schema_attribute("cameraProjectionType", lambda p: p.IsA(UsdGeom.Camera), None, "Projection Type", create_primspec_token(cpt_tokens, "pinhole"))
self.add_custom_schema_attribute("fthetaWidth", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1936.0))
self.add_custom_schema_attribute("fthetaHeight", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1216.0))
self.add_custom_schema_attribute("fthetaCx", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(970.942444))
self.add_custom_schema_attribute("fthetaCy", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(600.374817))
self.add_custom_schema_attribute("fthetaMaxFov", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(200.0))
self.add_custom_schema_attribute("fthetaPolyA", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(0.0))
self.add_custom_schema_attribute("fthetaPolyB", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(2.45417095720768e-3))
self.add_custom_schema_attribute("fthetaPolyC", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(3.72747912535942e-8))
self.add_custom_schema_attribute("fthetaPolyD", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-1.43520517692508e-9))
self.add_custom_schema_attribute("fthetaPolyE", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(9.76061787817672e-13))
self.add_custom_schema_attribute("fthetaPolyF", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(0.0))
self.add_custom_schema_attribute("p0", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0003672190538065101))
self.add_custom_schema_attribute("p1", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0007413905358394097))
self.add_custom_schema_attribute("s0", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0005839984838196491))
self.add_custom_schema_attribute("s1", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0002193412417918993))
self.add_custom_schema_attribute("s2", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(0.0001936268547567258))
self.add_custom_schema_attribute("s3", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0002042473404798113))
self.add_custom_schema_attribute("fisheyeResolutionBudget", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1.5))
self.add_custom_schema_attribute("fisheyeFrontFaceResolutionScale", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1.0))
self.add_custom_schema_attribute("interpupillaryDistance", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(6.4))
self.add_custom_schema_attribute("isLeftEye", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("sensorModelPluginName", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("sensorModelConfig", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("sensorModelSignals", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("crossCameraReferenceName", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("cameraSensorType", lambda p: p.IsA(UsdGeom.Camera), None, "Sensor Type", create_primspec_token(cst_tokens, "camera"))
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim or not prim.IsA(self._schema):
return False
used += [attr for attr in prim.GetAttributes() if attr.GetName() in self._schema_attr_names and not attr.IsHidden()]
camProjTypeAttr = prim.GetAttribute("cameraProjectionType")
if prim.IsA(UsdGeom.Camera) and camProjTypeAttr.GetTypeName() == Sdf.ValueTypeNames.Token:
tokens = camProjTypeAttr.GetMetadata("allowedTokens")
if not tokens:
camProjTypeAttr.SetMetadata("allowedTokens", ["pinhole", "fisheyeOrthographic", "fisheyeEquidistant", "fisheyeEquisolid", "fisheyePolynomial", "fisheyeSpherical", "fisheyeKannalaBrandtK3", "fisheyeRadTanThinPrism", "omniDirectionalStereo"])
if self.is_custom_schema_attribute_used(prim):
used.append(None)
camSensorTypeAttr = prim.GetAttribute("cameraSensorType")
if prim.IsA(UsdGeom.Camera) and camSensorTypeAttr.GetTypeName() == Sdf.ValueTypeNames.Token:
tokens = camSensorTypeAttr.GetMetadata("allowedTokens")
if not tokens:
camSensorTypeAttr.SetMetadata("allowedTokens", ["camera", "radar", "lidar", "rtxsensor"])
return used
def _customize_props_layout(self, attrs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.window.property.templates import (
SimplePropertyWidget,
LABEL_WIDTH,
LABEL_HEIGHT,
HORIZONTAL_SPACING,
)
self.add_custom_schema_attributes_to_props(attrs)
anchor_prim = self._get_prim(self._payload[-1])
frame = CustomLayoutFrame(hide_extra=False)
with frame:
with CustomLayoutGroup("Lens"):
CustomLayoutProperty("focalLength", "Focal Length")
CustomLayoutProperty("focusDistance", "Focus Distance")
CustomLayoutProperty("fStop", "fStop")
CustomLayoutProperty("projection", "Projection")
CustomLayoutProperty("stereoRole", "Stereo Role")
with CustomLayoutGroup("Horizontal Aperture"):
CustomLayoutProperty("horizontalAperture", "Aperture")
CustomLayoutProperty("horizontalApertureOffset", "Offset")
with CustomLayoutGroup("Vertical Aperture"):
CustomLayoutProperty("verticalAperture", "Aperture")
CustomLayoutProperty("verticalApertureOffset", "Offset")
with CustomLayoutGroup("Clipping"):
CustomLayoutProperty("clippingPlanes", "Clipping Planes")
CustomLayoutProperty("clippingRange", "Clipping Range")
with CustomLayoutGroup("Fisheye Lens", collapsed=True):
CustomLayoutProperty("cameraProjectionType", "Projection Type")
CustomLayoutProperty("fthetaWidth", "Nominal Width")
CustomLayoutProperty("fthetaHeight", "Nominal Height")
CustomLayoutProperty("fthetaCx", "Optical Center X")
CustomLayoutProperty("fthetaCy", "Optical Center Y")
CustomLayoutProperty("fthetaMaxFov", "Max FOV")
CustomLayoutProperty("fthetaPolyA", "Poly k0")
CustomLayoutProperty("fthetaPolyB", "Poly k1")
CustomLayoutProperty("fthetaPolyC", "Poly k2")
CustomLayoutProperty("fthetaPolyD", "Poly k3")
CustomLayoutProperty("fthetaPolyE", "Poly k4")
CustomLayoutProperty("fthetaPolyF", "Poly k5")
CustomLayoutProperty("p0", "p0")
CustomLayoutProperty("p1", "p1")
CustomLayoutProperty("s0", "s0")
CustomLayoutProperty("s1", "s1")
CustomLayoutProperty("s2", "s2")
CustomLayoutProperty("s3", "s3")
CustomLayoutProperty("fisheyeResolutionBudget", "Max Fisheye Resolution (% of Viewport Resolution")
CustomLayoutProperty("fisheyeFrontFaceResolutionScale", "Front Face Resolution Scale")
CustomLayoutProperty("interpupillaryDistance", "Interpupillary Distance (cm)")
CustomLayoutProperty("isLeftEye", "Is left eye")
with CustomLayoutGroup("Shutter", collapsed=True):
CustomLayoutProperty("shutter:open", "Open")
CustomLayoutProperty("shutter:close", "Close")
with CustomLayoutGroup("Sensor Model", collapsed=True):
CustomLayoutProperty("cameraSensorType", "Sensor Type")
CustomLayoutProperty("sensorModelPluginName", "Sensor Plugin Name")
CustomLayoutProperty("sensorModelConfig", "Sensor Config")
CustomLayoutProperty("sensorModelSignals", "Sensor Signals")
with CustomLayoutGroup("Synthetic Data Generation", collapsed=True):
CustomLayoutProperty("crossCameraReferenceName", "Cross Camera Reference")
return frame.apply(attrs)
def get_additional_kwargs(self, ui_prop: UsdPropertyUiEntry):
"""
Override this function if you want to supply additional arguments when building the label or ui widget.
"""
additional_widget_kwargs = None
if ui_prop.prop_name == "fisheyeResolutionBudget":
additional_widget_kwargs = {"min": 0, "max": 10}
if ui_prop.prop_name == "fisheyeFrontFaceResolutionScale":
additional_widget_kwargs = {"min": 0, "max": 10}
return None, additional_widget_kwargs
| 14,637 | Python | 57.087301 | 260 | 0.581813 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/scripts/__init__.py | from .camera_properties import *
| 33 | Python | 15.999992 | 32 | 0.787879 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/tests/__init__.py | from .test_camera import *
from .test_prim_edits_and_auto_target import *
| 74 | Python | 23.999992 | 46 | 0.756757 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/tests/test_prim_edits_and_auto_target.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 os
import carb
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf, Usd
class TestPrimEditsAndAutoTarget(omni.kit.test.AsyncTestCase):
def __init__(self, tests=()):
super().__init__(tests)
# Before running each test
async def setUp(self):
self._usd_context = omni.usd.get_context()
await self._usd_context.new_stage_async()
self._stage = self._usd_context.get_stage()
from omni.kit.test_suite.helpers import arrange_windows
await arrange_windows(topleft_window="Property", topleft_height=64, topleft_width=800.0)
await self.wait()
# After running each test
async def tearDown(self):
from omni.kit.test_suite.helpers import wait_stage_loading
await wait_stage_loading()
async def wait(self, updates=3):
for i in range(updates):
await omni.kit.app.get_app().next_update_async()
async def test_built_in_camera_editing(self):
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
# wait for material to load & UI to refresh
await wait_stage_loading()
prim_path = "/OmniverseKit_Persp"
await select_prims([prim_path])
# Loading all inputs
await self.wait()
all_widgets = ui_test.find_all("Property//Frame/**/.identifier!=''")
self.assertNotEqual(all_widgets, [])
for w in all_widgets:
id = w.widget.identifier
if id.startswith("float_slider_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
await w.input(str(0.3456))
await ui_test.human_delay()
elif id.startswith("integer_slider_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[15:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = old_value + 1
await w.input(str(new_value))
await ui_test.human_delay()
elif id.startswith("drag_per_channel_int"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/IntSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/IntDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
child.model.set_value(0)
await child.input("9999")
await ui_test.human_delay()
elif id.startswith("drag_per_channel_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/FloatSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/FloatDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
await child.input("0.12345")
await self.wait()
elif id.startswith("bool_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[5:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = not old_value
w.widget.model.set_value(new_value)
elif id.startswith("sdf_asset_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
new_value = "testpath/abc.png"
w.widget.model.set_value(new_value)
await ui_test.human_delay()
# All property edits to built-in cameras should be retargeted into session layer.
root_layer = self._stage.GetRootLayer()
prim_spec = root_layer.GetPrimAtPath("/OmniverseKit_Persp")
self.assertTrue(bool(prim_spec))
| 4,561 | Python | 39.371681 | 96 | 0.578163 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/tests/test_camera.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf
import pathlib
class TestCameraWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
from omni.kit.property.camera.scripts.camera_properties import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_camera_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=675,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("camera_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/Camera"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_camera_ui.png")
| 2,162 | Python | 35.661016 | 107 | 0.691489 |
omniverse-code/kit/exts/omni.rtx.multinode.dev/omni/rtx/multinode/dev/multinode.py | import traceback
import uuid
import carb
import carb.settings
import omni.ext
import omni.ui as ui
import omni.gpu_foundation_factory
import omni.client
from random import random
import math
from omni.physx.scripts import physicsUtils
from pxr import UsdLux, UsdGeom, Gf, UsdPhysics
def print_exception(exc_info):
print(f"===== Exception: {exc_info[0]}, {exc_info[1]}. Begin Stack Trace =====")
traceback.print_tb(exc_info[2])
print("===== End Stack Trace ===== ")
class Extension(omni.ext.IExt):
def on_startup(self):
# Obtain multi process info
gpu = omni.gpu_foundation_factory.get_gpu_foundation_factory_interface()
processIndex = gpu.get_process_index()
processCount = gpu.get_process_count()
# Settings
self._settings = carb.settings.get_settings()
self._settings.set("/persistent/physics/updateToUsd", False)
self._settings.set("/persistent/physics/updateVelocitiesToUsd", False)
self._settings.set("/persistent/omnihydra/useFastSceneDelegate", True)
self._settings.set("/app/renderer/sleepMsOutOfFocus", 0)
if processIndex > 0:
self._settings.set("/app/window/title", "Kit Worker {} //".format(processIndex))
# UI
self._window = ui.Window("RTX Multi-Node Prototype", dockPreference=ui.DockPreference.LEFT_BOTTOM)
self._window.deferred_dock_in("Console", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
with self._window.frame:
with omni.ui.HStack(height=0):
omni.ui.Spacer(width=6)
with omni.ui.VStack(height=0):
omni.ui.Spacer(height=10)
with omni.ui.HStack(height=0):
if processIndex == 0:
omni.ui.Label("Master process of {}".format(processCount))
else:
omni.ui.Label("Worker process {} of {}".format(processIndex, processCount))
if processIndex == 0:
omni.ui.Spacer(height=20)
with omni.ui.HStack():
with omni.ui.VStack(height=0):
omni.ui.Label("Settings")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=10)
with omni.ui.VStack(width = 200, height = 0):
with omni.ui.HStack():
omni.ui.Label("Fabric Replication")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/flatcacheReplication/enabled"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/flatcacheReplication/enabled", a.get_value_as_bool()))
omni.ui.Label("Enabled")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/flatcacheReplication/profile"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/flatcacheReplication/profile", a.get_value_as_bool()))
omni.ui.Label("Profile")
omni.ui.Spacer(height=10)
with omni.ui.HStack():
omni.ui.Label("Gather Render Results")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/gatherResults/enabled"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/gatherResults/enabled", a.get_value_as_bool()))
omni.ui.Label("Enabled")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/gatherResults/profile"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/gatherResults/profile", a.get_value_as_bool()))
omni.ui.Label("Profile")
with omni.ui.VStack(width = 200, height=0):
with omni.ui.HStack():
omni.ui.Label("Render Product Replication")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/enabled"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/enabled", a.get_value_as_bool()))
omni.ui.Label("Enabled")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/includeCameraAttributes"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/includeCameraAttributes", a.get_value_as_bool()))
omni.ui.Label("Include Camera Attributes")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/fullSessionLayer"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/fullSessionLayer", a.get_value_as_bool()))
omni.ui.Label("Full Session Layer")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/profile"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/profile", a.get_value_as_bool()))
omni.ui.Label("Profile")
omni.ui.Spacer(height=5)
with omni.ui.HStack():
omni.ui.Spacer(width=20)
box = omni.ui.CheckBox(width = 22)
box.model.set_value(self._settings.get("/multiNode/renderProductReplication/print"))
box.model.add_value_changed_fn(lambda a: self._settings.set("/multiNode/renderProductReplication/print", a.get_value_as_bool()))
omni.ui.Label("Print")
omni.ui.Spacer(width=200)
with omni.ui.VStack(height=0):
omni.ui.Label("Deprecated: Physics prototype")
omni.ui.Spacer(height=10)
with omni.ui.HStack(height=0):
load_button = omni.ui.Button("Load Stage", width=150, height=30)
load_button.set_clicked_fn(self._on_load_button_fn)
omni.ui.Spacer(height=5)
with omni.ui.HStack(height=0):
self._numBoxesDrag = omni.ui.IntDrag(min = 1, max = 1000000, step = 1, width = 100)
self._numBoxesDrag.model.set_value(1000)
omni.ui.Spacer(width=10)
omni.ui.Label("Boxes")
omni.ui.Spacer(height=5)
with omni.ui.HStack(height=0):
init_button = omni.ui.Button("Init Simulation", width=150, height=30)
init_button.set_clicked_fn(self._on_init_button_fn)
omni.ui.Spacer(height=5)
with omni.ui.HStack(height=0):
play_button = omni.ui.Button("Play Simulation", width=150, height=30)
play_button.set_clicked_fn(self._on_play_button_fn)
omni.ui.Spacer()
def on_shutdown(self):
pass
def _on_load_button_fn(self):
carb.log_warn("Load stage")
srcPath = "omniverse://content.ov.nvidia.com/Users/[email protected]/multi-node/empty.usd"
dstPath = "omniverse://content.ov.nvidia.com/Users/[email protected]/multi-node/gen/" + str(uuid.uuid4()) + ".usd"
# Create a temporary copy
try:
result = omni.client.copy(srcPath, dstPath, omni.client.CopyBehavior.OVERWRITE)
if result != omni.client.Result.OK:
carb.log_error(f"Cannot copy from {srcPath} to {dstPath}, error code: {result}.")
else:
carb.log_warn(f"Copied from {srcPath} to {dstPath}.")
except Exception as e:
traceback.print_exc()
carb.log_error(str(e))
# Load the temporary copy
omni.usd.get_context().open_stage(str(dstPath))
# FIXME: Add compatible API for legacy usage.
# Enable live sync
# omni.usd.get_context().set_stage_live(layers.LayerLiveMode.ALWAYS_ON)
def _on_init_button_fn(self):
carb.log_warn("Init simulation")
# Disable FlatCache replication
self._settings.set("/multiNode/flatcacheReplication/enabled", False)
# set up axis to z
stage = omni.usd.get_context().get_stage()
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(stage, 0.01)
# Disable default light
defaultPrimPath = str(stage.GetDefaultPrim().GetPath())
stage.RemovePrim(defaultPrimPath + "/defaultLight")
# light
sphereLight = UsdLux.SphereLight.Define(stage, defaultPrimPath + "/SphereLight")
sphereLight.CreateRadiusAttr(30)
sphereLight.CreateIntensityAttr(50000)
sphereLight.AddTranslateOp().Set(Gf.Vec3f(0.0, 0.0, 150.0))
# Boxes
numBoxes = self._numBoxesDrag.model.get_value_as_int()
size = 25.0
radius = 100.0
self._boxes = [None] * numBoxes
for i in range(numBoxes):
box = UsdGeom.Cube.Define(stage, defaultPrimPath + "/box_" + str(i))
box.CreateSizeAttr(size)
box.CreateExtentAttr([(-size / 2, -size / 2, -size / 2), (size / 2, size / 2, size / 2)])
box.AddTranslateOp().Set(Gf.Vec3f(radius * math.cos(0.5 * i), radius * math.sin(0.5 * i), size + (i * 0.2) * size))
box.AddOrientOp().Set(Gf.Quatf(random(), random(), random(), random()).GetNormalized())
box.CreateDisplayColorAttr().Set([Gf.Vec3f(random(), random(), random())])
self._boxes[i] = box.GetPrim()
# Plane
planeActorPath = defaultPrimPath + "/plane"
size = 1500.0
planeGeom = UsdGeom.Cube.Define(stage, planeActorPath)
self._plane = stage.GetPrimAtPath(planeActorPath)
planeGeom.CreateSizeAttr(size)
planeGeom.CreateExtentAttr([(-size / 2, -size / 2, -size / 2), (size / 2, size / 2, size / 2)])
planeGeom.AddTranslateOp().Set(Gf.Vec3f(0.0, 0.0, 0.0))
planeGeom.AddOrientOp().Set(Gf.Quatf(1.0))
planeGeom.AddScaleOp().Set(Gf.Vec3f(1.0, 1.0, 0.01))
planeGeom.CreateDisplayColorAttr().Set([Gf.Vec3f(0.5)])
def _on_play_button_fn(self):
carb.log_warn("Play simulation")
# FIXME: Add compatible API for legacy usage.
# Disable live sync
# omni.usd.get_context().set_stage_live(layers.LayerLiveMode.TOGGLE_OFF)
# Enable FlatCache replication
self._settings.set("/multiNode/flatcacheReplication/enabled", True)
# Add physics to scene
stage = omni.usd.get_context().get_stage()
defaultPrimPath = str(stage.GetDefaultPrim().GetPath())
scene = UsdPhysics.Scene.Define(stage, defaultPrimPath + "/physicsScene")
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(981.0)
for box in self._boxes:
UsdPhysics.CollisionAPI.Apply(box)
physicsAPI = UsdPhysics.RigidBodyAPI.Apply(box)
UsdPhysics.MassAPI.Apply(box)
UsdPhysics.CollisionAPI.Apply(self._plane)
# Play animation
omni.timeline.get_timeline_interface().play()
| 14,830 | Python | 53.127737 | 190 | 0.494066 |
omniverse-code/kit/exts/omni.rtx.multinode.dev/omni/rtx/multinode/dev/__init__.py | from .multinode import *
| 25 | Python | 11.999994 | 24 | 0.76 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ext
from .stage_listener import StageListener
_global_instance = None
class SelectionOutlineExtension(omni.ext.IExt):
def on_startup(self):
global _global_instance
_global_instance = self
self._stage_listener = StageListener()
self._stage_listener.start()
def on_shutdown(self):
global _global_instance
_global_instance = None
self._stage_listener.stop()
@staticmethod
def _get_instance():
global _global_instance
return _global_instance
| 989 | Python | 28.999999 | 76 | 0.723964 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/stage_listener.py | import asyncio
import carb
import omni.client
import omni.usd
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
from omni.kit.async_engine import run_coroutine
from .manipulator import PeerUserList
from pxr import Sdf, Usd, UsdGeom, Tf, Trace
from typing import Dict, List, Union
SETTING_MULTI_USER_OUTLINE = "/app/viewport/multiUserOutlineMode"
SETTING_SAVED_OUTLINE_COLOR = "/persistent/app/viewport/live_session/saved_outline_color"
SETTING_OUTLINE_COLOR = "/persistent/app/viewport/outline/color"
SETTING_MAXIMUM_SELECTION_ICONS_PER_USER = "/exts/omni/kit/collaboration/selection_outline/maximum_selection_icons_per_user"
class MultiUserSelectionOutlineManager:
def __init__(self, usd_context: omni.usd.UsdContext) -> None:
self.__usd_context = usd_context
self.__settings = carb.settings.get_settings()
self.__user_last_selected_prims = {}
self.__prim_selection_queue = {}
self.__user_selection_group = {}
self.__selection_group_pool = []
self.__prim_viewport_widget = {}
self._delay_refresh_task_or_future = None
def clear_all_selection(self):
self.__user_last_selected_prims = {}
self.__prim_selection_queue = {}
self.__user_selection_group = {}
for widget in self.__prim_viewport_widget.values():
widget.destroy()
self.__prim_viewport_widget = {}
if self._delay_refresh_task_or_future:
self._delay_refresh_task_or_future.cancel()
self._delay_refresh_task_or_future = None
def clear_selection(self, user_id):
"""Deregister user from selection group."""
selection_group = self.__user_selection_group.pop(user_id, None)
if selection_group:
self.__update_selection_outline_internal(user_id, selection_group, {})
# Returns selection group to re-use as it supports 255 at maximum due to limitation of renderer.
self.__selection_group_pool.append(selection_group)
def on_usd_objects_changed(self, notice):
stage = self.__usd_context.get_stage()
to_remove_paths = []
to_update_paths = []
for widget_path, widget in self.__prim_viewport_widget.items():
prim = stage.GetPrimAtPath(widget_path)
if not prim or not prim.IsActive() or not prim.IsDefined():
to_remove_paths.append(widget_path)
elif notice.ResyncedObject(prim):
to_update_paths.append(widget_path)
else:
changed_info_only_paths = notice.GetChangedInfoOnlyPaths()
slice_object = Sdf.Path.FindPrefixedRange(changed_info_only_paths, widget_path)
if not slice_object:
continue
paths = changed_info_only_paths[slice_object]
if not paths:
continue
for path in paths:
if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name):
to_update_paths.append(widget_path)
break
for path in to_remove_paths:
widget = self.__prim_viewport_widget.pop(path, None)
widget.destroy()
for path in to_update_paths:
widget = self.__prim_viewport_widget.get(path, None)
widget.on_transform_changed()
def refresh_selection(self, selection_paths: List[Sdf.Path]):
"""
Calls this to refresh selection. This is normally called after selection changed, which will
override the outline of remote users.
"""
if not selection_paths:
return
for path in selection_paths:
self.__set_prim_outline(0, path)
async def delay_refresh(paths):
await omni.kit.app.get_app().next_update_async()
for path in paths:
selection_queue = self.__get_selection_queue(path)
for _, group in selection_queue.items():
self.__set_prim_outline(group, path)
break
self._delay_refresh_task_or_future = None
if self._delay_refresh_task_or_future and not self._delay_refresh_task_or_future.done():
self._delay_refresh_task_or_future.cancel()
self._delay_refresh_task_or_future = run_coroutine(delay_refresh(selection_paths))
def update_selection_outline(self, user_info: layers.LiveSessionUser, selection_paths: List[Sdf.Path]):
user_id = user_info.user_id
selection_group = self.__user_selection_group.get(user_id, None)
if not selection_group:
# Re-use selection group.
if self.__selection_group_pool:
selection_group = self.__selection_group_pool.pop(0)
else:
selection_group = self.__usd_context.register_selection_group()
self.__user_selection_group[user_id] = selection_group
# RGBA
color = (
user_info.user_color[0] / 255.0,
user_info.user_color[1] / 255.0,
user_info.user_color[2] / 255.0,
1.0
)
self.__usd_context.set_selection_group_outline_color(selection_group, color)
self.__usd_context.set_selection_group_shade_color(selection_group, (0.0, 0.0, 0.0, 0.0))
if selection_group == 0:
carb.log_error("The maximum number (255) of selection groups is reached.")
return
selection_paths = [Sdf.Path(path) for path in selection_paths]
selection_paths = Sdf.Path.RemoveDescendentPaths(selection_paths)
stage = self.__usd_context.get_stage()
# Find all renderable prims
all_renderable_prims = {}
for path in selection_paths:
prim = stage.GetPrimAtPath(path)
if not prim:
continue
renderable_prims = []
for prim in Usd.PrimRange(prim, Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)):
# Camera in Kit has special representation, which needs to be excluded.
if (
not prim.IsActive()
or omni.usd.editor.is_hide_in_ui(prim)
or omni.usd.editor.is_hide_in_stage_window(prim)
):
break
if (
not prim.GetPath().name == "CameraModel"
and not prim.GetPath().GetParentPath().name == "OmniverseKitViewportCameraMesh"
and prim.IsA(UsdGeom.Gprim)
):
renderable_prims.append(prim.GetPath())
if renderable_prims:
all_renderable_prims[path] = renderable_prims
selection_paths = all_renderable_prims
# Draw user icon
maximum_count = self.__settings.get(SETTING_MAXIMUM_SELECTION_ICONS_PER_USER)
if not maximum_count or maximum_count <= 0:
maximum_count = 3
for index, path in enumerate(selection_paths.keys()):
path = Sdf.Path(path)
widget = self.__prim_viewport_widget.get(path, None)
if not widget:
widget = PeerUserList(self.__usd_context, path)
self.__prim_viewport_widget[path] = widget
widget.add_user(user_info)
# OMFP-2736: Don't show all selections to avoid cluttering the viewport.
if index + 1 >= maximum_count:
break
self.__update_selection_outline_internal(user_id, selection_group, selection_paths)
def __update_selection_outline_internal(
self, user_id, selection_group,
all_renderable_paths: Dict[Sdf.Path, List[Sdf.Path]]
):
last_selected_prim_and_renderable_paths = self.__user_last_selected_prims.get(user_id, {})
last_selected_prim_paths = set(last_selected_prim_and_renderable_paths.keys())
selection_paths = set(all_renderable_paths.keys())
if last_selected_prim_paths == selection_paths:
return
if last_selected_prim_paths:
old_selected_paths = last_selected_prim_paths.difference(selection_paths)
new_selected_paths = selection_paths.difference(last_selected_prim_paths)
else:
old_selected_paths = set()
new_selected_paths = selection_paths
# Update selection outline for old paths
to_clear_paths = []
for path in old_selected_paths:
# Remove user icon
widget = self.__prim_viewport_widget.get(path, None)
if widget:
widget.remove_user(user_id)
if widget.empty_user_list():
self.__prim_viewport_widget.pop(path, None)
widget.destroy()
# Remove outline of all renderable prims under the selected path.
renderable_paths = last_selected_prim_and_renderable_paths.get(path, None)
for renderable_path in renderable_paths:
selection_queue = self.__get_selection_queue(renderable_path)
if selection_queue:
# FIFO queue that first user that selects the prim decides the color of selection.
group = next(iter(selection_queue.values()))
same_group = selection_group == group
# Pop this user and outline the prim with next user's selection color.
selection_queue.pop(user_id, None)
if same_group and selection_queue:
for _, group in selection_queue.items():
self.__set_prim_outline(group, renderable_path)
break
elif same_group:
to_clear_paths.append(renderable_path)
# Update selection outline for new paths
to_select_paths = []
for path in new_selected_paths:
renderable_paths = all_renderable_paths.get(path, None)
if not renderable_paths:
continue
for renderable_path in renderable_paths:
selection_queue = self.__get_selection_queue(renderable_path)
has_outline = not not selection_queue
selection_queue[user_id] = selection_group
if not has_outline:
to_select_paths.append(renderable_path)
if to_clear_paths:
self.__clear_prim_outline(to_clear_paths)
if to_select_paths:
self.__set_prim_outline(selection_group, to_select_paths)
self.__user_last_selected_prims[user_id] = all_renderable_paths
def __get_selection_queue(self, prim_path):
prim_path = Sdf.Path(prim_path)
if prim_path not in self.__prim_selection_queue:
# Value is dict to keep order of insertion.
self.__prim_selection_queue[prim_path] = {}
return self.__prim_selection_queue[prim_path]
def __set_prim_outline(self, selection_group, prim_path: Union[Sdf.Path, List[Sdf.Path]]):
if isinstance(prim_path, list):
paths = [str(path) for path in prim_path]
else:
paths = [str(prim_path)]
selection = self.__usd_context.get_selection().get_selected_prim_paths()
for path in paths:
# If it's locally selected, don't override the outline.
if path in selection:
continue
self.__usd_context.set_selection_group(selection_group, path)
def __clear_prim_outline(self, prim_path: Union[Sdf.Path, List[Sdf.Path]]):
self.__set_prim_outline(0, prim_path)
class StageListener:
def __init__(self, usd_context_name=""):
self.__usd_context = omni.usd.get_context(usd_context_name)
self.__presence_layer = pl.get_presence_layer_interface(self.__usd_context)
self.__live_syncing = layers.get_live_syncing(self.__usd_context)
self.__layers = layers.get_layers(self.__usd_context)
self.__layers_event_subscriptions = []
self.__stage_event_subscription = None
self.__settings = carb.settings.get_settings()
self.__selection_paths_initialized = False
self.__stage_objects_changed = None
self.__multi_user_selection_manager = MultiUserSelectionOutlineManager(self.__usd_context)
self.__delayed_task_or_future = None
self.__changed_user_ids = set()
def start(self):
self.__restore_local_outline_color()
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
pl.PresenceLayerEventType.SELECTIONS_CHANGED,
]:
layers_event_sub = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event, name=f"omni.kit.collaboration.selection_outline {str(event)}"
)
self.__layers_event_subscriptions.append(layers_event_sub)
self.__stage_event_subscription = self.__usd_context.get_stage_event_stream().create_subscription_to_pop(
self.__on_stage_event, name="omni.kit.collaboration.selection_outline stage event"
)
self.__start_subscription()
def __start_subscription(self):
self.__settings.set(SETTING_MULTI_USER_OUTLINE, True)
live_session = self.__live_syncing.get_current_live_session()
if not live_session:
return
for peer_user in live_session.peer_users:
selection_paths = self.__presence_layer.get_selections(peer_user.user_id)
self.__multi_user_selection_manager.update_selection_outline(peer_user, selection_paths)
if not self.__selection_paths_initialized:
self.__selection_paths_initialized = True
selection = self.__usd_context.get_selection().get_selected_prim_paths()
self.__on_selection_changed(selection)
root_layer_session = self.__live_syncing.get_current_live_session()
if root_layer_session:
logged_user = root_layer_session.logged_user
user_color = logged_user.user_color
rgba = (user_color[0] / 255.0, user_color[1] / 255.0, user_color[2] / 255.0, 1.0)
self.__save_and_set_local_outline_color(rgba)
self.__stage_objects_changed = Tf.Notice.Register(
Usd.Notice.ObjectsChanged, self.__on_usd_changed, self.__usd_context.get_stage()
)
@Trace.TraceFunction
@carb.profiler.profile
def __on_usd_changed(self, notice, sender):
if not sender or sender != self.__usd_context.get_stage():
return
self.__multi_user_selection_manager.on_usd_objects_changed(notice)
def __stop_subscription(self):
self.__changed_user_ids.clear()
if self.__delayed_task_or_future and not self.__delayed_task_or_future.done():
self.__delayed_task_or_future.cancel()
self.__delayed_task_or_future = None
self.__restore_local_outline_color()
self.__selection_paths_initialized = False
self.__multi_user_selection_manager.clear_all_selection()
self.__settings.set(SETTING_MULTI_USER_OUTLINE, False)
if self.__stage_objects_changed:
self.__stage_objects_changed.Revoke()
self.__stage_objects_changed = None
def stop(self):
self.__stop_subscription()
self.__layers_event_subscription = None
self.__stage_event_subscription = None
def __save_and_set_local_outline_color(self, color):
old_color = self.__settings.get(SETTING_OUTLINE_COLOR)
if old_color:
self.__settings.set(SETTING_SAVED_OUTLINE_COLOR, old_color)
old_color[-4:] = color
else:
# It has maximum 255 group + selection_outline
old_color = [0] * 256
old_color[-4:] = color
color = old_color
self.__settings.set(SETTING_OUTLINE_COLOR, color)
def __restore_local_outline_color(self):
# It's possible that Kit is shutdown abnormally. So it can
# be used to restore the outline color before live session or abort.
color = self.__settings.get(SETTING_SAVED_OUTLINE_COLOR)
if not color:
return
self.__settings.set(SETTING_OUTLINE_COLOR, color)
# Clear saved color
self.__settings.set(SETTING_SAVED_OUTLINE_COLOR, None)
def __on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
if not self.__live_syncing.get_current_live_session():
return
selection = self.__usd_context.get_selection().get_selected_prim_paths()
self.__on_selection_changed(selection)
elif event.type == int(omni.usd.StageEventType.CLOSING):
self.__stop_subscription()
def __on_selection_changed(self, selection_paths):
self.__multi_user_selection_manager.refresh_selection(selection_paths)
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
if self.__live_syncing.get_current_live_session():
self.__start_subscription()
else:
self.__stop_subscription()
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED:
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
user_id = payload.user_id
live_session = self.__live_syncing.get_current_live_session()
user_info = live_session.get_peer_user_info(user_id)
selection_paths = self.__presence_layer.get_selections(user_id)
self.__multi_user_selection_manager.update_selection_outline(user_info, selection_paths)
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
user_id = payload.user_id
self.__multi_user_selection_manager.clear_selection(user_id)
else:
payload = pl.get_presence_layer_event_payload(event)
if payload.event_type == pl.PresenceLayerEventType.SELECTIONS_CHANGED:
self.__changed_user_ids.update(payload.changed_user_ids)
# Delay the selection updates.
if not self.__delayed_task_or_future or self.__delayed_task_or_future.done():
self.__delayed_task_or_future = run_coroutine(self.__handle_selection_changes())
async def __handle_selection_changes(self):
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session:
return
for user_id in self.__changed_user_ids:
user_info = current_live_session.get_peer_user_info(user_id)
if not user_info:
continue
selection_paths = self.__presence_layer.get_selections(user_id)
self.__multi_user_selection_manager.update_selection_outline(user_info, selection_paths)
self.__changed_user_ids.clear()
self.__delayed_task_or_future = None
| 19,602 | Python | 41.522776 | 124 | 0.604173 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/manipulator/peer_user_list_manipulator_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["PeerUserListManipulatorModel"]
import carb
import omni.usd
import omni.kit.usd.layers as layers
from omni.ui import scene as sc
from pxr import Gf, UsdGeom, Usd, Sdf, Tf, Trace
class PeerUserListManipulatorModel(sc.AbstractManipulatorModel):
"""The model tracks the position of peer user's camera in a live session."""
class PositionItem(sc.AbstractManipulatorItem):
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class UserListItem(sc.AbstractManipulatorItem):
def __init__(self):
super().__init__()
self.value = {}
def __init__(self, prim_path, usd_context: omni.usd.UsdContext):
super().__init__()
self.position = PeerUserListManipulatorModel.PositionItem()
self.user_list = PeerUserListManipulatorModel.UserListItem()
self.__prim_path = Sdf.Path(prim_path)
self.__usd_context = usd_context
self.__update_position = True
def destroy(self):
self.position = None
self.__usd_context = None
def add_user(self, user_info: layers.LiveSessionUser):
if user_info.user_id in self.user_list.value:
return
self.user_list.value[user_info.user_id] = user_info
# This makes the manipulator updated
self._item_changed(self.user_list)
def remove_user(self, user_id):
item = self.user_list.value.pop(user_id, None)
if not item:
# This makes the manipulator updated
self._item_changed(self.user_list)
def empty_user_list(self):
return len(self.user_list.value) == 0
def get_item(self, identifier):
if identifier == "position":
return self.position
elif identifier == "user_list":
return self.user_list
return None
def get_as_floats(self, item):
if item == self.position:
# Requesting position
if self.__update_position:
self.position.value = self._get_position()
self.__update_position = False
return self.position.value
return []
def set_floats(self, item, value):
if item != self.position:
return
if not value or item.value == value:
return
# Set directly to the item
item.value = value
self.__update_position = False
# This makes the manipulator updated
self._item_changed(item)
def on_transform_changed(self, position=None):
"""When position is provided, it will not re-calculate position but use provided value instead."""
# Position is changed
if position:
self.set_floats(self.position, position)
else:
self.__update_position = True
self._item_changed(self.position)
def _get_position(self):
"""Returns center position at the top of the bbox for the current selected object."""
stage = self.__usd_context.get_stage()
prim = stage.GetPrimAtPath(self.__prim_path)
if not prim:
return []
# Get bounding box from prim
aabb_min, aabb_max = self.__usd_context.compute_path_world_bounding_box(
str(self.__prim_path)
)
gf_range = Gf.Range3d(
Gf.Vec3d(aabb_min[0], aabb_min[1], aabb_min[2]),
Gf.Vec3d(aabb_max[0], aabb_max[1], aabb_max[2])
)
if gf_range.IsEmpty():
# May be empty (UsdGeom.Xform for example), so build a scene-scaled constant box
world_units = UsdGeom.GetStageMetersPerUnit(stage)
if Gf.IsClose(world_units, 0.0, 1e-6):
world_units = 0.01
xformable_prim = UsdGeom.Xformable(prim)
world_xform = xformable_prim.ComputeLocalToWorldTransform(Usd.TimeCode.Default())
ref_position = world_xform.ExtractTranslation()
extent = Gf.Vec3d(0.1 / world_units) # 10cm by default
gf_range.SetMin(ref_position - extent)
gf_range.SetMax(ref_position + extent)
bboxMin = gf_range.GetMin()
bboxMax = gf_range.GetMax()
position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1], (bboxMin[2] + bboxMax[2]) * 0.5]
return position
| 4,784 | Python | 32 | 106 | 0.607232 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/manipulator/__init__.py | from .peer_user_list import PeerUserList
| 41 | Python | 19.99999 | 40 | 0.829268 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/manipulator/peer_user_list_manipulator.py | ## Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ["PeerUserListManipulator"]
import omni.ui as ui
import omni.kit.usd.layers as layers
from omni.ui import scene as sc
from omni.ui import color as cl
class PeerUserListManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.__position_transform = None
self.__user_list_transform = None
self.__hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: self.__show_tooltip(sender),
on_ended_fn=lambda sender: self.__show_tooltip(sender)
)
def destroy(self):
self.__hover_gesture = None
self.__clear()
def __clear(self):
if self.__position_transform:
self.__position_transform.clear()
self.__position_transform = None
if self.__user_list_transform:
self.__user_list_transform.clear()
self.__user_list_transform = None
def __show_tooltip(self, sender):
pass
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
position = self.model.get_as_floats(self.model.get_item("position"))
if not position:
return
user_list_item = self.model.get_item("user_list")
if not user_list_item:
return
self.__position_transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position))
with self.__position_transform:
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
self.__user_list_transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 30, 0))
with self.__user_list_transform:
self.__build_user_list(user_list_item.value)
def __invalidate(self):
self.__clear()
self.invalidate()
def __build_user_list(self, user_list):
size = min(3, len(user_list))
index = 0
current_offset = 0
space = 4
icon_size = 28
self.__user_list_transform.clear()
with self.__user_list_transform:
for user_info in user_list.values():
if index == size:
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(current_offset, 0, 0)):
sc.Label("...", color=cl.white, alignment=ui.Alignment.CENTER, size=28)
break
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(current_offset, 0, 0)):
color = ui.color(*user_info.user_color)
sc.Arc(radius=icon_size, color=color)
sc.Label(
layers.get_short_user_name(user_info.user_name), color=cl.white,
alignment=ui.Alignment.CENTER, size=16
)
current_offset += icon_size * 2 + space
index += 1
if index > size:
break
def on_model_updated(self, item):
if not self.__position_transform or not self.__user_list_transform or not item:
self.__invalidate()
return
position_item = self.model.get_item("position")
user_list_item = self.model.get_item("user_list")
if item == position_item:
position = self.model.get_as_floats(position_item)
if not position:
return
self.__position_transform.transform = sc.Matrix44.get_translation_matrix(*position)
elif item == user_list_item:
self.__build_user_list(user_list_item.value)
| 4,202 | Python | 35.232758 | 117 | 0.583532 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/manipulator/peer_user_list.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["PeerUserList"]
import omni.usd
import omni.kit.usd.layers as layers
from pxr import Sdf
from omni.ui import scene as sc
from omni.kit.viewport.utility import get_active_viewport_window
from .peer_user_list_manipulator_model import PeerUserListManipulatorModel
from .peer_user_list_manipulator import PeerUserListManipulator
class PeerUserList:
def __init__(self, usd_context: omni.usd.UsdContext, prim_path: Sdf.Path):
self.__usd_context = usd_context
self.__prim_path = Sdf.Path(prim_path)
self.__manipulator = None
self.__manipulator_model = None
self.__scene_view = None
self.__build_window()
def destroy(self):
if self.__manipulator:
self.__manipulator.destroy()
self.__manipulator = None
if self.__manipulator_model:
self.__manipulator_model.destroy()
self.__manipulator_model = None
if self.__viewport_window:
vp_api = self.__viewport_window.viewport_api
if self.__scene_view:
vp_api.remove_scene_view(self.__scene_view)
self.__scene_view.scene.clear()
self.__scene_view.destroy()
self.__scene_view = None
self.__viewport_window = None
def add_user(self, user_info: layers.LiveSessionUser):
if self.__manipulator_model:
self.__manipulator_model.add_user(user_info)
def remove_user(self, user_id):
if self.__manipulator_model:
self.__manipulator_model.remove_user(user_id)
def empty_user_list(self):
if self.__manipulator_model:
return self.__manipulator_model.empty_user_list()
return True
@property
def position(self):
if self.__manipulator_model:
return self.__manipulator_model._get_position()
return None
def on_transform_changed(self, position=None):
if self.__manipulator_model:
self.__manipulator_model.on_transform_changed(position)
def __build_window(self):
"""Called to build the widgets of the window"""
self.__viewport_window = get_active_viewport_window()
frame = self.__viewport_window.get_frame("selection_outline." + str(self.__prim_path))
with frame:
self.__scene_view = sc.SceneView()
with self.__scene_view.scene:
self.__manipulator_model = PeerUserListManipulatorModel(self.__prim_path, self.__usd_context)
self.__manipulator = PeerUserListManipulator(model=self.__manipulator_model)
vp_api = self.__viewport_window.viewport_api
vp_api.add_scene_view(self.__scene_view)
| 3,188 | Python | 33.663043 | 109 | 0.637077 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/tests/__init__.py | from .test_collaboration_selection_outline import TestCollaborationSelectionOutline
| 84 | Python | 41.499979 | 83 | 0.904762 |
omniverse-code/kit/exts/omni.kit.collaboration.selection_outline/omni/kit/collaboration/selection_outline/tests/test_collaboration_selection_outline.py | from pathlib import Path
import omni.usd
import omni.client
import omni.kit.app
import omni.kit.usd.layers as layers
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.collaboration.presence_layer.utils as pl_utils
from pxr import Usd, Sdf, UsdGeom, Gf
from typing import List
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi, join_new_simulated_user, quit_simulated_user
CURRENT_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) + "/data")
class TestCollaborationSelectionOutline(OmniUiTest):
user_counter = 0
# Before running each test
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self.app = omni.kit.app.get_app()
self.usd_context = omni.usd.get_context()
self.layers = layers.get_layers(self.usd_context)
self.live_syncing = self.layers.get_live_syncing()
await omni.usd.get_context().new_stage_async()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self.simulated_user_names = []
self.simulated_user_ids = []
self.test_session_name = "test"
self.stage_url = "omniverse://__faked_omniverse_server__/test/live_session.usd"
async def tearDown(self):
if omni.usd.get_context().get_stage():
await omni.usd.get_context().close_stage_async()
self.stage = None
omni.client.set_retries(*self.previous_retry_values)
self.live_syncing.stop_all_live_sessions()
async def __create_fake_stage(self):
format = Sdf.FileFormat.FindByExtension(".usd")
# Sdf.Layer.New will not save layer so it won't fail.
# This can be used to test layer identifier with omniverse sheme without
# touching real server.
layer = Sdf.Layer.New(format, self.stage_url)
stage = Usd.Stage.Open(layer.identifier)
session = self.live_syncing.create_live_session(self.test_session_name, layer_identifier=layer.identifier)
self.assertTrue(session)
await self.usd_context.attach_stage_async(stage)
self.live_syncing.join_live_session(session)
return stage, layer
def __manipulate_stage(self, stage):
sphere = stage.DefinePrim('/sphere01', 'Sphere')
cube = stage.DefinePrim('/cube01', 'Cube')
UsdGeom.XformCommonAPI(sphere).SetTranslate((100, 0, 0))
UsdGeom.XformCommonAPI(sphere).SetScale(Gf.Vec3f(40.0, 40.0, 40.0))
UsdGeom.XformCommonAPI(cube).SetTranslate((0, 100, 0))
UsdGeom.XformCommonAPI(cube).SetScale(Gf.Vec3f(40.0, 40.0, 40.0))
async def __create_simulated_users(self, count=2):
for i in range(count):
user_name = chr(ord('A') + TestCollaborationSelectionOutline.user_counter) # f"test{i}"
user_id = user_name
self.simulated_user_names.append(user_name)
self.simulated_user_ids.append(user_id)
join_new_simulated_user(user_name, user_id)
await self.wait_n_updates(2)
TestCollaborationSelectionOutline.user_counter += 1
def __get_shared_stage(self, current_session: layers.LiveSession):
shared_data_stage_url = current_session.url + "/shared_data/users.live"
layer = Sdf.Layer.FindOrOpen(shared_data_stage_url)
if not layer:
layer = Sdf.Layer.CreateNew(shared_data_stage_url)
return Usd.Stage.Open(layer)
async def __select_prims(self, shared_stage: Usd.Stage, user_id: str, selections: List[str]):
selection_property_path = pl_utils.get_selection_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), selection_property_path,
Sdf.ValueTypeNames.StringArray
)
property_spec.default = selections
await self.wait_n_updates()
async def __prepare_stage(self, num_users=2):
await self.wait_n_updates(n_frames=10)
# create stage and add users
stage, layer = await self.__create_fake_stage()
await self.wait_n_updates(n_frames=10)
self.__manipulate_stage(stage)
await self.__create_simulated_users(num_users)
await self.wait_n_updates(n_frames=10)
current_session = self.live_syncing.get_current_live_session()
shared_stage = self.__get_shared_stage(current_session)
assert(stage is not shared_stage)
return shared_stage
async def __check_and_leave(self):
await self.finalize_test(golden_img_dir=self._golden_img_dir)
self.live_syncing.stop_all_live_sessions()
await self.wait_n_updates(n_frames=10)
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_1_selection(self):
shared_stage = await self.__prepare_stage()
selections = ["/cube01"]
await self.__select_prims(shared_stage, self.simulated_user_ids[0], selections)
await self.wait_n_updates(n_frames=10)
await self.__check_and_leave()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_2_select_two_prims(self):
shared_stage = await self.__prepare_stage()
selections = ["/sphere01", "/cube01"]
await self.__select_prims(shared_stage, self.simulated_user_ids[0], selections)
await self.wait_n_updates(n_frames=10)
await self.__check_and_leave()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_3_select_identical_prim(self):
shared_stage = await self.__prepare_stage()
selections = ["/cube01"]
await self.__select_prims(shared_stage, self.simulated_user_ids[0], selections)
await self.wait_n_updates(n_frames=10)
await self.__select_prims(shared_stage, self.simulated_user_ids[1], selections)
await self.wait_n_updates(n_frames=10)
await self.__check_and_leave()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_4_selection_overflow(self):
num_users = 4
shared_stage = await self.__prepare_stage(num_users=num_users)
selections = ["/cube01"]
for i in range(num_users):
await self.__select_prims(shared_stage, self.simulated_user_ids[i], selections)
await self.__check_and_leave()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_5_select_and_unselect(self):
shared_stage = await self.__prepare_stage()
selections = ["/cube01", "/sphere01"]
await self.__select_prims(shared_stage, self.simulated_user_ids[0], selections)
await self.wait_n_updates(n_frames=10)
selections = ["/sphere01"]
await self.__select_prims(shared_stage, self.simulated_user_ids[0], selections)
await self.wait_n_updates(n_frames=10)
await self.__check_and_leave()
| 6,901 | Python | 39.840236 | 116 | 0.656716 |
omniverse-code/kit/exts/omni.app.setup/omni/app/setup/imgui_helper.py | import carb
def _trans_color(color):
if isinstance(color, (list, tuple)):
if len(color) == 3:
return carb.Float4(color[0], color[1], color[2], 1.0)
elif len(color) == 4:
return carb.Float4(color[0], color[1], color[2], color[3])
elif isinstance(color, str):
argb_int = int(color, 16)
r = ((argb_int >> 16) & 0x000000FF) / 255.0
g = ((argb_int >> 8) & 0x000000FF) / 255.0
b = (argb_int & 0x000000FF) / 255.0
w = ((argb_int >> 24) & 0x000000FF) / 255.0
return carb.Float4(r, g, b, w)
elif isinstance(color, float):
return carb.Float4(color, color, color, 1.0)
else:
return None
def setup_imgui():
settings = carb.settings.get_settings()
import omni.kit.imgui as _imgui
imgui = _imgui.acquire_imgui()
imgui_configs = settings.get("/exts/omni.app.setup/imgui")
if not imgui_configs:
return
colors = imgui_configs.get("color", {})
if colors:
for name, value in colors.items():
color = _trans_color(value)
if color:
def _push_color(imgui, name, color):
try:
source = f"imgui.push_style_color(carb.imgui.StyleColor.{name}, {color})"
carb.log_info(f"config style color {name} tp {color}")
exec(source)
except Exception as e:
carb.log_error(f"Failed to config imgui style color {name} to {color}: {e}")
_push_color(imgui, name, color)
else:
carb.log_error(f"Unknown color format for {name}: {value}")
floats = imgui_configs.get("float", {})
if floats:
for name, value in floats.items():
if value != "":
def _push_float_var(imgui, name, value):
try:
source = f"imgui.push_style_var_float(carb.imgui.StyleVar.{name}, {value})"
carb.log_info(f"config float var {name} tp {value}")
exec(source)
except Exception as e:
carb.log_error(f"Failed to config imgui float var {name} to {color}: {e}")
_push_float_var(imgui, name, value)
| 2,308 | Python | 34.523076 | 100 | 0.516031 |
omniverse-code/kit/exts/omni.app.setup/omni/app/setup/application_setup.py | import asyncio
import sys
import os
import carb.tokens
import omni.ui as ui
import omni.kit.ui
import omni.kit.app
import carb.settings
import omni.kit.menu.utils
import carb.input
import omni.kit.stage_templates as stage_templates
from omni.kit.window.title import get_main_window_title
from typing import Optional, Tuple
class ApplicationSetup:
def __init__(self):
self._settings = carb.settings.get_settings_interface()
# storage for the lazy menu items
self._lazy_menus = []
# storage for the layout menu items
self._layout_menu = None
# storage for workflows
self._workflows = []
async def _load_layout(self, layout_file: str, keep_windows_open=False):
try:
from omni.kit.quicklayout import QuickLayout
# few frames delay to avoid the conflict with the layout of omni.kit.mainwindow
for i in range(3):
await omni.kit.app.get_app().next_update_async()
QuickLayout.load_file(layout_file, keep_windows_open)
# load layout file again to make sure layout correct
for i in range(3):
await omni.kit.app.get_app().next_update_async()
QuickLayout.load_file(layout_file, keep_windows_open)
except Exception as exc:
pass
def force_viewport_settings(self):
display_options = self._settings.get("/persistent/app/viewport/displayOptions")
# Note: flags are from omni/kit/ViewportTypes.h
kShowFlagAxis = 1 << 1
kShowFlagGrid = 1 << 6
kShowFlagSelectionOutline = 1 << 7
kShowFlagLight = 1 << 8
display_options = (
display_options
| (kShowFlagAxis)
| (kShowFlagGrid)
| (kShowFlagSelectionOutline)
| (kShowFlagLight)
)
self._settings.set("/persistent/app/viewport/displayOptions", display_options)
# Make sure these are in sync from changes above
self._settings.set("/app/viewport/show/lights", True)
self._settings.set("/app/viewport/grid/enabled", True)
self._settings.set("/app/viewport/outline/enabled", True)
def setup_application_title(self):
# Adjust the Window Title to show the Create Version
window_title = get_main_window_title()
app_version = self._settings.get("/app/version")
if not app_version:
app_version = open(
carb.tokens.get_tokens_interface().resolve("${app}/../VERSION")
).read()
if app_version:
if "+" in app_version:
app_version, _ = app_version.split("+")
# for RC version we remove some details
production = self._settings.get("/privacy/externalBuild")
if production:
if "-" in app_version:
app_version, _ = app_version.split("-")
if self._settings.get("/app/beta"):
window_title.set_app_version(app_version + " Beta")
else:
window_title.set_app_version(app_version)
def load_default_layout(self, keep_windows_open=False):
default_layout = self._settings.get("/app/layout/default")
default_layout = carb.tokens.get_tokens_interface().resolve(default_layout)
self.__setup_window_task = asyncio.ensure_future(
self._load_layout(default_layout, keep_windows_open=keep_windows_open)
)
def __load_extension_and_show_window(self, menu_path, ext_id, window_name):
# Remove "lazy" menu here because it could not handle menu states while window closed
# Extension should create menu item again and handle menu states
editor_menu = omni.kit.ui.get_editor_menu()
editor_menu.remove_item(menu_path)
manager = omni.kit.app.get_app().get_extension_manager()
# if the extension is not enabled, enable it and show the window
if not manager.is_extension_enabled(ext_id):
manager.set_extension_enabled_immediate(ext_id, True)
ui.Workspace.show_window(window_name, True)
else:
# the extensions was enabled already check for the window and toggle it
window: ui.WindowHandle = ui.Workspace.get_window(window_name)
if window:
ui.Workspace.show_window(window_name, not window.visible)
else:
ui.Workspace.show_window(window_name, True)
def create_trigger_menu(self):
""" Create a menu item for each extension that has a [[trigger]] entry with a menu in it's config."""
editor_menu = omni.kit.ui.get_editor_menu()
manager = omni.kit.app.get_app().get_extension_manager()
include_list = self._settings.get("/exts/omni.app.setup/lazy_menu/include_list") or []
exclude_list = self._settings.get("/exts/omni.app.setup/lazy_menu/exclude_list") or []
for ext in manager.get_extensions():
# if the extensions is already enabled skip it, it already has a menu item if it need
if ext["enabled"]:
continue
ext_id = ext["id"]
info = manager.get_extension_dict(ext_id)
for trigger in info.get("trigger", []):
menu = trigger.get("menu", {})
# enable to discover and debug the auto menu creation
# print(f'menu: {menu} {menu.__class__}')
menu_name = menu.get("name", None)
# If the menu path not in white list or in black list, ignore
if include_list and menu_name not in include_list:
continue
if exclude_list and menu_name in exclude_list:
continue
window_name = menu.get("window", None)
if window_name is None or menu_name is None:
carb.log_error(f"Invalid [[trigger]] entry for extension: {ext_id}")
continue
# get priority or default to 0
priority = menu.get("priority", 0)
self._lazy_menus.append(
editor_menu.add_item(
menu_name,
lambda window, value, menu_path=menu_name, ext_id=ext_id, window_name=window_name: self.__load_extension_and_show_window(
menu_path, ext_id, window_name
),
toggle=True,
value=False,
priority=priority,
)
)
# TODO: this should be validated and those settings clean up
def set_defaults(self):
""" this is trying to setup some defaults for extensions to avoid warning """
self._settings.set_default("/persistent/app/omniverse/bookmarks", {})
self._settings.set_default("/persistent/app/stage/timeCodeRange", [0, 100])
self._settings.set_default(
"/persistent/audio/context/closeAudioPlayerOnStop", False
)
self._settings.set_default(
"/persistent/app/primCreation/PrimCreationWithDefaultXformOps", True
)
self._settings.set_default(
"/persistent/app/primCreation/DefaultXformOpType",
"Scale, Rotate, Translate",
)
self._settings.set_default(
"/persistent/app/primCreation/DefaultRotationOrder", "ZYX"
)
self._settings.set_default(
"/persistent/app/primCreation/DefaultXformOpPrecision", "Double"
)
# omni.kit.property.tagging
self._settings.set_default(
"/persistent/exts/omni.kit.property.tagging/showAdvancedTagView", False
)
self._settings.set_default(
"/persistent/exts/omni.kit.property.tagging/showHiddenTags", False
)
self._settings.set_default(
"/persistent/exts/omni.kit.property.tagging/modifyHiddenTags", False
)
# adjust couple of viewport settings
self._settings.set("/app/viewport/boundingBoxes/enabled", True)
def build_layout_menu(self):
"""Build the layout menu based on registered Layouts and main views"""
editor_menu = omni.kit.ui.get_editor_menu()
self._layout_menu_items = []
self._current_layout_priority = 20
self._current_key_index = 1
def add_layout_menu_entry(name, parameter, workflow=None):
import inspect
menu_path = f"Layout/{name}"
menu = editor_menu.add_item(
menu_path, None, False, self._current_layout_priority
)
self._current_layout_priority = self._current_layout_priority + 1
hotkey = (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, eval(f"carb.input.KeyboardInput.KEY_{self._current_key_index}")) if self._current_key_index <= 9 else None
self._current_key_index += 1
if inspect.isfunction(parameter):
menu_action = omni.kit.menu.utils.add_action_to_menu(
menu_path,
lambda *_: parameter(),
name,
hotkey,
)
else:
menu_action = omni.kit.menu.utils.add_action_to_menu(
menu_path,
lambda *_: asyncio.ensure_future(self._activate_layout(parameter, workflow)),
name,
hotkey,
)
self._layout_menu_items.append((menu, menu_action))
# Default layout menu items
add_layout_menu_entry(
"Reset Layout", lambda: self.load_default_layout()
)
add_layout_menu_entry(
"Viewport Only",
"${omni.app.setup}/layouts/viewport_only.json",
)
# Layout menu items for workflows
workflows = self._settings.get("/exts/omni.app.setup/workflow")
active_now = self._settings.get("/exts/omni.app.setup/activeWorkflowAtStartup")
self._workflows = []
if workflows:
for workflow in workflows:
name = workflow.get("name", None)
workflow_name = workflow.get("workflow", None)
layout_name = workflow.get("layout", None)
if name is None:
carb.log_error(f"Invalid [[app.workflow]] entry for extension: {workflow}")
continue
self._workflows.append(workflow)
add_layout_menu_entry(
" ".join([n.capitalize() for n in name.split(" ")]),
layout_name,
workflow_name,
)
if active_now:
self.active_workflow(name)
async def _activate_layout(self, layout: str, workflow: str):
if workflow:
ext_manager = omni.kit.app.get_app_interface().get_extension_manager()
ext_manager.set_extension_enabled_immediate(workflow, True)
if not layout:
layout = self._settings.get(f"/exts/{workflow}/default_layout")
if layout:
await omni.kit.app.get_app().next_update_async()
layout_path = carb.tokens.get_tokens_interface().resolve(layout)
if layout_path:
await self._load_layout(layout_path)
def active_workflow(self, name: str) -> None:
for workflow in self._workflows:
if workflow.get("name") == name:
asyncio.ensure_future(self._activate_layout(workflow.get("layout"), workflow.get("workflow")))
return
else:
carb.log_error(f"Cannot find workflow '{name}'!")
def __config_menu_layout(self, title, info: dict, default_type="Menu"):
from omni.kit.menu.utils import MenuLayout, LayoutSourceSearch
def __split_title(title: str) -> Tuple[str, Optional[str], bool]:
(name, source) = title.split("=") if "=" in title else (title, None)
if name.startswith("-"):
remove = True
name = name[1:]
else:
remove = False
return (name, source, remove)
(name, source, remove) = __split_title(title)
items = info.get("items", None) if info else None
type = info.get("type", default_type) if info else default_type
children = []
if items:
for item_title in items:
(item_name, item_source, _) = __split_title(item_title)
item_info = info.get(item_name, None)
child = self.__config_menu_layout(item_title, item_info, default_type="Item")
if child:
children.append(child)
source_search = LayoutSourceSearch.EVERYWHERE if source else LayoutSourceSearch.LOCAL_ONLY
if name == "":
return MenuLayout.Seperator()
elif type == "Menu":
return MenuLayout.Menu(name, items=children, source=source, source_search=source_search, remove=remove)
elif type == "SubMenu":
return MenuLayout.SubMenu(name, items=children, source=source, source_search=source_search, remove=remove)
elif type == "Item":
return MenuLayout.Item(name, source=source, source_search=source_search, remove=remove)
elif type == "Group":
return MenuLayout.Group(name, items=children, source_search=source_search, source=source)
elif type == "Sort":
exclude_items = info.get("exclude_items", []) if info else []
sort_submenus = info.get("sort_submenus", False) if info else False
return MenuLayout.Sort(exclude_items=exclude_items, sort_submenus=sort_submenus)
else:
return None
def setup_menu_layout(self):
menu_layouts = self._settings.get("/exts/omni.app.setup/menu_layout")
if not menu_layouts:
return
self._layout_menu = []
for (menu_name, menu_info) in menu_layouts.items():
menu = self.__config_menu_layout(menu_name, menu_info)
if menu:
self._layout_menu.append(menu)
omni.kit.menu.utils.add_layout(self._layout_menu)
def setup_menu_order(self):
menu_order_presets = self._settings.get("/exts/omni.app.setup/menu_order")
if menu_order_presets:
menu_self = omni.kit.menu.utils.get_instance()
_, menu_order, _ = menu_self.get_menu_data()
menu_order.update(menu_order_presets)
menu_self.rebuild_menus()
| 14,620 | Python | 39.955182 | 171 | 0.577975 |
omniverse-code/kit/exts/omni.app.setup/omni/app/setup/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ext
import carb.settings
import omni.kit.app
import asyncio
from .application_setup import ApplicationSetup
from .actions import register_actions, deregister_actions
from .viewport_rendering import enable_viewport_rendering
from .imgui_helper import setup_imgui
class AppSetupExtension(omni.ext.IExt):
"""Create Final Configuration"""
def on_startup(self, ext_id):
""" setup the window layout, menu, final configuration of the extensions etc """
self.__ext_id = omni.ext.get_extension_name(ext_id)
self._settings = carb.settings.get_settings()
setup_editor = self._settings.get("/app/kit/editor/setup")
if not setup_editor:
return
self._application_setup = ApplicationSetup()
self._menu_layout = []
# this is a work around as some Extensions don't properly setup their default setting in time
self._application_setup.set_defaults()
# Force enable Axis, Grid, Outline and Lights
forceEnable = self._settings.get("/app/kit/editor/forceViewportSettings")
if forceEnable:
self._application_setup.force_viewport_settings()
# setup the application title based on settings and few rules
self._application_setup.setup_application_title()
# Keep windows open to make sure Welcome window could be visible at startup
self._application_setup.load_default_layout(keep_windows_open=True)
self._application_setup.create_trigger_menu()
self._application_setup.build_layout_menu()
self._application_setup.setup_menu_layout()
self._application_setup.setup_menu_order()
def on_app_ready(*args, **kwargs):
self._app_ready_sub = None
# OM-93646: setup imgui when app ready otherwise there will be crash in Linux
setup_imgui()
# Start background loading of renderer if requested
bg_render_load = self._settings.get("/exts/omni.app.setup/backgroundRendererLoad/renderer")
if not bg_render_load:
return
# We delay loading those so we leave time for the welcome window
# and the first tab to be displayed
async def __load_renderer(bg_render_load):
# Get setting whether to show the renderer init progress in Viewport
show_viewport_ready = self._settings.get("/exts/omni.app.setup/backgroundRendererLoad/showViewportReady")
# Get setting for the number of frames to wait before starting the load
initial_wait = self._settings.get("/exts/omni.app.setup/backgroundRendererLoad/initialWait")
# When not set it will default to 20
if initial_wait is None:
initial_wait = 20
if initial_wait:
app = omni.kit.app.get_app()
for _ in range(initial_wait):
await app.next_update_async()
# await self._application_setup.start_loading_renderer(bg_render_load)
carb.log_info(f"Loading {bg_render_load} in background")
show_viewport_ready = self._settings.get("/exts/omni.app.setup/backgroundRendererLoad/showViewportReady")
enable_viewport_rendering(renderer=bg_render_load, show_viewport_ready=show_viewport_ready)
self.__setup_window_task = asyncio.ensure_future(__load_renderer(bg_render_load))
self._app_ready_sub = omni.kit.app.get_app().get_startup_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY,
on_app_ready,
name="omni.app.setup.app_ready.startup"
)
"""
# At some points around here we will want to close the splash Images
splash_interface = None
try:
import omni.splash
splash_interface = omni.splash.acquire_splash_screen_interface()
except (ImportError, ModuleNotFoundError):
splash_interface = None
if splash_interface:
splash_interface.close_all()
"""
register_actions(self.__ext_id, self._application_setup)
def on_shutdown(self):
deregister_actions(self.__ext_id)
self._app_ready_sub = None
| 4,762 | Python | 40.060344 | 121 | 0.652877 |
omniverse-code/kit/exts/omni.app.setup/omni/app/setup/viewport_rendering.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["enable_viewport_rendering", "start_render_loading_ui"]
from typing import Optional
import omni.usd
_g_enabled_renderers = []
g_renderers_ready = []
def start_render_loading_ui(ext_manager: "omni.ext.ExtensionManager", renderer: str):
import carb
import time
time_begin = time.time()
# Extension to show viewport loading progress
ext_manager.set_extension_enabled_immediate("omni.activity.profiler", True)
ext_manager.set_extension_enabled_immediate("omni.activity.pump", True)
carb.settings.get_settings().set("/exts/omni.kit.viewport.ready/startup/enabled", False)
ext_manager.set_extension_enabled_immediate("omni.kit.viewport.ready", True)
from omni.kit.viewport.ready.viewport_ready import ViewportReady, ViewportReadyDelegate
class TimerDelegate(ViewportReadyDelegate):
def __init__(self, time_begin):
super().__init__()
self.__timer_start = time.time()
self.__vp_ready_cost = self.__timer_start - time_begin
@property
def font_size(self) -> float:
return 48
@property
def message(self) -> str:
rtx_mode = {
"RaytracedLighting": "Real-Time",
"PathTracing": "Interactive (Path Tracing)",
"LightspeedAperture": "Aperture (Game Path Tracer)"
}.get(carb.settings.get_settings().get("/rtx/rendermode"), "Real-Time")
renderer_label = {
"rtx": f"RTX - {rtx_mode}",
"iray": "RTX - Accurate (Iray)",
"pxr": "Pixar Storm",
"index": "RTX - Scientific (IndeX)"
}.get(renderer, renderer)
return f"Waiting for {renderer_label} to start"
def on_complete(self):
global g_renderers_ready
g_renderers_ready.append(renderer)
rtx_load_time = time.time() - self.__timer_start
super().on_complete()
carb.log_info(f"Time until pixel: {rtx_load_time}")
carb.log_info(f"ViewportReady cost: {self.__vp_ready_cost}")
settings = carb.settings.get_settings()
if settings.get("/exts/omni.kit.welcome.window/autoSetupOnClose"):
async def async_enable_all_renderers(app, renderer: str, all_renderers: str):
for enabled_renderer in all_renderers.split(","):
if enabled_renderer != renderer:
enable_viewport_rendering(enabled_renderer, False)
await app.next_update_async()
import omni.kit.app
import omni.kit.async_engine
omni.kit.async_engine.run_coroutine(async_enable_all_renderers(omni.kit.app.get_app(), renderer,
settings.get("/renderer/enabled") or ""))
return ViewportReady(TimerDelegate(time_begin))
def enable_viewport_rendering(renderer: Optional[str] = None, show_viewport_ready: bool = True):
import carb
settings = carb.settings.get_settings()
# If no renderer is specified, choose the 'active' one or what is set as active, or finally RTX - Realtime
if renderer is None:
renderer = (settings.get("/renderer/active") or
settings.get("/exts/omni.app.setup/backgroundRendererLoad/renderer") or
"rtx")
# Only enable the Viewport for a renderer once, and only do Viewport Ready the first time
global _g_enabled_renderers
if renderer in _g_enabled_renderers:
if renderer not in g_renderers_ready and show_viewport_ready:
import omni.kit.app
app = omni.kit.app.get_app()
ext_manager = app.get_extension_manager()
start_render_loading_ui(ext_manager, renderer)
return
elif show_viewport_ready and bool(_g_enabled_renderers):
show_viewport_ready = False
_g_enabled_renderers.append(renderer)
settings.set("/renderer/asyncInit", True)
settings.set("/rtx/hydra/mdlMaterialWarmup", True)
import omni.kit.app
app = omni.kit.app.get_app()
ext_manager = app.get_extension_manager()
ext_manager.set_extension_enabled_immediate("omni.kit.viewport.bundle", True)
if renderer == "iray" or renderer == "index":
ext_manager.set_extension_enabled_immediate(f"omni.hydra.rtx", True)
ext_manager.set_extension_enabled_immediate(f"omni.hydra.{renderer}", True)
else:
ext_manager.set_extension_enabled_immediate(f"omni.kit.viewport.{renderer}", True)
# we might need to have the engine_name as part of the flow
ext_manager.set_extension_enabled("omni.rtx.settings.core", True)
# TODO: It will block omni.kit.viewport.Ready.ViewportReady while it is enabled before this function
# omni.usd.add_hydra_engine(renderer, usd_context)
if show_viewport_ready:
start_render_loading_ui(ext_manager, renderer)
| 5,417 | Python | 41.328125 | 120 | 0.636515 |
omniverse-code/kit/exts/omni.app.setup/omni/app/setup/actions.py | from .application_setup import ApplicationSetup
from .viewport_rendering import enable_viewport_rendering
def register_actions(extension_id: str, application_setup: ApplicationSetup):
"""
Register actions.
Args:
extension_id (str): Extension ID which actions belongs to
application_setup: Instance of application_setup
"""
try:
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "app.setup"
action_registry.register_action(
extension_id,
"active_workflow",
lambda name: application_setup.active_workflow(name),
display_name="Active workflow",
description="Active workflow",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"enable_viewport_rendering",
lambda: enable_viewport_rendering(),
display_name="Enable viewport rendering",
description="Enable viewport rendering",
tag=actions_tag,
)
except ImportError:
pass
def deregister_actions(extension_id: str):
"""
Deregister actions.
Args:
extension_id (str): Extension ID whcih actions belongs to
"""
try:
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
except ImportError:
pass | 1,529 | Python | 28.999999 | 77 | 0.631131 |
omniverse-code/kit/exts/omni.kit.search_example/omni/kit/search_example/search_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.kit.search_core import AbstractSearchItem
from omni.kit.search_core import AbstractSearchModel
import asyncio
import carb
import functools
import omni.client
import traceback
def handle_exception(func):
"""
Decorator to print exception in async functions
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except asyncio.CancelledError:
pass
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
class SearchItem(AbstractSearchItem):
def __init__(self, dir_path, file_entry):
super().__init__()
self._dir_path = dir_path
self._file_entry = file_entry
@property
def path(self):
return f"{self._dir_path}/{self._file_entry.relative_path}"
@property
def name(self):
return str(self._file_entry.relative_path)
@property
def date(self):
# TODO: Grid View needs datatime, but Tree View needs a string. We need to make them the same.
return self._file_entry.modified_time
@property
def size(self):
# TODO: Grid View needs int, but Tree View needs a string. We need to make them the same.
return self._file_entry.size
@property
def is_folder(self):
return (self._file_entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN) > 0
class SearchModel(AbstractSearchModel):
def __init__(self, **kwargs):
super().__init__()
self._search_text = kwargs.get("search_text", None)
self._current_dir = kwargs.get("current_dir", None)
self._search_lifetime = kwargs.get("search_lifetime", None)
# omni.client doesn't understand my-computer
if self._current_dir.startswith("my-computer://"):
self._current_dir = self._current_dir[len("my-computer://"):]
self.__list_task = asyncio.ensure_future(self.__list())
self.__items = []
def destroy(self):
if not self.__list_task.done():
self.__list_task.cancel()
self._search_lifetime = None
@property
def items(self):
return self.__items
@handle_exception
async def __list(self):
result, entries = await omni.client.list_async(self._current_dir)
if result != omni.client.Result.OK:
self.__items = []
else:
self.__items = [
SearchItem(self._current_dir, entry) for entry in entries if self._search_text in entry.relative_path
]
self._item_changed()
self._search_lifetime = None
| 3,171 | Python | 30.098039 | 117 | 0.637023 |
omniverse-code/kit/exts/omni.kit.search_example/omni/kit/search_example/search_extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .search_model import SearchModel
from omni.kit.search_core import SearchEngineRegistry
import omni.ext
class SearchExampleExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._subscription = SearchEngineRegistry().register_search_model("Example Search", SearchModel)
def on_shutdown(self):
self._subscription = None
| 789 | Python | 38.499998 | 104 | 0.782003 |
omniverse-code/kit/exts/omni.kit.search_example/omni/kit/search_example/__init__.py | from .search_extension import SearchExampleExtension
| 53 | Python | 25.999987 | 52 | 0.886792 |
omniverse-code/kit/exts/omni.kit.search_example/omni/kit/search_example/tests/test_search_example.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
from pathlib import Path
from omni.kit.search_core import SearchEngineRegistry
from ..search_model import SearchModel
from ..search_model import SearchItem
import asyncio
from functools import partial
CURRENT_PATH = Path(__file__).parent
async def _wait_model_changed_async(model: SearchModel):
"""Async wait when the model is changed"""
def _on_item_changed(item: SearchItem, future: asyncio.Future):
"""Callback set the future when called"""
if not future.done():
future.set_result(None)
f = asyncio.Future()
sub = model.subscribe_item_changed(partial(_on_item_changed, future=f))
return await f
class TestSearchExample(omni.kit.test.AsyncTestCase):
async def test_search(self):
model_type = SearchEngineRegistry().get_search_model("Example Search")
self.assertIs(model_type, SearchModel)
model = model_type(search_text="test", current_dir=f"{CURRENT_PATH}")
await _wait_model_changed_async(model)
# In the current folder we only have the file "test_search_example.py"
self.assertEqual(["test_search_example.py"], [item.name for item in model.items])
| 1,619 | Python | 36.674418 | 89 | 0.728227 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/async_utils.py | import os
import platform
import sys
import re
import asyncio
import traceback
from functools import partial, wraps
from pxr import Sdf, Usd
# This piece of wrapper is borrowed from aiofiles, see following for details
# https://github.com/Tinche/aiofiles/blob/master/aiofiles/os.py
def wrap(func):
@asyncio.coroutine
@wraps(func)
def run(*args, loop=None, executor=None, **kwargs):
if loop is None:
loop = asyncio.get_event_loop()
pfunc = partial(func, *args, **kwargs)
return loop.run_in_executor(executor, pfunc)
return run
def _read_file(path):
with open(path, "rb") as f:
return f.read()
def _encode_content(content):
if type(content) == str:
payload = bytes(content.encode("utf-8"))
elif type(content) != type(None):
payload = bytes(content)
else:
payload = bytes()
return payload
def _write_file(file, content):
with open(file, "wb") as f:
payload = _encode_content(content)
f.write(payload)
def _open_layer(path):
return Sdf.Layer.FindOrOpen(path)
def _open_stage(stage_path):
return Usd.Stage.Open(stage_path)
def _transfer_layer_content(layer, target_layer):
return target_layer.TransferContent(layer)
def _layer_save(layer):
return layer.Save()
def _export_layer_to_string(layer):
return layer.ExportToString()
def _re_find_all(regex, content):
return re.findall(regex, content)
def _replace_all(s, old_text, new_text):
if type(s) == bytes:
s = s.decode()
return s.replace(old_text, new_text)
aio_write_file = wrap(_write_file)
aio_read_file = wrap(_read_file)
aio_open_layer = wrap(_open_layer)
aio_export_layer_to_string = wrap(_export_layer_to_string)
aio_re_find_all = wrap(_re_find_all)
aio_replace_all = wrap(_replace_all)
aio_transfer_layer = wrap(_transfer_layer_content)
aio_open_stage = wrap(_open_stage)
aio_save_layer = wrap(_layer_save)
| 1,951 | Python | 21.436781 | 76 | 0.670425 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/mdl_parser.py | import os
from .async_utils import aio_replace_all, aio_re_find_all
from .utils import Utils
class MDLImportItem:
def __init__(self):
self.import_clause = "" # The import clause like `import xx`
self.import_package = "" # The package name without import directive
self.package_path = "" # The package path converted from import package
self.module_preset = False # If it's preset.
def __repr__(self):
s = f"<'import_clause': {self.import_clause},"
s += f"'import_package': {self.import_package},"
s += f"'packag_path': {self.package_path}>"
return s
class MDLParser:
"""A parser of mdl file, for get the relative texture files.
Args:
mdl_file_path (str): Human readable string describing the exception.
mdl_content(bytes): MDL content in bytes array.
"""
def __init__(self, mdl_file_path, mdl_content):
self._parsed = False
self._mdl_file_path = mdl_file_path
self._mdl_content = mdl_content
if type(self._mdl_content) == bytes:
self._mdl_content = self._mdl_content.decode()
self._raw_to_absolute_texture_paths = {}
self._mdl_imports = {}
@property
def content(self):
return self._mdl_content
async def parse(self):
if not self._parsed:
self._parsed = True
texture_paths, self._mdl_imports = await self._parse_internal()
absolute_mdl_basepath = os.path.dirname(self._mdl_file_path)
if absolute_mdl_basepath != "/":
absolute_mdl_basepath += "/"
for raw_texture_path in texture_paths:
if not raw_texture_path.strip():
continue
if raw_texture_path[0] == '/':
texture_path = "." + raw_texture_path
else:
texture_path = raw_texture_path
absolute_texture_path = Utils.compute_absolute_path(absolute_mdl_basepath, texture_path)
self._raw_to_absolute_texture_paths[raw_texture_path] = absolute_texture_path
for mdl_import in self._mdl_imports:
mdl_import.package_path = Utils.compute_absolute_path(
absolute_mdl_basepath, mdl_import.package_path
)
return self._raw_to_absolute_texture_paths, self._mdl_imports
async def _parse_internal(self):
if not self._mdl_content:
return [], []
texture_paths = await aio_re_find_all(
'texture_2d[ \t]*\([ \t]*"(.*?)"', self._mdl_content
)
texture_paths.extend(
await aio_re_find_all(
'texture_3d[ \t]*\([ \t]*"(.*?)"', self._mdl_content
)
)
texture_paths.extend(
await aio_re_find_all(
'texture_cube[ \t]*\([ \t]*"(.*?)"', self._mdl_content
)
)
texture_paths.extend(
await aio_re_find_all(
'texture_ptex[ \t]*\([ \t]*"(.*?)"', self._mdl_content
)
)
mdl_packages = await aio_re_find_all("import[ \t]+(.*)::.*;", self._mdl_content)
mdl_imports = await aio_re_find_all("(import[ \t]+.*::.*);", self._mdl_content)
mdl_packages += await aio_re_find_all("using[ \t]+(.*)[ \t]+import.*;", self._mdl_content)
mdl_imports += await aio_re_find_all("(using[ \t]+.*import.*);", self._mdl_content)
mdl_packages += await aio_re_find_all("=[ \t]+(.*)::.*", self._mdl_content)
mdl_imports += await aio_re_find_all("(=[ \t]+.*::.*)", self._mdl_content)
mdl_paths = await self._convert_packages(mdl_packages)
import_items = []
for clause, package, path in zip(mdl_imports, mdl_packages, mdl_paths):
item = MDLImportItem()
item.import_clause = clause
item.import_package = package
item.package_path = path
if clause.startswith("="):
item.module_preset = True
import_items.append(item)
return texture_paths, import_items
async def _convert_packages(self, packages):
paths = []
for mdl_package in packages:
path = await aio_replace_all(mdl_package, "::", "/")
if path:
paths.append(path + ".mdl")
return paths
| 4,407 | Python | 33.4375 | 104 | 0.540958 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/main_window.py | import os
from omni import ui
from .icons import Icons
from .filebrowser import FileBrowserSelectionType, FileBrowserMode
from .file_picker import FilePicker
class CollectMainWindow:
def __init__(self, collect_button_fn=None, cancel_button_fn=None):
self._collect_button_fn = collect_button_fn
self._cancel_button_fn = cancel_button_fn
self._file_picker = None
self._collection_path_field = None
self._build_content_ui()
def destroy(self):
self._collect_button_fn = None
self._cancel_button_fn = None
self._collection_path_field = None
if self._file_picker:
self._file_picker.destroy()
self._file_picker = None
if self._cancel_button:
self._cancel_button.set_clicked_fn(None)
self._cancel_button = None
if self._collect_button:
self._collect_button.set_clicked_fn(None)
self._collect_button = None
if self._folder_button:
self._folder_button.set_clicked_fn(None)
self._folder_button = None
self._window = None
def set_collect_fn(self, collect_fn):
self._collect_button_fn = collect_fn
def set_cancel_fn(self, cancel_fn):
self._cancel_button_fn = cancel_fn
def _build_content_ui(self):
self._window = ui.Window(
"Collection Options", visible=False, height=0, dockPreference=ui.DockPreference.DISABLED
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
def _build_option_checkbox(text, default_value, identifier, tooltip=None):
stack = ui.HStack(height=0, width=0)
with stack:
checkbox = ui.CheckBox(width=20, identifier=identifier, style={"font_size": 16})
checkbox.model.set_value(default_value)
ui.Label(text, alignment=ui.Alignment.LEFT)
if tooltip:
stack.set_tooltip(tooltip)
return checkbox
style = {
"Rectangle::hovering": {"background_color": 0x0, "border_radius": 2, "margin": 0, "padding": 0},
"Rectangle::hovering:hovered": {"background_color": 0xFF9E9E9E},
"Button.Image::folder": {"image_url": Icons().get("folder")},
"Button.Image::folder:checked": {"image_url": Icons().get("folder")},
"Button::folder": {"background_color": 0x0, "margin": 0},
"Button::folder:checked": {"background_color": 0x0, "margin": 0},
"Button::folder:pressed": {"background_color": 0x0, "margin": 0},
"Button::folder:hovered": {"background_color": 0x0, "margin": 0},
}
self._window.width = 600
with self._window.frame:
with ui.HStack(height=0, style=style):
ui.Spacer(width=40)
with ui.VStack(spacing=10):
ui.Spacer(height=10)
# build collection path widgets
with ui.HStack(height=0):
ui.Label("Collection Path: ", width=0)
with ui.VStack(height=0):
ui.Spacer(height=4)
self._collection_path_field = ui.StringField(
height=20, identifier="collect_path", width=ui.Fraction(1)
)
ui.Spacer(height=4)
ui.Spacer(width=5)
with ui.VStack(width=0):
ui.Spacer()
with ui.ZStack(width=20, height=20):
ui.Rectangle(name="hovering")
self._folder_button = ui.Button(
name="folder", identifier="folder_button", width=24, height=24
)
self._folder_button.set_tooltip("Choose folder")
ui.Spacer()
ui.Spacer(width=2)
self._folder_button.set_clicked_fn(lambda: self._show_file_picker())
# build collection options
with ui.HStack(height=0, spacing=10):
self._usd_only_checkbox = _build_option_checkbox(
"USD Only",
False,
"usd_only_checkbox",
"Only USD files will be collected. Any materials bindings will be removed.",
)
self._material_only_checkbox = _build_option_checkbox(
"Material Only",
False,
"material_only_checkbox",
"Only MDL files and their depdendent textures will be collected.",
)
self._flat_collection_checkbox = _build_option_checkbox(
"Flat Collection",
False,
"flat_collection_checkbox",
"By default, it will keep the folder structure after collection. "
"After this option is enabled, assets will be collected into specified folders.",
)
# add value changed callback to enable flat collection settings combo
self._flat_collection_checkbox.model.add_value_changed_fn(self._on_flat_collection_toggled)
# build flat collection texture options (visibility toggled by flat collection checkbox)
with ui.HStack(spacing=10):
tooltip = "Options for grouping for textures.\nTextures can be grouped under parent folders by MDL or USD, or flat in the same hierarchy."
self._flat_options_widgets = [
ui.Label("Flat Collection Texture Option: ", name="label", width=0, tooltip=tooltip),
ui.ComboBox(
0,
"Group By MDL",
"Group By USD",
"Flat",
height=10,
name="choices",
identifier="texture_option_combo",
),
]
for widget in self._flat_options_widgets:
widget.visible = False
ui.Spacer(height=0)
# build action buttons
with ui.HStack(height=0):
ui.Spacer()
self._collect_button = ui.Button("Start", width=120, height=0)
self._collect_button.set_clicked_fn(self._on_collect_button_clicked)
self._cancel_button = ui.Button("Cancel", width=120, height=0)
self._cancel_button.set_clicked_fn(self._on_cancel_button_clicked)
ui.Spacer()
ui.Spacer(height=20)
ui.Spacer(width=40)
def _on_collect_button_clicked(self):
if self._collect_button_fn:
collect_dir = self._collection_path_field.model.get_value_as_string()
usd_only = self._usd_only_checkbox.model.get_value_as_bool()
material_only = self._material_only_checkbox.model.get_value_as_bool()
flat_collection = self._flat_collection_checkbox.model.get_value_as_bool()
texture_option = self._flat_options_widgets[1].model.get_item_value_model().as_int
self._collect_button_fn(collect_dir, usd_only, flat_collection, material_only, texture_option)
self._window.visible = False
def _on_cancel_button_clicked(self):
if self._cancel_button_fn:
self._cancel_button_fn()
self._window.visible = False
def _select_picked_folder_callback(self, path):
self._collection_path_field.model.set_value(path)
self._window.visible = True
def _cancel_picked_folder_callback(self):
self._window.visible = True
def _show_file_picker(self):
self._window.visible = False
if not self._file_picker:
mode = FileBrowserMode.SAVE
file_type = FileBrowserSelectionType.DIRECTORY_ONLY
filters = [(".*", "All Files (*.*)")]
self._file_picker = FilePicker(
"Select Collect Destination", mode=mode, file_type=file_type, filter_options=filters
)
self._file_picker.set_filebar_label_name("Folder name")
self._file_picker.set_file_selected_fn(self._select_picked_folder_callback)
self._file_picker.set_cancel_fn(self._cancel_picked_folder_callback)
path = self._collection_path_field.model.get_value_as_string().rstrip("/")
dir_name = os.path.dirname(path)
folder_name = os.path.basename(path)
self._file_picker.show(dir_name, folder_name)
def _on_flat_collection_toggled(self, model):
for widget in self._flat_options_widgets:
widget.visible = model.as_bool
def show(self, export_folder=None):
if export_folder:
self._collection_path_field.model.set_value(export_folder)
self._window.visible = True
def hide(self):
self._window.visible = False
| 9,770 | Python | 45.089622 | 162 | 0.524258 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/extension.py | import os
import asyncio
import weakref
import omni
import omni.usd
import carb
from typing import Callable
from omni.kit.widget.prompt import PromptButtonInfo, PromptManager
from .omni_client_wrapper import OmniClientWrapper
from .main_window import CollectMainWindow
from .collector import Collector, CollectorException, CollectorFailureOptions, FlatCollectionTextureOptions
from .progress_popup import ProgressPopup
from .utils import Utils
from omni.kit.menu.utils import MenuItemDescription
g_singleton = None
def get_instance():
global g_singleton
return g_singleton
class PublicExtension(omni.ext.IExt):
def on_startup(self):
self._main_window = None
self._context_menu_name = None
self._register_menus()
global g_singleton
g_singleton = self
def on_shutdown(self):
global g_singleton
g_singleton = None
content_window = self.get_content_window()
if content_window and self._context_menu_name:
content_window.delete_context_menu(self._context_menu_name)
self._context_menu_name = None
if self._main_window:
self._main_window.destroy()
self._main_window = None
def collect(self, filepath: str, finish_callback: Callable[[], None] = None) -> None:
"""
Collect a usd file.
Args:
filepath: Path to usd file to be collected.
"""
if not omni.usd.is_usd_writable_filetype(filepath):
self._show_file_not_supported_popup()
else:
self._show_main_window(filepath, finish_callback)
def _register_menus(self):
content_window = self.get_content_window()
if content_window:
self._context_menu_name = content_window.add_context_menu(
"Collect Asset", "upload.svg",
lambda b, c: self._on_menu_click(b, c),
omni.usd.is_usd_writable_filetype
)
def _collect():
stage = omni.usd.get_context().get_stage()
self.collect(stage.GetRootLayer().identifier)
def _enable_collect_menu():
stage = omni.usd.get_context().get_stage()
return stage is not None and not stage.GetRootLayer().anonymous
self._file_menu_list = [
MenuItemDescription(
name="Collect As...",
glyph="none.svg",
appear_after="Save Flattened As...",
enable_fn=_enable_collect_menu,
onclick_fn=_collect,
)
]
omni.kit.menu.utils.add_menu_items(self._file_menu_list, "File")
def _get_collection_dir(self, folder, usd_file_name):
stage_name = os.path.splitext(usd_file_name)[0]
if not folder.endswith("/"):
folder += "/"
folder = Utils.normalize_path(folder)
return f"{folder}Collected_{stage_name}"
def _show_folder_exist_popup(
self,
usd_path,
collect_dir,
usd_only,
flat_collection,
material_only,
texture_option,
finish_callback: Callable[[], None] = None,
):
def on_confirm():
self._start_collecting(
usd_path, collect_dir, usd_only, flat_collection, material_only, texture_option, finish_callback
)
def on_cancel():
self._show_main_window(usd_path)
PromptManager.post_simple_prompt(
"Overwrite",
"The target directory already exists, do you want to overwrite it?",
PromptButtonInfo("Confirm", on_confirm),
PromptButtonInfo("Cancel", on_cancel),
modal=False,
)
def _start_collecting(
self,
usd_path,
collect_folder,
usd_only,
flat_collection,
material_only,
texture_option,
finish_callback: Callable[[], None] = None,
):
progress_popup = self._show_progress_popup()
progress_popup.status_text = "Collecting dependencies..."
collector = Collector(
usd_path,
collect_folder,
usd_only,
flat_collection,
material_only,
texture_option=FlatCollectionTextureOptions(texture_option),
)
collector_weakref = weakref.ref(collector)
def on_cancel():
carb.log_info("Cancelling collector...")
if not collector_weakref():
return
collector_weakref().cancel()
progress_popup.set_cancel_fn(on_cancel)
def on_progress(step, total):
progress_popup.status_text = f"Collecting USD {os.path.basename(usd_path)}..."
if total != 0:
progress_popup.progress = float(step) / total
else:
progress_popup.progress = 0.0
def on_finish():
if finish_callback:
finish_callback()
progress_popup.hide()
self._refresh_current_directory()
if self._main_window:
self._main_window.set_collect_fn(None)
if not collector_weakref():
return
collector_weakref().destroy()
asyncio.ensure_future(collector.collect(on_progress, on_finish))
def _show_main_window(self, usd_path, finish_callback: Callable[[], None] = None):
if not self._main_window:
self._main_window = CollectMainWindow(None, None)
def on_collect(collect_folder, usd_only, flat_collection, material_only, texture_option):
existed = OmniClientWrapper.exists_sync(collect_folder)
if existed:
self._show_folder_exist_popup(
usd_path, collect_folder, usd_only, flat_collection, material_only, texture_option, finish_callback
)
else:
self._start_collecting(
usd_path, collect_folder, usd_only, flat_collection, material_only, texture_option, finish_callback
)
self._main_window.set_collect_fn(on_collect)
default_folder = self._get_collection_dir(os.path.dirname(usd_path), os.path.basename(usd_path))
self._main_window.show(default_folder)
def _on_menu_click(self, menu, value):
self.collect(value)
def _refresh_current_directory(self):
content_window = self.get_content_window()
if content_window:
content_window.refresh_current_directory()
def _show_progress_popup(self):
progress_popup = ProgressPopup("Collecting")
progress_popup.progress = 0
progress_popup.show()
return progress_popup
def _show_file_not_supported_popup(self):
PromptManager.post_simple_prompt("Warning", "Only USD file can be collected")
def get_content_window(self):
try:
import omni.kit.window.content_browser as content
return content.get_content_window()
except Exception as e:
pass
return None
| 7,097 | Python | 30.6875 | 119 | 0.588136 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/__init__.py | from .extension import PublicExtension, get_instance, CollectorFailureOptions, Collector, CollectorException
| 109 | Python | 53.999973 | 108 | 0.87156 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/file_picker.py | import omni
import os
from omni.kit.widget.prompt import PromptManager, PromptButtonInfo
from .omni_client_wrapper import OmniClientWrapper
from .filebrowser import FileBrowserMode
from .filebrowser.app_filebrowser import FileBrowserUI
class FilePicker:
def __init__(self, title, mode, file_type, filter_options, ok_button_title="Open"):
self._mode = mode
self._app = omni.kit.app.get_app()
self._open_handler = None
self._cancel_handler = None
self._ui_handler = FileBrowserUI(title, mode, file_type, filter_options, ok_button_title)
def _show_prompt(self, file_path, file_save_handler):
def on_confirm():
if file_save_handler:
file_save_handler(file_path)
PromptManager.post_simple_prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Overwrite',
f"File {os.path.basename(file_path)} already exists, do you want to overwrite it?",
PromptButtonInfo("Confirm", on_confirm),
PromptButtonInfo("Cancel")
)
def _save_and_prompt_if_exists(self, file_path, file_save_handler=None):
existed = OmniClientWrapper.exists_sync(file_path)
if existed:
self._show_prompt(file_path, file_save_handler)
elif file_save_handler:
file_save_handler(file_path)
def _on_file_open(self, path):
if self._mode == FileBrowserMode.SAVE:
self._save_and_prompt_if_exists(path, self._open_handler)
elif self._open_handler:
self._open_handler(path)
def _on_cancel_open(self):
if self._cancel_handler:
self._cancel_handler()
def set_file_selected_fn(self, file_open_handler):
self._open_handler = file_open_handler
def set_cancel_fn(self, cancel_handler):
self._cancel_handler = cancel_handler
def show(self, dir=None, filename=None):
if self._ui_handler:
if dir and OmniClientWrapper.exists_sync(dir):
self._ui_handler.set_current_directory(dir)
if filename:
self._ui_handler.set_current_filename(filename)
self._ui_handler.open(self._on_file_open, self._on_cancel_open)
def set_current_directory(self, dir):
if self._ui_handler:
if dir and OmniClientWrapper.exists_sync(dir):
self._ui_handler.set_current_directory(dir)
def set_current_filename(self, filename):
if self._ui_handler:
self._ui_handler.set_current_filename(filename)
def set_filebar_label_name(self, name):
if self._ui_handler:
self._ui_handler.set_filebar_label_name(name)
def destroy(self):
self._open_handler = None
self._cancel_handler = None
if self._ui_handler:
self._ui_handler.destroy()
self._ui_handler = None
| 2,900 | Python | 34.378048 | 97 | 0.628276 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/progress_popup.py | from omni import ui
class CustomProgressModel(ui.AbstractValueModel):
def __init__(self):
super().__init__()
self._value = 0.0
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 str(int(self._value * 100)) + "%"
class ProgressPopup:
"""Creates a modal window with a status label and a progress bar inside.
Args:
title (str): Title of this window.
cancel_button_text (str): It will have a cancel button by default. This is the title of it.
cancel_button_fn (function): The callback after cancel button is clicked.
status_text (str): The status text.
min_value: The min value of the progress bar. It's 0 by default.
max_value: The max value of the progress bar. It's 100 by default.
dark_style: If it's to use dark style or light style. It's dark stye by default.
"""
def __init__(self, title, cancel_button_text="Cancel", cancel_button_fn=None, status_text="", modal=False):
self._status_text = status_text
self._title = title
self._cancel_button_text = cancel_button_text
self._cancel_button_fn = cancel_button_fn
self._progress_bar_model = None
self._modal = modal
self._popup = None
self._buttons = []
self._build_ui()
def destroy(self):
self._cancel_button_fn = None
self._progress_bar_model = None
for button in self._buttons:
button.set_clicked_fn(None)
self._popup = None
def __enter__(self):
self._popup.visible = True
return self
def __exit__(self, type, value, trace):
self._popup.visible = False
def set_cancel_fn(self, on_cancel_button_clicked):
self._cancel_button_fn = on_cancel_button_clicked
def set_progress(self, progress):
self._progress_bar.model.set_value(progress)
def get_progress(self):
return self._progress_bar.model.get_value_as_float()
progress = property(get_progress, set_progress)
def set_status_text(self, status_text):
self._status_label.text = status_text
def get_status_text(self):
return self._status_label.text
status_text = property(get_status_text, set_status_text)
def show(self):
self._popup.visible = True
def hide(self):
self._popup.visible = False
def is_visible(self):
return self._popup.visible
def _on_cancel_button_fn(self):
self.hide()
if self._cancel_button_fn:
self._cancel_button_fn()
def _build_ui(self):
self._popup = ui.Window(
self._title, visible=False,
auto_resize=True, height=0,
dockPreference=ui.DockPreference.DISABLED
)
self._popup.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
)
if self._modal:
self._popup.flags = self._popup.flags | ui.WINDOW_FLAGS_MODAL
with self._popup.frame:
with ui.VStack(height=0, width=400):
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Spacer()
self._status_label = ui.Label(self._status_text, width=0, height=0)
ui.Spacer()
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Spacer(width=40)
self._progress_bar_model = CustomProgressModel()
self._progress_bar = ui.ProgressBar(
self._progress_bar_model, width=320, style={"color": 0xFFFF9E3D}
)
ui.Spacer(width=40)
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Spacer(height=0)
cancel_button = ui.Button(self._cancel_button_text, width=120, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(cancel_button)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
| 4,521 | Python | 32.007299 | 111 | 0.564919 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/utils.py | import re
import omni
from urllib.parse import unquote
class Utils:
MDL_RE = re.compile("^.*\\.mdl?$", re.IGNORECASE)
# References https://gitlab-master.nvidia.com/omniverse/rtxdev/kit/blob/d37f0906c58cb1a5d8591f9e47125b4154b19b88/rendering/source/plugins/common/UDIM.h#L22
# for regex details to detect udim textures.
UDIM_MARKER_RE = re.compile("^.*(<UDIM>|<UVTILE0>|<UVTILE1>).*")
UDIM_GROUP_RE = re.compile("^(.*)(<UDIM>|<UVTILE0>|<UVTILE1>)(.*)")
@staticmethod
def normalize_path(path):
path = omni.client.normalize_url(path)
# Hard-decoding url currently since combine_urls will encode url
path = unquote(path)
return path.replace("\\", "/")
@staticmethod
def compute_absolute_path(base_path, path):
# Handles old omni path
if path.startswith("omni:"):
path = path[5:]
absolute_path = omni.client.combine_urls(base_path, path)
return Utils.normalize_path(absolute_path)
@staticmethod
def is_material(path):
if not path:
return False
path = Utils.remove_query_from_url(path)
if Utils.MDL_RE.match(path):
return True
return False
@staticmethod
def is_local_path(path):
if not path:
return False
client_url = omni.client.break_url(path)
return client_url and client_url.is_raw
@staticmethod
def is_omniverse_path(path):
return path and path.startswith("omniverse://")
@staticmethod
def remove_query_from_url(url):
if not url:
return url
client_url = omni.client.break_url(url)
url_without_query = omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=client_url.path,
query=None,
fragment=client_url.fragment,
)
url_without_query = url_without_query.replace("\\", "/")
return url_without_query
@staticmethod
def is_udim_texture(path):
if not path:
return False
path = Utils.remove_query_from_url(path)
url = omni.client.break_url(path)
if url and Utils.UDIM_MARKER_RE.match(url.path):
return True
return False
@staticmethod
def is_udim_wildcard_texture(path, udim_texture_path):
if not path or not udim_texture_path:
return False
udim_path = Utils.remove_query_from_url(udim_texture_path)
url = omni.client.break_url(udim_path)
groups = Utils.UDIM_GROUP_RE.match(url.path)
if not groups:
return False
base_path = groups[1]
suffix_path = groups[3]
wildcard_re = re.compile(re.escape(base_path) + "((\\d\\d\\d\\d)|(_u\\d*_v\\d*))" + suffix_path)
path = Utils.remove_query_from_url(path)
url = omni.client.break_url(path)
if wildcard_re.match(url.path):
return True
return False
@staticmethod
def make_relative_path(relative_to, path):
relative_path = omni.client.make_relative_url(relative_to, path)
return Utils.normalize_path(relative_path)
| 3,259 | Python | 28.107143 | 159 | 0.602332 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/icons.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.
#
from pathlib import Path
from .singleton import Singleton
@Singleton
class Icons:
"""A singleton that scans the icon folder and returns the icon depending on the type"""
def __init__(self):
self._current_path = Path(__file__).parent
self._icon_path = self._current_path.parent.parent.parent.parent.joinpath("icons")
self._icons = {icon.stem: icon for icon in self._icon_path.glob("*.png")}
def get(self, name, default=None):
"""Checks the icon cache and returns the icon if exists"""
found = self._icons.get(name)
if not found and default:
found = self._icons.get(default)
if found:
return str(found)
| 1,132 | Python | 35.548386 | 91 | 0.699647 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/collector.py | import os
import asyncio
import omni
import omni.usd
import carb
import traceback
from enum import IntFlag, Enum
from pxr import Sdf, Usd, UsdUtils, UsdShade, UsdLux, Tf
from .omni_client_wrapper import OmniClientWrapper
from .utils import Utils
from .async_utils import aio_open_layer, aio_replace_all, aio_save_layer
from .mdl_parser import MDLParser
from .async_utils import wrap
class CollectorFailureOptions(IntFlag):
"""Options to customize failure options"""
SILENT = 0 # Silent for all failures except root USD.
EXTERNAL_USD_REFERENCES = 1 # Throws exception if any external USD file is not found.
OTHER_EXTERNAL_REFERENCES = 4 # Throws exception if external references other than all above are missing.
class CollectorException(Exception):
def __init__(self, error: str):
self._error = error
def __str__(self):
return self._error
class CollectorTaskType:
"""Task type"""
READ_TASK = 0
WRITE_TASK = 1
COPY_TASK = 2
RESOLVE_TASK = 3
class FlatCollectionTextureOptions(Enum):
"""Collection options for textures under 'Flat Collection' mode"""
BY_MDL = 0 # group textures by MDL
BY_USD = 1 # group textures by USD
FLAT = 2 # all textures will be under the same hierarchy, flat
class Collector:
"""Collect stage related asset to {target_folder}/collected_stagename/}.
Args:
usd_path (str): The usd stage to be collected.
collect_dir (str): The target dir to collect the usd stage to.
usd_only (bool): Collects usd files only or not. It will ignore all asset types.
flat_collection (bool): Collects stage without keeping the original dir structure.
material_only (bool): Collects material and textures only or not. It will ignore all other asset types.
skip_existing (bool): If files already exist in the target location, don't copy again. Be careful of corrupt files
texture_option (FlatCollectionTextureOptions): Specifies how textures are grouped in flat collection mode.
This is to avoid name collision which results in textures overwriting each other in the cases where textures
for different assets are not uniquely named.
If both `usd_only` and `material_only` are true, it will collect all.
"""
def __init__(
self,
usd_path: str,
collect_dir: str,
usd_only: bool,
flat_collection: bool,
material_only: bool = False,
failure_options=CollectorFailureOptions.SILENT,
skip_existing: bool = False,
max_concurrent_tasks=64,
texture_option=FlatCollectionTextureOptions.BY_MDL,
):
self._usd_path = Utils.normalize_path(usd_path)
self._collect_dir = Utils.normalize_path(collect_dir)
if not self._collect_dir.endswith("/"):
self._collect_dir += "/"
self._usd_only = usd_only and not material_only
self._material_only = material_only and not usd_only
self._flat_collection = flat_collection
self._texture_option = texture_option
self._finished = False
self._cancelled = False
self.MAX_CONCURRENT_TASKS = max_concurrent_tasks
self._current_tasks = set([])
self._finished_callback = None
self._progress_callback = None
self._unique_path_name = {} # Records the count key that appears in the collected paths to generate unique name
self._source_target_path_mapping = {} # It records source to target
self._failure_options = failure_options
self._skip_existing = skip_existing
self._layer_store = {}
self._mdl_parsers = {}
self._sublayer_offsets = {}
self._other_asset_paths = set({})
self._current_progress = 0
self._total_steps = 0
self._all_read_paths = set({})
def destroy(self):
self._finished_callback = None
self._progress_callback = None
def _caculate_flat_target_path(self, path, parent_asset=None):
target_dir = self._collect_dir
master_usd = Utils.normalize_path(path) == self._usd_path
material_only = self._material_only
file_url = omni.client.break_url(path)
target_url = omni.client.break_url(target_dir)
file_path = file_url.path
file_name = os.path.basename(file_path)
if omni.usd.is_usd_writable_filetype(path) and master_usd:
int_dir = ""
else:
if not material_only:
int_dir = "SubUSDs/"
else:
int_dir = ""
if Utils.is_material(file_name):
int_dir = f"{int_dir}materials/"
elif not omni.usd.is_usd_writable_filetype(file_name):
int_dir = f"{int_dir}textures/"
# OM-52799 add options to group textures by MDL / USD assets to avoid name collision causing overwrites
if parent_asset:
parent_name, _ = os.path.splitext(os.path.basename(parent_asset))
# currently not including the file extension in parent folder names, but could add it in if it is
# more clear to show the ext as a suffix to the folder name
int_dir += f"{parent_name}/"
target_path = target_url.path + int_dir + file_name
if file_url.query:
branch_checkpoint = omni.client.get_branch_and_checkpoint_from_query(file_url.query)
if branch_checkpoint:
branch, checkpoint = branch_checkpoint
file_path, ext = os.path.splitext(target_path)
if not branch:
branch = "default"
target_path = f"{file_path}__{branch}__v{checkpoint}{ext}"
target_path = omni.client.make_url(
scheme=target_url.scheme,
user=target_url.user,
host=target_url.host,
port=target_url.port,
path=target_path,
query=None,
fragment=None,
)
return Utils.normalize_path(target_path)
# All paths must be absolute path
def _calculate_target_path(self, file_path, parent_asset=None):
file_path = Utils.normalize_path(file_path)
if self._flat_collection:
return self._caculate_flat_target_path(file_path, parent_asset=parent_asset)
target_dir = self._collect_dir
if not target_dir.endswith("/"):
target_dir += "/"
stage_path = self._usd_path
stage_url = omni.client.break_url(stage_path)
if not stage_url.scheme:
stage_path_with_scheme = "file://" + stage_path
else:
stage_path_with_scheme = stage_path
file_url = omni.client.break_url(file_path)
if not file_url.scheme:
file_path_with_shceme = "file://" + file_path
else:
file_path_with_shceme = file_path
stage_url = omni.client.break_url(stage_path_with_scheme)
file_url = omni.client.break_url(file_path_with_shceme)
target_url = omni.client.break_url(target_dir)
if stage_url.scheme != file_url.scheme or stage_url.host != file_url.host:
file_path = file_url.path.lstrip("/")
if file_url.host:
target_path = target_url.path + file_url.host + "/" + file_path
else:
target_path = target_url.path + file_path
else:
stage_url_path = stage_url.path.replace("//", "/")
file_url_path = file_url.path.replace("//", "/")
common_path = os.path.commonpath([os.path.dirname(stage_url_path), os.path.dirname(file_url_path)])
common_path = common_path.replace("\\", "/")
file_path = file_url_path[len(common_path) :].lstrip("/")
target_path = target_url.path + file_path
if file_url.query:
branch_checkpoint = omni.client.get_branch_and_checkpoint_from_query(file_url.query)
if branch_checkpoint:
branch, checkpoint = branch_checkpoint
file_name, ext = os.path.splitext(target_path)
if not branch:
branch = "default"
target_path = f"{file_name}__{branch}__v{checkpoint}{ext}"
target_path = omni.client.make_url(
scheme=target_url.scheme,
user=target_url.user,
host=target_url.host,
port=target_url.port,
path=target_path,
query=None,
fragment=None,
)
return Utils.normalize_path(target_path)
async def _get_total_steps(self):
stage_path = self._usd_path
collect_usd_only = self._usd_only
carb.log_info(f"Downloading and collecting dependencies: {stage_path}...")
# Pre-warming to download all USDs and MDLs in parallel.
target_path = self._calculate_target_path(stage_path)
self._source_target_path_mapping[stage_path] = target_path
if target_path and target_path == stage_path:
self._raise_or_log(
stage_path, f"Failed to collect layer {stage_path} as it tries to overwrite itself.", True
)
await self.__add_read_task(stage_path)
# Cancelled
if not await self.wait_all_unfinished_tasks(True):
return None
if collect_usd_only:
total = len(self._layer_store)
else:
total_textures = 0
for parser in self._mdl_parsers.values():
raw_to_absolute_texture_paths, _ = await parser.parse()
total_textures += len(raw_to_absolute_texture_paths)
total_material_assets = len(self._mdl_parsers) + total_textures
if self._material_only:
total = len(self._other_asset_paths) + total_material_assets
else:
total = len(self._layer_store) + len(self._other_asset_paths) + total_material_assets
return total
def _remove_prim_spec(self, layer: Sdf.Layer, prim_spec_path: str):
prim_spec = layer.GetPrimAtPath(prim_spec_path)
if not prim_spec:
return False
if prim_spec.nameParent:
name_parent = prim_spec.nameParent
else:
name_parent = layer.pseudoRoot
if not name_parent:
return False
name = prim_spec.name
if name in name_parent.nameChildren:
del name_parent.nameChildren[name]
def _remove_all_materials_and_bindings(self, stage_path):
stage = Usd.Stage.Open(stage_path)
if not stage:
return
to_be_removed = []
for prim in stage.Traverse():
if prim.IsA(UsdShade.Material):
to_be_removed.append(prim)
binding_api = UsdShade.MaterialBindingAPI(prim)
if binding_api:
binding_api.UnbindAllBindings()
if prim.IsA(UsdLux.DomeLight):
dome_light = UsdLux.DomeLight(prim)
dome_light.GetTextureFileAttr().Set("")
for prim in to_be_removed:
to_remove_paths = []
if prim:
for prim_spec in prim.GetPrimStack():
layer = prim_spec.layer
to_remove_paths.append((layer, prim_spec.path))
for item in to_remove_paths:
self._remove_prim_spec(item[0], item[1])
stage.Save()
def __modify_external_references(self, original_layer_identifier, target_layer):
def modifiy_paths_cb(path):
absolute_path = Utils.compute_absolute_path(original_layer_identifier, path)
target_path = self._source_target_path_mapping.get(absolute_path, None)
if not target_path:
return path
return Utils.make_relative_path(target_layer.identifier, target_path)
try:
UsdUtils.ModifyAssetPaths(target_layer, modifiy_paths_cb)
except Exception as e:
carb.log_error(f"Failed to modify asset paths {target_layer.identifier}:" + str(e))
LAYER_OMNI_CUSTOM_KEY = "omni_layer"
LAYER_MUTENESS_CUSTOM_KEY = "muteness"
custom_data = target_layer.customLayerData
if LAYER_OMNI_CUSTOM_KEY in custom_data:
omni_data = custom_data[LAYER_OMNI_CUSTOM_KEY]
if LAYER_MUTENESS_CUSTOM_KEY in omni_data:
new_muteness_data = {}
for path, muted in omni_data[LAYER_MUTENESS_CUSTOM_KEY].items():
absolute_path = Utils.compute_absolute_path(original_layer_identifier, path)
target_path = self._source_target_path_mapping.get(absolute_path, None)
if target_path:
target_path = Utils.make_relative_path(target_layer.identifier, target_path)
new_muteness_data[target_path] = muted
if new_muteness_data:
omni_data[LAYER_MUTENESS_CUSTOM_KEY] = new_muteness_data
custom_data[LAYER_OMNI_CUSTOM_KEY] = omni_data
target_layer.customLayerData = custom_data
def __mapping_source_path(self, source_path, parent_asset=None):
if source_path in self._source_target_path_mapping:
return False
# OM-52799 add options to group textures by MDL / USD assets to avoid name collision causing overwrites
target_path = self._calculate_target_path(source_path, parent_asset=parent_asset)
target_path = self._make_sure_unique_path(target_path)
self._source_target_path_mapping[source_path] = target_path
return True
# Gets external references.
async def __get_external_references(self, original_layer_identifier, target_layer):
stage_path = self._usd_path
try:
sublayer_paths, reference_paths, payload_paths = UsdUtils.ExtractExternalReferences(target_layer.identifier)
except Exception as e:
carb.log_error(f"Failed to collect {target_layer.identifier}: " + str(e))
sublayer_paths = []
reference_paths = []
payload_paths = []
all_usd_paths = set()
all_mdl_paths = set()
other_asset_paths = set()
async def track_path(path):
absolute_path = Utils.compute_absolute_path(original_layer_identifier, path)
if absolute_path in self._source_target_path_mapping:
return
if Utils.is_material(path):
existed = await OmniClientWrapper.exists(absolute_path)
# OM-44975: If it's not existed locally and it cannot be resolved with search paths,
# just leave the path as it is.
if not existed:
absolute_path = Utils.compute_absolute_path(stage_path, path)
# OM-43965: resolve agaist stage path.
existed = await OmniClientWrapper.exists(absolute_path)
if not existed:
return
mapping_kwargs = {}
if Utils.is_udim_texture(absolute_path):
all_asset_paths = await self.__populate_udim_textures(absolute_path)
for path in all_asset_paths:
self.__mapping_source_path(path, **mapping_kwargs)
else:
all_asset_paths = [absolute_path]
if omni.usd.is_usd_writable_filetype(absolute_path):
all_usd_paths.add(absolute_path)
elif Utils.is_material(absolute_path):
all_mdl_paths.add(absolute_path)
else:
# should only add parent asset option in mapping if the current path is not USD or MDL
if self._flat_collection and self._texture_option is FlatCollectionTextureOptions.BY_USD:
# do not add the root stage itself as a parent
if original_layer_identifier != self._usd_path:
mapping_kwargs["parent_asset"] = original_layer_identifier
# Adds udim mapping but not into copy list.
if Utils.is_udim_texture(absolute_path):
all_asset_paths = await self.__populate_udim_textures(absolute_path)
for path in all_asset_paths:
self.__mapping_source_path(path, **mapping_kwargs)
else:
all_asset_paths = [absolute_path]
other_asset_paths.update(all_asset_paths)
self.__mapping_source_path(absolute_path, **mapping_kwargs)
async def check_paths(paths):
tasks = []
for path in paths:
future = asyncio.ensure_future(track_path(path))
tasks.append(future)
if tasks:
await asyncio.wait(tasks, return_when=asyncio.ALL_COMPLETED)
await check_paths(sublayer_paths)
await check_paths(reference_paths)
await check_paths(payload_paths)
return all_usd_paths, all_mdl_paths, other_asset_paths
async def open_or_create_layer(self, layer_path, clear=True):
# WA to fix OM-33212
await omni.client.create_folder_async(os.path.dirname(layer_path))
layer = await aio_open_layer(layer_path)
if not layer:
layer = Sdf.Layer.CreateNew(layer_path)
elif clear:
layer.Clear()
return layer
async def add_copy_task(self, source, target, skip_if_existed=False):
if self._skip_existing and await OmniClientWrapper.exists(target):
carb.log_info(f"Asset file {target} already exists, skipping copy")
else:
carb.log_info(f"Adding copy task from {source} to {target}")
task = asyncio.ensure_future(OmniClientWrapper.copy(source, target, True))
task.source = source
task.target = target
task.task_type = CollectorTaskType.COPY_TASK
self._current_tasks.add(task)
if len(self._current_tasks) >= self.MAX_CONCURRENT_TASKS:
await self.wait_all_unfinished_tasks()
async def add_write_task(self, target, content):
carb.log_info(f"Adding write task to {target}")
task = asyncio.ensure_future(OmniClientWrapper.write(target, content))
task.task_type = CollectorTaskType.WRITE_TASK
task.source = None
task.target = target
self._current_tasks.add(task)
if len(self._current_tasks) >= self.MAX_CONCURRENT_TASKS:
await self.wait_all_unfinished_tasks()
async def __add_layer_resolve_task(self, source_layer_path, target_layer):
carb.log_info(f"Adding layer resolve task for {target_layer.identifier}")
task = asyncio.ensure_future(self.__resolve_layer(source_layer_path, target_layer))
task.task_type = CollectorTaskType.RESOLVE_TASK
task.source = target_layer.identifier
task.target = None
self._current_tasks.add(task)
if len(self._current_tasks) >= self.MAX_CONCURRENT_TASKS:
await self.wait_all_unfinished_tasks()
async def __resolve_layer(self, source_layer_path, target_layer):
# Resolve all external assets
__aio_modify_external_references = wrap(self.__modify_external_references)
await __aio_modify_external_references(source_layer_path, target_layer)
# OM-40291: Copy sublayer offsets.
sublayer_offsets = self._sublayer_offsets.get(source_layer_path, None)
if sublayer_offsets:
for i in range(len(sublayer_offsets)):
target_layer.subLayerOffsets[i] = sublayer_offsets[i]
return await aio_save_layer(target_layer)
async def __open_and_analyze_layer(self, source_path, target_path):
if self._material_only:
target_layer = await aio_open_layer(source_path)
else:
# OM-52207: copy it firstly to keep tags for omniverse path.
success = await OmniClientWrapper.copy(source_path, target_path, True)
if not success:
return False
try:
target_layer = await self.open_or_create_layer(target_path, False)
except Tf.ErrorException:
# WA for OM-52094: usda in server may be saved as usdc format,
# which cannot be opened with USD library locally.
# The solution here is to rename it as .usd.
target_layer = None
root, _ = os.path.splitext(target_path)
renamed_usd = root + ".usd"
success = await OmniClientWrapper.copy(target_path, renamed_usd)
if success:
await OmniClientWrapper.delete(target_path)
target_layer = await self.open_or_create_layer(renamed_usd, False)
self._source_target_path_mapping[source_path] = renamed_usd
if not target_layer:
return False
self._layer_store[source_path] = target_layer
if target_layer.subLayerOffsets:
self._sublayer_offsets[source_path] = target_layer.subLayerOffsets.copy()
carb.log_info(f"Collecting dependencies for usd {source_path}...")
all_usd_paths, all_mdl_paths, all_other_paths = await self.__get_external_references(source_path, target_layer)
for path in all_usd_paths:
if self._cancelled:
break
await self.__add_read_task(path)
if self._usd_only:
self._remove_all_materials_and_bindings(target_layer.identifier)
else:
for path in all_mdl_paths:
if self._cancelled:
break
await self.__add_read_task(path)
self._other_asset_paths.update(all_other_paths)
return True
async def __populate_udim_textures(self, udim_texture_path):
src_dir = os.path.dirname(udim_texture_path)
if not src_dir.endswith("/"):
src_dir = src_dir + "/"
result, entries = await omni.client.list_async(src_dir)
if result != omni.client.Result.OK:
self._raise_or_log(
udim_texture_path, f"Failed to list UDIM textures {udim_texture_path}, error code: {result}"
)
texture_paths = []
for entry in entries:
texture_path = Utils.compute_absolute_path(src_dir, entry.relative_path)
if Utils.is_udim_wildcard_texture(texture_path, udim_texture_path):
texture_paths.append(texture_path)
return texture_paths
async def __open_and_analyze_mdl(self, path, target_path):
# OM-52207: copy it firstly to keep tags for omniverse path.
if Utils.is_omniverse_path(path):
success = await OmniClientWrapper.copy(path, target_path, True)
if not success:
return False
content = await OmniClientWrapper.read(path)
if not content:
return False
mdl_parser = MDLParser(path, content)
self._mdl_parsers[path] = mdl_parser
carb.log_info(f"Collecting dependencies for mdl {path}...")
raw_to_absolute_texture_paths, imports = await mdl_parser.parse()
mapping_kwargs = {}
if self._flat_collection and self._texture_option is FlatCollectionTextureOptions.BY_MDL:
mapping_kwargs["parent_asset"] = path
for absolute_texture_path in raw_to_absolute_texture_paths.values():
if not self.__mapping_source_path(absolute_texture_path, **mapping_kwargs):
continue
if Utils.is_udim_texture(absolute_texture_path):
all_asset_paths = await self.__populate_udim_textures(absolute_texture_path)
for path in all_asset_paths:
self.__mapping_source_path(path, **mapping_kwargs)
for mdl_import in imports:
if self._cancelled:
break
absolute_import_path = mdl_import.package_path
if not await OmniClientWrapper.exists(absolute_import_path):
continue
self.__mapping_source_path(absolute_import_path)
await self.__add_read_task(absolute_import_path)
return True
async def __add_read_task(self, path):
if path in self._all_read_paths:
return
self._all_read_paths.add(path)
if path in self._layer_store or path in self._mdl_parsers:
return
carb.log_info(f"Adding read task to {path}")
is_usd_type = omni.usd.is_usd_writable_filetype(path)
is_mdl_path = Utils.is_material(path)
target_path = self._source_target_path_mapping.get(path)
if is_usd_type:
task = asyncio.ensure_future(self.__open_and_analyze_layer(path, target_path))
elif is_mdl_path and not self._usd_only:
task = asyncio.ensure_future(self.__open_and_analyze_mdl(path, target_path))
else:
return
task.task_type = CollectorTaskType.READ_TASK
task.source = path
task.target = None
self._current_tasks.add(task)
if len(self._current_tasks) >= self.MAX_CONCURRENT_TASKS:
await self.wait_all_unfinished_tasks()
def __cancel_all_tasks(self):
try:
self._progress_callback = None
for task in self._current_tasks:
task.cancel()
except Exception:
pass
finally:
self._current_tasks.clear()
async def wait_all_unfinished_tasks(self, all_completed=False):
if len(self._current_tasks) == 0:
return True
carb.log_info(f"Waiting for {len(self._current_tasks)} tasks...")
while len(self._current_tasks) > 0:
if self._cancelled:
self.__cancel_all_tasks()
return False
try:
done, _ = await asyncio.wait(self._current_tasks, return_when=asyncio.FIRST_COMPLETED)
failed_tasks = set()
for task in done:
if task not in self._current_tasks:
continue
if task.task_type != CollectorTaskType.READ_TASK:
self.__report_one_progress()
result = task.result()
if not result:
failed_tasks.add(task)
if task.task_type == CollectorTaskType.COPY_TASK:
self._raise_or_log(task.source, f"Failed to move from {task.source} to {task.target}.")
elif task.task_type == CollectorTaskType.WRITE_TASK:
self._raise_or_log(task.target, f"Failed to write {task.target}.")
elif task.task_type == CollectorTaskType.READ_TASK:
self._raise_or_log(task.source, f"Failed to read {task.source} as it's not existed.")
elif task.task_type == CollectorTaskType.RESOLVE_TASK:
self._raise_or_log(task.source, f"Failed to resolve layer {task.source}.")
self._current_tasks.discard(task)
except CollectorException as e:
raise e
except Exception:
traceback.print_exc()
if not all_completed:
break
await asyncio.sleep(0.1)
carb.log_info(f"Waiting for unfinished done, left {len(self._current_tasks)} tasks...")
return True
def is_finished(self):
return self._finished
def cancel(self):
self._cancelled = True
self.__cancel_all_tasks()
if self._finished_callback:
self._finished_callback()
def _make_sure_unique_path(self, path):
# Generates unique path name
if Utils.is_udim_texture(path):
return path
path = Utils.normalize_path(path)
while True:
index = self._unique_path_name.get(path, -1)
if index == -1:
self._unique_path_name[path] = 0
break
else:
index += 1
self._unique_path_name[path] = index
file_path, ext = os.path.splitext(path)
path = file_path + "_" + str(index) + ext
self._unique_path_name[path] = 0
return path
def _raise_or_log(self, path, error, force_raise=False):
is_usd_type = omni.usd.is_usd_writable_filetype(path)
has_usd_failure_option = self._failure_options & CollectorFailureOptions.EXTERNAL_USD_REFERENCES
has_other_failure_option = self._failure_options & CollectorFailureOptions.OTHER_EXTERNAL_REFERENCES
if force_raise or (is_usd_type and has_usd_failure_option) or (not is_usd_type and has_other_failure_option):
raise CollectorException(error)
else:
carb.log_warn(error)
async def collect(self, progress_callback, finish_callback):
def __reset():
self._layer_store = {}
self._mdl_parsers = {}
self._sublayer_offsets = {}
self._other_asset_paths = set()
self._unique_path_name.clear()
self._source_target_path_mapping = {}
self._current_progress = 0
self._total_steps = 0
self._progress_callback = None
self._finished_callback = None
self._all_read_paths.clear()
try:
__reset()
self._finished = False
self._finished_callback = finish_callback
self._progress_callback = progress_callback
await self._collect_internal()
finally:
self._finished = True
if finish_callback:
finish_callback()
__reset()
def __report_one_progress(self):
self._current_progress += 1
if self._current_progress >= self._total_steps:
self._current_progress = self._total_steps
if self._progress_callback:
self._progress_callback(self._current_progress, self._total_steps)
async def _collect_internal(self):
carb.log_info(f"Collecting stage {self._usd_path} to {self._collect_dir}...")
total = await self._get_total_steps()
if total == 0:
raise CollectorException(f"Failed to collect {self._usd_path} as it cannot be opened.")
elif total is None:
carb.log_info(f"Collecting stage {self._usd_path} to {self._collect_dir} is cancelled.")
return
# Add one more step to wait for tasks to be done.
self._total_steps = total + 1
carb.log_info(f"Starting to collect: total steps {self._total_steps} found...")
if not self._material_only:
for source_layer_path, target_layer in self._layer_store.items():
carb.log_info(f"Modifying external references for {target_layer.identifier}...")
if self._cancelled:
break
await self.__add_layer_resolve_task(source_layer_path, target_layer)
if not self._usd_only:
for mdl_absolute_path, mdl_parser in self._mdl_parsers.items():
if self._cancelled:
break
carb.log_info(f"Collecting mdl {mdl_absolute_path}...")
# Per MDL.
processed_texture_path = set([])
mdl_target_path = self._source_target_path_mapping.get(mdl_absolute_path)
mdl_content = mdl_parser.content
raw_to_absolute_texture_paths, mdl_imports = await mdl_parser.parse()
for raw_texture_path, absolute_texture_path in raw_to_absolute_texture_paths.items():
if self._cancelled:
break
if absolute_texture_path in processed_texture_path:
continue
processed_texture_path.add(absolute_texture_path)
texture_target_path = self._source_target_path_mapping.get(absolute_texture_path)
relative_path = Utils.make_relative_path(mdl_target_path, texture_target_path)
mdl_content = await aio_replace_all(
mdl_content, f'texture_2d("{raw_texture_path}', f'texture_2d("{relative_path}'
)
mdl_content = await aio_replace_all(
mdl_content, f'texture_3d("{raw_texture_path}', f'texture_3d("{relative_path}'
)
mdl_content = await aio_replace_all(
mdl_content, f'texture_cube("{raw_texture_path}', f'texture_cube("{relative_path}'
)
mdl_content = await aio_replace_all(
mdl_content, f'texture_ptex("{raw_texture_path}', f'texture_ptex("{relative_path}'
)
carb.log_info(f"Moving texture file {absolute_texture_path} to {texture_target_path}")
await self.add_copy_task(absolute_texture_path, texture_target_path, self._skip_existing)
# handl mdls that's imported
for mdl_import in mdl_imports:
if self._cancelled:
break
import_target_path = self._source_target_path_mapping.get(mdl_import.package_path)
# It's not mapped so it's not existed.
if not import_target_path:
continue
relative_path = Utils.make_relative_path(mdl_target_path, import_target_path)
import_clause = mdl_import.import_clause
if relative_path.endswith(".mdl"):
relative_path = relative_path[:-4]
while relative_path.startswith("./"):
relative_path = relative_path[2:]
relative_path = relative_path.replace("/", "::")
if mdl_import.module_preset:
# OM-7604
has_prefix = False
while relative_path.startswith("..::"):
has_prefix = True
relative_path = relative_path[4:]
if has_prefix and relative_path:
relative_path = f"::{relative_path}"
import_clause = import_clause.replace(mdl_import.import_package, relative_path)
mdl_content = await aio_replace_all(mdl_content, mdl_import.import_clause, import_clause)
if self._flat_collection:
import_package = mdl_import.import_package
while import_package.startswith(".::") or import_package.startswith("..::"):
if import_package.startswith(".::"):
import_package = import_package[3:]
else:
import_package = import_package[4:]
# OM-37410: It's possible that function is referenced with full module path.
if import_package:
if not import_package.startswith("::"):
import_package = "::" + import_package
if not relative_path.startswith("::"):
relative_path = f"::{relative_path}"
mdl_content = await aio_replace_all(mdl_content, import_package, relative_path)
await self.add_write_task(mdl_target_path, mdl_content)
# Copy all external assets except USD and MDLs to target path
for absolute_asset_path in self._other_asset_paths:
if self._cancelled:
break
asset_target_path = self._source_target_path_mapping.get(absolute_asset_path)
carb.log_info(f"Moving asset file from {absolute_asset_path} to {asset_target_path}")
await self.add_copy_task(absolute_asset_path, asset_target_path, self._skip_existing)
if not await self.wait_all_unfinished_tasks(True):
carb.log_info("Collecting is cancelled.")
else:
carb.log_info("Collecting is finished.")
| 36,492 | Python | 40.469318 | 122 | 0.578291 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/omni_client_wrapper.py | import os
import traceback
import asyncio
import carb
import omni.client
import stat
def _encode_content(content):
if type(content) == str:
payload = bytes(content.encode("utf-8"))
elif type(content) != type(None):
payload = bytes(content)
else:
payload = bytes()
return payload
class OmniClientWrapper:
@staticmethod
async def exists(path):
try:
result, entry = await omni.client.stat_async(path)
return result == omni.client.Result.OK
except Exception:
return False
@staticmethod
def exists_sync(path):
try:
result, entry = omni.client.stat(path)
return result == omni.client.Result.OK
except Exception:
return False
@staticmethod
async def write(path: str, content):
carb.log_info(f"Writing {path}...")
try:
result = await omni.client.write_file_async(path, _encode_content(content))
if result != omni.client.Result.OK:
carb.log_warn(f"Cannot write {path}, error code: {result}.")
return False
except Exception as e:
carb.log_warn(f"Cannot write {path}: {str(e)}.")
return False
finally:
carb.log_info(f"Writing {path} done...")
return True
@staticmethod
async def delete(path: str):
carb.log_info(f"Removing {path}...")
try:
result = await omni.client.delete_async(path)
if result != omni.client.Result.OK:
carb.log_warn(f"Cannot remove {path}, error code: {result}.")
return False
except Exception:
carb.log_warn(f"Cannot delete {path}: {str(e)}.")
return False
return True
@staticmethod
async def set_write_permission(src_path: str):
# It can change ACIs for o
url = omni.client.break_url(src_path)
# Local path
try:
if url.is_raw:
st = os.stat(src_path)
os.chmod(src_path, st.st_mode | stat.S_IWRITE)
elif src_path.startswith("omniverse://"):
result, server_info = await omni.client.get_server_info_async(src_path)
if result != omni.client.Result.OK:
return False
user_acl = omni.client.AclEntry(
server_info.username,
omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE | omni.client.AccessFlags.ADMIN
)
result = await omni.client.set_acls_async(src_path, [user_acl])
return result == omni.client.Result.OK
except Exception as e:
carb.log_warn(f"Failed to set write permission for url {src_path}: {str(e)}.")
return False
@staticmethod
async def copy(src_path: str, dest_path: str, set_target_writable_if_read_only=False):
carb.log_info(f"Copying from {src_path} to {dest_path}...")
try:
result = await omni.client.copy_async(src_path, dest_path, omni.client.CopyBehavior.OVERWRITE)
if result != omni.client.Result.OK:
carb.log_warn(f"Cannot copy from {src_path} to {dest_path}, error code: {result}.")
return False
else:
if set_target_writable_if_read_only:
await OmniClientWrapper.set_write_permission(dest_path)
return True
except Exception as e:
carb.log_warn(f"Cannot copy {src_path} to {dest_path}: {str(e)}.")
return False
@staticmethod
async def read(src_path: str):
carb.log_info(f"Reading {src_path}...")
try:
result, version, content = await omni.client.read_file_async(src_path)
if result == omni.client.Result.OK:
return memoryview(content).tobytes()
else:
carb.log_warn(f"Cannot read {src_path}, error code: {result}.")
except Exception as e:
carb.log_warn(f"Cannot read {src_path}: {str(e)}.")
finally:
carb.log_info(f"Reading {src_path} done.")
return None
@staticmethod
async def create_folder(path):
carb.log_info(f"Creating dir {path}...")
result = await omni.client.create_folder_async(path)
return result == omni.client.Result.OK
| 4,455 | Python | 32.007407 | 112 | 0.562738 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/filebrowser/__init__.py | class FileBrowserSelectionType:
FILE_ONLY = 0
DIRECTORY_ONLY = 1
ALL = 2
class FileBrowserMode:
OPEN = 0
SAVE = 1
| 136 | Python | 12.699999 | 31 | 0.632353 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/filebrowser/app_filebrowser.py | import asyncio
import re
import omni.ui
import omni.client
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.widget.filebrowser import FileBrowserItem
from . import FileBrowserSelectionType, FileBrowserMode
class FileBrowserUI:
def __init__(
self, title: str, mode: FileBrowserMode,
selection_type: FileBrowserSelectionType,
filter_options, ok_button_title="Open"
):
self._file_picker = FilePickerApp(title, ok_button_title, selection_type, filter_options, mode)
def set_current_directory(self, dir):
self._file_picker.set_current_directory(dir)
def set_current_filename(self, filename):
self._file_picker.set_current_filename(filename)
def set_filebar_label_name(self, name):
self._file_picker.set_filebar_label_name(name)
def open(self, select_fn, cancel_fn):
self._file_picker.set_custom_fn(select_fn, cancel_fn)
self._file_picker.show_dialog()
def destroy(self):
if self._file_picker:
self._file_picker.destroy()
self._file_picker = None
class FilePickerApp:
"""
Standalone app to demonstrate the use of the FilePicker dialog.
Args:
title (str): Title of the window.
apply_button_name (str): Name of the confirm button.
selection_type (FileBrowserSelectionType): The file type that confirm event will respond to.
item_filter_options (list): Array of filter options. Element of array
is a tuple that first element of this tuple is the regex string for filtering,
and second element of this tuple is the descriptions, like ("*.*", "All Files").
By default, it will list all files.
"""
APP_SETTINGS_PREFIX = "/persistent/app/omniverse/savedServers"
def __init__(
self,
title: str,
apply_button_name: str,
selection_type: FileBrowserSelectionType = FileBrowserSelectionType.ALL,
item_filter_options: list = [("*.*", "All Files (*.*)")],
mode: FileBrowserMode = FileBrowserMode.OPEN
):
self._title = title
self._filepicker = None
self._mode = mode
self._selection_type = selection_type
self._custom_select_fn = None
self._custom_cancel_fn = None
self._apply_button_name = apply_button_name
self._filter_regexes = []
self._filter_descriptions = []
self._current_directory = None
for item in item_filter_options:
self._filter_regexes.append(re.compile(item[0], re.IGNORECASE))
self._filter_descriptions.append(item[1])
self._build_ui()
def destroy(self):
self._custom_cancel_fn = None
self._custom_select_fn = None
if self._filepicker:
self._filepicker.destroy()
def set_custom_fn(self, select_fn, cancel_fn):
self._custom_select_fn = select_fn
self._custom_cancel_fn = cancel_fn
def show_dialog(self):
self._filepicker.show(self._current_directory)
self._current_directory = None
def hide_dialog(self):
self._filepicker.hide()
def set_current_directory(self, dir: str):
self._current_directory = dir
if not self._current_directory.endswith("/"):
self._current_directory += "/"
def set_current_filename(self, filename: str):
self._filepicker.set_filename(filename)
def set_filebar_label_name(self, name):
self._filepicker.set_filebar_label_name(name)
def _build_ui(self):
on_click_open = lambda f, d: asyncio.ensure_future(self._on_click_open(f, d))
on_click_cancel = lambda f, d: asyncio.ensure_future(self._on_click_cancel(f, d))
# Create the dialog
self._filepicker = FilePickerDialog(
self._title,
allow_multi_selection=False,
apply_button_label=self._apply_button_name,
click_apply_handler=on_click_open,
click_cancel_handler=on_click_cancel,
item_filter_options=self._filter_descriptions,
item_filter_fn=lambda item: self._on_filter_item(item),
error_handler=lambda m: self._on_error(m),
)
# Start off hidden
self.hide_dialog()
def _on_filter_item(self, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if self._selection_type == FileBrowserSelectionType.DIRECTORY_ONLY:
return False
if self._filepicker.current_filter_option >= len(self._filter_regexes):
return False
regex = self._filter_regexes[self._filepicker.current_filter_option]
if regex.match(item.path):
return True
else:
return False
def _on_error(self, msg: str):
"""
Demonstrates error handling. Instead of just printing to the shell, the App can
display the error message to a console window.
"""
print(msg)
async def _on_click_open(self, filename: str, dirname: str):
"""
The meat of the App is done in this callback when the user clicks 'Accept'. This is
a potentially costly operation so we implement it as an async operation. The inputs
are the filename and directory name. Together they form the fullpath to the selected
file.
"""
dirname = dirname.strip()
if dirname and not dirname.endswith("/"):
dirname += "/"
fullpath = f"{dirname}{filename}"
result, entry = omni.client.stat(fullpath)
existed = True
if result == omni.client.Result.OK and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
is_folder = True
else:
existed = False
is_folder = False
# If it's open, it cannot open non-existed file.
if not existed and self._mode == FileBrowserMode.OPEN:
return
if existed or self._mode == FileBrowserMode.OPEN:
if (is_folder and self._selection_type == FileBrowserSelectionType.FILE_ONLY) or (
not is_folder and self._selection_type == FileBrowserSelectionType.DIRECTORY_ONLY
):
return
self.hide_dialog()
await omni.kit.app.get_app().next_update_async()
if self._custom_select_fn:
self._custom_select_fn(fullpath)
async def _on_click_cancel(self, filename: str, dirname: str):
"""
This function is called when the user clicks 'Cancel'.
"""
self.hide_dialog()
await omni.kit.app.get_app().next_update_async()
if self._custom_cancel_fn:
self._custom_cancel_fn()
| 6,735 | Python | 34.083333 | 103 | 0.619005 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/tests/test_collect.py | import os
import asyncio
import carb
import omni.kit.test
import omni.usd
import omni.client
import omni.kit.commands
from pathlib import Path
from omni.kit.tool.collect import get_instance
from omni.kit.tool.collect.collector import (
Collector,
CollectorException,
CollectorFailureOptions,
FlatCollectionTextureOptions,
)
from omni.kit.tool.collect.utils import Utils
from pxr import Usd
# NOTE: those tests belong to omni.kit.tool.collect extension.
class TestCollect(omni.kit.test.AsyncTestCase):
def list_folder(self, folder_path):
all_file_names = []
result, entry = omni.client.stat(folder_path)
if result == omni.client.Result.OK and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
is_folder = True
else:
is_folder = False
if not is_folder:
all_file_names = [os.path.basename(folder_path)]
else:
folder_queue = [folder_path]
while len(folder_queue) > 0:
folder = folder_queue.pop(0)
(result, entries) = omni.client.list(folder)
if result != omni.client.Result.OK:
break
folders = set((e.relative_path for e in entries if e.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN))
for f in folders:
folder_queue.append(f"{folder}/{f}")
files = set((e.relative_path for e in entries if not e.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN))
for file in files:
all_file_names.append(os.path.basename(file))
return all_file_names
def get_test_dir(self):
token = carb.tokens.get_tokens_interface()
data_dir = token.resolve("${data}")
if not data_dir.endswith("/"):
data_dir += "/"
data_dir = Utils.normalize_path(data_dir)
return f"{data_dir}collect_tool_tests"
async def setUp(self):
pass
async def tearDown(self):
await omni.client.delete_async(self.get_test_dir())
async def __test_internal(
self,
stage_name,
root_usd,
usd_only,
material_only,
flat_collection,
texture_option=FlatCollectionTextureOptions.FLAT,
):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
extension_path = Path(extension_path)
test_data_path = extension_path.joinpath("data")
test_stage_dir = str(test_data_path.joinpath("test_stages").joinpath(stage_name))
test_root_usd = test_stage_dir + "/" + root_usd
collected_stage_dir = self.get_test_dir() + f"/collected_{stage_name}"
collector = Collector(
test_root_usd, collected_stage_dir, usd_only, flat_collection, material_only, texture_option=texture_option
)
await collector.collect(None, None)
before = self.list_folder(test_stage_dir)
after = self.list_folder(collected_stage_dir)
self.assertTrue(len(after) > 0)
if usd_only:
before_filtered = []
for f in before:
if omni.usd.is_usd_writable_filetype(f):
before_filtered.append(f)
before = before_filtered
if material_only:
before_filtered = []
for f in before:
if not omni.usd.is_usd_writable_filetype(f):
before_filtered.append(f)
before = before_filtered
self.assertEqual(set(before), set(after))
async def test_collect_with_usd_and_material(self):
await self.__test_internal("normal", "FullScene.usd", False, False, False)
async def test_collect_with_udim_textures(self):
await self.__test_internal("udim", "SM_Hood_A1_1.usd", False, False, False)
async def test_collect_without_material(self):
await self.__test_internal("normal", "FullScene.usd", False, True, False)
async def test_collect_without_usd(self):
await self.__test_internal("normal", "FullScene.usd", True, False, False)
async def test_flatten_collection(self):
await self.__test_internal("normal", "FullScene.usd", False, False, True)
await self.__test_internal("layer_offsets", "root.usd", False, False, True)
async def test_flatten_collection_texture_options(self):
stage_name = "texture_options"
texture_dir = self.get_test_dir() + f"/collected_{stage_name}/SubUSDs/textures/"
mdl_name = "Contour1_Surface_0"
mdl_texture_name = "Contour1_Surface_1.bmp"
usd_preview_texture_name = "another_texture.bmp"
# test group textures by MDL
await self.__test_internal(
stage_name, "test_scene.usd", False, False, True, texture_option=FlatCollectionTextureOptions.BY_MDL
)
# mdl texture should be under the mdl named folder, while the usd preview texture should be directly under
# textures dir
self.assertTrue(os.path.exists(os.path.join(texture_dir, mdl_name, mdl_texture_name)))
self.assertTrue(os.path.exists(os.path.join(texture_dir, usd_preview_texture_name)))
await omni.client.delete_async(self.get_test_dir())
# test group textures by USD
await self.__test_internal(
stage_name, "test_scene.usd", False, False, True, texture_option=FlatCollectionTextureOptions.BY_USD
)
# usd preview texture should be under the usd asset named folder, while the mdl texture should be directly under
# textures dir
self.assertTrue(os.path.exists(os.path.join(texture_dir, "assetB", usd_preview_texture_name)))
self.assertTrue(os.path.exists(os.path.join(texture_dir, mdl_texture_name)))
await omni.client.delete_async(self.get_test_dir())
# test flat
await self.__test_internal(
stage_name, "test_scene.usd", False, False, True, texture_option=FlatCollectionTextureOptions.FLAT
)
# all textures should be directly under textures dir
self.assertEqual(set([mdl_texture_name, usd_preview_texture_name]), set(os.listdir(texture_dir)))
async def test_layer_offsets_collect(self):
current_path = Path(__file__).parent
test_data_path = current_path.parent.parent.parent.parent.parent.joinpath("data")
test_stage_dir = str(test_data_path.joinpath("test_stages").joinpath("layer_offsets"))
test_root_usd = test_stage_dir + "/root.usd"
collected_stage_dir = self.get_test_dir() + f"/collected_layer_offfsets"
collector = Collector(test_root_usd, collected_stage_dir, False, False, False)
await collector.collect(None, None)
before = self.list_folder(test_stage_dir)
after = self.list_folder(collected_stage_dir)
self.assertEqual(set(before), set(after))
after_stage_usd = collected_stage_dir + "/root.usd"
before_stage = Usd.Stage.Open(test_root_usd)
after_stage = Usd.Stage.Open(after_stage_usd)
before_root = before_stage.GetRootLayer()
after_root = after_stage.GetRootLayer()
before_sublayers = before_root.subLayerPaths
after_sublayers = after_root.subLayerPaths
self.assertTrue(len(before_sublayers) > 0)
self.assertEqual(len(before_sublayers), len(after_sublayers))
self.assertEqual(len(before_sublayers), len(after_sublayers))
for i in range(len(before_sublayers)):
before_sublayer = before_root.ComputeAbsolutePath(before_sublayers[i])
after_sublayer = after_root.ComputeAbsolutePath(after_sublayers[i])
self.assertNotEqual(before_sublayer, after_sublayer)
self.assertEqual(before_root.subLayerOffsets, after_root.subLayerOffsets)
async def test_collect_failure_with_exception(self):
with self.assertRaises(CollectorException):
collector = Collector("invalid_source.usd", self.get_test_dir(), False, False, False)
await collector.collect(None, None)
with self.assertRaises(CollectorException):
current_path = Path(__file__).parent
test_data_path = current_path.parent.parent.parent.parent.parent.joinpath("data")
test_stage_path = str(test_data_path.joinpath("test_stages").joinpath("normal/FullScene.usd"))
collector = Collector(test_stage_path, "omniverse://invalid_path", False, False, False)
await collector.collect(None, None)
usd_error_option = CollectorFailureOptions.EXTERNAL_USD_REFERENCES
other_error_option = CollectorFailureOptions.OTHER_EXTERNAL_REFERENCES
all_option = CollectorFailureOptions.EXTERNAL_USD_REFERENCES | CollectorFailureOptions.OTHER_EXTERNAL_REFERENCES
for option in [usd_error_option, other_error_option, all_option]:
with self.assertRaises(CollectorException):
current_path = Path(__file__).parent
test_data_path = current_path.parent.parent.parent.parent.parent.joinpath("data")
test_stage_path = str(test_data_path.joinpath("test_stages/normal").joinpath("FullScene.usd"))
collected_stage_dir = self.get_test_dir() + "/collected_normal"
collector = Collector(test_stage_path, collected_stage_dir, False, False, False, failure_options=option)
await collector.collect(None, None)
async def test_utils(self):
self.assertTrue(Utils.is_udim_texture("test.<UDIM>.png"))
self.assertTrue(Utils.is_udim_texture("test_<UDIM>_suffix.png"))
self.assertTrue(Utils.is_udim_texture("test.%3cUDIM%3e.png"))
self.assertFalse(Utils.is_udim_texture(""))
self.assertFalse(Utils.is_udim_texture("random"))
self.assertTrue(Utils.is_udim_wildcard_texture("test_0001_suffix.png", "test_<UDIM>_suffix.png"))
self.assertFalse(Utils.is_udim_wildcard_texture("test_0001_another_suffix.png", "test_<UDIM>_suffix.png"))
self.assertTrue(
Utils.is_udim_wildcard_texture(
"omniverse://fake-server/base_path/test_0001_suffix.png",
"omniverse://fake-server/base_path/test_<UDIM>_suffix.png",
)
)
self.assertFalse(
Utils.is_udim_wildcard_texture(
"omniverse://fake-server/base_path/test_0001_another_suffix.png",
"omniverse://fake-server/base_path/test_<UDIM>_suffix.png",
)
)
async def test_path_calculation(self):
# Tests for https://nvidia-omniverse.atlassian.net/browse/OM-34746
current_path = Path(__file__).parent
test_data_path = current_path.parent.parent.parent.parent.parent.joinpath("data")
test_stage_path = str(test_data_path.joinpath("test_stages").joinpath("normal/FullScene.usd"))
collector = Collector(test_stage_path, self.get_test_dir(), False, False, False)
path = collector._calculate_target_path("http://test_server/testfile.png")
self.assertEqual(path, self.get_test_dir() + "/test_server/testfile.png")
path = collector._calculate_target_path(str(test_data_path) + "/deep_folder/testfile.png")
self.assertEqual(path, self.get_test_dir() + "/deep_folder/testfile.png")
path = collector._calculate_target_path("omniverse://test_server/testfile.png")
self.assertEqual(path, self.get_test_dir() + "/test_server/testfile.png")
# Flat collect
collector._flat_collection = True
collector._material_only = False
path = collector._calculate_target_path("omniverse://test_server/testfile.png")
self.assertEqual(path, self.get_test_dir() + "/SubUSDs/textures/testfile.png")
path = collector._calculate_target_path("http://test_server/testfile.png")
self.assertEqual(path, self.get_test_dir() + "/SubUSDs/textures/testfile.png")
path = collector._calculate_target_path("http://test_server/testfile.usd")
self.assertEqual(path, self.get_test_dir() + "/SubUSDs/testfile.usd")
# Materials only with flat collect
collector._flat_collection = True
collector._material_only = True
path = collector._calculate_target_path("omniverse://test_server/testfile.png")
self.assertEqual(path, self.get_test_dir() + "/textures/testfile.png")
path = collector._calculate_target_path("http://test_server/testfile.png")
self.assertEqual(path, self.get_test_dir() + "/textures/testfile.png")
# Master USD with flat collect
collector._flat_collection = True
collector._material_only = False
path = collector._calculate_target_path(test_stage_path)
self.assertEqual(path, self.get_test_dir() + "/FullScene.usd")
async def __wait(self, frames=2):
for _ in range(frames):
await omni.kit.app.get_app().next_update_async()
async def __test_ui_internal(self, stage_name, root_usd, usd_only, material_only, flat_collection):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
extension_path = Path(extension_path)
test_data_path = extension_path.joinpath("data")
test_stage_dir = str(test_data_path.joinpath("test_stages").joinpath(stage_name))
test_root_usd = test_stage_dir + "/" + root_usd
collected_stage_dir = self.get_test_dir() + f"/collected_{stage_name}"
done = False
def on_finish():
nonlocal done
done = True
collect_extension = get_instance()
collect_extension.collect(test_root_usd, on_finish)
await self.__wait()
from omni.kit import ui_test
collect_window = ui_test.find("Collection Options")
await collect_window.focus()
usd_only_checkbox = collect_window.find("**/CheckBox[*].identifier=='usd_only_checkbox'")
material_only_checkbox = collect_window.find("**/CheckBox[*].identifier=='material_only_checkbox'")
flat_collection_checkbox = collect_window.find("**/CheckBox[*].identifier=='flat_collection_checkbox'")
folder_button = collect_window.find("**/Button[*].identifier=='folder_button'")
path_field = collect_window.find("**/StringField[*].identifier=='collect_path'")
start_button = collect_window.find("**/Button[*].text=='Start'")
cancel_button = collect_window.find("**/Button[*].text=='Cancel'")
option_combo = collect_window.find("**/ComboBox[*].identifier=='texture_option_combo'")
self.assertTrue(usd_only_checkbox)
self.assertTrue(material_only_checkbox)
self.assertTrue(flat_collection_checkbox)
self.assertTrue(folder_button)
self.assertTrue(path_field)
self.assertTrue(start_button)
self.assertTrue(cancel_button)
self.assertTrue(option_combo)
usd_only_checkbox.model.set_value(False)
material_only_checkbox.model.set_value(False)
flat_collection_checkbox.model.set_value(False)
if usd_only:
await usd_only_checkbox.click()
if material_only:
await material_only_checkbox.click()
if flat_collection:
self.assertFalse(option_combo.widget.visible)
await flat_collection_checkbox.click()
# should show texture options combo here
self.assertTrue(option_combo.widget.visible)
await folder_button.click()
file_picker = ui_test.find("Select Collect Destination")
self.assertTrue(file_picker)
await file_picker.focus()
open_button = file_picker.find("**/Button[*].text=='Open'")
cancel_button = file_picker.find("**/Button[*].text=='Cancel'")
self.assertTrue(open_button)
self.assertTrue(cancel_button)
await cancel_button.click()
path_field.model.set_value(collected_stage_dir)
await start_button.click()
await self.__wait()
progress_window = ui_test.find("Collecting")
self.assertTrue(progress_window)
while not done:
await self.__wait()
self.assertFalse(progress_window.window.visible)
before = self.list_folder(test_stage_dir)
after = self.list_folder(collected_stage_dir)
self.assertTrue(len(after) > 0)
if usd_only:
before_filtered = []
for f in before:
if omni.usd.is_usd_writable_filetype(f):
before_filtered.append(f)
before = before_filtered
if material_only:
before_filtered = []
for f in before:
if not omni.usd.is_usd_writable_filetype(f):
before_filtered.append(f)
before = before_filtered
self.assertEqual(set(before), set(after))
self.assertTrue(done)
async def test_ui_collect_with_usd_and_material(self):
await self.__test_ui_internal("normal", "FullScene.usd", False, False, False)
async def test_ui_collect_without_material(self):
await self.__test_ui_internal("normal", "FullScene.usd", False, True, False)
async def test_ui_collect_without_usd(self):
await self.__test_ui_internal("normal", "FullScene.usd", True, False, False)
async def test_om_55150(self):
await self.__test_ui_internal("OM_55150", "collect_donut.usd", False, False, False)
async def test_ui_flatten_collection(self):
await self.__test_ui_internal("normal", "FullScene.usd", False, False, True)
async def test_file_menu(self):
await omni.usd.get_context().new_stage_async()
from omni.kit import ui_test
await ui_test.menu_click("File/Collect As...")
# It cannot collect anonymous stage
collect_window = ui_test.find("Collection Options")
self.assertFalse(collect_window)
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
extension_path = Path(extension_path)
test_data_path = extension_path.joinpath("data")
test_stage_dir = str(test_data_path.joinpath("test_stages").joinpath("udim"))
test_root_usd = test_stage_dir + "/SM_Hood_A1_1.usd"
await omni.usd.get_context().open_stage_async(test_root_usd)
await ui_test.menu_click("File/Collect As...")
# It cannot collect anonymous stage
collect_window = ui_test.find("Collection Options")
self.assertFalse(collect_window)
| 18,559 | Python | 43.401914 | 120 | 0.640552 |
omniverse-code/kit/exts/omni.kit.tool.collect/omni/kit/tool/collect/tests/__init__.py | from .test_collect import *
| 28 | Python | 13.499993 | 27 | 0.75 |
omniverse-code/kit/exts/omni.graph.instancing/omni/graph/instancing/__init__.py | import carb
carb.log_warn("omni.graph.instancing has been deprecated. All functionality has been moved to omni.graph.core and omni.graph.ui.")
| 144 | Python | 35.249991 | 130 | 0.791667 |
omniverse-code/kit/exts/omni.rtx.ovtextureconverter/omni/rtx/ovtextureconverter/__init__.py | from ._ovtextureconverter import *
from .scripts import *
| 58 | Python | 18.66666 | 34 | 0.775862 |
omniverse-code/kit/exts/omni.rtx.ovtextureconverter/omni/rtx/ovtextureconverter/scripts/commands.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import carb
import omni.kit.commands
import omni.rtx.ovtextureconverter
class IssueTextureCompressionRequest(omni.kit.commands.Command):
def __init__(
self,
**kwargs,
):
# pull out the stage name to process from the entry
# check for a couple different forms
self._path = None
for key in ["path", "texture_path"]:
if key in kwargs:
self._path = kwargs[key]
break
# standardize the path separator character
self._path = self._path.replace("\\", "/") if self._path else None
self._convert_iface = omni.rtx.ovtextureconverter.acquire_ovtextureconverter_interface()
def do(self):
if not self._path:
carb.log_warn("'path' not valid")
return False
carb.log_info("Processing Texture: " + self._path)
# This inserts an async request, but we can't yet "await" it.
# TODO: May need to sleep after this?
return self._convert_iface.compressFileOnly(str(self._path))
omni.kit.commands.register_all_commands_in_module(__name__)
| 1,558 | Python | 34.431817 | 96 | 0.661746 |
omniverse-code/kit/exts/omni.rtx.ovtextureconverter/omni/rtx/ovtextureconverter/scripts/__init__.py | from .commands import * | 23 | Python | 22.999977 | 23 | 0.782609 |
omniverse-code/kit/exts/omni.rtx.ovtextureconverter/omni/rtx/ovtextureconverter/tests/test_ovtextureconverter.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 omni.rtx.ovtextureconverter
class TestConverter(AsyncTestCase):
async def setUp(self):
self._convert_iface = omni.rtx.ovtextureconverter.acquire_ovtextureconverter_interface()
async def tearDown(self):
pass
async def test_001_compress(self):
print("Disabled because somehow on linux the gpufoundation shaders cannot be found 1/2.")
#results = self._convert_iface.compressFile("./resources/test/dot.png", "./resources/test", "BlaBlaBla")
#for x in results:
# print(x)
| 1,039 | Python | 36.142856 | 112 | 0.739172 |
omniverse-code/kit/exts/omni.rtx.ovtextureconverter/omni/rtx/ovtextureconverter/tests/__init__.py | from .test_commands import *
| 29 | Python | 13.999993 | 28 | 0.758621 |
omniverse-code/kit/exts/omni.rtx.ovtextureconverter/omni/rtx/ovtextureconverter/tests/test_commands.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import carb.settings
import omni.kit.app
from omni.kit.test import AsyncTestCase
import omni.rtx.ovtextureconverter.scripts.commands as commands
import asyncio
import os
import os.path
import pathlib
import shutil
TEST_DATA_DIR = str(pathlib.Path(__file__).parent.joinpath("data"))
TEST_OUTPUT_DIR = omni.kit.test.get_test_output_path()
class TestCommands(AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
async def test_IssueTextureCompressionRequest(self):
"""
Test Command to create texture caches with new UJITSO build system
"""
source_texture = pathlib.Path(TEST_DATA_DIR, "dot.png")
tex_cache_dir = pathlib.Path(TEST_OUTPUT_DIR, "ujitso_texcache")
settings = carb.settings.get_settings()
self.assertTrue(settings.get_as_bool("/rtx-transient/resourcemanager/UJITSO/enabled"))
# Set the destination for texture caching
settings.set_string("/rtx-transient/resourcemanager/remoteTextureCachePath", str(tex_cache_dir))
# Clear the local texture cache path to allow repeated tests, otherwise only works first time.
settings.set_string("/rtx-transient/resourcemanager/localTextureCachePath", "")
# Disable omnihub
settings.set_bool("/rtx-transient/resourcemanager/useOmniHubCache", False)
settings.set_bool("/rtx-transient/resourcemanager/useMDBCache", False)
# Remove results from any previous run
if os.path.exists(tex_cache_dir):
shutil.rmtree(tex_cache_dir)
cmd = commands.IssueTextureCompressionRequest(path=str(source_texture))
self.assertTrue(cmd.do())
# NOTE: the datastore that handles the upload currently has no way to wait for all uploads to complete.
print("Waiting for UJITSO texture uploads...")
await asyncio.sleep(5)
self.assertTrue(os.path.exists(tex_cache_dir))
files = os.listdir(tex_cache_dir)
self.assertTrue(len(files) > 0)
| 2,454 | Python | 36.76923 | 111 | 0.714344 |
omniverse-code/kit/exts/omni.activity.profiler/omni/activity/profiler/tests/test_activity_profiler.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.test
import omni.activity.profiler
import carb.profiler
class TestActivityProfiler(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._activity_profiler = omni.activity.profiler.get_activity_profiler()
self._carb_profiler = carb.profiler.acquire_profiler_interface(plugin_name="omni.activity.profiler.plugin")
async def tearDown(self):
self._carb_profiler = None
self._activity_profiler = None
async def test_activity_profiler_masks(self):
# Verify the initial value of the activity profiler capture mask.
self.assertEqual(self._carb_profiler.get_capture_mask(), 0)
# Set the base activity profiler capture mask directly through the carb profiler API.
self._carb_profiler.set_capture_mask(omni.activity.profiler.CAPTURE_MASK_STARTUP)
self.assertEqual(self._carb_profiler.get_capture_mask(), omni.activity.profiler.CAPTURE_MASK_STARTUP)
# Enable an activity profiler capture mask through the activity profiler API.
uid1 = self._activity_profiler.enable_capture_mask(omni.activity.profiler.CAPTURE_MASK_LATENCY)
self.assertEqual(self._carb_profiler.get_capture_mask(), omni.activity.profiler.CAPTURE_MASK_STARTUP |
omni.activity.profiler.CAPTURE_MASK_LATENCY)
# Enable another activity profiler capture mask through the activity profiler API.
uid2 = self._activity_profiler.enable_capture_mask(omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING)
self.assertEqual(self._carb_profiler.get_capture_mask(), omni.activity.profiler.CAPTURE_MASK_STARTUP |
omni.activity.profiler.CAPTURE_MASK_LATENCY |
omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING)
# Enable an activity profiler capture mask for the second time through the activity profiler API.
uid3 = self._activity_profiler.enable_capture_mask(omni.activity.profiler.CAPTURE_MASK_LATENCY)
self.assertEqual(self._carb_profiler.get_capture_mask(), omni.activity.profiler.CAPTURE_MASK_STARTUP |
omni.activity.profiler.CAPTURE_MASK_LATENCY |
omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING)
# Disable the activity profiler capture mask that was set a second time through the activity profiler API.
self._activity_profiler.disable_capture_mask(uid3)
self.assertEqual(self._carb_profiler.get_capture_mask(), omni.activity.profiler.CAPTURE_MASK_STARTUP |
omni.activity.profiler.CAPTURE_MASK_LATENCY |
omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING)
# Disable the first activity profiler capture mask that was set through the activity profiler API.
self._activity_profiler.disable_capture_mask(uid1)
self.assertEqual(self._carb_profiler.get_capture_mask(), omni.activity.profiler.CAPTURE_MASK_STARTUP |
omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING)
# Enable the same base activity profiler capture mask through the activity profiler API.
uid4 = self._activity_profiler.enable_capture_mask(omni.activity.profiler.CAPTURE_MASK_STARTUP)
self.assertEqual(self._carb_profiler.get_capture_mask(), omni.activity.profiler.CAPTURE_MASK_STARTUP |
omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING)
# Disable the same base activity profiler capture mask that was set through the activity profiler API.
self._activity_profiler.disable_capture_mask(uid4)
self.assertEqual(self._carb_profiler.get_capture_mask(), omni.activity.profiler.CAPTURE_MASK_STARTUP |
omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING)
# Set the base activity profiler capture mask directly through the carb profiler API.
self._carb_profiler.set_capture_mask(0)
self.assertEqual(self._carb_profiler.get_capture_mask(), omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING)
# Disable the second activity profiler capture mask that was set through the activity profiler API.
self._activity_profiler.disable_capture_mask(uid2)
self.assertEqual(self._carb_profiler.get_capture_mask(), 0)
# Set the base activity profiler capture mask to something that is not an activity mask.
self._activity_profiler.disable_capture_mask(1)
self.assertEqual(self._carb_profiler.get_capture_mask(), 0)
# Enable an activity profiler capture mask that is not an activity mask.
uid5 = self._activity_profiler.enable_capture_mask(1)
self.assertEqual(self._carb_profiler.get_capture_mask(), 0)
# Disable the activity profiler capture mask that is not an activity mask.
self._activity_profiler.disable_capture_mask(uid5)
self.assertEqual(self._carb_profiler.get_capture_mask(), 0)
| 5,761 | Python | 63.022222 | 115 | 0.664121 |
omniverse-code/kit/exts/omni.kit.widget.browser_bar/omni/kit/widget/browser_bar/style.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons")
UI_STYLES = {}
UI_STYLES["NvidiaLight"] = {
"Rectangle": {"background_color": 0xFF535354},
"Button": {"background_color": 0xFFE0E0E0, "margin": 4, "padding": 0, "border_width": 0},
"Button:hovered": {"background_color": 0xFFACACAF},
"Button:selected": {"background_color": 0xFFACACAF},
"Button:disabled": {"background_color": 0xFFE0E0E0},
"Button.Image": {"color": 0xFF6E6E6E},
"Button.Image:disabled": {"color": 0x0},
"ComboBox": {"background_color": 0xFF535354, "selected_color": 0xFFACACAF, "color": 0xFFD6D6D6},
"ComboBox:hovered": {"background_color": 0xFFACACAF},
"ComboBox:selected": {"background_color": 0xFFACACAF},
}
UI_STYLES["NvidiaDark"] = {
"Rectangle": {"background_color": 0xFF23211F},
"Button": {"background_color": 0x0, "margin": 4, "padding": 0},
"Button:disabled": {"background_color": 0x0},
"Button.Image": {"color": 0xFFFFFFFF},
"Button.Image:disabled": {"color": 0xFF888888},
"ComboBox": {
"background_color": 0xFF23211F,
"selected_color": 0x0,
"color": 0xFF4A4A4A,
"border_radius": 0,
"margin": 0,
"padding": 4,
"secondary_color": 0xFF23211F,
},
"ComboBox.Active": {
"background_color": 0xFF23211F,
"selected_color": 0xFF3A3A3A,
"color": 0xFF9E9E9E,
"border_radius": 0,
"margin": 0,
"padding": 4,
"secondary_selected_color": 0xFF9E9E9E,
"secondary_color": 0xFF23211F,
},
"ComboBox.Active:hovered": {"color": 0xFF4A4A4A, "secondary_color": 0x0,},
"ComboBox.Active:pressed": {"color": 0xFF4A4A4A, "secondary_color": 0x0,},
"ComboBox.Bg": {
"background_color": 0x0,
"margin": 0,
"padding": 2,
},
"ComboBox.Bg.Active": {
"background_color": 0x0,
"margin": 0,
"padding": 2,
},
"ComboBox.Bg.Active:hovered": {
"background_color": 0xFF6E6E6E,
},
"ComboBox.Bg.Active:pressed": {
"background_color": 0xFF6E6E6E,
},
}
| 2,623 | Python | 34.459459 | 100 | 0.633626 |
omniverse-code/kit/exts/omni.kit.widget.browser_bar/omni/kit/widget/browser_bar/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""
The :obj:`PathField` widget supes up tree navigation via keyboard entry. This widget extends that
experience further by queuing up the user's navigation history. As in any modern day browser, the
user can then directly jump to any previously visited path.
Example:
.. code-block:: python
browser_bar = BrowserBar(
visited_history_size=20,
branching_options_provider=branching_options_provider,
apply_path_handler=apply_path_handler,
)
"""
from .widget import BrowserBar
| 944 | Python | 35.346152 | 98 | 0.768008 |
omniverse-code/kit/exts/omni.kit.widget.browser_bar/omni/kit/widget/browser_bar/model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import sys, os
import omni.ui as ui
class StringQueueItem(ui.AbstractItem):
def __init__(self, value: str):
super().__init__()
self._model = ui.SimpleStringModel(value)
@property
def model(self):
return self._model
@property
def value(self):
return self._model.get_value_as_string()
class StringQueueModel(ui.AbstractItemModel):
def __init__(self, max_items: int = 4, value_changed_fn=None):
super().__init__()
self._value_changed_fn = value_changed_fn
self._max_items = max_items
self._items = []
self._selected_index = ui.SimpleIntModel(0)
# TODO: There's a bug that if the item selected doesn't have a different
# index, then it doesn't trigger this callback. It's better to trigger on
# mouse pressed but we don't have this option.
self._selected_index.add_value_changed_fn(self._on_selection_changed)
def __getitem__(self, idx: int) -> StringQueueItem:
if idx < len(self._items):
return self._items[idx]
return None
@property
def selected_index(self) -> int:
return self._selected_index.get_value_as_int()
@selected_index.setter
def selected_index(self, index: int):
self._selected_index.set_value(index)
def get_selected_item(self) -> StringQueueItem:
index = self._selected_index.get_value_as_int()
if index >= 0 and index < len(self._items):
return self._items[index]
return None
def get_item_children(self, item) -> [StringQueueItem]:
if item is None:
return self._items
return []
def get_item_value_model(self, item, column_id) -> ui.AbstractValueModel:
if item is None:
return self._selected_index
return item.model
def find_item(self, value: str) -> StringQueueItem:
for item in self._items:
if item.value == value:
return item
return None
def size(self) -> int:
return len(self._items)
def peek(self) -> StringQueueItem:
if self._items:
return self._items[0]
return None
def enqueue(self, value: str):
if not value:
return
found = self.find_item(value)
if not found:
item = StringQueueItem(value)
self._items.insert(0, item)
while len(self._items) > self._max_items:
self.dequeue()
self.selected_index = 0
self._item_changed(None)
def dequeue(self):
if self._items:
self._items.pop(-1)
self.selected_index = min(self.selected_index, self.size()-1)
self._item_changed(None)
def _on_selection_changed(self, model: ui.AbstractValueModel):
if self._value_changed_fn:
self._value_changed_fn(model)
self._item_changed(None)
def destroy(self):
self._items = None
self._selected_index = None
class VisitedHistory():
def __init__(self, max_items: int = 100):
self._max_items = max_items
self._items = []
self._selected_index = 0
# the activation state for the visited history; when we are jumping between history entries, the visited history
# should not change; for example, when we click the prev/next button, the path field would update to that entry
# but those should not be counted in visited history.
self._active = True
def __getitem__(self, idx: int) -> str:
if idx < len(self._items):
return self._items[idx]
return None
def activate(self):
self._active = True
def deactivate(self):
self._active = False
@property
def selected_index(self) -> int:
return self._selected_index
@selected_index.setter
def selected_index(self, index: int):
self._selected_index = index
def get_selected_item(self) -> str:
index = self._selected_index
if index >= 0 and index < len(self._items):
return self._items[index]
return None
def size(self) -> int:
return len(self._items)
def insert(self, value: str):
if self._active is False:
return
if not value:
return
# avoid adding the same entry twice
# this could happen when actions on top sets the browser bar path to the same path twice
if self.size() > 0 and self._items[0] == value:
return
self._items.insert(0, value)
while self.size() > self._max_items:
self.pop()
self.selected_index = 0
def pop(self):
if self._items:
self._items.pop()
self.selected_index = min(self.selected_index, self.size()-1)
def destroy(self):
self._items.clear()
| 5,320 | Python | 30.485207 | 120 | 0.603008 |
omniverse-code/kit/exts/omni.kit.widget.browser_bar/omni/kit/widget/browser_bar/widget.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import sys, os
import omni.ui as ui
from omni.kit.widget.path_field import PathField
from .model import StringQueueModel, VisitedHistory
from .style import UI_STYLES, ICON_PATH
class BrowserBar:
"""
The Browser Bar extends the :obj:`PathField` UI widget for navigating tree views via the
keyboard. Namely, it adds navigation history. As in any modern day browser, this allows the
user to diectly jump to any previously visited path.
Args:
None
Keyword Args:
visited_history_size (int): Maximum number of previously visited paths to queue up. Default 10.
apply_path_handler (Callable): This function is called when the user updates the path and is
expected to update the caller app accordingly. The user can update the path in one of 3
ways: 1. by hitting Enter on the input field, 2. selecting a path from the dropdown,
or 3. by clicking on the "prev" or "next" buttons. Function signature:
void apply_path_handler(path: str)
branching_options_handler (Callable): This function is required to provide a list of possible
branches whenever prompted with a path. For example, if path = "C:", then the list of values
produced might be ["Program Files", "temp", ..., "Users"]. Function signature:
list(str) branching_options_handler(path: str, callback: func)
modal (bool): Used for modal window. Default False.
"""
def __init__(self, **kwargs):
self._path_field = None
self._next_button = None
self._prev_button = None
self._visited_menu = None
self._visited_queue = None
self._visited_history = None
self._visited_menu_bg = None
import carb.settings
theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
self._style = UI_STYLES[theme]
self._icon_path = f"{ICON_PATH}/{theme}"
self._visited_max_size = kwargs.get("visited_history_size", 10)
self._visited_history_max_size = kwargs.get("visited_history_max_size", 100)
self._apply_path_handler = kwargs.get("apply_path_handler", None)
self._branching_options_handler = kwargs.get("branching_options_handler", None)
# OM-49484: Add subscription to begin edit and apply callback, for example we could add callback to cancel
# initial navigation upon user edit
self._begin_edit_handler = kwargs.get("begin_edit_handler", None)
self._branching_options_provider = kwargs.get("branching_options_provider", None) # OBSOLETE
self._prefix_separator = kwargs.get("prefix_separator", None)
self._modal = kwargs.get("modal", False)
self._build_ui()
@property
def path(self) -> str:
"""str: Returns the current path as entered in the field box."""
if self._path_field:
return self._path_field.path
return None
def set_path(self, path: str):
"""
Sets the path and adds it to the history queue.
Args:
path (str): The full path name.
"""
if not path:
return
if self._path_field:
self._path_field.set_path(path)
self._update_visited(path)
def _build_ui(self):
import carb.settings
font_size = carb.settings.get_settings().get("/app/font/size") or 0
with ui.HStack(height=0, style=self._style):
self._prev_button = ui.Button(
image_url=f"{self._icon_path}/angle_left.svg",
image_height=16,
width=24,
clicked_fn=self._on_prev_button_pressed,
enabled=False,
)
self._next_button = ui.Button(
image_url=f"{self._icon_path}/angle_right.svg",
image_height=16,
width=24,
clicked_fn=self._on_next_button_pressed,
enabled=False,
)
with ui.ZStack():
ui.Rectangle()
# OM-66124: Update look for browser bar, use full width combobox and hide beneath Pathfield;
# FIXME: this is because currently we cannot control the menu width for arrow_only combo box;
with ui.ZStack():
# OM-66124: manually add combo box drop down background, since it is hard to control combo box height
# FIXME: Ideally should fix in ui.ComboBox directly
combo_dropdown_size = font_size + 8
with ui.HStack():
ui.Spacer()
with ui.VStack(width=combo_dropdown_size):
ui.Spacer()
self._visited_menu_bg = ui.Rectangle(height=22, style=self._style, style_type_name_override="ComboBox.Bg")
ui.Spacer()
with ui.HStack():
self._path_field = PathField(
apply_path_handler=self._apply_path_handler,
branching_options_handler=self._branching_options_handler,
prefix_separator=self._prefix_separator,
modal=self._modal,
begin_edit_handler=self._begin_edit_handler,
)
ui.Spacer(width=combo_dropdown_size)
self._build_visited_menu()
def _build_visited_menu(self):
self._visited_queue = StringQueueModel(
max_items=self._visited_max_size, value_changed_fn=self._on_menu_item_selected
)
self._visited_history = VisitedHistory(max_items=self._visited_history_max_size)
self._visited_menu = ui.ComboBox(self._visited_queue, arrow_only=False, style=self._style)
# Note: This callback is needed to trigger a refresh
self._visited_menu.model.add_item_changed_fn(lambda model, item: None)
def _update_visited(self, path: str):
if self._visited_queue:
self._visited_queue.enqueue(path)
self._visited_menu.style_type_name_override = "ComboBox.Active"
self._visited_menu_bg.style_type_name_override = "ComboBox.Bg.Active"
# update visited history
self._visited_history.insert(path)
self._update_nav_buttons()
self._visited_history.activate()
def _on_prev_button_pressed(self):
self._visited_history.deactivate()
selected_index = self._visited_history.selected_index
if selected_index >= self._visited_history.size() - 1:
return
else:
self._visited_history.selected_index = selected_index + 1
if self._path_field:
self._path_field.set_path(self._visited_history.get_selected_item())
if self._apply_path_handler:
self._apply_path_handler(self._visited_history.get_selected_item())
self._update_nav_buttons()
def _on_next_button_pressed(self):
self._visited_history.deactivate()
selected_index = self._visited_history.selected_index
if selected_index <= 0:
return
else:
self._visited_history.selected_index = selected_index - 1
if self._path_field:
self._path_field.set_path(self._visited_history.get_selected_item())
if self._apply_path_handler:
self._apply_path_handler(self._visited_history.get_selected_item())
self._update_nav_buttons()
def _update_nav_buttons(self):
if self._visited_history.selected_index > 0:
self._next_button.enabled = True
else:
self._next_button.enabled = False
if self._visited_history.selected_index < self._visited_history.size() - 1:
self._prev_button.enabled = True
else:
self._prev_button.enabled = False
def _on_menu_item_selected(self, model: ui.SimpleIntModel):
if not model:
return
menu_item = self._visited_queue[model.get_value_as_int()]
if menu_item:
if self._path_field:
self._path_field.set_path(menu_item.value)
if self._apply_path_handler:
self._apply_path_handler(menu_item.value)
def destroy(self):
if self._path_field:
self._path_field.destroy()
self._path_field = None
self._next_button = None
self._prev_button = None
self._visited_menu = None
self._visited_queue = None
if self._visited_history:
self._visited_history.destroy()
self._visited_menu_bg = None
self._style = None
self._apply_path_handler = None
self._branching_options_handler = None
self._begin_edit_handler = None
self._branching_options_provider = None
| 9,403 | Python | 42.537037 | 134 | 0.59917 |
omniverse-code/kit/exts/omni.kit.widget.browser_bar/omni/kit/widget/browser_bar/tests/test_widget.py | ## Copyright (c) 2018-2019, 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
from omni.ui.tests.test_base import OmniUiTest
from unittest.mock import Mock, call
from ..widget import BrowserBar
class TestBrowserBar(OmniUiTest):
"""Testing PathField.set_path"""
async def setUp(self):
pass
async def tearDown(self):
pass
async def test_nav_buttons(self):
"""Testing navigation buttons"""
window = await self.create_test_window()
mock_path_handler = Mock()
with window.frame:
under_test = BrowserBar(apply_path_handler=mock_path_handler)
for path in ["one", "two", "three", "two", "three"]:
under_test.set_path(path)
self.assertEqual(under_test.path, "three/")
self.assertEqual(under_test._visited_history.size(), 5)
self.assertEqual(under_test._visited_queue.size(), 3)
under_test._prev_button.call_clicked_fn()
self.assertEqual(under_test.path, "two/")
under_test._prev_button.call_clicked_fn()
self.assertEqual(under_test.path, "three/")
under_test._prev_button.call_clicked_fn()
under_test._prev_button.call_clicked_fn()
self.assertEqual(under_test.path, "one/")
self.assertFalse(under_test._prev_button.enabled)
for _ in range(4):
under_test._next_button.call_clicked_fn()
self.assertEqual(under_test.path, "three/")
self.assertFalse(under_test._next_button.enabled)
self.assertEqual(
mock_path_handler.call_args_list,
[call('two'), call('three'), call('two'), call('one'), call('two'), call('three'), call('two'), call('three')]
)
async def test_nav_menu(self):
"""Testing navigation menu"""
window = await self.create_test_window()
mock_path_handler = Mock()
with window.frame:
under_test = BrowserBar(apply_path_handler=mock_path_handler)
for path in ["one", "two", "three"]:
under_test.set_path(path)
self.assertEqual(under_test.path, "three/")
model = under_test._visited_menu.model
self.assertEqual(model, under_test._visited_queue)
model.selected_index = 2
self.assertEqual(under_test.path, "one/")
# selecting one of navigation menu browse to that path, and will appear as the most recent visited history
self.assertFalse(under_test._next_button.enabled)
under_test.set_path("four")
self.assertEqual(model.selected_index, 0)
self.assertEqual(under_test.path, "four/")
| 2,988 | Python | 35.901234 | 122 | 0.649264 |
omniverse-code/kit/exts/omni.kit.widget.cache_indicator/omni/kit/widget/cache_indicator/cache_state_menu.py | import asyncio
import aiohttp
import carb
import os
import toml
import time
import omni.client
import webbrowser
from omni.kit.menu.utils import MenuItemDescription, MenuAlignment
from omni import ui
from typing import Union
from .style import Styles
class CacheStateDelegate(ui.MenuDelegate):
def __init__(self, cache_enabled, hub_enabled, **kwargs):
super().__init__(**kwargs)
self._hub_enabled = hub_enabled
self._cache_enabled = cache_enabled
self._cache_widget = None
def destroy(self):
self._cache_widget = None
def build_item(self, item: ui.MenuHelper):
with ui.HStack(width=0, style={"margin" : 0}):
self._cache_widget = ui.HStack(content_clipping=1, width=0, style=Styles.CACHE_STATE_ITEM_STYLE)
ui.Spacer(width=10)
self.update_cache_state(self._cache_enabled, self._hub_enabled)
def get_menu_alignment(self):
return MenuAlignment.RIGHT
def update_menu_item(self, menu_item: Union[ui.Menu, ui.MenuItem], menu_refresh: bool):
if isinstance(menu_item, ui.MenuItem):
menu_item.visible = False
def update_cache_state(self, cache_enabled, hub_enabled):
self._hub_enabled = hub_enabled
self._cache_enabled = cache_enabled
if not self._cache_widget:
return
margin = 2
self._cache_widget.clear()
with self._cache_widget:
ui.Label("CACHE: ")
if hub_enabled:
ui.Label("HUB", style={"color": 0xff00b86b})
elif cache_enabled:
ui.Label("ON", style={"color": 0xff00b86b})
else:
with ui.VStack():
ui.Spacer(height=margin)
with ui.ZStack(width=0):
with ui.HStack(width=20):
ui.Spacer()
ui.Label("OFF", name="offline", width=0)
ui.Spacer(width=margin)
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=14, height=14, name="doc")
ui.Spacer()
ui.Spacer()
button = ui.InvisibleButton(width=20)
button.set_clicked_fn(lambda: webbrowser.open('https://docs.omniverse.nvidia.com/nucleus/cache_troubleshoot.html', new=2))
ui.Spacer(height=margin)
class CacheStateMenu:
def __init__(self):
self._live_menu_name = "Cache State Widget"
self._menu_list = [MenuItemDescription(name="placeholder", show_fn=lambda: False)]
global_config_path = carb.tokens.get_tokens_interface().resolve("${omni_global_config}")
self._omniverse_config_path = os.path.join(global_config_path, "omniverse.toml").replace("\\", "/")
self._all_cache_apis = []
self._hub_enabled = False
self._cache_enabled = False
self._last_time_check = 0
self._ping_cache_future = None
self._update_subscription = None
def _load_cache_config(self):
if os.path.exists(self._omniverse_config_path):
try:
contents = toml.load(self._omniverse_config_path)
except Exception as e:
carb.log_error(f"Unable to parse {self._omniverse_config_path}. File corrupted?")
contents = None
if contents:
self._all_cache_apis = self._load_all_cache_server_apis(contents)
if self._all_cache_apis:
self._cache_enabled = True
self._update_subscription = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(
self._on_update, name="omni.kit.widget.live update"
)
else:
carb.log_warn("Unable to detect Omniverse Cache Server. Consider installing it for better IO performance.")
self._cache_enabled = False
else:
carb.log_warn(f"Unable to detect Omniverse Cache Server. File {self._omniverse_config_path} is not found."
f" Consider installing it for better IO performance.")
def _get_hub_version_cb(self, result, version):
if result == omni.client.Result.OK:
self._hub_enabled = True
else:
self._hub_enabled = False
self._load_cache_config()
if self._cache_state_delegate:
self._cache_state_delegate.update_cache_state(self._cache_enabled, self._hub_enabled)
def _initialize(self):
self._get_hub_version_request = omni.client.get_hub_version_with_callback(self._get_hub_version_cb)
def register_menu_widgets(self):
self._initialize()
self._cache_state_delegate = CacheStateDelegate(self._cache_enabled, self._hub_enabled)
omni.kit.menu.utils.add_menu_items(self._menu_list, name=self._live_menu_name, delegate=self._cache_state_delegate)
def unregister_menu_widgets(self):
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._live_menu_name)
if self._cache_state_delegate:
self._cache_state_delegate.destroy()
self._cache_state_delegate = None
self._menu_list = None
self._update_subscription = None
self._all_cache_apis = []
try:
if self._ping_cache_future and not self._ping_cache_future.done():
self._ping_cache_future.cancel()
self._ping_cache_future = None
except Exception:
self._ping_cache_future = None
def _on_update(self, dt):
if not self._cache_state_delegate or not self._all_cache_apis:
return
if not self._ping_cache_future or self._ping_cache_future.done():
now = time.time()
duration = now - self._last_time_check
# 30s
if duration < 30:
return
self._last_time_check = now
async def _ping_cache():
async with aiohttp.ClientSession() as session:
cache_enabled = None
for cache_api in self._all_cache_apis:
try:
async with session.head(cache_api):
''' If we're here the service port is alive '''
cache_enabled = True
except Exception as e:
cache_enabled = False
break
if cache_enabled is not None and self._cache_enabled != cache_enabled:
self._cache_enabled = cache_enabled
if self._cache_state_delegate:
self._cache_state_delegate.update_cache_state(self._cache_enabled, self._hub_enabled)
self._ping_cache_future = asyncio.ensure_future(_ping_cache())
def _load_all_cache_server_apis(self, config_contents):
mapping = os.environ.get("OMNI_CONN_CACHE", None)
if mapping:
mapping = f"*#{mapping},f"
else:
mapping = os.environ.get("OMNI_CONN_REDIRECTION_DICT", None)
if not mapping:
mapping = os.environ.get("OM_REDIRECTION_DICT", None)
if not mapping:
connection_library_dict = config_contents.get("connection_library", None)
if connection_library_dict:
mapping = connection_library_dict.get("proxy_dict", None)
all_proxy_apis = set([])
if mapping:
mapping = mapping.lstrip("\"")
mapping = mapping.rstrip("\"")
mapping = mapping.lstrip("'")
mapping = mapping.rstrip("'")
redirections = mapping.split(";")
for redirection in redirections:
parts = redirection.split("#")
if not parts or len(parts) < 2:
continue
source, target = parts[0], parts[1]
targets = target.split(",")
if not targets:
continue
if len(targets) > 1:
proxy_address = targets[0]
else:
proxy_address = target
if not proxy_address.startswith("http://") and not proxy_address.startswith("https://"):
proxy_address_api = f"http://{proxy_address}/ping"
else:
if proxy_address.endswith("/"):
proxy_address_api = f"{proxy_address}ping"
else:
proxy_address_api = f"{proxy_address}/ping"
all_proxy_apis.add(proxy_address_api)
return all_proxy_apis
| 8,866 | Python | 38.584821 | 146 | 0.545906 |
omniverse-code/kit/exts/omni.kit.widget.cache_indicator/omni/kit/widget/cache_indicator/style.py | from .icons import Icons
class Styles:
CACHE_STATE_ITEM_STYLE = None
LIVE_STATE_ITEM_STYLE = None
@staticmethod
def on_startup():
# It needs to delay initialization of style as icons need to be initialized firstly.
Styles.CACHE_STATE_ITEM_STYLE = {
"Image::doc": {"image_url": Icons.get("docs"), "color": 0xB04B4BFF},
"Label::offline": {"color": 0xB04B4BFF},
"Rectangle::offline": {"border_radius": 2.0},
"Rectangle::offline": {"background_color": 0xff808080},
"Rectangle::offline:hovered": {"background_color": 0xFF9E9E9E},
}
| 630 | Python | 34.055554 | 92 | 0.606349 |
omniverse-code/kit/exts/omni.kit.widget.cache_indicator/omni/kit/widget/cache_indicator/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ext
import omni.kit.app
from .cache_state_menu import CacheStateMenu
from .icons import Icons
from .style import Styles
class OmniCacheIndicatorWidgetExtension(omni.ext.IExt):
def on_startup(self, ext_id):
extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
Icons.on_startup(extension_path)
Styles.on_startup()
self._cache_state_menu = CacheStateMenu()
self._cache_state_menu.register_menu_widgets()
def on_shutdown(self):
self._cache_state_menu.unregister_menu_widgets()
Icons.on_shutdown()
| 1,056 | Python | 34.233332 | 108 | 0.746212 |
omniverse-code/kit/exts/omni.kit.widget.cache_indicator/omni/kit/widget/cache_indicator/__init__.py | from .extension import OmniCacheIndicatorWidgetExtension | 56 | Python | 55.999944 | 56 | 0.928571 |
omniverse-code/kit/exts/omni.kit.widget.cache_indicator/omni/kit/widget/cache_indicator/tests/__init__.py | from .test_cache_indicator_widget import TestCacheIndicatorWidget | 65 | Python | 64.999935 | 65 | 0.892308 |
omniverse-code/kit/exts/omni.kit.widget.cache_indicator/omni/kit/widget/cache_indicator/tests/test_cache_indicator_widget.py | import omni.kit.test
import omni.client
import omni.kit.app
class TestCacheIndicatorWidget(omni.kit.test.AsyncTestCase):
async def test_menu_setup(self):
import omni.kit.ui_test as ui_test
menu_widget = ui_test.get_menubar()
menu = menu_widget.find_menu("Cache State Widget")
self.assertTrue(menu)
| 337 | Python | 24.999998 | 60 | 0.700297 |
omniverse-code/kit/exts/omni.kit.renderer.imgui/omni/kit/imgui_renderer/__init__.py | from ._imgui_renderer import *
# Cached interface instance pointer
def get_imgui_renderer_interface() -> IImGuiRenderer:
"""Returns cached :class:`omni.kit.renderer.IImGuiRenderer` interface"""
if not hasattr(get_imgui_renderer_interface, "imgui_renderer"):
get_imgui_renderer_interface.imgui_renderer = acquire_imgui_renderer_interface()
return get_imgui_renderer_interface.imgui_renderer
| 413 | Python | 36.63636 | 88 | 0.755448 |
omniverse-code/kit/exts/omni.kit.renderer.imgui/omni/kit/imgui_renderer/tests/test_imgui_renderer.py | import inspect
import pathlib
import carb
import carb.settings
import carb.tokens
import carb.windowing
import omni.kit.app
import omni.kit.test
import omni.kit.test_helpers_gfx
import omni.kit.renderer.bind
import omni.kit.imgui_renderer
import omni.kit.imgui_renderer_test
# Maximum allowed difference of the same pixel between two images. If the object is moved, the difference will be
# close to 255. 10 is enough to filter out the artifacts of antialiasing on the different systems.
THRESHOLD = 10
OUTPUTS_DIR = omni.kit.test.get_test_output_path()
EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("data/tests")
RENDERER_CAPTURE_EXT_NAME = "omni.kit.renderer.capture"
class ImGuiRendererTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.acquire_settings_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
self._imgui_renderer_test = omni.kit.imgui_renderer_test.acquire_imgui_renderer_test_interface()
self._renderer.startup()
self._imgui_renderer.startup()
self._imgui_renderer_test.startup()
async def tearDown(self):
self._imgui_renderer_test.shutdown()
self._imgui_renderer.shutdown()
self._renderer.shutdown()
self._imgui_renderer_test = None
self._imgui_renderer = None
self._renderer = None
self._app_window_factory = None
self._settings = None
async def __create_app_window(self, title: str, width: int = 300, height: int = 300):
app_window = self._app_window_factory.create_window_from_settings()
app_window.startup_with_desc(
title=f"ImGui renderer test {title}",
width=width,
height=height,
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)
self._imgui_renderer.attach_app_window(app_window)
self._imgui_renderer_test.register_empty_window(
app_window,
50,
50,
200,
200,
title
)
# Test the carb.imgui is_valid returns True since it is now properly setup
await self.test_carb_imgui_is_valid(True)
await omni.kit.app.get_app().next_update_async()
return app_window
async def __destroy_app_window(self, app_window):
self._app_window_factory.set_default_window(None)
self._imgui_renderer.detach_app_window(app_window)
self._renderer.detach_app_window(app_window)
app_window.shutdown()
await omni.kit.app.get_app().next_update_async()
return None
@omni.kit.test.omni_test_registry(guid="4ecaf4c3-17bd-40fa-8a76-f0e12291d0ef")
async def test_1000_empty_imgui_window(self):
TESTNAME = "test_1000_empty_imgui_window"
FILENAME = f"{TESTNAME}.png"
app_window = await self.__create_app_window("Test Empty Window")
diff = await omni.kit.test_helpers_gfx.capture_and_compare(FILENAME, THRESHOLD, OUTPUTS_DIR, GOLDEN_DIR, app_window)
if diff != 0:
carb.log_warn(f"[TEST_NAME] the generated image has max difference {diff}")
if diff > THRESHOLD:
carb.log_error(f'The generated image {FILENAME} has a difference of {diff}, but max difference is {THRESHOLD}')
self.assertTrue(False)
app_window = await self.__destroy_app_window(app_window)
@omni.kit.test.omni_test_registry(guid="bf09077f-e44a-11ed-ade6-ac91a108fede")
async def test_null_app_window_0(self):
"""Test crash avoidance on API abuse 0"""
result = self._imgui_renderer_test.attach_null_window(0)
self.assertTrue(result)
@omni.kit.test.omni_test_registry(guid="65059f66-e44d-11ed-9523-ac91a108fede")
async def test_null_app_window_1(self):
"""Test crash avoidance on API abuse 1"""
result = self._imgui_renderer_test.attach_null_window(1)
self.assertTrue(result)
async def test_set_cursor_shape_override(self):
"""Test crash avoidance on set_cursor_shape_override"""
app_window = await self.__create_app_window("Test Empty Window")
self._imgui_renderer.set_cursor_shape_override(app_window, carb.windowing.CursorStandardShape.HAND)
app_window = await self.__destroy_app_window(app_window)
async def test_cursor_shape_override_extend(self):
"""Test crash avoidance on set_cursor_shape_override_extend"""
app_window = await self.__create_app_window("Test Empty Window")
self._imgui_renderer.get_all_cursor_shape_names()
self._imgui_renderer.set_cursor_shape_override_extend(app_window, "Arrow")
self._imgui_renderer.get_cursor_shape_override_extend(app_window)
self._imgui_renderer.register_cursor_shape_extend("test_cursor", r"${exe-path}/resources/icons/Ok_64.png")
self._imgui_renderer.unregister_cursor_shape_extend("test_cursor")
app_window = await self.__destroy_app_window(app_window)
async def test_carb_imgui_is_valid(self, should_be_valid: bool = False):
"""Test low level carb.imgui is_valid API"""
import carb.imgui
imgui = carb.imgui.acquire_imgui()
self.assertIsNotNone(imgui)
self.assertEqual(imgui.is_valid(), should_be_valid)
| 5,904 | Python | 40.879432 | 127 | 0.667683 |
omniverse-code/kit/exts/omni.kit.renderer.imgui/omni/kit/imgui_renderer/tests/__init__.py | from .test_imgui_renderer import *
| 35 | Python | 16.999992 | 34 | 0.771429 |
omniverse-code/kit/exts/omni.kit.renderer.imgui/omni/kit/imgui_renderer_test/__init__.py | from ._imgui_renderer_test import *
# Cached interface instance pointer
def get_imgui_renderer_test_interface() -> IImGuiRendererTest:
if not hasattr(get_imgui_renderer_test_interface, "imgui_renderer_test"):
get_imgui_renderer_test_interface.imgui_renderer_test = acquire_imgui_renderer_test_interface()
return get_imgui_renderer_test_interface.imgui_renderer_test
| 384 | Python | 41.777773 | 103 | 0.770833 |
omniverse-code/kit/exts/omni.kit.renderer.imgui/omni/kit/ui/editor_menu.py | import carb
from typing import Callable, Union, Tuple
extension_id = "omni.kit.ui.editor_menu_bridge"
class EditorMenu():
active_menus = {}
window_handler = {}
setup_hook = False
omni_kit_menu_utils_loaded = False
def __init__(self):
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
self._hooks = []
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: EditorMenu.set_menu_loaded(True),
on_disable_fn=lambda _: EditorMenu.set_menu_loaded(False),
ext_name="omni.kit.menu.utils",
hook_name="editor menu omni.kit.menu.utils listener",
)
)
@staticmethod
def clean_menu_path(path):
import re
return re.sub(r"[^\x00-\x7F]+", "", path).lstrip()
@staticmethod
def set_menu_loaded(state: bool):
EditorMenu.omni_kit_menu_utils_loaded = state
class EditorMenuItem:
def __init__(self, menu_path):
self._menu_path = menu_path
def __del__(self):
carb.log_info(f"{self._menu_path} went out of scope and is being automatically removed from the menu system")
EditorMenu.remove_item(self._menu_path)
@staticmethod
def sort_menu_hook(merged_menu):
from omni.kit.menu.utils import MenuItemDescription
def priority_sort(menu_entry):
if hasattr(menu_entry, "priority"):
return menu_entry.priority
return 0
for name in ["Window", "Help"]:
if name in merged_menu:
merged_menu[name].sort(key=priority_sort)
priority = 0
for index, menu_entry in enumerate(merged_menu[name]):
if hasattr(menu_entry, "priority"):
if index > 0 and abs(menu_entry.priority - priority) > 9:
spacer = MenuItemDescription()
spacer.priority = menu_entry.priority
merged_menu[name].insert(index, spacer)
priority = menu_entry.priority
@staticmethod
def get_action_name(menu_path):
import re
action = re.sub(r'[^\x00-\x7F]','', menu_path).lower().strip().replace('/', '_').replace(' ', '_').replace('__', '_')
return(f"action_editor_menu_bridge_{action}")
@staticmethod
def convert_to_new_menu(menu_path:str, menu_name: Union[str, list], on_click: Callable, toggle: bool, priority: int, value: bool, enabled: bool, original_svg_color: bool):
from omni.kit.menu.utils import MenuItemDescription
action_name = EditorMenu.get_action_name(menu_path)
if on_click:
import omni.kit.actions.core
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
action_name,
lambda: on_click(menu_path, EditorMenu.toggle_value(menu_path)),
display_name=action_name,
description=action_name,
tag=action_name,
)
if isinstance(menu_name, list):
menu_item = menu_name.pop(-1)
sub_menu_item = MenuItemDescription(name=menu_item,
enabled=enabled,
ticked=toggle,
ticked_value=value if toggle else None,
onclick_action=(extension_id, action_name),
original_svg_color=original_svg_color)
sub_menu = [sub_menu_item]
while(len(menu_name) > 0):
menu_item = menu_name.pop(-1)
menu = MenuItemDescription(name=menu_item, sub_menu=sub_menu, original_svg_color=original_svg_color)
menu.priority=priority
sub_menu = [menu]
return menu, sub_menu_item
else:
menu = MenuItemDescription(name=menu_name,
enabled=enabled,
ticked=toggle,
ticked_value=value if toggle else None,
onclick_action=(extension_id, action_name),
original_svg_color=original_svg_color)
menu.priority=priority
return menu, menu
@staticmethod
def split_menu_path(menu_path: str):
menu_name = None
menu_parts = menu_path.replace("\/", "@TEMPSLASH@").split("/")
menu_title = menu_parts.pop(0)
if len(menu_parts) > 1:
menu_name = menu_parts
elif menu_parts:
menu_name = menu_parts[0]
if menu_name:
if isinstance(menu_name, list):
menu_name = [name.replace("@TEMPSLASH@", "\\") for name in menu_name]
else:
menu_name = menu_name.replace("@TEMPSLASH@", "\\")
if menu_title:
menu_title = menu_title.replace("@TEMPSLASH@", "\\")
return menu_title, menu_name
@staticmethod
def add_item(menu_path: str, on_click: Callable=None, toggle: bool=False, priority: int=0, value: bool=False, enabled: bool=True, original_svg_color: bool=False, auto_release=True):
if not EditorMenu.omni_kit_menu_utils_loaded:
carb.log_warn(f"omni.kit.menu.utils not loaded for add_item({EditorMenu.clean_menu_path(menu_path)}) - Extension needs dependency to omni.kit.menu.utils")
return
import omni.kit.menu.utils
if EditorMenu.setup_hook == False:
omni.kit.menu.utils.add_hook(EditorMenu.sort_menu_hook)
EditorMenu.setup_hook = True
menu_title, menu_name = EditorMenu.split_menu_path(menu_path)
menu, menuitem = EditorMenu.convert_to_new_menu(menu_path, menu_name, on_click, toggle, priority, value, enabled, original_svg_color)
EditorMenu.active_menus[menu_path] = (menu, menuitem)
omni.kit.menu.utils.add_menu_items([menu], menu_title)
# disabled for fastShutdown as auto-release causes exceptions on shutdown, so editor_menus may leak as most are not removed
if auto_release:
return EditorMenu.EditorMenuItem(menu_path)
return menu_path
@staticmethod
def set_on_click(menu_path: str, on_click: Callable=None):
if not EditorMenu.omni_kit_menu_utils_loaded:
carb.log_warn(f"omni.kit.menu.utils not loaded for set_on_click({EditorMenu.clean_menu_path(menu_path)}) - Extension needs dependency to omni.kit.menu.utils")
return
import omni.kit.menu.utils
action_name = EditorMenu.get_action_name(menu_path)
if menu_path in EditorMenu.active_menus:
import omni.kit.actions.core
omni.kit.actions.core.get_action_registry().deregister_action(
extension_id,
action_name
)
if on_click:
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
action_name,
lambda: on_click(menu_path, EditorMenu.toggle_value(menu_path)),
display_name=action_name,
description=action_name,
tag=action_name,
)
menu_title, menu_name = EditorMenu.split_menu_path(menu_path)
menu, menuitem = EditorMenu.active_menus[menu_path]
omni.kit.menu.utils.remove_menu_items([menu], menu_title)
menuitem.onclick_action = None
if on_click:
menuitem.onclick_action=(extension_id, action_name)
omni.kit.menu.utils.add_menu_items([menu], menu_title)
return None
carb.log_warn(f"set_on_click menu {EditorMenu.clean_menu_path(menu_path)} not found")
return None
@staticmethod
def remove_item(menu_path: str):
if not EditorMenu.omni_kit_menu_utils_loaded:
carb.log_warn(f"omni.kit.menu.utils not loaded for remove_item({EditorMenu.clean_menu_path(menu_path)}) - Extension needs dependency to omni.kit.menu.utils")
return
import omni.kit.menu.utils
import omni.kit.actions.core
if menu_path in EditorMenu.active_menus:
menu_title, menu_name = EditorMenu.split_menu_path(menu_path)
menu, menuitem = EditorMenu.active_menus[menu_path]
omni.kit.menu.utils.remove_menu_items([menu], menu_title)
del EditorMenu.active_menus[menu_path]
omni.kit.actions.core.get_action_registry().deregister_action(
extension_id,
EditorMenu.get_action_name(menu_path)
)
return None
carb.log_warn(f"remove_item menu {EditorMenu.clean_menu_path(menu_path)} not found")
return None
@staticmethod
def set_priority(menu_path: str, priority: int):
if not EditorMenu.omni_kit_menu_utils_loaded:
carb.log_warn(f"omni.kit.menu.utils not loaded for set_priority({EditorMenu.clean_menu_path(menu_path)}) - Extension needs dependency to omni.kit.menu.utils")
return
import omni.kit.menu.utils
menu_title_id, menu_name = EditorMenu.split_menu_path(menu_path)
if menu_title_id and not menu_name:
for menu_id in EditorMenu.active_menus:
menu_title, menu_name = EditorMenu.split_menu_path(menu_id)
if menu_title == menu_title_id:
menu, menuitem = EditorMenu.active_menus[menu_id]
omni.kit.menu.utils.remove_menu_items([menu], menu_title)
omni.kit.menu.utils.add_menu_items([menu], menu_title, priority)
return
if menu_path in EditorMenu.active_menus:
menu_title, menu_name = EditorMenu.split_menu_path(menu_path)
menu, menuitem = EditorMenu.active_menus[menu_path]
omni.kit.menu.utils.remove_menu_items([menu], menu_title)
menuitem.priority = priority
omni.kit.menu.utils.add_menu_items([menu], menu_title)
return
carb.log_warn(f"set_priority menu {EditorMenu.clean_menu_path(menu_path)} not found")
return
@staticmethod
def set_enabled(menu_path: str, enabled: bool):
if not EditorMenu.omni_kit_menu_utils_loaded:
return None
import omni.kit.menu.utils
if menu_path in EditorMenu.active_menus:
menu_title, menu_name = EditorMenu.split_menu_path(menu_path)
menu, menuitem = EditorMenu.active_menus[menu_path]
menuitem.enabled = enabled
return None
carb.log_warn(f"set_enabled menu {EditorMenu.clean_menu_path(menu_path)} not found")
return None
@staticmethod
def set_hotkey(menu_path: str, modifier: int, key: int):
if not EditorMenu.omni_kit_menu_utils_loaded:
carb.log_warn(f"omni.kit.menu.utils not loaded for set_hotkey({EditorMenu.clean_menu_path(menu_path)}) - Extension needs dependency to omni.kit.menu.utils")
return None
import omni.kit.menu.utils
if menu_path in EditorMenu.active_menus:
menu_title, menu_name = EditorMenu.split_menu_path(menu_path)
menu, menuitem = EditorMenu.active_menus[menu_path]
omni.kit.menu.utils.remove_menu_items([menu], menu_title)
menuitem.set_hotkey((modifier, key))
omni.kit.menu.utils.add_menu_items([menu], menu_title)
return None
carb.log_warn(f"set_hotkey menu {EditorMenu.clean_menu_path(menu_path)} not found")
return None
@staticmethod
def set_value(menu_path: str, value: bool):
if not EditorMenu.omni_kit_menu_utils_loaded:
carb.log_warn(f"omni.kit.menu.utils not loaded for set_value({EditorMenu.clean_menu_path(menu_path)}) - Extension needs dependency to omni.kit.menu.utils")
return None
import omni.kit.menu.utils
if menu_path in EditorMenu.active_menus:
menu_title, menu_name = EditorMenu.split_menu_path(menu_path)
menu, menuitem = EditorMenu.active_menus[menu_path]
if menuitem.ticked_value != value:
menuitem.ticked_value = value
omni.kit.menu.utils.refresh_menu_items(menu_title)
return None
carb.log_warn(f"set_value menu {EditorMenu.clean_menu_path(menu_path)} not found")
return None
@staticmethod
def get_value(menu_path: str):
if not EditorMenu.omni_kit_menu_utils_loaded:
carb.log_warn(f"omni.kit.menu.utils not loaded for get_value({EditorMenu.clean_menu_path(menu_path)}) - Extension needs dependency to omni.kit.menu.utils")
return None
if menu_path in EditorMenu.active_menus:
menu, menuitem = EditorMenu.active_menus[menu_path]
return menuitem.ticked_value
carb.log_warn(f"get_value menu {EditorMenu.clean_menu_path(menu_path)} not found")
return None
@staticmethod
def toggle_value(menu_path: str):
if not EditorMenu.omni_kit_menu_utils_loaded:
carb.log_warn(f"omni.kit.menu.utils not loaded for toggle_value({EditorMenu.clean_menu_path(menu_path)}) - Extension needs dependency to omni.kit.menu.utils")
return None
import omni.kit.menu.utils
if menu_path in EditorMenu.active_menus:
menu_title, menu_name = EditorMenu.split_menu_path(menu_path)
menu, menuitem = EditorMenu.active_menus[menu_path]
menuitem.ticked_value = not menuitem.ticked_value
omni.kit.menu.utils.refresh_menu_items(menu_title)
return menuitem.ticked_value
carb.log_warn(f"toggle_value menu {EditorMenu.clean_menu_path(menu_path)} not found")
return None
@staticmethod
def has_item(menu_path: str):
return (menu_path in EditorMenu.active_menus)
@staticmethod
def set_on_right_click(menu_path: str, on_click: Callable=None):
carb.log_warn(f"EditorMenu.set_on_right_click(menu_path='{EditorMenu.clean_menu_path(menu_path)}', on_click={on_click}) not supported")
return None
@staticmethod
def set_action(menu_path: str, action_mapping_path: str, action_name: str):
carb.log_warn(f"EditorMenu.set_action(menu_path='{EditorMenu.clean_menu_path(menu_path)}', action_mapping_path='{action_mapping_path}', action_name='{action_name}') not supported")
return None
@staticmethod
def add_action_to_menu(
menu_path: str,
on_action: Callable,
action_name: str = None,
default_hotkey: Tuple[int, int] = None,
on_rmb_click: Callable = None,
) -> None:
if not EditorMenu.omni_kit_menu_utils_loaded:
carb.log_warn(f"omni.kit.menu.utils not loaded for add_action_to_menu({EditorMenu.clean_menu_path(menu_path)}) - Extension needs dependency to omni.kit.menu.utils")
return None
import omni.kit.menu.utils
from omni.kit.menu.utils import MenuActionControl
if on_rmb_click:
carb.log_warn(f"add_action_to_menu {EditorMenu.clean_menu_path(menu_path)} on_rmb_click not supported")
if menu_path in EditorMenu.active_menus:
menu_title, menu_name = EditorMenu.split_menu_path(menu_path)
menu, menuitem = EditorMenu.active_menus[menu_path]
omni.kit.menu.utils.remove_menu_items([menu], menu_title)
action_name = EditorMenu.get_action_name(menu_path)
if on_action:
import omni.kit.actions.core
omni.kit.actions.core.get_action_registry().deregister_action(
extension_id,
action_name
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
action_name,
on_action,
display_name=action_name,
description=action_name,
tag=action_name,
)
# HACK - async/frame delay breaks fullscreen mode
if action_name in ["action_editor_menu_bridge_window_fullscreen_mode"]:
menuitem.onclick_action=(extension_id, action_name, MenuActionControl.NODELAY)
else:
menuitem.onclick_action=(extension_id, action_name)
menuitem.set_hotkey(default_hotkey)
omni.kit.menu.utils.add_menu_items([menu], menu_title)
return None
carb.log_warn(f"add_action_to_menu menu {EditorMenu.clean_menu_path(menu_path)} not found")
return None
| 16,924 | Python | 41.848101 | 188 | 0.594718 |
omniverse-code/kit/exts/omni.kit.renderer.imgui/omni/kit/ui/__init__.py | """UI Toolkit
Starting with the release 2020.1, Omniverse Kit UI Toolkit has been replaced by the alternative UI toolkit :mod:`Omni::UI <omni.ui>`. Currently the Omniverse Kit UI Toolkit is deprecated.
Omniverse Kit UI Toolkit is retained mode UI library which enables extending and changing Omniverse Kit look and feel in any direction.
It contains fundamental building primitives, like windows, containers, layouts, widgets. As well as additional API (built on top of it) to create widgets for USD attributes and omni.kit settings.
Typical example to create a window with a drag slider widget:
.. code-block::
import omni.kit.ui
window = omni.kit.ui.Window('My Window')
d = omni.kit.ui.DragDouble()
d.width = omni.kit.ui.Percent(30)
window.layout.add_child(d)
All objects are python-friendly reference counted object. You don't need to explicitly release or control lifetime. In the code example above `window` will be kept alive until `window` is released.
Core:
------
* :class:`.Window`
* :class:`.Popup`
* :class:`.Container`
* :class:`.Value`
* :class:`.Length`
* :class:`.UnitType`
* :class:`.Widget`
Widgets:
--------
* :class:`.Label`
* :class:`.Button`
* :class:`.Spacer`
* :class:`.CheckBox`
* :class:`.ComboBox`
* :class:`.ComboBoxInt`
* :class:`.ListBox`
* :class:`.SliderInt`
* :class:`.SliderDouble`
* :class:`.DragInt`
* :class:`.DragInt2`
* :class:`.DragDouble`
* :class:`.DragDouble2`
* :class:`.DragDouble3`
* :class:`.DragDouble4`
* :class:`.Transform`
* :class:`.FieldInt`
* :class:`.FieldDouble`
* :class:`.TextBox`
* :class:`.ColorRgb`
* :class:`.ColorRgba`
* :class:`.Image`
Containers:
-----------
* :class:`.ColumnLayout`
* :class:`.RowLayout`
* :class:`.RowColumnLayout`
* :class:`.CollapsingFrame`
* :class:`.ScrollingFrame`
"""
# This module depends on other modules. VSCode python language server scrapes modules in an isolated environment
# (ignoring PYTHONPATH set). import fails and for that we have separate code path to explicitly add it's folder to
# sys.path and import again.
try:
import weakref
import carb
import carb.dictionary
import omni.ui
except:
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "..")))
import weakref
import carb
import carb.dictionary
import omni.ui
from ._ui import *
from .editor_menu import EditorMenu
legacy_mode = False
def add_item_attached(self: _ui.Menu, *args, **kwargs):
subscription = self.add_item(*args, **kwargs)
self.user_data.setdefault("items", []).append(subscription)
return subscription
def create_window_hook(self, title:str, *args, **kwargs):
menu_path = None
add_to_menu = True
if "menu_path" in kwargs:
menu_path = kwargs["menu_path"]
kwargs["menu_path"] = ""
if "add_to_menu" in kwargs:
add_to_menu = kwargs["add_to_menu"]
kwargs["add_to_menu"] = False
Window.create_window_hook(self, title, *args, **kwargs)
if add_to_menu and not menu_path:
menu_path = f"Window/{title}"
if menu_path:
def on_window_click(visible, weak_window):
window = weak_window()
if window:
if visible:
window.show()
else:
window.hide()
def on_window_showhide(visible, weak_window):
window = weak_window()
if window:
Menu.static_class.set_value(menu_path, visible)
EditorMenu.window_handler[title] = omni.kit.ui.get_editor_menu().add_item(menu_path, on_click=lambda m, v, w=weakref.ref(self): on_window_click(v, w), toggle=True, value=self.is_visible())
self.set_visibility_changed_fn(lambda v, w=weakref.ref(self): on_window_showhide(v, w))
def get_editor_menu():
if legacy_mode:
return get_editor_menu_legacy()
elif Menu.static_class == None:
Menu.static_class = EditorMenu()
return Menu.static_class
def using_legacy_mode():
carb.log_warn(f"using_legacy_mode: function is depricated as it always return False")
return legacy_mode
def init_ui():
import carb.settings
import carb
# Avoid calling code below at documentation building time with try/catch
try:
settings = carb.settings.get_settings()
except RuntimeError:
return
if not legacy_mode:
if hasattr(Window, "create_window_hook"):
carb.log_warn(f"init_ui window hook already initialized")
else:
# hook into omni.kit.ui.window to override menu creation
Window.create_window_hook = Window.__init__
Window.__init__ = create_window_hook
Menu.static_class = None
Menu.add_item_attached = add_item_attached
Menu.get_editor_menu = get_editor_menu
Menu.using_legacy_mode = using_legacy_mode
init_ui()
| 4,868 | Python | 27.144509 | 197 | 0.658998 |
omniverse-code/kit/exts/omni.kit.renderer.imgui/omni/kit/extensionwindow/__init__.py | from ._extensionwindow import *
| 32 | Python | 15.499992 | 31 | 0.78125 |
omniverse-code/kit/exts/omni.kit.renderer.imgui/omni/kit/ui_windowmanager/__init__.py | from ._window_manager import *
| 31 | Python | 14.999993 | 30 | 0.741935 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundlesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleManipulation
This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents.
"""
import carb
import numpy
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialBundlesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleManipulation
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.filteredBundle
inputs.filters
inputs.fullBundle
Outputs:
outputs.combinedBundle
"""
# 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:filteredBundle', 'bundle', 0, 'Filtered Bundle', 'Bundle whose contents are filtered before being added to the output', {}, True, None, False, ''),
('inputs:filters', 'token[]', 0, None, "List of filter names to be applied to the filteredBundle. Any filter name\nappearing in this list will be applied to members of that bundle and only those\npassing all filters will be added to the output bundle. Legal filter values are\n'big' (arrays of size > 10), 'x' (attributes whose name contains the letter x), \nand 'int' (attributes whose base type is integer).", {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:fullBundle', 'bundle', 0, 'Full Bundle', 'Bundle whose contents are passed to the output in their entirety', {}, True, None, False, ''),
('outputs:combinedBundle', 'bundle', 0, None, 'This is the union of fullBundle and filtered members of the filteredBundle.', {}, 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.filteredBundle = og.AttributeRole.BUNDLE
role_data.inputs.fullBundle = og.AttributeRole.BUNDLE
role_data.outputs.combinedBundle = og.AttributeRole.BUNDLE
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def filteredBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.filteredBundle"""
return self.__bundles.filteredBundle
@property
def filters(self):
data_view = og.AttributeValueHelper(self._attributes.filters)
return data_view.get()
@filters.setter
def filters(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.filters)
data_view = og.AttributeValueHelper(self._attributes.filters)
data_view.set(value)
self.filters_size = data_view.get_array_size()
@property
def fullBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.fullBundle"""
return self.__bundles.fullBundle
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def combinedBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.combinedBundle"""
return self.__bundles.combinedBundle
@combinedBundle.setter
def combinedBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.combinedBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.combinedBundle.bundle = bundle
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 = OgnTutorialBundlesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundlesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundlesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,335 | Python | 51.4 | 475 | 0.678391 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCudaDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CudaData
This is a tutorial node. It performs different functions on the GPU to illustrate different types of data access. The first
adds inputs 'a' and 'b' to yield output 'sum', all of which are on the GPU. The second is a sample expansion deformation
that multiplies every point on a set of input points, stored on the GPU, by a constant value, stored on the CPU, to yield
a set of output points, also on the GPU. The third is an assortment of different data types illustrating how different data
is passed to the GPU. This particular node uses CUDA for its GPU computations, as indicated in the memory type value. Normal
use case for GPU compute is large amounts of data. For testing purposes this node only handles a very small amount but the
principle is the same.
"""
import carb
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 OgnTutorialCudaDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CudaData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
inputs.color
inputs.half
inputs.matrix
inputs.multiplier
inputs.points
Outputs:
outputs.color
outputs.half
outputs.matrix
outputs.points
outputs.sum
"""
# 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:a', 'float', 0, None, 'First value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:b', 'float', 0, None, 'Second value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:color', 'color3d', 0, None, 'Input with three doubles as a color for algorithm 3', {ogn.MetadataKeys.DEFAULT: '[1.0, 0.5, 1.0]'}, True, [1.0, 0.5, 1.0], False, ''),
('inputs:half', 'half', 0, None, 'Input of type half for algorithm 3', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:matrix', 'matrix4d', 0, None, 'Input with 16 doubles interpreted as a double-precision 4d matrix', {ogn.MetadataKeys.DEFAULT: '[[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]]'}, True, [[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]], False, ''),
('inputs:multiplier', 'float3', 0, None, 'Amplitude of the expansion for the input points in algorithm 2', {ogn.MetadataKeys.MEMORY_TYPE: 'cpu', ogn.MetadataKeys.DEFAULT: '[1.0, 1.0, 1.0]'}, True, [1.0, 1.0, 1.0], False, ''),
('inputs:points', 'float3[]', 0, None, 'Points to be moved by algorithm 2', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:color', 'color3d', 0, None, 'Output with three doubles as a color for algorithm 3', {}, True, None, False, ''),
('outputs:half', 'half', 0, None, 'Output of type half for algorithm 3', {}, True, None, False, ''),
('outputs:matrix', 'matrix4d', 0, None, 'Output with 16 doubles interpreted as a double-precision 4d matrix', {}, True, None, False, ''),
('outputs:points', 'float3[]', 0, None, 'Final positions of points from algorithm 2', {}, True, None, False, ''),
('outputs:sum', 'float', 0, None, 'Sum of the two inputs from algorithm 1', {}, 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.color = og.AttributeRole.COLOR
role_data.inputs.matrix = og.AttributeRole.MATRIX
role_data.outputs.color = og.AttributeRole.COLOR
role_data.outputs.matrix = og.AttributeRole.MATRIX
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 a(self):
data_view = og.AttributeValueHelper(self._attributes.a)
return data_view.get(on_gpu=True)
@a.setter
def a(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a)
data_view = og.AttributeValueHelper(self._attributes.a)
data_view.set(value, on_gpu=True)
@property
def b(self):
data_view = og.AttributeValueHelper(self._attributes.b)
return data_view.get(on_gpu=True)
@b.setter
def b(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.b)
data_view = og.AttributeValueHelper(self._attributes.b)
data_view.set(value, on_gpu=True)
@property
def color(self):
data_view = og.AttributeValueHelper(self._attributes.color)
return data_view.get(on_gpu=True)
@color.setter
def color(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.color)
data_view = og.AttributeValueHelper(self._attributes.color)
data_view.set(value, on_gpu=True)
@property
def half(self):
data_view = og.AttributeValueHelper(self._attributes.half)
return data_view.get(on_gpu=True)
@half.setter
def half(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.half)
data_view = og.AttributeValueHelper(self._attributes.half)
data_view.set(value, on_gpu=True)
@property
def matrix(self):
data_view = og.AttributeValueHelper(self._attributes.matrix)
return data_view.get(on_gpu=True)
@matrix.setter
def matrix(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.matrix)
data_view = og.AttributeValueHelper(self._attributes.matrix)
data_view.set(value, on_gpu=True)
@property
def multiplier(self):
data_view = og.AttributeValueHelper(self._attributes.multiplier)
return data_view.get()
@multiplier.setter
def multiplier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.multiplier)
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.set(value)
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
return data_view.get(on_gpu=True)
@points.setter
def points(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.points)
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.set(value, on_gpu=True)
self.points_size = data_view.get_array_size()
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.points_size = None
self._batchedWriteValues = { }
@property
def color(self):
data_view = og.AttributeValueHelper(self._attributes.color)
return data_view.get(on_gpu=True)
@color.setter
def color(self, value):
data_view = og.AttributeValueHelper(self._attributes.color)
data_view.set(value, on_gpu=True)
@property
def half(self):
data_view = og.AttributeValueHelper(self._attributes.half)
return data_view.get(on_gpu=True)
@half.setter
def half(self, value):
data_view = og.AttributeValueHelper(self._attributes.half)
data_view.set(value, on_gpu=True)
@property
def matrix(self):
data_view = og.AttributeValueHelper(self._attributes.matrix)
return data_view.get(on_gpu=True)
@matrix.setter
def matrix(self, value):
data_view = og.AttributeValueHelper(self._attributes.matrix)
data_view.set(value, on_gpu=True)
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
return data_view.get(reserved_element_count=self.points_size, on_gpu=True)
@points.setter
def points(self, value):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.set(value, on_gpu=True)
self.points_size = data_view.get_array_size()
@property
def sum(self):
data_view = og.AttributeValueHelper(self._attributes.sum)
return data_view.get(on_gpu=True)
@sum.setter
def sum(self, value):
data_view = og.AttributeValueHelper(self._attributes.sum)
data_view.set(value, on_gpu=True)
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 = OgnTutorialCudaDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCudaDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCudaDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,300 | Python | 45.950382 | 343 | 0.633252 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuData
This is a tutorial node. It illustrates how to access data whose memory location, CPU or GPU, is determined at runtime in
the compute method. The data types are the same as for the purely CPU and purely GPU tutorials, it is only the access method
that changes. The input 'is_gpu' determines where the data of the other attributes can be accessed.
"""
import carb
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 OgnTutorialCpuGpuDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a
inputs.b
inputs.is_gpu
inputs.multiplier
inputs.points
Outputs:
outputs.points
outputs.sum
"""
# 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:a', 'float', 0, None, 'First value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:b', 'float', 0, None, 'Second value to be added in algorithm 1', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:is_gpu', 'bool', 0, None, 'Runtime switch determining where the data for the other attributes lives.', {ogn.MetadataKeys.MEMORY_TYPE: 'cpu', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:multiplier', 'float3', 0, None, 'Amplitude of the expansion for the input points in algorithm 2', {ogn.MetadataKeys.DEFAULT: '[1.0, 1.0, 1.0]'}, True, [1.0, 1.0, 1.0], False, ''),
('inputs:points', 'float3[]', 0, None, 'Points to be moved by algorithm 2', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:points', 'float3[]', 0, None, 'Final positions of points from algorithm 2', {}, True, None, False, ''),
('outputs:sum', 'float', 0, None, 'Sum of the two inputs from algorithm 1', {}, 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 = []
class __a:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.a)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.a)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def a(self):
return self.__class__.__a(self)
class __b:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.b)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.b)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def b(self):
return self.__class__.__b(self)
@property
def is_gpu(self):
data_view = og.AttributeValueHelper(self._attributes.is_gpu)
return data_view.get()
@is_gpu.setter
def is_gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.is_gpu)
data_view = og.AttributeValueHelper(self._attributes.is_gpu)
data_view.set(value)
class __multiplier:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.multiplier)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.multiplier)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def multiplier(self):
return self.__class__.__multiplier(self)
class __points:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get()
@cpu.setter
def cpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.cpu)
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
self._parent.cpu_size = data_view.get_array_size()
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
if self._parent._setting_locked:
raise og.ReadOnlyError(self._parent._attributes.gpu)
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
self._parent.gpu_size = data_view.get_array_size()
@property
def points(self):
return self.__class__.__points(self)
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.points_size = None
self._batchedWriteValues = { }
class __points:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get(reserved_element_count=self._parent.points_size)
@cpu.setter
def cpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
self._parent.cpu_size = data_view.get_array_size()
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.points)
return data_view.get(reserved_element_count=self._parent.points_size, on_gpu=True)
@gpu.setter
def gpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
self._parent.gpu_size = data_view.get_array_size()
@property
def points(self):
return self.__class__.__points(self)
class __sum:
def __init__(self, parent):
self._parent = parent
@property
def cpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.sum)
return data_view.get()
@cpu.setter
def cpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.cpu)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._parent._attributes.sum)
return data_view.get(on_gpu=True)
@gpu.setter
def gpu(self, value):
data_view = og.AttributeValueHelper(self._parent._attributes.gpu)
data_view.set(value)
@property
def sum(self):
return self.__class__.__sum(self)
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 = OgnTutorialCpuGpuDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 12,813 | Python | 41.430463 | 218 | 0.590806 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialStateAttributesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.StateAttributesPy
This is a tutorial node. It exercises state attributes to remember data from on evaluation to the next.
"""
import carb
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialStateAttributesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.StateAttributesPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.ignored
State:
state.monotonic
state.reset
"""
# 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:ignored', 'bool', 0, None, 'Ignore me', {}, True, False, False, ''),
('state:monotonic', 'int', 0, None, 'The monotonically increasing output value, reset to 0 when the reset value is true', {}, True, None, False, ''),
('state:reset', 'bool', 0, None, 'If true then the inputs are ignored and outputs are set to default values, then this\nflag is set to false for subsequent evaluations.', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"ignored", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""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._attributes.ignored]
self._batchedReadValues = [False]
@property
def ignored(self):
return self._batchedReadValues[0]
@ignored.setter
def ignored(self, value):
self._batchedReadValues[0] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_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)
@property
def monotonic(self):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
return data_view.get()
@monotonic.setter
def monotonic(self, value):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
data_view.set(value)
@property
def reset(self):
data_view = og.AttributeValueHelper(self._attributes.reset)
return data_view.get()
@reset.setter
def reset(self, value):
data_view = og.AttributeValueHelper(self._attributes.reset)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnTutorialStateAttributesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialStateAttributesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialStateAttributesPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.StateAttributesPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialStateAttributesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialStateAttributesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialStateAttributesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialStateAttributesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialStateAttributesPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialStateAttributesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialStateAttributesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: State Attributes")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises state attributes to remember data from on evaluation to the next.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.StateAttributesPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialStateAttributesPyDatabase.INTERFACE.add_to_node_type(node_type)
node_type.set_has_state(True)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialStateAttributesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialStateAttributesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.StateAttributesPy")
| 11,647 | Python | 47.132231 | 238 | 0.649008 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundlesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleManipulationPy
This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents. The configuration
is the same as omni.graph.tutorials.BundleManipulation except that the implementation language is Python
"""
import carb
import numpy
import sys
import traceback
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialBundlesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleManipulationPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.filteredBundle
inputs.filters
inputs.fullBundle
Outputs:
outputs.combinedBundle
"""
# 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:filteredBundle', 'bundle', 0, 'Filtered Bundle', 'Bundle whose contents are filtered before being added to the output', {}, True, None, False, ''),
('inputs:filters', 'token[]', 0, None, "List of filter names to be applied to the filteredBundle. Any filter name\nappearing in this list will be applied to members of that bundle and only those\npassing all filters will be added to the output bundle. Legal filter values are\n'big' (arrays of size > 10), 'x' (attributes whose name contains the letter x), \nand 'int' (attributes whose base type is integer).", {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:fullBundle', 'bundle', 0, 'Full Bundle', 'Bundle whose contents are passed to the output in their entirety', {}, True, None, False, ''),
('outputs:combinedBundle', 'bundle', 0, None, 'This is the union of fullBundle and filtered members of the filteredBundle.', {}, 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.filteredBundle = og.AttributeRole.BUNDLE
role_data.inputs.fullBundle = og.AttributeRole.BUNDLE
role_data.outputs.combinedBundle = og.AttributeRole.BUNDLE
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def filteredBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.filteredBundle"""
return self.__bundles.filteredBundle
@property
def filters(self):
data_view = og.AttributeValueHelper(self._attributes.filters)
return data_view.get()
@filters.setter
def filters(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.filters)
data_view = og.AttributeValueHelper(self._attributes.filters)
data_view.set(value)
self.filters_size = data_view.get_array_size()
@property
def fullBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.fullBundle"""
return self.__bundles.fullBundle
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def combinedBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.combinedBundle"""
return self.__bundles.combinedBundle
@combinedBundle.setter
def combinedBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.combinedBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.combinedBundle.bundle = bundle
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 = OgnTutorialBundlesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundlesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundlesPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.BundleManipulationPy'
@staticmethod
def compute(context, node):
def database_valid():
if not db.inputs.filteredBundle.valid:
db.log_warning('Required bundle inputs.filteredBundle is invalid or not connected, compute skipped')
return False
if not db.inputs.fullBundle.valid:
db.log_warning('Required bundle inputs.fullBundle is invalid or not connected, compute skipped')
return False
if not db.outputs.combinedBundle.valid:
db.log_error('Required bundle outputs.combinedBundle is invalid, compute skipped')
return False
return True
try:
per_node_data = OgnTutorialBundlesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialBundlesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialBundlesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialBundlesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialBundlesPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialBundlesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialBundlesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Bundle Manipulation")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises functionality for the manipulation of bundle attribute contents. The configuration is the same as omni.graph.tutorials.BundleManipulation except that the implementation language is Python")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.BundleManipulationPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialBundlesPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialBundlesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialBundlesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.BundleManipulationPy")
| 13,575 | Python | 51.015325 | 475 | 0.657459 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialRoleDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.RoleData
This is a tutorial node. It creates both an input and output attribute of every supported role-based data type. The values
are modified in a simple way so that the compute modifies values.
"""
import carb
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 OgnTutorialRoleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.RoleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_color3d
inputs.a_color3f
inputs.a_color3h
inputs.a_color4d
inputs.a_color4f
inputs.a_color4h
inputs.a_frame
inputs.a_matrix2d
inputs.a_matrix3d
inputs.a_matrix4d
inputs.a_normal3d
inputs.a_normal3f
inputs.a_normal3h
inputs.a_point3d
inputs.a_point3f
inputs.a_point3h
inputs.a_quatd
inputs.a_quatf
inputs.a_quath
inputs.a_texcoord2d
inputs.a_texcoord2f
inputs.a_texcoord2h
inputs.a_texcoord3d
inputs.a_texcoord3f
inputs.a_texcoord3h
inputs.a_timecode
inputs.a_vector3d
inputs.a_vector3f
inputs.a_vector3h
Outputs:
outputs.a_color3d
outputs.a_color3f
outputs.a_color3h
outputs.a_color4d
outputs.a_color4f
outputs.a_color4h
outputs.a_frame
outputs.a_matrix2d
outputs.a_matrix3d
outputs.a_matrix4d
outputs.a_normal3d
outputs.a_normal3f
outputs.a_normal3h
outputs.a_point3d
outputs.a_point3f
outputs.a_point3h
outputs.a_quatd
outputs.a_quatf
outputs.a_quath
outputs.a_texcoord2d
outputs.a_texcoord2f
outputs.a_texcoord2h
outputs.a_texcoord3d
outputs.a_texcoord3f
outputs.a_texcoord3h
outputs.a_timecode
outputs.a_vector3d
outputs.a_vector3f
outputs.a_vector3h
"""
# 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:a_color3d', 'color3d', 0, None, 'This is an attribute interpreted as a double-precision 3d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_color3f', 'color3f', 0, None, 'This is an attribute interpreted as a single-precision 3d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_color3h', 'color3h', 0, None, 'This is an attribute interpreted as a half-precision 3d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_color4d', 'color4d', 0, None, 'This is an attribute interpreted as a double-precision 4d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_color4f', 'color4f', 0, None, 'This is an attribute interpreted as a single-precision 4d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_color4h', 'color4h', 0, None, 'This is an attribute interpreted as a half-precision 4d color', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_frame', 'frame4d', 0, None, 'This is an attribute interpreted as a coordinate frame', {ogn.MetadataKeys.DEFAULT: '[[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]]'}, True, [[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]], False, ''),
('inputs:a_matrix2d', 'matrix2d', 0, None, 'This is an attribute interpreted as a double-precision 2d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0], [0.0, 1.0]]'}, True, [[1.0, 0.0], [0.0, 1.0]], False, ''),
('inputs:a_matrix3d', 'matrix3d', 0, None, 'This is an attribute interpreted as a double-precision 3d matrix', {ogn.MetadataKeys.DEFAULT: '[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]'}, True, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], False, ''),
('inputs:a_matrix4d', 'matrix4d', 0, None, 'This is an attribute interpreted as a double-precision 4d matrix', {ogn.MetadataKeys.DEFAULT: '[[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]]'}, True, [[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]], False, ''),
('inputs:a_normal3d', 'normal3d', 0, None, 'This is an attribute interpreted as a double-precision 3d normal', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_normal3f', 'normal3f', 0, None, 'This is an attribute interpreted as a single-precision 3d normal', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_normal3h', 'normal3h', 0, None, 'This is an attribute interpreted as a half-precision 3d normal', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_point3d', 'point3d', 0, None, 'This is an attribute interpreted as a double-precision 3d point', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_point3f', 'point3f', 0, None, 'This is an attribute interpreted as a single-precision 3d point', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_point3h', 'point3h', 0, None, 'This is an attribute interpreted as a half-precision 3d point', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_quatd', 'quatd', 0, None, 'This is an attribute interpreted as a double-precision 4d quaternion', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_quatf', 'quatf', 0, None, 'This is an attribute interpreted as a single-precision 4d quaternion', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_quath', 'quath', 0, None, 'This is an attribute interpreted as a half-precision 4d quaternion', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0, 0.0], False, ''),
('inputs:a_texcoord2d', 'texCoord2d', 0, None, 'This is an attribute interpreted as a double-precision 2d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0]'}, True, [0.0, 0.0], False, ''),
('inputs:a_texcoord2f', 'texCoord2f', 0, None, 'This is an attribute interpreted as a single-precision 2d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0]'}, True, [0.0, 0.0], False, ''),
('inputs:a_texcoord2h', 'texCoord2h', 0, None, 'This is an attribute interpreted as a half-precision 2d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0]'}, True, [0.0, 0.0], False, ''),
('inputs:a_texcoord3d', 'texCoord3d', 0, None, 'This is an attribute interpreted as a double-precision 3d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_texcoord3f', 'texCoord3f', 0, None, 'This is an attribute interpreted as a single-precision 3d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_texcoord3h', 'texCoord3h', 0, None, 'This is an attribute interpreted as a half-precision 3d texcoord', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_timecode', 'timecode', 0, None, 'This is a computed attribute interpreted as a timecode', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:a_vector3d', 'vector3d', 0, None, 'This is an attribute interpreted as a double-precision 3d vector', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_vector3f', 'vector3f', 0, None, 'This is an attribute interpreted as a single-precision 3d vector', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('inputs:a_vector3h', 'vector3h', 0, None, 'This is an attribute interpreted as a half-precision 3d vector', {ogn.MetadataKeys.DEFAULT: '[0.0, 0.0, 0.0]'}, True, [0.0, 0.0, 0.0], False, ''),
('outputs:a_color3d', 'color3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d color', {}, True, None, False, ''),
('outputs:a_color3f', 'color3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d color', {}, True, None, False, ''),
('outputs:a_color3h', 'color3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d color', {}, True, None, False, ''),
('outputs:a_color4d', 'color4d', 0, None, 'This is a computed attribute interpreted as a double-precision 4d color', {}, True, None, False, ''),
('outputs:a_color4f', 'color4f', 0, None, 'This is a computed attribute interpreted as a single-precision 4d color', {}, True, None, False, ''),
('outputs:a_color4h', 'color4h', 0, None, 'This is a computed attribute interpreted as a half-precision 4d color', {}, True, None, False, ''),
('outputs:a_frame', 'frame4d', 0, None, 'This is a computed attribute interpreted as a coordinate frame', {}, True, None, False, ''),
('outputs:a_matrix2d', 'matrix2d', 0, None, 'This is a computed attribute interpreted as a double-precision 2d matrix', {}, True, None, False, ''),
('outputs:a_matrix3d', 'matrix3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d matrix', {}, True, None, False, ''),
('outputs:a_matrix4d', 'matrix4d', 0, None, 'This is a computed attribute interpreted as a double-precision 4d matrix', {}, True, None, False, ''),
('outputs:a_normal3d', 'normal3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d normal', {}, True, None, False, ''),
('outputs:a_normal3f', 'normal3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d normal', {}, True, None, False, ''),
('outputs:a_normal3h', 'normal3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d normal', {}, True, None, False, ''),
('outputs:a_point3d', 'point3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d point', {}, True, None, False, ''),
('outputs:a_point3f', 'point3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d point', {}, True, None, False, ''),
('outputs:a_point3h', 'point3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d point', {}, True, None, False, ''),
('outputs:a_quatd', 'quatd', 0, None, 'This is a computed attribute interpreted as a double-precision 4d quaternion', {}, True, None, False, ''),
('outputs:a_quatf', 'quatf', 0, None, 'This is a computed attribute interpreted as a single-precision 4d quaternion', {}, True, None, False, ''),
('outputs:a_quath', 'quath', 0, None, 'This is a computed attribute interpreted as a half-precision 4d quaternion', {}, True, None, False, ''),
('outputs:a_texcoord2d', 'texCoord2d', 0, None, 'This is a computed attribute interpreted as a double-precision 2d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord2f', 'texCoord2f', 0, None, 'This is a computed attribute interpreted as a single-precision 2d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord2h', 'texCoord2h', 0, None, 'This is a computed attribute interpreted as a half-precision 2d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord3d', 'texCoord3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord3f', 'texCoord3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d texcoord', {}, True, None, False, ''),
('outputs:a_texcoord3h', 'texCoord3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d texcoord', {}, True, None, False, ''),
('outputs:a_timecode', 'timecode', 0, None, 'This is a computed attribute interpreted as a timecode', {}, True, None, False, ''),
('outputs:a_vector3d', 'vector3d', 0, None, 'This is a computed attribute interpreted as a double-precision 3d vector', {}, True, None, False, ''),
('outputs:a_vector3f', 'vector3f', 0, None, 'This is a computed attribute interpreted as a single-precision 3d vector', {}, True, None, False, ''),
('outputs:a_vector3h', 'vector3h', 0, None, 'This is a computed attribute interpreted as a half-precision 3d vector', {}, 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.a_color3d = og.AttributeRole.COLOR
role_data.inputs.a_color3f = og.AttributeRole.COLOR
role_data.inputs.a_color3h = og.AttributeRole.COLOR
role_data.inputs.a_color4d = og.AttributeRole.COLOR
role_data.inputs.a_color4f = og.AttributeRole.COLOR
role_data.inputs.a_color4h = og.AttributeRole.COLOR
role_data.inputs.a_frame = og.AttributeRole.FRAME
role_data.inputs.a_matrix2d = og.AttributeRole.MATRIX
role_data.inputs.a_matrix3d = og.AttributeRole.MATRIX
role_data.inputs.a_matrix4d = og.AttributeRole.MATRIX
role_data.inputs.a_normal3d = og.AttributeRole.NORMAL
role_data.inputs.a_normal3f = og.AttributeRole.NORMAL
role_data.inputs.a_normal3h = og.AttributeRole.NORMAL
role_data.inputs.a_point3d = og.AttributeRole.POSITION
role_data.inputs.a_point3f = og.AttributeRole.POSITION
role_data.inputs.a_point3h = og.AttributeRole.POSITION
role_data.inputs.a_quatd = og.AttributeRole.QUATERNION
role_data.inputs.a_quatf = og.AttributeRole.QUATERNION
role_data.inputs.a_quath = og.AttributeRole.QUATERNION
role_data.inputs.a_texcoord2d = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord2f = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord2h = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord3d = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord3f = og.AttributeRole.TEXCOORD
role_data.inputs.a_texcoord3h = og.AttributeRole.TEXCOORD
role_data.inputs.a_timecode = og.AttributeRole.TIMECODE
role_data.inputs.a_vector3d = og.AttributeRole.VECTOR
role_data.inputs.a_vector3f = og.AttributeRole.VECTOR
role_data.inputs.a_vector3h = og.AttributeRole.VECTOR
role_data.outputs.a_color3d = og.AttributeRole.COLOR
role_data.outputs.a_color3f = og.AttributeRole.COLOR
role_data.outputs.a_color3h = og.AttributeRole.COLOR
role_data.outputs.a_color4d = og.AttributeRole.COLOR
role_data.outputs.a_color4f = og.AttributeRole.COLOR
role_data.outputs.a_color4h = og.AttributeRole.COLOR
role_data.outputs.a_frame = og.AttributeRole.FRAME
role_data.outputs.a_matrix2d = og.AttributeRole.MATRIX
role_data.outputs.a_matrix3d = og.AttributeRole.MATRIX
role_data.outputs.a_matrix4d = og.AttributeRole.MATRIX
role_data.outputs.a_normal3d = og.AttributeRole.NORMAL
role_data.outputs.a_normal3f = og.AttributeRole.NORMAL
role_data.outputs.a_normal3h = og.AttributeRole.NORMAL
role_data.outputs.a_point3d = og.AttributeRole.POSITION
role_data.outputs.a_point3f = og.AttributeRole.POSITION
role_data.outputs.a_point3h = og.AttributeRole.POSITION
role_data.outputs.a_quatd = og.AttributeRole.QUATERNION
role_data.outputs.a_quatf = og.AttributeRole.QUATERNION
role_data.outputs.a_quath = og.AttributeRole.QUATERNION
role_data.outputs.a_texcoord2d = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord2f = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord2h = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord3d = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord3f = og.AttributeRole.TEXCOORD
role_data.outputs.a_texcoord3h = og.AttributeRole.TEXCOORD
role_data.outputs.a_timecode = og.AttributeRole.TIMECODE
role_data.outputs.a_vector3d = og.AttributeRole.VECTOR
role_data.outputs.a_vector3f = og.AttributeRole.VECTOR
role_data.outputs.a_vector3h = og.AttributeRole.VECTOR
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 a_color3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
return data_view.get()
@a_color3d.setter
def a_color3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color3d)
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
data_view.set(value)
@property
def a_color3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
return data_view.get()
@a_color3f.setter
def a_color3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color3f)
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
data_view.set(value)
@property
def a_color3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
return data_view.get()
@a_color3h.setter
def a_color3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color3h)
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
data_view.set(value)
@property
def a_color4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
return data_view.get()
@a_color4d.setter
def a_color4d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color4d)
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
data_view.set(value)
@property
def a_color4f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
return data_view.get()
@a_color4f.setter
def a_color4f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color4f)
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
data_view.set(value)
@property
def a_color4h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
return data_view.get()
@a_color4h.setter
def a_color4h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_color4h)
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
data_view.set(value)
@property
def a_frame(self):
data_view = og.AttributeValueHelper(self._attributes.a_frame)
return data_view.get()
@a_frame.setter
def a_frame(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_frame)
data_view = og.AttributeValueHelper(self._attributes.a_frame)
data_view.set(value)
@property
def a_matrix2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
return data_view.get()
@a_matrix2d.setter
def a_matrix2d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix2d)
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
data_view.set(value)
@property
def a_matrix3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
return data_view.get()
@a_matrix3d.setter
def a_matrix3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix3d)
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
data_view.set(value)
@property
def a_matrix4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
return data_view.get()
@a_matrix4d.setter
def a_matrix4d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix4d)
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
data_view.set(value)
@property
def a_normal3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
return data_view.get()
@a_normal3d.setter
def a_normal3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_normal3d)
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
data_view.set(value)
@property
def a_normal3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
return data_view.get()
@a_normal3f.setter
def a_normal3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_normal3f)
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
data_view.set(value)
@property
def a_normal3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
return data_view.get()
@a_normal3h.setter
def a_normal3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_normal3h)
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
data_view.set(value)
@property
def a_point3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
return data_view.get()
@a_point3d.setter
def a_point3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_point3d)
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
data_view.set(value)
@property
def a_point3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
return data_view.get()
@a_point3f.setter
def a_point3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_point3f)
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
data_view.set(value)
@property
def a_point3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
return data_view.get()
@a_point3h.setter
def a_point3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_point3h)
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
data_view.set(value)
@property
def a_quatd(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
return data_view.get()
@a_quatd.setter
def a_quatd(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_quatd)
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
data_view.set(value)
@property
def a_quatf(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
return data_view.get()
@a_quatf.setter
def a_quatf(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_quatf)
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
data_view.set(value)
@property
def a_quath(self):
data_view = og.AttributeValueHelper(self._attributes.a_quath)
return data_view.get()
@a_quath.setter
def a_quath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_quath)
data_view = og.AttributeValueHelper(self._attributes.a_quath)
data_view.set(value)
@property
def a_texcoord2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
return data_view.get()
@a_texcoord2d.setter
def a_texcoord2d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord2d)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
data_view.set(value)
@property
def a_texcoord2f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
return data_view.get()
@a_texcoord2f.setter
def a_texcoord2f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord2f)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
data_view.set(value)
@property
def a_texcoord2h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
return data_view.get()
@a_texcoord2h.setter
def a_texcoord2h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord2h)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
data_view.set(value)
@property
def a_texcoord3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
return data_view.get()
@a_texcoord3d.setter
def a_texcoord3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord3d)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
data_view.set(value)
@property
def a_texcoord3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
return data_view.get()
@a_texcoord3f.setter
def a_texcoord3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord3f)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
data_view.set(value)
@property
def a_texcoord3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
return data_view.get()
@a_texcoord3h.setter
def a_texcoord3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_texcoord3h)
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
data_view.set(value)
@property
def a_timecode(self):
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
return data_view.get()
@a_timecode.setter
def a_timecode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_timecode)
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
data_view.set(value)
@property
def a_vector3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
return data_view.get()
@a_vector3d.setter
def a_vector3d(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_vector3d)
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
data_view.set(value)
@property
def a_vector3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
return data_view.get()
@a_vector3f.setter
def a_vector3f(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_vector3f)
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
data_view.set(value)
@property
def a_vector3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
return data_view.get()
@a_vector3h.setter
def a_vector3h(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_vector3h)
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
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 a_color3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
return data_view.get()
@a_color3d.setter
def a_color3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color3d)
data_view.set(value)
@property
def a_color3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
return data_view.get()
@a_color3f.setter
def a_color3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color3f)
data_view.set(value)
@property
def a_color3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
return data_view.get()
@a_color3h.setter
def a_color3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color3h)
data_view.set(value)
@property
def a_color4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
return data_view.get()
@a_color4d.setter
def a_color4d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color4d)
data_view.set(value)
@property
def a_color4f(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
return data_view.get()
@a_color4f.setter
def a_color4f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color4f)
data_view.set(value)
@property
def a_color4h(self):
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
return data_view.get()
@a_color4h.setter
def a_color4h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_color4h)
data_view.set(value)
@property
def a_frame(self):
data_view = og.AttributeValueHelper(self._attributes.a_frame)
return data_view.get()
@a_frame.setter
def a_frame(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_frame)
data_view.set(value)
@property
def a_matrix2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
return data_view.get()
@a_matrix2d.setter
def a_matrix2d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix2d)
data_view.set(value)
@property
def a_matrix3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
return data_view.get()
@a_matrix3d.setter
def a_matrix3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix3d)
data_view.set(value)
@property
def a_matrix4d(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
return data_view.get()
@a_matrix4d.setter
def a_matrix4d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix4d)
data_view.set(value)
@property
def a_normal3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
return data_view.get()
@a_normal3d.setter
def a_normal3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_normal3d)
data_view.set(value)
@property
def a_normal3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
return data_view.get()
@a_normal3f.setter
def a_normal3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_normal3f)
data_view.set(value)
@property
def a_normal3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
return data_view.get()
@a_normal3h.setter
def a_normal3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_normal3h)
data_view.set(value)
@property
def a_point3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
return data_view.get()
@a_point3d.setter
def a_point3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_point3d)
data_view.set(value)
@property
def a_point3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
return data_view.get()
@a_point3f.setter
def a_point3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_point3f)
data_view.set(value)
@property
def a_point3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
return data_view.get()
@a_point3h.setter
def a_point3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_point3h)
data_view.set(value)
@property
def a_quatd(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
return data_view.get()
@a_quatd.setter
def a_quatd(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_quatd)
data_view.set(value)
@property
def a_quatf(self):
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
return data_view.get()
@a_quatf.setter
def a_quatf(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_quatf)
data_view.set(value)
@property
def a_quath(self):
data_view = og.AttributeValueHelper(self._attributes.a_quath)
return data_view.get()
@a_quath.setter
def a_quath(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_quath)
data_view.set(value)
@property
def a_texcoord2d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
return data_view.get()
@a_texcoord2d.setter
def a_texcoord2d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2d)
data_view.set(value)
@property
def a_texcoord2f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
return data_view.get()
@a_texcoord2f.setter
def a_texcoord2f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2f)
data_view.set(value)
@property
def a_texcoord2h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
return data_view.get()
@a_texcoord2h.setter
def a_texcoord2h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord2h)
data_view.set(value)
@property
def a_texcoord3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
return data_view.get()
@a_texcoord3d.setter
def a_texcoord3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3d)
data_view.set(value)
@property
def a_texcoord3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
return data_view.get()
@a_texcoord3f.setter
def a_texcoord3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3f)
data_view.set(value)
@property
def a_texcoord3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
return data_view.get()
@a_texcoord3h.setter
def a_texcoord3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_texcoord3h)
data_view.set(value)
@property
def a_timecode(self):
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
return data_view.get()
@a_timecode.setter
def a_timecode(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_timecode)
data_view.set(value)
@property
def a_vector3d(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
return data_view.get()
@a_vector3d.setter
def a_vector3d(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_vector3d)
data_view.set(value)
@property
def a_vector3f(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
return data_view.get()
@a_vector3f.setter
def a_vector3f(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_vector3f)
data_view.set(value)
@property
def a_vector3h(self):
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
return data_view.get()
@a_vector3h.setter
def a_vector3h(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_vector3h)
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 = OgnTutorialRoleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialRoleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialRoleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 42,891 | Python | 46.446903 | 346 | 0.616936 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTokensPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.TokensPy
This is a tutorial node. It exercises the feature of providing hardcoded token values in the database after a node type has
been initialized. It sets output booleans to the truth value of whether corresponding inputs appear in the hardcoded token
list.
"""
import carb
import numpy
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialTokensPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.TokensPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.valuesToCheck
Outputs:
outputs.isColor
Predefined Tokens:
tokens.red
tokens.green
tokens.blue
"""
# 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:valuesToCheck', 'token[]', 0, None, 'Array of tokens that are to be checked', {}, True, [], False, ''),
('outputs:isColor', 'bool[]', 0, None, 'True values if the corresponding input value appears in the token list', {}, True, None, False, ''),
])
class tokens:
red = "red"
green = "green"
blue = "blue"
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 valuesToCheck(self):
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
return data_view.get()
@valuesToCheck.setter
def valuesToCheck(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.valuesToCheck)
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
data_view.set(value)
self.valuesToCheck_size = data_view.get_array_size()
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.isColor_size = None
self._batchedWriteValues = { }
@property
def isColor(self):
data_view = og.AttributeValueHelper(self._attributes.isColor)
return data_view.get(reserved_element_count=self.isColor_size)
@isColor.setter
def isColor(self, value):
data_view = og.AttributeValueHelper(self._attributes.isColor)
data_view.set(value)
self.isColor_size = data_view.get_array_size()
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 = OgnTutorialTokensPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTokensPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTokensPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.TokensPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialTokensPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialTokensPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialTokensPyDatabase(node)
try:
compute_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialTokensPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialTokensPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialTokensPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialTokensPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Tokens")
node_type.set_metadata(ogn.MetadataKeys.TOKENS, "[\"red\", \"green\", \"blue\"]")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises the feature of providing hardcoded token values in the database after a node type has been initialized. It sets output booleans to the truth value of whether corresponding inputs appear in the hardcoded token list.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.TokensPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialTokensPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialTokensPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialTokensPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.TokensPy")
| 11,282 | Python | 46.407563 | 324 | 0.649885 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialStateDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.State
This is a tutorial node. It makes use of internal state information to continuously increment an output.
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialStateDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.State
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.override
inputs.overrideValue
Outputs:
outputs.monotonic
"""
# 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:override', 'bool', 0, 'Enable Override', 'When true get the output from the overrideValue, otherwise use the internal value', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:overrideValue', 'int64', 0, 'Override Value', "Value to use instead of the monotonically increasing internal one when 'override' is true", {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:monotonic', 'int64', 0, 'State-Based Output', 'Monotonically increasing output, set by internal state information', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, 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 override(self):
data_view = og.AttributeValueHelper(self._attributes.override)
return data_view.get()
@override.setter
def override(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.override)
data_view = og.AttributeValueHelper(self._attributes.override)
data_view.set(value)
@property
def overrideValue(self):
data_view = og.AttributeValueHelper(self._attributes.overrideValue)
return data_view.get()
@overrideValue.setter
def overrideValue(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.overrideValue)
data_view = og.AttributeValueHelper(self._attributes.overrideValue)
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 monotonic(self):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
return data_view.get()
@monotonic.setter
def monotonic(self, value):
data_view = og.AttributeValueHelper(self._attributes.monotonic)
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 = OgnTutorialStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,974 | Python | 47.185483 | 209 | 0.67392 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialDynamicAttributesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.DynamicAttributes
This is a C++ node that exercises the ability to add and remove database attribute accessors for dynamic attributes. When
the dynamic attribute is added the property will exist and be able to get/set the attribute values. When it does not the
property will not exist. The dynamic attribute names are found in the tokens below. If neither exist then the input value
is copied to the output directly. If 'firstBit' exists then the 'firstBit'th bit of the input is x-ored for the copy. If
'secondBit' exists then the 'secondBit'th bit of the input is x-ored for the copy. (Recall bitwise match xor(0,0)=0, xor(0,1)=1,
xor(1,0)=1, and xor(1,1)=0.) For example, if 'firstBit' is present and set to 1 then the bitmask will be b0010, where bit
1 is set. If the input is 7, or b0111, then the xor operation will flip bit 1, yielding b0101, or 5 as the result. If on
the next run 'secondBit' is also present and set to 2 then its bitmask will be b0100, where bit 2 is set. The input of 7
(b0111) flips bit 1 because firstBit=1 and flips bit 2 because secondBit=2, yielding a final result of 1 (b0001).
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialDynamicAttributesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.DynamicAttributes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.value
Outputs:
outputs.result
Predefined Tokens:
tokens.firstBit
tokens.secondBit
tokens.invert
"""
# 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:value', 'uint', 0, None, 'Original value to be modified.', {}, True, 0, False, ''),
('outputs:result', 'uint', 0, None, 'Modified value', {}, True, None, False, ''),
])
class tokens:
firstBit = "inputs:firstBit"
secondBit = "inputs:secondBit"
invert = "inputs:invert"
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 value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.value)
data_view = og.AttributeValueHelper(self._attributes.value)
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 result(self):
data_view = og.AttributeValueHelper(self._attributes.result)
return data_view.get()
@result.setter
def result(self, value):
data_view = og.AttributeValueHelper(self._attributes.result)
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 = OgnTutorialDynamicAttributesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialDynamicAttributesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialDynamicAttributesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,314 | Python | 48.335937 | 128 | 0.684194 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialDefaultsDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.Defaults
This is a tutorial node. It will move the values of inputs to corresponding outputs. Inputs all have unspecified, and therefore
empty, default values.
"""
import carb
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 OgnTutorialDefaultsDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.Defaults
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_array
inputs.a_bool
inputs.a_double
inputs.a_float
inputs.a_half
inputs.a_int
inputs.a_int2
inputs.a_int64
inputs.a_matrix
inputs.a_string
inputs.a_token
inputs.a_uchar
inputs.a_uint
inputs.a_uint64
Outputs:
outputs.a_array
outputs.a_bool
outputs.a_double
outputs.a_float
outputs.a_half
outputs.a_int
outputs.a_int2
outputs.a_int64
outputs.a_matrix
outputs.a_string
outputs.a_token
outputs.a_uchar
outputs.a_uint
outputs.a_uint64
"""
# 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:a_array', 'float[]', 0, None, 'This is an attribute of type array of floats', {}, True, [], False, ''),
('inputs:a_bool', 'bool', 0, None, 'This is an attribute of type boolean', {}, True, False, False, ''),
('inputs:a_double', 'double', 0, None, 'This is an attribute of type 64 bit floating point', {}, True, 0.0, False, ''),
('inputs:a_float', 'float', 0, None, 'This is an attribute of type 32 bit floating point', {}, True, 0.0, False, ''),
('inputs:a_half', 'half', 0, None, 'This is an attribute of type 16 bit floating point', {}, True, 0.0, False, ''),
('inputs:a_int', 'int', 0, None, 'This is an attribute of type 32 bit integer', {}, True, 0, False, ''),
('inputs:a_int2', 'int2', 0, None, 'This is an attribute of type 2-tuple of integers', {}, True, [0, 0], False, ''),
('inputs:a_int64', 'int64', 0, None, 'This is an attribute of type 64 bit integer', {}, True, 0, False, ''),
('inputs:a_matrix', 'matrix2d', 0, None, 'This is an attribute of type 2x2 matrix', {}, True, [[1.0, 0.0], [0.0, 1.0]], False, ''),
('inputs:a_string', 'string', 0, None, 'This is an attribute of type string', {}, True, "", False, ''),
('inputs:a_token', 'token', 0, None, 'This is an attribute of type interned string with fast comparison and hashing', {}, True, "", False, ''),
('inputs:a_uchar', 'uchar', 0, None, 'This is an attribute of type unsigned 8 bit integer', {}, True, 0, False, ''),
('inputs:a_uint', 'uint', 0, None, 'This is an attribute of type unsigned 32 bit integer', {}, True, 0, False, ''),
('inputs:a_uint64', 'uint64', 0, None, 'This is an attribute of type unsigned 64 bit integer', {}, True, 0, False, ''),
('outputs:a_array', 'float[]', 0, None, 'This is a computed attribute of type array of floats', {}, True, None, False, ''),
('outputs:a_bool', 'bool', 0, None, 'This is a computed attribute of type boolean', {}, True, None, False, ''),
('outputs:a_double', 'double', 0, None, 'This is a computed attribute of type 64 bit floating point', {}, True, None, False, ''),
('outputs:a_float', 'float', 0, None, 'This is a computed attribute of type 32 bit floating point', {}, True, None, False, ''),
('outputs:a_half', 'half', 0, None, 'This is a computed attribute of type 16 bit floating point', {}, True, None, False, ''),
('outputs:a_int', 'int', 0, None, 'This is a computed attribute of type 32 bit integer', {}, True, None, False, ''),
('outputs:a_int2', 'int2', 0, None, 'This is a computed attribute of type 2-tuple of integers', {}, True, None, False, ''),
('outputs:a_int64', 'int64', 0, None, 'This is a computed attribute of type 64 bit integer', {}, True, None, False, ''),
('outputs:a_matrix', 'matrix2d', 0, None, 'This is a computed attribute of type 2x2 matrix', {}, True, None, False, ''),
('outputs:a_string', 'string', 0, None, 'This is a computed attribute of type string', {}, True, None, False, ''),
('outputs:a_token', 'token', 0, None, 'This is a computed attribute of type interned string with fast comparison and hashing', {}, True, None, False, ''),
('outputs:a_uchar', 'uchar', 0, None, 'This is a computed attribute of type unsigned 8 bit integer', {}, True, None, False, ''),
('outputs:a_uint', 'uint', 0, None, 'This is a computed attribute of type unsigned 32 bit integer', {}, True, None, False, ''),
('outputs:a_uint64', 'uint64', 0, None, 'This is a computed attribute of type unsigned 64 bit integer', {}, 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.a_matrix = og.AttributeRole.MATRIX
role_data.inputs.a_string = og.AttributeRole.TEXT
role_data.outputs.a_matrix = og.AttributeRole.MATRIX
role_data.outputs.a_string = og.AttributeRole.TEXT
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 a_array(self):
data_view = og.AttributeValueHelper(self._attributes.a_array)
return data_view.get()
@a_array.setter
def a_array(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_array)
data_view = og.AttributeValueHelper(self._attributes.a_array)
data_view.set(value)
self.a_array_size = data_view.get_array_size()
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_bool)
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double)
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float)
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_half)
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int)
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int2)
data_view = og.AttributeValueHelper(self._attributes.a_int2)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int64)
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_matrix(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
return data_view.get()
@a_matrix.setter
def a_matrix(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_matrix)
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
data_view.set(value)
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get()
@a_string.setter
def a_string(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_string)
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_token)
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
return data_view.get()
@a_uchar.setter
def a_uchar(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_uchar)
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
data_view.set(value)
@property
def a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint)
return data_view.get()
@a_uint.setter
def a_uint(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_uint)
data_view = og.AttributeValueHelper(self._attributes.a_uint)
data_view.set(value)
@property
def a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
return data_view.get()
@a_uint64.setter
def a_uint64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_uint64)
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
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.a_array_size = None
self.a_string_size = None
self._batchedWriteValues = { }
@property
def a_array(self):
data_view = og.AttributeValueHelper(self._attributes.a_array)
return data_view.get(reserved_element_count=self.a_array_size)
@a_array.setter
def a_array(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_array)
data_view.set(value)
self.a_array_size = data_view.get_array_size()
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_matrix(self):
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
return data_view.get()
@a_matrix.setter
def a_matrix(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_matrix)
data_view.set(value)
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get(reserved_element_count=self.a_string_size)
@a_string.setter
def a_string(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
return data_view.get()
@a_uchar.setter
def a_uchar(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
data_view.set(value)
@property
def a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint)
return data_view.get()
@a_uint.setter
def a_uint(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_uint)
data_view.set(value)
@property
def a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
return data_view.get()
@a_uint64.setter
def a_uint64(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
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 = OgnTutorialDefaultsDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialDefaultsDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialDefaultsDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 19,763 | Python | 41.412017 | 162 | 0.601882 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTupleDataDatabase.py | """Support for simplified access to data on nodes of type omni.tutorials.TupleData
This is a tutorial node. It creates both an input and output attribute of some of the supported tuple types. The values
are modified in a simple way so that the compute can be tested.
"""
import carb
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 OgnTutorialTupleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.tutorials.TupleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_double2
inputs.a_double3
inputs.a_float2
inputs.a_float3
inputs.a_half2
inputs.a_int2
Outputs:
outputs.a_double2
outputs.a_double3
outputs.a_float2
outputs.a_float3
outputs.a_half2
outputs.a_int2
"""
# 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:a_double2', 'double2', 0, None, 'This is an attribute with two double values', {ogn.MetadataKeys.DEFAULT: '[1.1, 2.2]'}, True, [1.1, 2.2], False, ''),
('inputs:a_double3', 'double3', 0, None, 'This is an attribute with three double values', {ogn.MetadataKeys.DEFAULT: '[1.1, 2.2, 3.3]'}, True, [1.1, 2.2, 3.3], False, ''),
('inputs:a_float2', 'float2', 0, None, 'This is an attribute with two float values', {ogn.MetadataKeys.DEFAULT: '[4.4, 5.5]'}, True, [4.4, 5.5], False, ''),
('inputs:a_float3', 'float3', 0, None, 'This is an attribute with three float values', {ogn.MetadataKeys.DEFAULT: '[6.6, 7.7, 8.8]'}, True, [6.6, 7.7, 8.8], False, ''),
('inputs:a_half2', 'half2', 0, None, 'This is an attribute with two 16-bit float values', {ogn.MetadataKeys.DEFAULT: '[7.0, 8.0]'}, True, [7.0, 8.0], False, ''),
('inputs:a_int2', 'int2', 0, None, 'This is an attribute with two 32-bit integer values', {ogn.MetadataKeys.DEFAULT: '[10, 11]'}, True, [10, 11], False, ''),
('outputs:a_double2', 'double2', 0, None, 'This is a computed attribute with two double values', {}, True, None, False, ''),
('outputs:a_double3', 'double3', 0, None, 'This is a computed attribute with three double values', {}, True, None, False, ''),
('outputs:a_float2', 'float2', 0, None, 'This is a computed attribute with two float values', {}, True, None, False, ''),
('outputs:a_float3', 'float3', 0, None, 'This is a computed attribute with three float values', {}, True, None, False, ''),
('outputs:a_half2', 'half2', 0, None, 'This is a computed attribute with two 16-bit float values', {}, True, None, False, ''),
('outputs:a_int2', 'int2', 0, None, 'This is a computed attribute with two 32-bit integer values', {}, 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 a_double2(self):
data_view = og.AttributeValueHelper(self._attributes.a_double2)
return data_view.get()
@a_double2.setter
def a_double2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double2)
data_view = og.AttributeValueHelper(self._attributes.a_double2)
data_view.set(value)
@property
def a_double3(self):
data_view = og.AttributeValueHelper(self._attributes.a_double3)
return data_view.get()
@a_double3.setter
def a_double3(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double3)
data_view = og.AttributeValueHelper(self._attributes.a_double3)
data_view.set(value)
@property
def a_float2(self):
data_view = og.AttributeValueHelper(self._attributes.a_float2)
return data_view.get()
@a_float2.setter
def a_float2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float2)
data_view = og.AttributeValueHelper(self._attributes.a_float2)
data_view.set(value)
@property
def a_float3(self):
data_view = og.AttributeValueHelper(self._attributes.a_float3)
return data_view.get()
@a_float3.setter
def a_float3(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float3)
data_view = og.AttributeValueHelper(self._attributes.a_float3)
data_view.set(value)
@property
def a_half2(self):
data_view = og.AttributeValueHelper(self._attributes.a_half2)
return data_view.get()
@a_half2.setter
def a_half2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_half2)
data_view = og.AttributeValueHelper(self._attributes.a_half2)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int2)
data_view = og.AttributeValueHelper(self._attributes.a_int2)
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 a_double2(self):
data_view = og.AttributeValueHelper(self._attributes.a_double2)
return data_view.get()
@a_double2.setter
def a_double2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double2)
data_view.set(value)
@property
def a_double3(self):
data_view = og.AttributeValueHelper(self._attributes.a_double3)
return data_view.get()
@a_double3.setter
def a_double3(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double3)
data_view.set(value)
@property
def a_float2(self):
data_view = og.AttributeValueHelper(self._attributes.a_float2)
return data_view.get()
@a_float2.setter
def a_float2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float2)
data_view.set(value)
@property
def a_float3(self):
data_view = og.AttributeValueHelper(self._attributes.a_float3)
return data_view.get()
@a_float3.setter
def a_float3(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float3)
data_view.set(value)
@property
def a_half2(self):
data_view = og.AttributeValueHelper(self._attributes.a_half2)
return data_view.get()
@a_half2.setter
def a_half2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_half2)
data_view.set(value)
@property
def a_int2(self):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
return data_view.get()
@a_int2.setter
def a_int2(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int2)
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 = OgnTutorialTupleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTupleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTupleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,851 | Python | 43.842975 | 179 | 0.625933 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialExtendedTypesPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypesPy
This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types. It is identical
to OgnTutorialExtendedTypes.ogn, except the language of implementation is selected to be python.
"""
from typing import Any
import carb
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialExtendedTypesPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypesPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.flexible
inputs.floatOrToken
inputs.toNegate
inputs.tuple
Outputs:
outputs.doubledResult
outputs.flexible
outputs.negatedResult
outputs.tuple
"""
# 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:flexible', 'float[3][],token', 1, 'Flexible Values', 'Flexible data type input', {}, True, None, False, ''),
('inputs:floatOrToken', 'float,token', 1, 'Float Or Token', 'Attribute that can either be a float value or a token value', {}, True, None, False, ''),
('inputs:toNegate', 'bool[],float[]', 1, 'To Negate', 'Attribute that can either be an array of booleans or an array of floats', {}, True, None, False, ''),
('inputs:tuple', 'any', 2, 'Tuple Values', 'Variable size/type tuple values', {}, True, None, False, ''),
('outputs:doubledResult', 'any', 2, 'Doubled Input Value', "If the input 'floatOrToken' is a float this is 2x the value.\nIf it is a token this contains the input token repeated twice.", {}, True, None, False, ''),
('outputs:flexible', 'float[3][],token', 1, 'Inverted Flexible Values', 'Flexible data type output', {}, True, None, False, ''),
('outputs:negatedResult', 'bool[],float[]', 1, 'Negated Array Values', "Result of negating the data from the 'toNegate' input", {}, True, None, False, ''),
('outputs:tuple', 'any', 2, 'Negative Tuple Values', 'Negated values of the tuple input', {}, 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 flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, True)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def floatOrToken(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.floatOrToken"""
return og.RuntimeAttribute(self._attributes.floatOrToken.get_attribute_data(), self._context, True)
@floatOrToken.setter
def floatOrToken(self, value_to_set: Any):
"""Assign another attribute's value to outputs.floatOrToken"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.floatOrToken.value = value_to_set.value
else:
self.floatOrToken.value = value_to_set
@property
def toNegate(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.toNegate"""
return og.RuntimeAttribute(self._attributes.toNegate.get_attribute_data(), self._context, True)
@toNegate.setter
def toNegate(self, value_to_set: Any):
"""Assign another attribute's value to outputs.toNegate"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.toNegate.value = value_to_set.value
else:
self.toNegate.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, True)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.value = value_to_set
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 doubledResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.doubledResult"""
return og.RuntimeAttribute(self._attributes.doubledResult.get_attribute_data(), self._context, False)
@doubledResult.setter
def doubledResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.doubledResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.doubledResult.value = value_to_set.value
else:
self.doubledResult.value = value_to_set
@property
def flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, False)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def negatedResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.negatedResult"""
return og.RuntimeAttribute(self._attributes.negatedResult.get_attribute_data(), self._context, False)
@negatedResult.setter
def negatedResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.negatedResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.negatedResult.value = value_to_set.value
else:
self.negatedResult.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, False)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.value = value_to_set
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 = OgnTutorialExtendedTypesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialExtendedTypesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialExtendedTypesPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.ExtendedTypesPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialExtendedTypesPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialExtendedTypesPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialExtendedTypesPyDatabase(node)
try:
compute_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialExtendedTypesPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialExtendedTypesPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialExtendedTypesPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialExtendedTypesPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Extended Attribute Types")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types. It is identical to OgnTutorialExtendedTypes.ogn, except the language of implementation is selected to be python.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.ExtendedTypesPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialExtendedTypesPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialExtendedTypesPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialExtendedTypesPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.ExtendedTypesPy")
| 16,110 | Python | 49.823344 | 290 | 0.646369 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuExtendedDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuExtended
This is a tutorial node. It exercises functionality for accessing data in extended attributes that are on the GPU as well
as those whose CPU/GPU location is decided at runtime. The compute adds the two inputs 'gpuData' and 'cpuData' together,
placing the result in `cpuGpuSum`, whose memory location is determined by the 'gpu' flag. This node is identical to OgnTutorialCpuGpuExtendedPy.ogn,
except is is implemented in C++.
"""
from typing import Any
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCpuGpuExtendedDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuExtended
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cpuData
inputs.gpu
inputs.gpuData
Outputs:
outputs.cpuGpuSum
"""
# 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:cpuData', 'any', 2, 'CPU Input Attribute', 'Input attribute whose data always lives on the CPU', {}, True, None, False, ''),
('inputs:gpu', 'bool', 0, 'Results To GPU', 'If true then put the sum on the GPU, otherwise put it on the CPU', {}, True, False, False, ''),
('inputs:gpuData', 'any', 2, 'GPU Input Attribute', 'Input attribute whose data always lives on the GPU', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda'}, True, None, False, ''),
('outputs:cpuGpuSum', 'any', 2, 'Sum', "This is the attribute with the selected data. If the 'gpu' attribute is set to true then this\nattribute's contents will be entirely on the GPU, otherwise it will be on the CPU.", {ogn.MetadataKeys.MEMORY_TYPE: 'any'}, 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 cpuData(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.cpuData"""
return og.RuntimeAttribute(self._attributes.cpuData.get_attribute_data(), self._context, True)
@cpuData.setter
def cpuData(self, value_to_set: Any):
"""Assign another attribute's value to outputs.cpuData"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.cpuData.value = value_to_set.value
else:
self.cpuData.value = value_to_set
@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 gpuData(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.gpuData"""
return og.RuntimeAttribute(self._attributes.gpuData.get_attribute_data(), self._context, True)
@gpuData.setter
def gpuData(self, value_to_set: Any):
"""Assign another attribute's value to outputs.gpuData"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.gpuData.value = value_to_set.value
else:
self.gpuData.value = value_to_set
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 cpuGpuSum(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.cpuGpuSum"""
return og.RuntimeAttribute(self._attributes.cpuGpuSum.get_attribute_data(), self._context, False)
@cpuGpuSum.setter
def cpuGpuSum(self, value_to_set: Any):
"""Assign another attribute's value to outputs.cpuGpuSum"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.cpuGpuSum.value = value_to_set.value
else:
self.cpuGpuSum.value = value_to_set
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 = OgnTutorialCpuGpuExtendedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuExtendedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuExtendedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,494 | Python | 49.986394 | 290 | 0.667734 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialSimpleDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.SimpleData
This is a tutorial node. It creates both an input and output attribute of every simple supported data type. The values are
modified in a simple way so that the compute modifies values.
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialSimpleDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.SimpleData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_bool
inputs.a_constant_input
inputs.a_double
inputs.a_float
inputs.a_half
inputs.a_int
inputs.a_int64
inputs.a_objectId
inputs.a_path
inputs.a_string
inputs.a_token
inputs.unsigned_a_uchar
inputs.unsigned_a_uint
inputs.unsigned_a_uint64
Outputs:
outputs.a_bool
outputs.a_double
outputs.a_float
outputs.a_half
outputs.a_int
outputs.a_int64
outputs.a_objectId
outputs.a_path
outputs.a_string
outputs.a_token
outputs.unsigned_a_uchar
outputs.unsigned_a_uint
outputs.unsigned_a_uint64
"""
# 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:a_bool', 'bool', 0, 'Sample Boolean Input', 'This is an attribute of type boolean', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('inputs:a_constant_input', 'int', 0, None, 'This is an input attribute whose value can be set but can only be connected as a source.', {ogn.MetadataKeys.OUTPUT_ONLY: '1'}, True, 0, False, ''),
('inputs:a_double', 'double', 0, None, 'This is an attribute of type 64 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_float', 'float', 0, None, 'This is an attribute of type 32 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_half', 'half', 0, 'Sample Half Precision Input', 'This is an attribute of type 16 bit float', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:a_int', 'int', 0, None, 'This is an attribute of type 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_int64', 'int64', 0, None, 'This is an attribute of type 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_objectId', 'objectId', 0, None, 'This is an attribute of type objectId', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_path', 'path', 0, None, 'This is an attribute of type path', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('inputs:a_string', 'string', 0, None, 'This is an attribute of type string', {ogn.MetadataKeys.DEFAULT: '"helloString"'}, True, "helloString", False, ''),
('inputs:a_token', 'token', 0, None, 'This is an attribute of type interned string with fast comparison and hashing', {ogn.MetadataKeys.DEFAULT: '"helloToken"'}, True, "helloToken", False, ''),
('inputs:unsigned:a_uchar', 'uchar', 0, None, 'This is an attribute of type unsigned 8 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:unsigned:a_uint', 'uint', 0, None, 'This is an attribute of type unsigned 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:unsigned:a_uint64', 'uint64', 0, None, 'This is an attribute of type unsigned 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:a_bool', 'bool', 0, 'Sample Boolean Output', 'This is a computed attribute of type boolean', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('outputs:a_double', 'double', 0, None, 'This is a computed attribute of type 64 bit floating point', {ogn.MetadataKeys.DEFAULT: '5.0'}, True, 5.0, False, ''),
('outputs:a_float', 'float', 0, None, 'This is a computed attribute of type 32 bit floating point', {ogn.MetadataKeys.DEFAULT: '4.0'}, True, 4.0, False, ''),
('outputs:a_half', 'half', 0, 'Sample Half Precision Output', 'This is a computed attribute of type 16 bit float', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('outputs:a_int', 'int', 0, None, 'This is a computed attribute of type 32 bit integer', {ogn.MetadataKeys.DEFAULT: '2'}, True, 2, False, ''),
('outputs:a_int64', 'int64', 0, None, 'This is a computed attribute of type 64 bit integer', {ogn.MetadataKeys.DEFAULT: '3'}, True, 3, False, ''),
('outputs:a_objectId', 'objectId', 0, None, 'This is a computed attribute of type objectId', {ogn.MetadataKeys.DEFAULT: '8'}, True, 8, False, ''),
('outputs:a_path', 'path', 0, None, 'This is a computed attribute of type path', {ogn.MetadataKeys.DEFAULT: '"/"'}, True, "/", False, ''),
('outputs:a_string', 'string', 0, None, 'This is a computed attribute of type string', {ogn.MetadataKeys.DEFAULT: '"seven"'}, True, "seven", False, ''),
('outputs:a_token', 'token', 0, None, 'This is a computed attribute of type interned string with fast comparison and hashing', {ogn.MetadataKeys.DEFAULT: '"six"'}, True, "six", False, ''),
('outputs:unsigned:a_uchar', 'uchar', 0, None, 'This is a computed attribute of type unsigned 8 bit integer', {ogn.MetadataKeys.DEFAULT: '9'}, True, 9, False, ''),
('outputs:unsigned:a_uint', 'uint', 0, None, 'This is a computed attribute of type unsigned 32 bit integer', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''),
('outputs:unsigned:a_uint64', 'uint64', 0, None, 'This is a computed attribute of type unsigned 64 bit integer', {ogn.MetadataKeys.DEFAULT: '11'}, True, 11, 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.a_objectId = og.AttributeRole.OBJECT_ID
role_data.inputs.a_path = og.AttributeRole.PATH
role_data.inputs.a_string = og.AttributeRole.TEXT
role_data.outputs.a_objectId = og.AttributeRole.OBJECT_ID
role_data.outputs.a_path = og.AttributeRole.PATH
role_data.outputs.a_string = og.AttributeRole.TEXT
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 a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_bool)
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_constant_input(self):
data_view = og.AttributeValueHelper(self._attributes.a_constant_input)
return data_view.get()
@a_constant_input.setter
def a_constant_input(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_constant_input)
data_view = og.AttributeValueHelper(self._attributes.a_constant_input)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_double)
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_float)
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_half)
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int)
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_int64)
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_objectId(self):
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
return data_view.get()
@a_objectId.setter
def a_objectId(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_objectId)
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
data_view.set(value)
@property
def a_path(self):
data_view = og.AttributeValueHelper(self._attributes.a_path)
return data_view.get()
@a_path.setter
def a_path(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_path)
data_view = og.AttributeValueHelper(self._attributes.a_path)
data_view.set(value)
self.a_path_size = data_view.get_array_size()
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get()
@a_string.setter
def a_string(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_string)
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.a_token)
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def unsigned_a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
return data_view.get()
@unsigned_a_uchar.setter
def unsigned_a_uchar(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.unsigned_a_uchar)
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
data_view.set(value)
@property
def unsigned_a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
return data_view.get()
@unsigned_a_uint.setter
def unsigned_a_uint(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.unsigned_a_uint)
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
data_view.set(value)
@property
def unsigned_a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
return data_view.get()
@unsigned_a_uint64.setter
def unsigned_a_uint64(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.unsigned_a_uint64)
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
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.a_path_size = 1
self.a_string_size = 5
self._batchedWriteValues = { }
@property
def a_bool(self):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_bool)
data_view.set(value)
@property
def a_double(self):
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_double)
data_view.set(value)
@property
def a_float(self):
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_float)
data_view.set(value)
@property
def a_half(self):
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_half)
data_view.set(value)
@property
def a_int(self):
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int)
data_view.set(value)
@property
def a_int64(self):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_int64)
data_view.set(value)
@property
def a_objectId(self):
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
return data_view.get()
@a_objectId.setter
def a_objectId(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
data_view.set(value)
@property
def a_path(self):
data_view = og.AttributeValueHelper(self._attributes.a_path)
return data_view.get(reserved_element_count=self.a_path_size)
@a_path.setter
def a_path(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_path)
data_view.set(value)
self.a_path_size = data_view.get_array_size()
@property
def a_string(self):
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get(reserved_element_count=self.a_string_size)
@a_string.setter
def a_string(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_string)
data_view.set(value)
self.a_string_size = data_view.get_array_size()
@property
def a_token(self):
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
data_view = og.AttributeValueHelper(self._attributes.a_token)
data_view.set(value)
@property
def unsigned_a_uchar(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
return data_view.get()
@unsigned_a_uchar.setter
def unsigned_a_uchar(self, value):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uchar)
data_view.set(value)
@property
def unsigned_a_uint(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
return data_view.get()
@unsigned_a_uint.setter
def unsigned_a_uint(self, value):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint)
data_view.set(value)
@property
def unsigned_a_uint64(self):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
return data_view.get()
@unsigned_a_uint64.setter
def unsigned_a_uint64(self, value):
data_view = og.AttributeValueHelper(self._attributes.unsigned_a_uint64)
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 = OgnTutorialSimpleDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialSimpleDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialSimpleDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 20,824 | Python | 44.769231 | 201 | 0.618565 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialExtendedTypesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypes
This is a tutorial node. It exercises functionality for the manipulation of the extended attribute types.
"""
from typing import Any
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialExtendedTypesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ExtendedTypes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.flexible
inputs.floatOrToken
inputs.toNegate
inputs.tuple
Outputs:
outputs.doubledResult
outputs.flexible
outputs.negatedResult
outputs.tuple
"""
# 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:flexible', 'float[3][],token', 1, 'Flexible Values', 'Flexible data type input', {}, True, None, False, ''),
('inputs:floatOrToken', 'float,token', 1, 'Float Or Token', 'Attribute that can either be a float value or a token value', {}, True, None, False, ''),
('inputs:toNegate', 'bool[],float[]', 1, 'To Negate', 'Attribute that can either be an array of booleans or an array of floats', {}, True, None, False, ''),
('inputs:tuple', 'any', 2, 'Tuple Values', 'Variable size/type tuple values', {}, True, None, False, ''),
('outputs:doubledResult', 'any', 2, 'Doubled Input Value', "If the input 'simpleInput' is a float this is 2x the value.\nIf it is a token this contains the input token repeated twice.", {}, True, None, False, ''),
('outputs:flexible', 'float[3][],token', 1, 'Inverted Flexible Values', 'Flexible data type output', {}, True, None, False, ''),
('outputs:negatedResult', 'bool[],float[]', 1, 'Negated Array Values', "Result of negating the data from the 'toNegate' input", {}, True, None, False, ''),
('outputs:tuple', 'any', 2, 'Negative Tuple Values', 'Negated values of the tuple input', {}, 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 flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, True)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def floatOrToken(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.floatOrToken"""
return og.RuntimeAttribute(self._attributes.floatOrToken.get_attribute_data(), self._context, True)
@floatOrToken.setter
def floatOrToken(self, value_to_set: Any):
"""Assign another attribute's value to outputs.floatOrToken"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.floatOrToken.value = value_to_set.value
else:
self.floatOrToken.value = value_to_set
@property
def toNegate(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.toNegate"""
return og.RuntimeAttribute(self._attributes.toNegate.get_attribute_data(), self._context, True)
@toNegate.setter
def toNegate(self, value_to_set: Any):
"""Assign another attribute's value to outputs.toNegate"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.toNegate.value = value_to_set.value
else:
self.toNegate.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, True)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.value = value_to_set
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 doubledResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.doubledResult"""
return og.RuntimeAttribute(self._attributes.doubledResult.get_attribute_data(), self._context, False)
@doubledResult.setter
def doubledResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.doubledResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.doubledResult.value = value_to_set.value
else:
self.doubledResult.value = value_to_set
@property
def flexible(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.flexible"""
return og.RuntimeAttribute(self._attributes.flexible.get_attribute_data(), self._context, False)
@flexible.setter
def flexible(self, value_to_set: Any):
"""Assign another attribute's value to outputs.flexible"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.flexible.value = value_to_set.value
else:
self.flexible.value = value_to_set
@property
def negatedResult(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.negatedResult"""
return og.RuntimeAttribute(self._attributes.negatedResult.get_attribute_data(), self._context, False)
@negatedResult.setter
def negatedResult(self, value_to_set: Any):
"""Assign another attribute's value to outputs.negatedResult"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.negatedResult.value = value_to_set.value
else:
self.negatedResult.value = value_to_set
@property
def tuple(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.tuple"""
return og.RuntimeAttribute(self._attributes.tuple.get_attribute_data(), self._context, False)
@tuple.setter
def tuple(self, value_to_set: Any):
"""Assign another attribute's value to outputs.tuple"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.tuple.value = value_to_set.value
else:
self.tuple.value = value_to_set
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 = OgnTutorialExtendedTypesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialExtendedTypesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialExtendedTypesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,390 | Python | 49.687805 | 221 | 0.648893 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialBundleAddAttributesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.BundleAddAttributes
This is a tutorial node. It exercises functionality for adding and removing attributes on output bundles.
"""
import carb
import numpy
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialBundleAddAttributesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.BundleAddAttributes
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.addedAttributeNames
inputs.removedAttributeNames
inputs.typesToAdd
inputs.useBatchedAPI
Outputs:
outputs.bundle
"""
# 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:addedAttributeNames', 'token[]', 0, None, "Names for the attribute types to be added. The size of this array must match the size\nof the 'typesToAdd' array to be legal.", {}, True, [], False, ''),
('inputs:removedAttributeNames', 'token[]', 0, None, 'Names for the attribute types to be removed. Non-existent attributes will be ignored.', {}, True, [], False, ''),
('inputs:typesToAdd', 'token[]', 0, 'Attribute Types To Add', 'List of type descriptions to add to the bundle. The strings in this list correspond to the\nstrings that represent the attribute types in the .ogn file (e.g. float[3][], colord[3], bool', {}, True, [], False, ''),
('inputs:useBatchedAPI', 'bool', 0, None, 'Controls whether or not to used batched APIS for adding/removing attributes', {}, True, False, False, ''),
('outputs:bundle', 'bundle', 0, 'Constructed Bundle', 'This is the bundle with all attributes added by compute.', {}, 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.outputs.bundle = og.AttributeRole.BUNDLE
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 addedAttributeNames(self):
data_view = og.AttributeValueHelper(self._attributes.addedAttributeNames)
return data_view.get()
@addedAttributeNames.setter
def addedAttributeNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.addedAttributeNames)
data_view = og.AttributeValueHelper(self._attributes.addedAttributeNames)
data_view.set(value)
self.addedAttributeNames_size = data_view.get_array_size()
@property
def removedAttributeNames(self):
data_view = og.AttributeValueHelper(self._attributes.removedAttributeNames)
return data_view.get()
@removedAttributeNames.setter
def removedAttributeNames(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.removedAttributeNames)
data_view = og.AttributeValueHelper(self._attributes.removedAttributeNames)
data_view.set(value)
self.removedAttributeNames_size = data_view.get_array_size()
@property
def typesToAdd(self):
data_view = og.AttributeValueHelper(self._attributes.typesToAdd)
return data_view.get()
@typesToAdd.setter
def typesToAdd(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.typesToAdd)
data_view = og.AttributeValueHelper(self._attributes.typesToAdd)
data_view.set(value)
self.typesToAdd_size = data_view.get_array_size()
@property
def useBatchedAPI(self):
data_view = og.AttributeValueHelper(self._attributes.useBatchedAPI)
return data_view.get()
@useBatchedAPI.setter
def useBatchedAPI(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.useBatchedAPI)
data_view = og.AttributeValueHelper(self._attributes.useBatchedAPI)
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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.bundle"""
return self.__bundles.bundle
@bundle.setter
def bundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.bundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.bundle.bundle = bundle
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 = OgnTutorialBundleAddAttributesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialBundleAddAttributesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialBundleAddAttributesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,372 | Python | 49.137724 | 284 | 0.671046 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialStatePyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.StatePy
This is a tutorial node. It makes use of internal state information to continuously increment an output.
"""
import carb
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialStatePyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.StatePy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.override
inputs.overrideValue
Outputs:
outputs.monotonic
"""
# 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:override', 'bool', 0, None, 'When true get the output from the overrideValue, otherwise use the internal value', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''),
('inputs:overrideValue', 'int64', 0, None, "Value to use instead of the monotonically increasing internal one when 'override' is true", {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:monotonic', 'int64', 0, None, 'Monotonically increasing output, set by internal state information', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"override", "overrideValue", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""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._attributes.override, self._attributes.overrideValue]
self._batchedReadValues = [False, 0]
@property
def override(self):
return self._batchedReadValues[0]
@override.setter
def override(self, value):
self._batchedReadValues[0] = value
@property
def overrideValue(self):
return self._batchedReadValues[1]
@overrideValue.setter
def overrideValue(self, value):
self._batchedReadValues[1] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_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 = {"monotonic", "_batchedWriteValues"}
"""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 monotonic(self):
value = self._batchedWriteValues.get(self._attributes.monotonic)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.monotonic)
return data_view.get()
@monotonic.setter
def monotonic(self, value):
self._batchedWriteValues[self._attributes.monotonic] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_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 = OgnTutorialStatePyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialStatePyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialStatePyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.StatePy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialStatePyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialStatePyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialStatePyDatabase(node)
try:
compute_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialStatePyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialStatePyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialStatePyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialStatePyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialStatePyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Internal States")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It makes use of internal state information to continuously increment an output.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.StatePy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialStatePyDatabase.INTERFACE.add_to_node_type(node_type)
node_type.set_has_state(True)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialStatePyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialStatePyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialStatePyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.StatePy")
| 12,036 | Python | 46.203921 | 197 | 0.638003 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialArrayDataDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.ArrayData
This is a tutorial node. It will compute the array 'result' as the input array 'original' with every element multiplied
by the constant 'multiplier'.
"""
import carb
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 OgnTutorialArrayDataDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.ArrayData
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.gates
inputs.info
inputs.multiplier
inputs.original
Outputs:
outputs.infoSize
outputs.negativeValues
outputs.result
"""
# 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:gates', 'bool[]', 0, None, 'Boolean mask telling which elements of the array should be multiplied', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('inputs:info', 'token[]', 0, None, 'List of strings providing commentary', {ogn.MetadataKeys.DEFAULT: '["There", "is", "no", "data"]'}, True, ['There', 'is', 'no', 'data'], False, ''),
('inputs:multiplier', 'float', 0, None, 'Multiplier of the array elements', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:original', 'float[]', 0, None, 'Array to be multiplied', {ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''),
('outputs:infoSize', 'int', 0, None, 'Number of letters in all strings in the info input', {}, True, None, False, ''),
('outputs:negativeValues', 'bool[]', 0, None, "Array of booleans set to true if the corresponding 'result' is negative", {}, True, None, False, ''),
('outputs:result', 'float[]', 0, None, 'Multiplied array', {}, 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 gates(self):
data_view = og.AttributeValueHelper(self._attributes.gates)
return data_view.get()
@gates.setter
def gates(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gates)
data_view = og.AttributeValueHelper(self._attributes.gates)
data_view.set(value)
self.gates_size = data_view.get_array_size()
@property
def info(self):
data_view = og.AttributeValueHelper(self._attributes.info)
return data_view.get()
@info.setter
def info(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.info)
data_view = og.AttributeValueHelper(self._attributes.info)
data_view.set(value)
self.info_size = data_view.get_array_size()
@property
def multiplier(self):
data_view = og.AttributeValueHelper(self._attributes.multiplier)
return data_view.get()
@multiplier.setter
def multiplier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.multiplier)
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.set(value)
@property
def original(self):
data_view = og.AttributeValueHelper(self._attributes.original)
return data_view.get()
@original.setter
def original(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.original)
data_view = og.AttributeValueHelper(self._attributes.original)
data_view.set(value)
self.original_size = data_view.get_array_size()
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.negativeValues_size = None
self.result_size = None
self._batchedWriteValues = { }
@property
def infoSize(self):
data_view = og.AttributeValueHelper(self._attributes.infoSize)
return data_view.get()
@infoSize.setter
def infoSize(self, value):
data_view = og.AttributeValueHelper(self._attributes.infoSize)
data_view.set(value)
@property
def negativeValues(self):
data_view = og.AttributeValueHelper(self._attributes.negativeValues)
return data_view.get(reserved_element_count=self.negativeValues_size)
@negativeValues.setter
def negativeValues(self, value):
data_view = og.AttributeValueHelper(self._attributes.negativeValues)
data_view.set(value)
self.negativeValues_size = data_view.get_array_size()
@property
def result(self):
data_view = og.AttributeValueHelper(self._attributes.result)
return data_view.get(reserved_element_count=self.result_size)
@result.setter
def result(self, value):
data_view = og.AttributeValueHelper(self._attributes.result)
data_view.set(value)
self.result_size = data_view.get_array_size()
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 = OgnTutorialArrayDataDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialArrayDataDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialArrayDataDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,507 | Python | 44.989189 | 193 | 0.645233 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialCpuGpuBundlesDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.CpuGpuBundles
This is a tutorial node. It exercises functionality for accessing data in bundles that are on the GPU as well as bundles
whose CPU/GPU location is decided at runtime. The compute looks for bundled attributes named 'points' and, if they are found,
computes their dot products. If the bundle on the output contains an integer array type named 'dotProducts' then the results
are placed there, otherwise a new attribute of that name and type is created on the output bundle to hold the results. This
node is identical to OgnTutorialCpuGpuBundlesPy.ogn, except it is implemented in C++.
"""
import carb
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialCpuGpuBundlesDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.CpuGpuBundles
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.cpuBundle
inputs.gpu
inputs.gpuBundle
Outputs:
outputs.cpuGpuBundle
Predefined Tokens:
tokens.points
tokens.dotProducts
"""
# 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:cpuBundle', 'bundle', 0, 'CPU Input Bundle', 'Input bundle whose data always lives on the CPU', {}, True, None, False, ''),
('inputs:gpu', 'bool', 0, 'Results To GPU', 'If true then copy gpuBundle onto the output, otherwise copy cpuBundle', {}, True, False, False, ''),
('inputs:gpuBundle', 'bundle', 0, 'GPU Input Bundle', 'Input bundle whose data always lives on the GPU', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda'}, True, None, False, ''),
('outputs:cpuGpuBundle', 'bundle', 0, 'Constructed Bundle', "This is the bundle with the merged data. If the 'gpu' attribute is set to true then this\nbundle's contents will be entirely on the GPU, otherwise they will be on the CPU.", {ogn.MetadataKeys.MEMORY_TYPE: 'any'}, True, None, False, ''),
])
class tokens:
points = "points"
dotProducts = "dotProducts"
@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.cpuBundle = og.AttributeRole.BUNDLE
role_data.inputs.gpuBundle = og.AttributeRole.BUNDLE
role_data.outputs.cpuGpuBundle = og.AttributeRole.BUNDLE
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.__bundles = og.BundleContainer(context, node, attributes, ['inputs:gpuBundle'], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def cpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.cpuBundle"""
return self.__bundles.cpuBundle
@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 gpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.gpuBundle"""
return self.__bundles.gpuBundle
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.__bundles = og.BundleContainer(context, node, attributes, ['outputs_cpuGpuBundle'], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def cpuGpuBundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.cpuGpuBundle"""
return self.__bundles.cpuGpuBundle
@cpuGpuBundle.setter
def cpuGpuBundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.cpuGpuBundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.cpuGpuBundle.bundle = bundle
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 = OgnTutorialCpuGpuBundlesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialCpuGpuBundlesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialCpuGpuBundlesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,696 | Python | 50.313333 | 305 | 0.680223 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialTokensDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.Tokens
This is a tutorial node. It exercises the feature of providing hardcoded token values in the database after a node type has
been initialized. It sets output booleans to the truth value of whether corresponding inputs appear in the hardcoded token
list.
"""
import carb
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 OgnTutorialTokensDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.Tokens
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.valuesToCheck
Outputs:
outputs.isColor
Predefined Tokens:
tokens.red
tokens.green
tokens.blue
"""
# 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:valuesToCheck', 'token[]', 0, None, 'Array of tokens that are to be checked', {}, True, [], False, ''),
('outputs:isColor', 'bool[]', 0, None, 'True values if the corresponding input value appears in the token list', {}, True, None, False, ''),
])
class tokens:
red = "red"
green = "green"
blue = "blue"
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 valuesToCheck(self):
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
return data_view.get()
@valuesToCheck.setter
def valuesToCheck(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.valuesToCheck)
data_view = og.AttributeValueHelper(self._attributes.valuesToCheck)
data_view.set(value)
self.valuesToCheck_size = data_view.get_array_size()
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.isColor_size = None
self._batchedWriteValues = { }
@property
def isColor(self):
data_view = og.AttributeValueHelper(self._attributes.isColor)
return data_view.get(reserved_element_count=self.isColor_size)
@isColor.setter
def isColor(self, value):
data_view = og.AttributeValueHelper(self._attributes.isColor)
data_view.set(value)
self.isColor_size = data_view.get_array_size()
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 = OgnTutorialTokensDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialTokensDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialTokensDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,709 | Python | 44.31746 | 148 | 0.673148 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/OgnTutorialSimpleDataPyDatabase.py | """Support for simplified access to data on nodes of type omni.graph.tutorials.SimpleDataPy
This is a tutorial node. It creates both an input and output attribute of every simple supported data type. The values are
modified in a simple way so that the compute modifies values. It is the same as node omni.graph.tutorials.SimpleData, except
it is implemented in Python instead of C++.
"""
import carb
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnTutorialSimpleDataPyDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.tutorials.SimpleDataPy
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.a_bool
inputs.a_constant_input
inputs.a_double
inputs.a_float
inputs.a_half
inputs.a_int
inputs.a_int64
inputs.a_objectId
inputs.a_path
inputs.a_string
inputs.a_token
inputs.a_uchar
inputs.a_uint
inputs.a_uint64
Outputs:
outputs.a_a_boolUiName
outputs.a_bool
outputs.a_double
outputs.a_float
outputs.a_half
outputs.a_int
outputs.a_int64
outputs.a_nodeTypeUiName
outputs.a_objectId
outputs.a_path
outputs.a_string
outputs.a_token
outputs.a_uchar
outputs.a_uint
outputs.a_uint64
"""
# 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:a_bool', 'bool', 0, 'Simple Boolean Input', 'This is an attribute of type boolean', {ogn.MetadataKeys.DEFAULT: 'true'}, False, True, False, ''),
('inputs:a_constant_input', 'int', 0, None, 'This is an input attribute whose value can be set but can only be connected as a source.', {ogn.MetadataKeys.OUTPUT_ONLY: '1'}, True, 0, False, ''),
('inputs:a_double', 'double', 0, None, 'This is an attribute of type 64 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_float', 'float', 0, None, 'This is an attribute of type 32 bit floating point', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_half', 'half', 0, None, 'This is an attribute of type 16 bit float', {ogn.MetadataKeys.DEFAULT: '0.0'}, True, 0.0, False, ''),
('inputs:a_int', 'int', 0, None, 'This is an attribute of type 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_int64', 'int64', 0, None, 'This is an attribute of type 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_objectId', 'objectId', 0, None, 'This is an attribute of type objectId', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_path', 'path', 0, None, 'This is an attribute of type path', {ogn.MetadataKeys.DEFAULT: '""'}, True, "", False, ''),
('inputs:a_string', 'string', 0, None, 'This is an attribute of type string', {ogn.MetadataKeys.DEFAULT: '"helloString"'}, True, "helloString", False, ''),
('inputs:a_token', 'token', 0, None, 'This is an attribute of type interned string with fast comparison and hashing', {ogn.MetadataKeys.DEFAULT: '"helloToken"'}, True, "helloToken", False, ''),
('inputs:a_uchar', 'uchar', 0, None, 'This is an attribute of type unsigned 8 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_uint', 'uint', 0, None, 'This is an attribute of type unsigned 32 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:a_uint64', 'uint64', 0, None, 'This is an attribute of type unsigned 64 bit integer', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('outputs:a_a_boolUiName', 'string', 0, None, 'Computed attribute containing the UI name of input a_bool', {}, True, None, False, ''),
('outputs:a_bool', 'bool', 0, None, 'This is a computed attribute of type boolean', {}, True, None, False, ''),
('outputs:a_double', 'double', 0, None, 'This is a computed attribute of type 64 bit floating point', {}, True, None, False, ''),
('outputs:a_float', 'float', 0, None, 'This is a computed attribute of type 32 bit floating point', {}, True, None, False, ''),
('outputs:a_half', 'half', 0, None, 'This is a computed attribute of type 16 bit float', {}, True, None, False, ''),
('outputs:a_int', 'int', 0, None, 'This is a computed attribute of type 32 bit integer', {}, True, None, False, ''),
('outputs:a_int64', 'int64', 0, None, 'This is a computed attribute of type 64 bit integer', {}, True, None, False, ''),
('outputs:a_nodeTypeUiName', 'string', 0, None, 'Computed attribute containing the UI name of this node type', {}, True, None, False, ''),
('outputs:a_objectId', 'objectId', 0, None, 'This is a computed attribute of type objectId', {}, True, None, False, ''),
('outputs:a_path', 'path', 0, None, 'This is a computed attribute of type path', {ogn.MetadataKeys.DEFAULT: '"/Child"'}, True, "/Child", False, ''),
('outputs:a_string', 'string', 0, None, 'This is a computed attribute of type string', {ogn.MetadataKeys.DEFAULT: '"This string is empty"'}, True, "This string is empty", False, ''),
('outputs:a_token', 'token', 0, None, 'This is a computed attribute of type interned string with fast comparison and hashing', {}, True, None, False, ''),
('outputs:a_uchar', 'uchar', 0, None, 'This is a computed attribute of type unsigned 8 bit integer', {}, True, None, False, ''),
('outputs:a_uint', 'uint', 0, None, 'This is a computed attribute of type unsigned 32 bit integer', {}, True, None, False, ''),
('outputs:a_uint64', 'uint64', 0, None, 'This is a computed attribute of type unsigned 64 bit integer', {}, 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.a_objectId = og.AttributeRole.OBJECT_ID
role_data.inputs.a_path = og.AttributeRole.PATH
role_data.inputs.a_string = og.AttributeRole.TEXT
role_data.outputs.a_a_boolUiName = og.AttributeRole.TEXT
role_data.outputs.a_nodeTypeUiName = og.AttributeRole.TEXT
role_data.outputs.a_objectId = og.AttributeRole.OBJECT_ID
role_data.outputs.a_path = og.AttributeRole.PATH
role_data.outputs.a_string = og.AttributeRole.TEXT
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"a_bool", "a_constant_input", "a_double", "a_float", "a_half", "a_int", "a_int64", "a_objectId", "a_path", "a_string", "a_token", "a_uchar", "a_uint", "a_uint64", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""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._attributes.a_bool, self._attributes.a_constant_input, self._attributes.a_double, self._attributes.a_float, self._attributes.a_half, self._attributes.a_int, self._attributes.a_int64, self._attributes.a_objectId, self._attributes.a_path, self._attributes.a_string, self._attributes.a_token, self._attributes.a_uchar, self._attributes.a_uint, self._attributes.a_uint64]
self._batchedReadValues = [True, 0, 0, 0, 0.0, 0, 0, 0, "", "helloString", "helloToken", 0, 0, 0]
@property
def a_bool(self):
return self._batchedReadValues[0]
@a_bool.setter
def a_bool(self, value):
self._batchedReadValues[0] = value
@property
def a_constant_input(self):
return self._batchedReadValues[1]
@a_constant_input.setter
def a_constant_input(self, value):
self._batchedReadValues[1] = value
@property
def a_double(self):
return self._batchedReadValues[2]
@a_double.setter
def a_double(self, value):
self._batchedReadValues[2] = value
@property
def a_float(self):
return self._batchedReadValues[3]
@a_float.setter
def a_float(self, value):
self._batchedReadValues[3] = value
@property
def a_half(self):
return self._batchedReadValues[4]
@a_half.setter
def a_half(self, value):
self._batchedReadValues[4] = value
@property
def a_int(self):
return self._batchedReadValues[5]
@a_int.setter
def a_int(self, value):
self._batchedReadValues[5] = value
@property
def a_int64(self):
return self._batchedReadValues[6]
@a_int64.setter
def a_int64(self, value):
self._batchedReadValues[6] = value
@property
def a_objectId(self):
return self._batchedReadValues[7]
@a_objectId.setter
def a_objectId(self, value):
self._batchedReadValues[7] = value
@property
def a_path(self):
return self._batchedReadValues[8]
@a_path.setter
def a_path(self, value):
self._batchedReadValues[8] = value
@property
def a_string(self):
return self._batchedReadValues[9]
@a_string.setter
def a_string(self, value):
self._batchedReadValues[9] = value
@property
def a_token(self):
return self._batchedReadValues[10]
@a_token.setter
def a_token(self, value):
self._batchedReadValues[10] = value
@property
def a_uchar(self):
return self._batchedReadValues[11]
@a_uchar.setter
def a_uchar(self, value):
self._batchedReadValues[11] = value
@property
def a_uint(self):
return self._batchedReadValues[12]
@a_uint.setter
def a_uint(self, value):
self._batchedReadValues[12] = value
@property
def a_uint64(self):
return self._batchedReadValues[13]
@a_uint64.setter
def a_uint64(self, value):
self._batchedReadValues[13] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_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 = {"a_a_boolUiName", "a_bool", "a_double", "a_float", "a_half", "a_int", "a_int64", "a_nodeTypeUiName", "a_objectId", "a_path", "a_string", "a_token", "a_uchar", "a_uint", "a_uint64", "_batchedWriteValues"}
"""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.a_a_boolUiName_size = None
self.a_nodeTypeUiName_size = None
self.a_path_size = 6
self.a_string_size = 20
self._batchedWriteValues = { }
@property
def a_a_boolUiName(self):
value = self._batchedWriteValues.get(self._attributes.a_a_boolUiName)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_a_boolUiName)
return data_view.get()
@a_a_boolUiName.setter
def a_a_boolUiName(self, value):
self._batchedWriteValues[self._attributes.a_a_boolUiName] = value
@property
def a_bool(self):
value = self._batchedWriteValues.get(self._attributes.a_bool)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_bool)
return data_view.get()
@a_bool.setter
def a_bool(self, value):
self._batchedWriteValues[self._attributes.a_bool] = value
@property
def a_double(self):
value = self._batchedWriteValues.get(self._attributes.a_double)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_double)
return data_view.get()
@a_double.setter
def a_double(self, value):
self._batchedWriteValues[self._attributes.a_double] = value
@property
def a_float(self):
value = self._batchedWriteValues.get(self._attributes.a_float)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_float)
return data_view.get()
@a_float.setter
def a_float(self, value):
self._batchedWriteValues[self._attributes.a_float] = value
@property
def a_half(self):
value = self._batchedWriteValues.get(self._attributes.a_half)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_half)
return data_view.get()
@a_half.setter
def a_half(self, value):
self._batchedWriteValues[self._attributes.a_half] = value
@property
def a_int(self):
value = self._batchedWriteValues.get(self._attributes.a_int)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_int)
return data_view.get()
@a_int.setter
def a_int(self, value):
self._batchedWriteValues[self._attributes.a_int] = value
@property
def a_int64(self):
value = self._batchedWriteValues.get(self._attributes.a_int64)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_int64)
return data_view.get()
@a_int64.setter
def a_int64(self, value):
self._batchedWriteValues[self._attributes.a_int64] = value
@property
def a_nodeTypeUiName(self):
value = self._batchedWriteValues.get(self._attributes.a_nodeTypeUiName)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_nodeTypeUiName)
return data_view.get()
@a_nodeTypeUiName.setter
def a_nodeTypeUiName(self, value):
self._batchedWriteValues[self._attributes.a_nodeTypeUiName] = value
@property
def a_objectId(self):
value = self._batchedWriteValues.get(self._attributes.a_objectId)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_objectId)
return data_view.get()
@a_objectId.setter
def a_objectId(self, value):
self._batchedWriteValues[self._attributes.a_objectId] = value
@property
def a_path(self):
value = self._batchedWriteValues.get(self._attributes.a_path)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_path)
return data_view.get()
@a_path.setter
def a_path(self, value):
self._batchedWriteValues[self._attributes.a_path] = value
@property
def a_string(self):
value = self._batchedWriteValues.get(self._attributes.a_string)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_string)
return data_view.get()
@a_string.setter
def a_string(self, value):
self._batchedWriteValues[self._attributes.a_string] = value
@property
def a_token(self):
value = self._batchedWriteValues.get(self._attributes.a_token)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_token)
return data_view.get()
@a_token.setter
def a_token(self, value):
self._batchedWriteValues[self._attributes.a_token] = value
@property
def a_uchar(self):
value = self._batchedWriteValues.get(self._attributes.a_uchar)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_uchar)
return data_view.get()
@a_uchar.setter
def a_uchar(self, value):
self._batchedWriteValues[self._attributes.a_uchar] = value
@property
def a_uint(self):
value = self._batchedWriteValues.get(self._attributes.a_uint)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_uint)
return data_view.get()
@a_uint.setter
def a_uint(self, value):
self._batchedWriteValues[self._attributes.a_uint] = value
@property
def a_uint64(self):
value = self._batchedWriteValues.get(self._attributes.a_uint64)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.a_uint64)
return data_view.get()
@a_uint64.setter
def a_uint64(self, value):
self._batchedWriteValues[self._attributes.a_uint64] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_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 = OgnTutorialSimpleDataPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnTutorialSimpleDataPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnTutorialSimpleDataPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.tutorials.SimpleDataPy'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnTutorialSimpleDataPyDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnTutorialSimpleDataPyDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnTutorialSimpleDataPyDatabase(node)
try:
compute_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnTutorialSimpleDataPyDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnTutorialSimpleDataPyDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnTutorialSimpleDataPyDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnTutorialSimpleDataPyDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Attributes With Simple Data")
node_type.set_metadata(ogn.MetadataKeys.ICON_COLOR, "#FF00FF00")
node_type.set_metadata(ogn.MetadataKeys.ICON_BACKGROUND_COLOR, "#7FFF0000")
node_type.set_metadata(ogn.MetadataKeys.ICON_BORDER_COLOR, "#FF0000FF")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a tutorial node. It creates both an input and output attribute of every simple supported data type. The values are modified in a simple way so that the compute modifies values. It is the same as node omni.graph.tutorials.SimpleData, except it is implemented in Python instead of C++.")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.SimpleDataPy.svg"
node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
OgnTutorialSimpleDataPyDatabase.INTERFACE.add_to_node_type(node_type)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnTutorialSimpleDataPyDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnTutorialSimpleDataPyDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.tutorials.SimpleDataPy")
| 27,413 | Python | 44.163097 | 415 | 0.605735 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial20/OgnTutorialTokensPy.py | """
Implementation of a node handling hardcoded tokens. Tokens are a fixed set of strings, usually used for things
like keywords and enum names. In C++ tokens are more efficient than strings for lookup as they are represented
as a single long integer. The Python access methods are set up the same way, though at present there is no
differentiation between strings and tokens in Python code.
"""
class OgnTutorialTokensPy:
"""Exercise access to hardcoded tokens"""
@staticmethod
def compute(db) -> bool:
"""
Run through a list of input tokens and set booleans in a corresponding output array indicating if the
token appears in the list of hardcoded color names.
"""
values_to_check = db.inputs.valuesToCheck
# When assigning the entire array the size does not have to be set in advance
db.outputs.isColor = [value in [db.tokens.red, db.tokens.green, db.tokens.blue] for value in values_to_check]
return True
| 990 | Python | 38.639998 | 117 | 0.717172 |
omniverse-code/kit/exts/omni.graph.tutorials/omni/graph/tutorials/ogn/tutorials/tutorial17/OgnTutorialStateAttributesPy.py | """
Implementation of a Python node that uses state attributes to maintain information between evaluations.
The node has a simple monotonically increasing state output "monotonic" that can be reset by setting the state
attribute "reset" to true.
"""
class OgnTutorialStateAttributesPy:
"""Use internal node state information in addition to inputs"""
@staticmethod
def compute(db) -> bool:
"""Compute the output based on inputs and internal state"""
# State attributes are the only ones guaranteed to remember and modify their values.
# Care must be taken to set proper defaults when the node initializes, otherwise you could be
# starting in an unknown state.
if db.state.reset:
db.state.monotonic = 0
db.state.reset = False
else:
db.state.monotonic = db.state.monotonic + 1
return True
| 897 | Python | 33.53846 | 110 | 0.688963 |
Subsets and Splits