file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/ramp.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 asyncio
import functools
from tokenize import Double
import numpy as np
import omni.kit as ok
import omni.ui as ui
import omni.usd as ou
from pxr import Gf
# will be eventually unified with omni.ramp extension
class RampValues:
def __init__(self, prim_path=None,
pos_attr_name=None,
val_attr_name=None,
old_positions=None,
old_values=None,
new_positions=None,
new_values=None):
self.prim_path = prim_path
self.pos_attr_name = pos_attr_name
self.val_attr_name = val_attr_name
self.old_pos = old_positions
self.old_val = old_values
self.new_pos = new_positions
self.new_val = new_values
class IndexSetRampValuesCommand(ok.commands.Command):
def __init__(self, ramps, **kwargs):
self.ramps = ramps
def do(self):
stage = ou.get_context().get_stage()
if not stage:
return
for ramp in self.ramps:
prim = stage.GetPrimAtPath(ramp.prim_path)
if not prim:
return
if ramp.new_pos and ramp.new_val:
pos_attr = prim.GetAttribute(ramp.pos_attr_name)
val_attr = prim.GetAttribute(ramp.val_attr_name)
if pos_attr and val_attr:
pos_attr.Set(ramp.new_pos)
val_attr.Set(ramp.new_val)
def undo(self):
stage = ou.get_context().get_stage()
if not stage:
return
for ramp in self.ramps:
prim = stage.GetPrimAtPath(ramp.prim_path)
if not prim:
return
if ramp.old_pos and ramp.old_val:
pos_attr = prim.GetAttribute(ramp.pos_attr_name)
val_attr = prim.GetAttribute(ramp.val_attr_name)
if pos_attr and val_attr:
pos_attr.Set(ramp.old_pos)
val_attr.Set(ramp.old_val)
ok.commands.register(IndexSetRampValuesCommand)
class RampModel:
positions_attr_name = ""
values_attr_name = ""
default_key_positions = [0]
default_key_values = [(0, 0, 0, 0)]
ALPHA_INDEX = 3
SCALAR_INDEX = 0
def __init__(self, ramp_type, selected, prim, attr_names, default_keys=None, clamp_values=True):
self.ramp_type = ramp_type
self.context = ou.get_context()
self.prim = prim
if prim:
self.prim_path = prim.GetPath()
else:
self.prim_path = None
self.clamp_values = clamp_values
if type(attr_names) == list:
self.positions_attr_name = attr_names[0]
self.values_attr_name = attr_names[1]
if type(default_keys) == list:
self.default_key_positions = default_keys[0]
self.default_key_values = default_keys[1]
# # # widget models - subscribe to get updates
# current selected index
self.selected = selected
# value on selected index
self.value = [] * 4
# position on selected index
self.position = None
# show only range up to max_display_value
self.max_range = None
self.min_value = 0
self.max_value = 1
self.max_display_value = 1
self.key_positions_attr = None
self.key_values_attr = None
self.key_positions = []
self.key_values = []
self.num_keys = 0
self.range = 1
self.stage = self.context.get_stage()
if self.stage:
if self.prim:
self.key_positions_attr = self.prim.GetAttribute(self.positions_attr_name)
self.key_values_attr = self.prim.GetAttribute(self.values_attr_name)
# public
# call this when the ramp has to sync with the usd stage
def update(self):
#print("update")
self.stage = self.context.get_stage()
if not self.stage:
return -1
self.prim = self.stage.GetPrimAtPath(self.prim_path)
if not self.prim:
return -1
self.key_positions_attr = self.prim.GetAttribute(self.positions_attr_name)
self.key_values_attr = self.prim.GetAttribute(self.values_attr_name)
self.initialize_if_empty_ramp()
if self.key_positions_attr:
self.key_positions = list(self.key_positions_attr.Get())
if self.key_values_attr:
self.key_values = list(self.key_values_attr.Get())
self.update_num_keys()
if len(self.key_positions) <= self.selected.as_int:
return len(self.key_positions) - 1
if len(self.key_values) <= self.selected.as_int:
return len(self.key_values) - 1
return -1
def update_position(self):
#print("update position")
if not self.position:
return
index = self.selected.as_int
position = self.position.as_float
self.key_positions = list(self.key_positions_attr.Get())
self.key_values = list(self.key_values_attr.Get())
# update keys data, order them if user dragged one in front, or behind others
self.key_positions[index] = position
new_index = self.order_keys(index, position)
if new_index != index:
self.key_values_attr.Set(self.key_values)
return new_index
def save_and_select_position(self, index):
self.key_positions_attr.Set(self.key_positions)
self.select_index(index)
def update_value(self, is_scalar=False, scalar_index=-1):
#print("update value: scalar: "+str(is_scalar)+" index: "+str(scalar_index) + " (clamping: "+str(self.clamp_values)+", ramptype: "+self.ramp_type+")")
#print(" - self value: "+str(self.value))
if not self.value:
return
# get currently selected key
index = self.selected.as_int
if is_scalar:
if scalar_index < 0:
value = self.value[RampModel.SCALAR_INDEX].as_float
else:
value = self.value[scalar_index].as_float
# clamp set value
if self.clamp_values:
value = max(self.min_value, value)
if scalar_index < 0:
self.key_values[index] = value
else:
self.key_values[index][scalar_index] = value
self.update_limits(scalar_index)
else:
if self.clamp_values:
value_r = max(self.min_value, self.value[0].as_float)
value_g = max(self.min_value, self.value[1].as_float)
value_b = max(self.min_value, self.value[2].as_float)
# get alpha value from RGBA array
value_alpha = self.key_values[index][RampModel.ALPHA_INDEX]
self.key_values[index] = Gf.Vec4f(value_r, value_g, value_b, value_alpha)
else:
# get alpha value from RGBA array
value_alpha = self.key_values[index][RampModel.ALPHA_INDEX]
self.key_values[index] = Gf.Vec4f(self.value[0].as_float, self.value[1].as_float, self.value[2].as_float, value_alpha)
# update key value entries
self.key_values_attr.Set(self.key_values)
def update_limits(self, scalar_index):
#print("update limits on "+str(self.ramp_type)+" ["+str(self.min_value)+","+str(self.max_value)+"], scalar index: "+str(scalar_index))
if len(self.key_values) == 0:
return
if self.max_range and self.max_range.as_bool:
self.max_value = 1
self.range = self.max_display_value - self.min_value
else:
if (scalar_index < 0):
# check ramp type
if (self.ramp_type == "alpha"):
# select max only from alpha entries
#self.max_value = max(np.array(self.key_values).T[self.ALPHA_INDEX])
# AK: use fixed max range
self.max_value = 1.0
else:
# select max from all values
#self.max_value = max(self.key_values)
# AK: use fixed range
self.max_value = 1.0
else:
#max(np.array(self.key_values).T[scalar_index])
self.max_value = 1.0
self.range = self.max_value - self.min_value
self.range = self.max_value - self.min_value
def save_position(self, index, position):
# update widgets
self.position.set_value(position)
def save_value(self, value, is_scalar, scalar_index):
self.key_values = list(self.key_values_attr.Get())
index = self.selected.as_int
if is_scalar:
# AK: update widgets
if scalar_index < 0:
#print(" * ramp.save_value: set scalar index with negative index: "+ str(scalar_index))
#print(" - retrieving value ("+str(len(self.value))+") at: "+str(RampModel.SCALAR_INDEX))
#print("* - value ("+str(value)+") scalar_index: "+str(scalar_index)+ " (is_scalar: "+str(is_scalar)+")")
#print(" - selected index: "+str(self.selected.as_int))
# update currently selected value
self.value[RampModel.SCALAR_INDEX].set_value(value)
else:
#print(" - ramp ("+str(self.ramp_type)+") save_value: set scalar "+str(value)+" index: "+ str(scalar_index) + " (length value: "+str(len(self.value))+")")
#print(" - sample: "+str(self.value))
if (self.ramp_type == "alpha"): self.value[0].set_value(value)
else: self.value[scalar_index].set_value(value)
if self.clamp_values:
#print(" - ramp: set scalar index + clamp: "+ str(scalar_index))
if (self.ramp_type == "alpha"): self.value[0].set_value(max(self.min_value, value))
else: self.value[scalar_index].set_value(max(self.min_value, value))
else:
#print(" - ramp: set scalar index, no clamp: "+ str(scalar_index))
self.value[scalar_index].set_value(value)
else:
#print(" - ramp: save value, no scalar: "+ str(scalar_index))
# update widgets
if self.clamp_values:
for i in range(3):
self.value[i].set_value(max(self.min_value, value[i]))
else:
for i in range(3):
self.value[i].set_value(value[i])
# get RGBA value for a given parameter position
def lookup(self, ct):
# get parameters
num_key = len(self.key_positions)
# check default cases
if (num_key == 1): return self.key_values[0]
elif (num_key == 0): return [0.0, 0.0, 0.0, 0.0]
# init parameters
cur_id = 0
# iterate to current parameter position
for i, cur_pos in enumerate(self.key_positions):
if ct > cur_pos:
cur_id = i + 1
else:
break
cur_id = min(cur_id, num_key - 1)
# get values and parameters
cur_val = self.key_values[cur_id]
prev_val = self.key_values[max(cur_id-1,0)]
cur_t = self.key_positions[cur_id]
prev_t = self.key_positions[max(cur_id-1,0)]
# check parameter positions
cur_it = 0.0
if (cur_t != prev_t):
cur_it = min(max((ct - prev_t) / (cur_t - prev_t), 0.0), 1.0)
if isinstance(self.key_values[0], float):
# interpolate single instance
#print(" - lookup interp (ct="+str(ct)+"): "+str(cur_it)+" ("+str(prev_t)+","+str(cur_t)+") with values: prev: "+str(prev_val)+" cur:"+str(cur_val))
return (1.0 - cur_it) * prev_val + cur_it * cur_val
elif len(self.key_values[0]) == 4:
# interpolate rgba values
itr = (1.0 - cur_it) * prev_val[0] + cur_it * cur_val[0]
itg = (1.0 - cur_it) * prev_val[1] + cur_it * cur_val[1]
itb = (1.0 - cur_it) * prev_val[2] + cur_it * cur_val[2]
ita = (1.0 - cur_it) * prev_val[3] + cur_it * cur_val[3]
rgba_result = [itr, itg, itb, ita]
#print(" * lookup RGBA value: "+str(rgba_result))
return rgba_result
def add_key(self, position):
value = 0
# check if prim attributes are valid
if self.key_positions_attr.IsValid() and self.key_values_attr.IsValid():
# lookup parameter position (interpolates RGBA value)
value = self.lookup(position)
# print(" - RampModel.add_key: adding value "+str(value)+" at "+str(position)+" to ramp "+str(self.ramp_type))
self.key_positions = list(self.key_positions_attr.Get())
self.key_values = list(self.key_values_attr.Get())
self.key_positions.append(position)
self.key_values.append(value)
self.update_num_keys()
new_index = self.order_keys(self.num_keys - 1, position)
self.key_values_attr.Set(self.key_values)
return new_index
def remove_selected_key(self):
index = self.selected.as_int
self.key_positions = list(self.key_positions_attr.Get())
if len(self.key_positions) > 1:
self.key_values = list(self.key_values_attr.Get())
self.key_positions.pop(index)
self.key_values.pop(index)
self.update_num_keys()
self.key_values_attr.Set(self.key_values)
return index - 1
else:
return -1
def select_index(self, index):
#print(f"select_index {index}")
if index < 0:
return
self.selected.set_value(index)
def update_widgets(self, is_scalar=False, scalar_index=-1):
#print("update widgets")
index = self.selected.as_int
if index < 0:
return
if len(self.key_positions) <= 0 or len(self.key_values) <= 0:
return
if self.position:
self.position.set_value(self.key_positions[index])
if self.value:
if is_scalar:
if scalar_index < 0:
#print(" * ramp:update_widget: value length: "+str(len(self.value)) +" SCALAR_INDEX: "+str(RampModel.SCALAR_INDEX))
self.value[RampModel.SCALAR_INDEX].set_value(self.key_values[index][3])
else:
num_value = len(self.value)
#print("RampModel.update_widget: value length: "+str(num_value) +" index: "+str(scalar_index))
#print(" - key value length: "+str(len(self.key_values)) +" index: "+str(index)+" sample: "+str(self.key_values[0]))
if (isinstance(self.key_values[0], list)):
self.value[min(scalar_index, num_value-1)].set_value(self.key_values[index][scalar_index])
#else: print(" ! RampModel.update_widget: Warning: input is no array type.")
else:
for i in range(3):
self.value[i].set_value(self.key_values[index][i])
# private
def initialize_if_empty_ramp(self):
if self.key_positions_attr and len(self.key_positions_attr.Get()) == 0 or \
self.key_values_attr and len(self.key_values_attr.Get()) == 0:
self.key_positions_attr.Set(self.default_key_positions)
self.key_values_attr.Set(self.default_key_values)
def order_keys(self, index, position):
self.key_positions.sort()
new_index = self.key_positions.index(position, 0, self.num_keys)
if new_index != index:
value = self.key_values.pop(index)
self.key_values.insert(new_index, value)
return new_index
def update_num_keys(self):
num_positions = len(self.key_positions)
num_keys = len(self.key_values)
self.num_keys = min(num_positions, num_keys)
#print(f"num keys: {self.num_keys}")
init_key_positions = None
init_key_values = None
def store_undo_data(self):
#print("store undo data")
self.init_key_positions = self.key_positions.copy()
self.init_key_values = self.key_values.copy()
def append_to_undo_stack(self):
#print("append to undo stack")
if self.init_key_positions != self.key_positions or \
self.init_key_values != self.key_values:
return RampValues(prim_path=self.prim_path,
pos_attr_name=self.positions_attr_name,
val_attr_name=self.values_attr_name,
old_positions=self.init_key_positions,
old_values=self.init_key_values,
new_positions=self.key_positions,
new_values=self.key_values)
return None
class RampWidget:
key_handle_scalar_style = {"background_color": 0xFF909090, "border_color": 0xFF000000, "border_width": 1}
key_handle_scalar_over_range_style = {"background_color": 0xFFDFDFDF, "border_color": 0xFF000000, "border_width": 1}
key_handle_scalar_selected_style = {"background_color": 0xFF909090, "border_color": 0xFFFFFFFF, "border_width": 1}
key_handle_scalar_over_range_selected_style = {"background_color": 0xFFDFDFDF, "border_color": 0xFFFFFFFF, "border_width": 1}
key_handle_outline_style = {"background_color": 0x00000000,
"border_color": 0xFF000000,
"border_width": 1}
key_handle_selected_style = {"border_color": 0xFFFFFFFF, "border_width": 2}
key_handle_style = {"border_color": 0xFF000000, "border_width": 1}
# attr_names - a list with 2 strings specifiying attribute names (positions, values)
# default_keys - a list with 2 elements:
# key positions - a list of floats
# key values - a list of tuples
def __init__(self,
parent_widget,
model,
model_add,
model_remove,
is_scalar=False,
width=400,
height=20,
scalar_index=-1,
name=""):
self.parent_widget = parent_widget
self.model = model
self.model_add = model_add
self.model_remove = model_remove
self.is_scalar = is_scalar
self.width = width
self.height = height
self.scalar_index = scalar_index
self.name = name
self.image = None
self.key_handle_size = 10
self.key_handle_offset_x = -0.5 * self.key_handle_size
self.placers_to_indices = {}
self.indices_to_placers = {}
self.handles = {}
self.new_placer = None
self.new_placer_offset_x = None
self.new_placer_offset_y = None
self.sub_position_changed = None
self.sub_value_changed = None
self.initial_key_index = -1
self.key_index = -1
self.width_ratio = 1
self.height_ratio = 1
self.async_task_update_keys = None
self.async_task_add_new_key = None
# AK: update flag
#self.do_ramp_update = False
with ui.ZStack():
vstack = ui.VStack(height=self.height)
with vstack:
self.byte_image_provider = ui.ByteImageProvider()
self.image = ui.ImageWithProvider(self.byte_image_provider,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
mouse_pressed_fn=functools.partial(self.on_mouse_button_pressed_2, vstack),
mouse_moved_fn=functools.partial(self.on_mouse_moved_2, vstack),
mouse_released_fn=self.on_mouse_button_released_2,
style={"border_color": 0xFF000000, "border_width": 1})
self.image.set_computed_content_size_changed_fn(self.update_ui_elements)
self.zstack_keys = ui.ZStack(height=self.key_handle_size * 2)
if len(self.indices_to_placers):
placer = self.indices_to_placers[0]
self.on_mouse_button_pressed(placer)
self.update()
# public
# call this when the ramp has to sync with the usd stage
def update(self, dt=None):
#print("update")
if not self.image:
return
self.model.update()
self.update_ui_elements()
def on_shutdown(self):
self.sub_position_changed = None
self.sub_value_changed = None
self.image = None
# private
def basic_clamp(self, num):
return max(min(num, 1.0), 0.0)
def update_ui_elements(self):
#print("update ui elements")
self.width_ratio = self.image.computed_width / self.width
self.height_ratio = self.image.computed_height / self.height
if self.is_scalar:
self.model.update_limits(self.scalar_index)
selected_key_index = self.model.selected.as_int
if selected_key_index >= 0:
if self.key_index >= 0:
index = self.key_index
else:
index = self.initial_key_index
if index < 0:
index = selected_key_index
self.update_ramp()
self.async_task_update_keys = asyncio.ensure_future(self.async_update_keys())
def set_key_position(self):
#print("set key positions")
selected_key_index = self.model.selected.as_int
if selected_key_index >= 0:
if self.key_index >= 0:
index = self.key_index
else:
index = self.initial_key_index
if index < 0:
index = selected_key_index
self.update_ramp()
self.async_task_update_keys = asyncio.ensure_future(self.async_update_keys())
def set_key_value(self):
#print("set key values")
selected_key_index = self.model.selected.as_int
if selected_key_index >= 0:
if self.key_index >= 0:
index = self.key_index
else:
index = self.initial_key_index
if index < 0:
index = selected_key_index
self.update_ramp()
self.async_task_update_keys = asyncio.ensure_future(self.async_update_keys())
async def async_update_keys(self):
await ok.app.get_app().next_update_async()
self.update_keys()
def on_mouse_button_double_clicked(self, *_):
#print("delete key")
selected_key_index = self.model.selected.as_int
if selected_key_index >= 0:
self.model_remove.set_value(-1)
self.model_remove.set_value(selected_key_index)
self.initial_key_index = -1
def on_mouse_button_pressed_2(self, *arg):
#print("mouse button pressed - add key")
self.RELEASED = True
# add key on the next Kit tick
if self.async_task_add_new_key:
self.async_task_add_new_key.cancel()
self.async_task_add_new_key = asyncio.ensure_future(self.async_add_new_key_on_mouse_button_press(arg))
def on_mouse_moved_2(self, *arg):
#print("add key, moved")
vstack = arg[0]
# omni.ui bug prevents us from moving the placer right
# upon its creation, so lets calculate its position x/y
# that will be used in on_mouse_moved
cursor_position_x = arg[1]
self.new_placer_offset_x = cursor_position_x - vstack.screen_position_x
if self.is_scalar:
cursor_position_y = arg[2]
self.new_placer_offset_y = cursor_position_y - vstack.screen_position_y
self.on_mouse_moved(self.new_placer)
def update_usd_data(self):
# update usd values to send to index
cmap_prim = self.model.prim
cmap_attr = cmap_prim.GetAttribute("colormapValues")
cmap_data = cmap_attr.Get()
num_cmap = len(cmap_data)
#print(" - properties: colormapValues: "+str(num_cmap)+" ramp type: "+str(self.model.ramp_type))
key_vals = self.model.key_values
num_keys = len(key_vals)
#print(" - key values: "+str(num_keys)+" sample: "+str(key_vals[0]))
# check if current model has RGBA or alpha data
if (isinstance(key_vals[0], float)):
print("RampWidget: updating usd float type values (alpha channel only)")
# update alpha channel only
new_data = np.ones((num_cmap, 4))
for x in range(num_cmap):
ct = x / num_cmap
alpha_it = self.model.lookup(ct)
#print(" - interp alpha "+str(ct)+": "+str(alpha_it))
new_data[x] = cmap_data[x]
new_data[x][3] = max(min(alpha_it,1.0),0.0)
cmap_attr.Set(new_data)
else:
num_values = len(key_vals[0])
print("RampWidget: updating usd data with "+str(num_values)+" channel RGBA type")
# update RGBA color data in usd
new_data = np.ones((num_cmap, 4))
for x in range(num_cmap):
ct = x / num_cmap
col_it = self.model.lookup(ct)
new_data[x] = col_it
cmap_attr.Set(new_data)
def on_mouse_button_released_2(self, *_):
# write data from control points to usd RGBA field
# self.update_usd_data() # now handled directly by omni.indexusd
# if user only clicked on the ramp the self.key_index
# won't be updated by ::on_mouse_move, use the
# self.initial_key_index instead
if self.key_index < 0:
self.key_index = self.initial_key_index
if self.key_index < 0:
self.key_index = self.model.selected.as_int
if self.key_index < 0:
self.key_index = 0
self.new_placer_offset_x = None
self.new_placer_offset_y = None
# PRESSED = False
def on_mouse_button_pressed(self, placer, *_):
#print("mouse button pressed")
if self.RELEASED:
self.initial_placer_position = placer.offset_x.value
if self.is_scalar:
self.initial_placer_value = placer.offset_y.value
index = self.placers_to_indices[placer]
self.model.select_index(index)
self.RELEASED = False
def select_key(self, selected_key_index):
#print(f"select key {selected_key_index} in model "+self.model.ramp_type)
if selected_key_index < 0:
return
# establish initial index and buffer index
self.initial_key_index = selected_key_index
self.key_index = -1
if len(self.handles) == 0:
return
if self.model.num_keys != len(self.handles):
return
# highlite selected key
for ii in range(self.model.num_keys):
if self.initial_key_index == ii:
if self.is_scalar:
key_style = self.key_handle_scalar_selected_style
if self.model.max_range and self.model.max_range.as_bool:
if self.scalar_index < 0:
scalar_value = self.model.key_values[ii]
else:
scalar_value = self.model.key_values[ii][self.scalar_index]
if scalar_value > self.model.max_display_value:
key_style = self.key_handle_scalar_over_range_selected_style
self.handles[ii].set_style(key_style)
else:
self.handles[ii][2].set_style(self.key_handle_selected_style)
self.handles[ii][3].set_style(self.key_handle_selected_style)
else:
if self.is_scalar:
key_style = self.key_handle_scalar_style
if self.model.max_range and self.model.max_range.as_bool:
if self.scalar_index < 0:
scalar_value = self.model.key_values[ii]
else:
scalar_value = self.model.key_values[ii][self.scalar_index]
if scalar_value > self.model.max_display_value:
key_style = self.key_handle_scalar_over_range_style
self.handles[ii].set_style(key_style)
else:
self.handles[ii][2].set_style(self.key_handle_style)
self.handles[ii][3].set_style(self.key_handle_style)
async def async_add_new_key_on_mouse_button_press(self, *arg):
await ok.app.get_app().next_update_async()
if self.RELEASED:
#print("async add key")
vstack = arg[0][0]
cursor_position_x = arg[0][1]
position = (cursor_position_x - vstack.screen_position_x) / self.image.computed_width
self.model_add.set_value(-1)
self.model_add.set_value(position)
self.RELEASED = False
async def async_update_keys_on_mouse_button_release(self, index):
await ok.app.get_app().next_update_async()
#print("asymc mouse button released")
self.update_keys()
self.RELEASED = True
RELEASED = False
def on_mouse_button_released(self, *_):
#print("mouse button released")
self.RELEASED = True
# remap ui widgets if user reordered keys
if self.initial_key_index >= 0 and self.key_index >= 0 and self.initial_key_index != self.key_index:
placer1 = self.indices_to_placers[self.initial_key_index]
placer2 = self.indices_to_placers[self.key_index]
self.placers_to_indices[placer1] = self.key_index
self.placers_to_indices[placer2] = self.initial_key_index
self.indices_to_placers[self.initial_key_index] = placer2
self.indices_to_placers[self.key_index] = placer1
handles1 = self.handles[self.initial_key_index]
handles2 = self.handles[self.key_index]
self.handles[self.initial_key_index] = handles2
self.handles[self.key_index] = handles1
if self.is_scalar:
self.model.update_limits(self.scalar_index)
# update keys on the next tick
if self.async_task_update_keys:
self.async_task_update_keys.cancel()
if self.key_index >= 0:
index = self.key_index
else:
index = self.initial_key_index
if index < 0:
index = self.model.selected.as_int
self.async_task_update_keys = asyncio.ensure_future(self.async_update_keys_on_mouse_button_release(index))
# restore initial conditions
self.initial_key_index = -1
self.key_index = -1
self.new_placer = None
self.RELEASED = False
def on_mouse_moved(self, *arg):
#print("move key")
placer = arg[0]
y = 0
if self.new_placer_offset_x is None:
x = placer.offset_x.value
else:
x = self.new_placer_offset_x
if self.is_scalar:
# Workaround to omni.ui bug where new placers
# cannot be moved right after their creation.
# If moving existing key use it's placer position,
# otherwise use the values provided by on_mouse_moved_2.
if self.new_placer_offset_y is None:
y = placer.offset_y.value
else:
y = self.new_placer_offset_y
key_scalar_value = (self.height - y) * (self.model.range / self.height)
if key_scalar_value < self.model.min_value:
key_scalar_value = self.model.min_value
# elif key_scalar_value > self.model.max_value:
# key_scalar_value = self.model.max_value
self.model.save_value(key_scalar_value, self.is_scalar, self.scalar_index)
width = self.width * self.width_ratio
key_position = round(max(0, min(1, x / width)), 4)
if self.key_index < 0:
self.key_index = self.initial_key_index
self.model.save_position(self.key_index, key_position)
def update_ramp(self):
#print("update ramp")
self.model.initialize_if_empty_ramp()
num_pixels_x = self.width
num_pixels_y = self.height if self.is_scalar else 1
# initialize pixel values
pixels = [1] * num_pixels_x * num_pixels_y * 4
if self.model.key_positions_attr.IsValid() and self.model.key_values_attr.IsValid():
if self.is_scalar:
if self.scalar_index == RampModel.ALPHA_INDEX:
# pixels = self.ramp.get_alpha_array_as_rgba8(self.width, self.height,
# self.model.min_value, self.model.max_value,
# self.model.key_positions_attr.GetPath().pathString,
# self.model.key_values_attr.GetPath().pathString)
#self.model.key_positions
#print("creating alpha pixel map")
# create pixel pattern
if (True):
# AK: create pixel pattern
for x in range(num_pixels_x):
# interpolate alpha value
xt = float(x / num_pixels_x)
cur_rgba = self.model.lookup(xt)
cur_alpha = cur_rgba[RampModel.ALPHA_INDEX]
max_y = (1.0 - cur_alpha) * num_pixels_y
# fill column
for y in range(num_pixels_y):
index = y * num_pixels_x * 4 + x * 4
if (max_y < y):
pixels[index + 0] = 0.5
pixels[index + 1] = 0.5
pixels[index + 2] = 0.5
pixels[index + 3] = cur_alpha
else:
pixels[index + 0] = 0.0
pixels[index + 1] = 0.0
pixels[index + 2] = 0.0
pixels[index + 3] = 0.0
elif self.scalar_index < 0:
# pixels = self.ramp.get_float_array_as_rgba8(self.width, self.height,
# self.model.min_value, self.model.range - self.model.min_value,
# self.model.key_positions_attr.GetPath().pathString,
# self.model.key_values_attr.GetPath().pathString)
#print("creating float pixel map (sample: "+str(self.model.key_values[0])+")")
if (True):
# AK: create pixel pattern
for x in range(num_pixels_x):
# interpolate alpha value
xt = float(x / num_pixels_x)
cur_rgba = self.model.lookup(xt)
cur_alpha = cur_rgba[RampModel.ALPHA_INDEX]
max_y = (1.0 - cur_alpha) * num_pixels_y
# fill column
for y in range(num_pixels_y):
index = y * num_pixels_x * 4 + x * 4
if (max_y < y):
pixels[index + 0] = 0.5
pixels[index + 1] = 0.5
pixels[index + 2] = 0.5
pixels[index + 3] = cur_alpha
else:
pixels[index + 0] = 0.0
pixels[index + 1] = 0.0
pixels[index + 2] = 0.0
pixels[index + 3] = 0.0
# set flag
#self.do_ramp_update = False
else:
positions = [x / (num_pixels_x - 1) for x in range(num_pixels_x)]
#print("creating generic pixel map from values (#positions: "+str(len(positions))+", sample: "+str(positions[1])+")")
#print(" - num-x: "+str(num_pixels_x)+" num-y: "+str(num_pixels_y))
#print(" - length values: "+str(len(self.model.key_values)))
#print(" - positions: "+str((self.model.key_positions)))
#print(" - values: "+str((self.model.key_values)))
num_values = len(self.model.key_values)
num_positions = len(self.model.key_positions) #FIXME: find out why these are not always the same?!??
pidx = 0
# values = self.ramp.get_float4_array(positions,
# self.model.key_positions_attr.GetPath().pathString,
# self.model.key_values_attr.GetPath().pathString, "")
if True:
for x in range(num_pixels_x):
xt = x / num_pixels_x
key_pos = self.model.key_positions[pidx]
key_pos_prev = self.model.key_positions[max(pidx-1,0)]
if (key_pos != key_pos_prev):
key_it = min(max((xt - key_pos_prev) / (key_pos - key_pos_prev),0.0),1.0)
else: key_it = 0.0
key_value_next = self.model.key_values[pidx]
key_value_prev = self.model.key_values[max(pidx-1,0)]
itr = (1.0 - key_it) * key_value_prev[0] + (key_it) * key_value_next[0]
itg = (1.0 - key_it) * key_value_prev[1] + (key_it) * key_value_next[1]
itb = (1.0 - key_it) * key_value_prev[2] + (key_it) * key_value_next[2]
ita = (1.0 - key_it) * key_value_prev[3] + (key_it) * key_value_next[3]
#print(" ramp: it: "+str(key_it))
if key_pos < xt and pidx + 1 < min(num_values, num_positions):
pidx += 1
for y in range(num_pixels_y):
# pixels[index + 0] = values[x][0]
# pixels[index + 1] = values[x][1]
# pixels[index + 2] = values[x][2]
# pixels[index + 3] = values[x][3]
index = y * num_pixels_x * 4 + x * 4
pixels[index + 0] = itr
pixels[index + 1] = itg
pixels[index + 2] = itb
pixels[index + 3] = 1.0
self.byte_image_provider.set_bytes_data(pixels, [num_pixels_x, num_pixels_y])
def update_keys(self):
#print("update keys")
# currently omni.ui API cannot delete widgets - hide them instead
for placer in self.indices_to_placers.values():
placer.visible = False
for handle in self.handles.values():
if self.is_scalar:
handle.visible = False
else:
handle[0].visible = False
handle[1].visible = False
handle[2].visible = False
handle[3].visible = False
self.placers_to_indices = {}
self.indices_to_placers = {}
self.handles = {}
self.model.update_num_keys()
with self.zstack_keys:
for i in range(self.model.num_keys):
x = self.model.key_positions[i] * self.width
value = None
if self.is_scalar:
if self.model.range:
if self.scalar_index < 0:
scalar_value = self.model.key_values[i]
else:
scalar_value = self.model.key_values[i][self.scalar_index]
if self.model.max_range and self.model.max_range.as_bool:
# the key will be clamped to max display value
scalar_value = min(scalar_value, self.model.max_display_value)
y = self.height - abs((scalar_value - self.model.min_value) / self.model.range * self.height)
else:
y = self.height
else:
y = 0
value = self.model.key_values[i]
self.create_key_handle(i, x, y, value)
self.select_key(self.model.selected.as_int)
def create_key_handle(self, index, x, y, value):
offset = self.key_handle_offset_x
with ui.Placer(offset_x=offset, offset_y=offset):
placer = ui.Placer(width=self.key_handle_size,
height=self.key_handle_size,
offset_x=x * self.width_ratio,
offset_y=y * self.height_ratio,
draggable=True,
drag_axis=ui.Axis.XY if self.is_scalar else ui.Axis.X,
stable_size=True)
placer.set_offset_x_changed_fn(functools.partial(self.on_mouse_moved, placer))
if self.is_scalar:
placer.set_offset_y_changed_fn(functools.partial(self.on_mouse_moved, placer))
with placer:
with ui.ZStack(mouse_pressed_fn=functools.partial(self.on_mouse_button_pressed, placer),
mouse_released_fn=self.on_mouse_button_released):
if self.is_scalar:
circle = ui.Circle(radius=self.key_handle_size * 0.5,
mouse_double_clicked_fn=self.on_mouse_button_double_clicked,
style=self.key_handle_scalar_style)
self.handles[index] = circle
else:
with ui.Placer():
border_triangle = ui.Triangle(
width=self.key_handle_size,
height=self.key_handle_size * 0.5,
alignment=ui.Alignment.CENTER_TOP,
style=self.key_handle_outline_style
)
with ui.Placer(offset_y=self.key_handle_size * 0.5 + 0.5):
border_rectangle = ui.Rectangle(width=self.key_handle_size,
height=self.key_handle_size - 2,
style=self.key_handle_outline_style)
r = int(self.basic_clamp(value[0]) * 255)
g = int(self.basic_clamp(value[1]) * 255) << 8
b = int(self.basic_clamp(value[2]) * 255) << 16
a = 255 << 24
with ui.Placer(offset_x=1, offset_y=1):
triangle = ui.Triangle(
width=self.key_handle_size - 2,
height=self.key_handle_size * 0.5 - 1,
mouse_double_clicked_fn=self.on_mouse_button_double_clicked,
alignment=ui.Alignment.CENTER_TOP,
style={"background_color": (r + g + b + a)}
)
with ui.Placer(offset_x=1, offset_y=self.key_handle_size * 0.5 - 0.5):
rectangle = ui.Rectangle(
width=self.key_handle_size - 1.75,
height=self.key_handle_size - 2,
mouse_double_clicked_fn=self.on_mouse_button_double_clicked,
style={"background_color": (r + g + b + a)}
)
self.handles[index] = (triangle, rectangle, border_triangle, border_rectangle)
self.placers_to_indices[placer] = index
self.indices_to_placers[index] = placer
return placer
| 45,780 | Python | 38.398451 | 170 | 0.514111 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/shader_properties_widget.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 carb
import omni.ui as ui
import omni.usd as ou
from pxr import Sdf, Usd, UsdShade
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import HORIZONTAL_SPACING
from carb.input import KeyboardInput as Key
from ..presets import ShaderPresets
from .index_properties_base_widget import IndexPropertiesBaseWidget
class ShaderPropertiesWidget(IndexPropertiesBaseWidget):
def __init__(self):
super().__init__("IndeX Shader", "Shader")
self.xac_source_asset_model = None
self.xac_source_code_field = None
self.id_combo_box = None
def switch_implementation_source(self, value):
key = "info:implementationSource"
# self.request_rebuild() # update UI to change mode
self.store_value(key, value, "")
def reload_shader(self):
prim = self.get_prim()
key = "info:xac:sourceAsset"
if prim.GetAttribute("info:implementationSource").Get() == "sourceAsset" and prim.GetAttribute(key).Get():
asset = prim.GetAttribute(key).Get()
prim.GetAttribute(key).Clear() # force an update
custom = False
prim.CreateAttribute(key, Sdf.ValueTypeNames.Asset, custom, Sdf.VariabilityUniform).Set(asset)
def convert_to_source_code(self):
prim = self.get_prim()
shader = UsdShade.Shader(prim)
if not shader:
return
XAC_SOURCE_TYPE = "xac"
source_asset = shader.GetSourceAsset(XAC_SOURCE_TYPE)
if not source_asset:
return
xac_path = source_asset.resolvedPath
if not xac_path:
carb.log_error("Error: Could not resolve asset path '" + str(source_asset) + "' for prim '" + prim.GetPath().pathString + "'")
return
try:
with open(xac_path, 'r') as file:
contents = file.read()
except IOError:
carb.log_error("Error: Could not load file '" + str(xac_path) + "' for prim '" + prim.GetPath().pathString + "'")
return
self.store_value("info:xac:sourceCode", contents)
self.switch_implementation_source("sourceCode")
def update_shader(self):
self.store_value("info:xac:sourceCode", self.xac_source_code_field.model.as_string)
def load_shader_preset(self, prim, preset_name):
if prim and preset_name:
UsdShade.Shader(prim).SetSourceCode(ShaderPresets.get(preset_name), "xac")
def on_key_pressed(self, key: int, key_mod: int, key_down: bool):
key = Key(key) # Convert to enumerated type
if key == Key.F9:
self.update_shader()
def _on_prop_changed(self, path):
e = path.elementString
if e == ".info:id" and self.id_combo_box:
value = self.get_prim().GetAttribute("info:id").Get() or ""
model = self.id_combo_box.model
if value in model.get_item_list():
model.set_current_index(model.get_item_list().index(value))
else:
model.set_current_index(0)
if e == ".info:implementationSource":
self.request_rebuild()
elif e == ".info:xac:sourceAsset" and self.xac_source_asset_model:
asset = self.get_prim().GetAttribute("info:xac:sourceAsset").Get()
self.xac_source_asset_model.set_value(asset.path if asset else "")
elif e == ".info:xac:sourceCode" and self.xac_source_code_field:
source_code = self.get_prim().GetAttribute("info:xac:sourceCode").Get() or ""
self.xac_source_code_field.model.set_value(source_code)
def build_properties(self, stage, prim, prim_path):
with ui.VStack(spacing=5):
#
# implementation source: asset, source code or id
#
with ui.HStack():
# self.info_id_implementation_source_model = UsdPropertiesWidgetBuilder._tftoken_builder(
# stage,
# "info:implementationSource",
# Sdf.ValueTypeNames.Token,
# { 'allowedTokens': ['id', 'sourceAsset', 'sourceCode'], 'default': 'id', 'typeName': 'token' }, # metadata
# [ prim_path ]
# )
key = "info:implementationSource"
with ui.HStack():
self.build_label("Implementation Source")
value = prim.GetAttribute(key).Get() or ""
self.implementation_source_combo_box = ui.ComboBox(self.create_combo_list_model(value, ['id', 'sourceAsset', 'sourceCode']), name=key)
self.implementation_source_combo_box.model.add_item_changed_fn(lambda m, i: self.switch_implementation_source(m.get_current_string()))
implementation_source = prim.GetAttribute("info:implementationSource").Get() or "id"
#
# source asset
#
if implementation_source == 'sourceAsset':
with ui.HStack():
models = UsdPropertiesWidgetBuilder._sdf_asset_path_builder(
stage,
"info:xac:sourceAsset",
Sdf.ValueTypeNames.Asset,
{ Sdf.PropertySpec.DisplayNameKey: 'Source Asset', 'default': '', 'typeName': 'asset' },
[ prim_path ]
)
if isinstance(models, list):
self.xac_source_asset_model = models[0]
else:
self.xac_source_asset_model = models
with ui.HStack():
ui.Button("Reload Asset", clicked_fn=self.reload_shader, name="reloadAsset")
with ui.HStack():
ui.Button("Integrate Asset Contents", clicked_fn=self.convert_to_source_code, name="integrateAssetContents",
tooltip="Switches 'implementationSource' to 'sourceCode'")
#
# source code
#
elif implementation_source == 'sourceCode':
key = "info:xac:sourceCode"
with ui.HStack():
self.build_label("Source Code")
with ui.HStack():
source_code = prim.GetAttribute(key).Get() or ""
self.xac_source_code_field = ui.StringField(name=key, multiline=True, tabInputAllowed=True, height=200)
self.xac_source_code_field.model.set_value(source_code)
self.xac_source_code_field.set_key_pressed_fn(self.on_key_pressed)
# Don't automatically update, as that would trigger recompile on each change
#self.xac_source_code_field.model.add_value_changed_fn(self.set_script)
with ui.HStack():
ui.Button("Save and Compile [F9]", clicked_fn=self.update_shader, name="saveAndCompile")
#
# id
#
else:
key = "info:id"
with ui.HStack():
self.build_label("Implementation ID")
id_value = prim.GetAttribute(key).Get() or ""
self.id_combo_box = ui.ComboBox(self.create_combo_list_model(id_value, ['', 'nvindex:phong_gl']), name=key)
self.id_combo_box.model.add_item_changed_fn(lambda m, i: self.store_value(key, m.get_current_string(), ""))
with ui.HStack():
self.build_label("Load Shader Preset")
preset_combo_box = ui.ComboBox(self.create_combo_list_model('', [''] + ShaderPresets.get_labels()), name='loadShaderPreset')
preset_combo_box.model.add_item_changed_fn(lambda model, i: self.load_shader_preset(prim, model.get_current_string()))
| 8,320 | Python | 43.497326 | 154 | 0.579808 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/__init__.py | from .common_settings import IndeXCommonSettingStack
from .cluster_settings import IndeXClusterSettingStack
| 108 | Python | 35.333322 | 54 | 0.888889 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/index_properties_base_widget.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 asyncio
import carb.settings
from omni.kit.async_engine import run_coroutine
import omni.kit.window.property as p
import omni.usd as ou
import omni.ui as ui
from pxr import Usd, Sdf, Tf
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget
from omni.kit.window.property.templates import LABEL_WIDTH, LABEL_HEIGHT
class ComboListItem(ui.AbstractItem):
def __init__(self, item):
super().__init__()
self.model = ui.SimpleStringModel(item)
class ComboListModel(ui.AbstractItemModel):
def __init__(self, item_list, default_index):
super().__init__()
self._default_index = default_index
self._current_index = ui.SimpleIntModel(default_index)
self._current_index.add_value_changed_fn(lambda a: self._item_changed(None))
self._item_list = item_list
self._items = []
if item_list:
for item in item_list:
self._items.append(ComboListItem(item))
def get_item_children(self, item):
return self._items
def get_item_list(self):
return self._item_list
def get_item_value_model(self, item=None, column_id=-1):
if item is None:
return self._current_index
return item.model
def get_current_index(self):
return self._current_index.get_value_as_int()
def set_current_index(self, index):
self._current_index.set_value(index)
def get_current_string(self):
return self._items[self._current_index.get_value_as_int()].model.get_value_as_string()
def is_default(self):
return self.get_current_index() == self._default_index
class IndexPropertiesBaseWidget(UsdPropertiesWidget):
USD_RENDERSETTINGS = 'nvindex.renderSettings'
def __init__(self, title, element_types):
super().__init__(title, collapsed=False, multi_edit=False)
if not isinstance(element_types, list):
element_types = [element_types]
self.element_types = element_types
w = p.get_window()
w.register_widget("prim", self.element_types[0], self)
settings = carb.settings.get_settings()
self.show_advanced_settings = settings.get("/nvindex/showAdvancedSettings")
def clean(self):
self.reset()
super().clean()
def reset(self):
super().reset()
def on_shutdown(self):
w = p.get_window()
w.unregister_widget("prim", self.element_types[0])
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
if len(self._payload) == 0:
return False
for path in self._payload:
prim = self._get_prim(path)
if prim is None:
return False
if prim.GetTypeName() in self.element_types:
return True
return False
def get_prim(self):
return ou.get_context().get_stage().GetPrimAtPath(self._payload[-1])
# def get_script(self):
# stage = ou.get_context().get_stage()
# return stage.GetPrimAtPath(self._payload[-1]).GetAttribute("inputs:script").Get() or ""
def set_render_setting(self, key, value, default):
prim = self.get_prim()
#render_settings = prim.GetCustomDataByKey(self.USD_RENDERSETTINGS)
path = self.USD_RENDERSETTINGS + ":" + key
if value == default:
prim.ClearCustomDataByKey(path )
# if render_settings and key in render_settings:
# del render_settings[key]
else:
prim.SetCustomDataByKey(path, value)
# if render_settings == None:
# render_settings = {}
# render_settings[key] = value
# if render_settings:
# prim.SetCustomDataByKey(self.USD_RENDERSETTINGS, render_settings)
# else:
# prim.ClearCustomDataByKey(self.USD_RENDERSETTINGS)
def set_volume_type(self, combo_model, item):
prim = self.get_prim()
volume_type = combo_model.get_current_string()
if volume_type == "default":
prim.GetAttribute("nvindex:type").Clear()
else:
prim.CreateAttribute("nvindex:type", Sdf.ValueTypeNames.Token, True, Sdf.VariabilityUniform).Set(volume_type)
def _on_domain_changed(self, *args):
pass
# self.target_attrib_name_model._set_dirty()
def create_combo_list_model(self, current_value, items_list):
index = 0
if current_value in items_list:
index = items_list.index(current_value)
return ComboListModel(items_list, index)
def build_label(self, caption, full_width=False):
if full_width:
ui.Label(caption, name="label", word_wrap=True, height=LABEL_HEIGHT)
else:
ui.Label(caption, name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT)
def store_value(self, key, value, default = '', valueType = Sdf.ValueTypeNames.String, custom = False):
prim = self.get_prim()
if value == default:
prim.GetAttribute(key).Clear()
else:
prim.CreateAttribute(key, valueType, custom, Sdf.VariabilityUniform).Set(value)
def get_render_setting_value(self, key, default, render_settings):
if render_settings and key in render_settings:
return render_settings[key]
else:
return default
def build_render_setting_combo_box(self, caption, key, items_list, render_settings):
with ui.HStack():
self.build_label(caption)
current_value = self.get_render_setting_value(key, "default", render_settings)
index = 0
if current_value in items_list:
index = items_list.index(current_value)
widget = ui.ComboBox(self.create_combo_list_model(current_value, items_list), name=key)
widget.model.add_item_changed_fn(lambda m, i: self.set_render_setting(key, m.get_current_string(), "default"))
def build_render_setting_float(self, caption, key, default, render_settings):
with ui.HStack():
self.build_label(caption)
current_value = self.get_render_setting_value(key, default, render_settings)
widget = ui.FloatField(name=key)
widget.model.set_value(current_value)
widget.model.add_value_changed_fn(lambda m: self.set_render_setting(key, m.get_value_as_float(), default))
def build_render_setting_int(self, caption, key, default, render_settings):
with ui.HStack():
self.build_label(caption)
current_value = self.get_render_setting_value(key, default, render_settings)
widget = ui.IntField(name=key)
widget.model.set_value(current_value)
widget.model.add_value_changed_fn(lambda m: self.set_render_setting(key, m.get_value_as_int(), default))
def build_render_setting_bool(self, caption, key, default, render_settings):
with ui.HStack():
self.build_label(caption)
current_value = self.get_render_setting_value(key, default, render_settings)
widget = ui.CheckBox(name=key)
widget.model.set_value(current_value)
widget.model.add_value_changed_fn(lambda m: self.set_render_setting(key, m.get_value_as_bool(), default))
# Copied from UsdPropertiesWidget with minor changes (force rebuild on
# non-property change, to handle modified custom data)
def _on_usd_changed(self, notice, stage):
if stage != self._payload.get_stage():
return
if not self._collapsable_frame:
return
if len(self._payload) == 0:
return
if self._pending_rebuild_task is not None:
return
dirty_paths = set()
for path in notice.GetResyncedPaths():
if path in self._payload:
self.request_rebuild()
return
elif path.GetPrimPath() in self._payload:
prop = stage.GetPropertyAtPath(path)
if (not prop.IsValid()) != (self._models.get(path) is None):
self.request_rebuild()
return
else:
dirty_paths.add(path)
for path in notice.GetChangedInfoOnlyPaths():
dirty_paths.add(path)
if path in self._payload and not path.IsPropertyPath():
# Handle changed custom data
self.request_rebuild()
return
self._pending_dirty_paths.update(dirty_paths)
if self._pending_dirty_task_or_future is None:
self._pending_dirty_task_or_future = run_coroutine(self._delayed_dirty_handler())
def build_items(self):
self.reset()
if len(self._payload) == 0:
return
prim_path = self._payload[-1]
last_prim = self._get_prim(prim_path)
if not last_prim:
return
stage = last_prim.GetStage()
if not stage:
return
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage)
self.build_properties(stage, last_prim, prim_path)
| 9,656 | Python | 34.766667 | 122 | 0.619615 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/colormap.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 as ok
import omni.ui as ui
import omni.usd as ou
from .ramp import RampWidget, RampModel
class ColorMap:
def rebuild_ramp(self):
self.parent_widget.rebuild()
def __init__(self,
parent_widget,
prim,
attr_names=["xPoints", "rgbaPoints"],
width=400,
height=20,
height_scalar=50,
label="",
clamp_values=True):
self.parent_widget = parent_widget
self.label = label
self.selected_model = ui.SimpleIntModel(-1)
self.selected_model.add_value_changed_fn(self.select_key)
self.rgba_model = RampModel("rgba", self.selected_model, prim, [attr_names[0], attr_names[1]], [[0], [(1, 1, 1, 1)]], True)
#self.rgba_model = RampModel(self.selected_model, prim, [attr_names[0], attr_names[1]], [default_positions, default_values], clamp_values)
self.alpha_model = RampModel("alpha", self.selected_model, prim, [attr_names[0], attr_names[1]], [[0], [(1, 1, 1, 1)]], True)
#self.alpha_model = RampModel(self.selected_model, prim, [attr_names[0], attr_names[2]], [default_positions, default_scale], clamp_values)
self.alpha_model.selected.add_value_changed_fn(self.select_key)
self.add_key_model = ui.SimpleFloatModel(0)
self.add_key_model.add_value_changed_fn(self.add_key)
self.remove_key_model = ui.SimpleIntModel(0)
self.remove_key_model.add_value_changed_fn(self.remove_key)
self.margin = 2
self.max_display_intensity = 1
self.ramp_widget_rgb = None
self.ramp_widget_alpha = None
self.intensity_range = None
self.alpha_range = None
ok.undo.subscribe_on_change(self.undo_redo_on_change)
usd_watcher = ou.get_watcher()
self.usd_subscription = usd_watcher.subscribe_to_change_info_path(
prim.GetPath(), self.on_usd_changed
)
from omni.kit.window.property.templates import LABEL_WIDTH, HORIZONTAL_SPACING
with self.parent_widget:
with ui.HStack(spacing=HORIZONTAL_SPACING):
if label != "":
ui.Label(self.label, style={"alignment": ui.Alignment.RIGHT_TOP}, width=LABEL_WIDTH)
ui.Spacer(width=HORIZONTAL_SPACING)
with ui.VStack(height=0, spacing=12):
with ui.HStack(spacing=HORIZONTAL_SPACING):
ui.Label(" ", style={"alignment": ui.Alignment.LEFT})
with ui.HStack():
ui.Spacer(width=HORIZONTAL_SPACING)
self.ramp_widget_alpha = RampWidget(
parent_widget,
self.alpha_model,
self.add_key_model,
self.remove_key_model,
True,
width,
height_scalar,
scalar_index=RampModel.ALPHA_INDEX,
name="alpha")
with ui.HStack():
ui.Spacer(width=HORIZONTAL_SPACING)
self.ramp_widget_rgb = RampWidget(
parent_widget,
self.rgba_model,
self.add_key_model,
self.remove_key_model,
False,
width,
height,
name="rgb")
with ui.HStack(style={"margin": self.margin}):
# element to change parameter position
ui.Label("position", alignment=ui.Alignment.RIGHT_CENTER)
self.position_drag = ui.FloatDrag(width=50, min=0, max=1, name="colormapPointPosition")
self.position_changed = self.position_drag.model.subscribe_value_changed_fn(self.set_key_position)
self.rgba_model.position = self.position_drag.model
self.alpha_model.position = self.position_drag.model
# add label for alpha & color selector
ui.Label("color", alignment=ui.Alignment.RIGHT_CENTER)
# add color selector widget
self.value_widget = ui.ColorWidget(0.0, 0.0, 0.0, width=50,name="colormapPointColor")
self.sub_value_changed = self.value_widget.model.add_item_changed_fn(self.set_rgb)
sub_models = self.value_widget.model.get_item_children()
self.rgba_model.value.append(self.value_widget.model.get_item_value_model(sub_models[0]))
self.rgba_model.value.append(self.value_widget.model.get_item_value_model(sub_models[1]))
self.rgba_model.value.append(self.value_widget.model.get_item_value_model(sub_models[2]))
# add opacity float box, sync value in both ramp models
ui.Label("opacity", alignment=ui.Alignment.RIGHT_CENTER)
self.alpha_drag = ui.FloatDrag(width=60, min=0, max=1, name="colormapPointOpacity")
self.alpha_model.value.append(self.alpha_drag.model)
self.rgba_model.value.append(self.alpha_drag.model)
self.alpha_value_changed = self.alpha_model.value[RampModel.SCALAR_INDEX].subscribe_value_changed_fn(self.set_alpha)
ui.Spacer(width=HORIZONTAL_SPACING)
self.update_ui_elements()
self.selected_model.set_value(0)
# public
def update_ui_elements(self, *_):
# print("update_ui_elements")
# update both ramp models
new_index_rgba = self.rgba_model.update()
new_index_intensity = self.alpha_model.update()
# update values
if new_index_rgba > 0 or new_index_intensity > 0:
self.selected_model.set_value(max(new_index_rgba, new_index_intensity))
# update both ramp widgets
self.ramp_widget_rgb.update_ui_elements()
self.ramp_widget_alpha.update_ui_elements()
def on_shutdown(self):
ok.undo.unsubscribe_on_change(self.undo_redo_on_change)
self.value_widget.model.remove_item_changed_fn(self.sub_value_changed)
# clear widgets & models
self.position_changed = None
self.intensity_value_changed = None
self.alpha_value_changed = None
self.ramp_widget_rgb = None
self.rgba_model = None
self.usd_subscription = None
def undo_redo_on_change(self, cmds):
if "IndexSetRampValuesCommand" in cmds:
self.update_ui_elements()
self.update_widgets()
# private
def on_usd_changed(self, *_):
self.update_ui_elements()
self.update_widgets()
def set_key_position(self, *_):
# print("set_key_position")
# update order of all value models first
new_index = self.rgba_model.update_position()
self.alpha_model.update_position()
# then update positions
self.rgba_model.save_and_select_position(new_index)
if self.ramp_widget_rgb:
self.ramp_widget_rgb.set_key_position()
if self.ramp_widget_alpha:
self.ramp_widget_alpha.set_key_position()
def set_intensity(self, *_):
self.alpha_model.update_value(True)
if self.ramp_widget_alpha:
self.ramp_widget_alpha.set_key_value()
def set_alpha(self, *_):
self.rgba_model.update_value(True, RampModel.ALPHA_INDEX)
def set_rgb(self, *_):
self.rgba_model.update_value()
if self.ramp_widget_rgb:
self.ramp_widget_rgb.set_key_value()
def select_key(self, model):
self.update_widgets()
index = model.as_int
if self.ramp_widget_rgb:
self.ramp_widget_rgb.select_key(index)
if self.ramp_widget_alpha:
self.ramp_widget_alpha.select_key(index)
def add_key(self, model):
position = model.as_float
if position < 0:
return
self.store_undo_data()
# add value to all models first
new_index = self.rgba_model.add_key(position)
self.alpha_model.add_key(position)
self.append_to_undo_stack()
# then update positions
self.rgba_model.save_and_select_position(new_index)
self.update_ui_elements()
def remove_key(self, model):
if model.as_int < 0:
return
self.store_undo_data()
# remove value from all models first
new_index = self.rgba_model.remove_selected_key()
self.alpha_model.remove_selected_key()
# then update positions
self.rgba_model.save_and_select_position(new_index)
self.append_to_undo_stack()
self.update_ui_elements()
def update_widgets(self):
self.value_widget.model.remove_item_changed_fn(self.sub_value_changed)
# update all values
self.rgba_model.update_widgets()
self.rgba_model.update_widgets(True, RampModel.ALPHA_INDEX)
self.alpha_model.update_widgets(True)
self.sub_value_changed = self.value_widget.model.add_item_changed_fn(self.set_rgb)
def store_undo_data(self):
# print("store undo data")
self.rgba_model.store_undo_data()
self.alpha_model.store_undo_data()
def append_to_undo_stack(self):
# print("append to undo stack")
rampValues_rgba = self.rgba_model.append_to_undo_stack()
rampValues_intensity = self.alpha_model.append_to_undo_stack()
if rampValues_rgba and rampValues_intensity:
ok.commands.execute("IndexSetRampValuesCommand", ramps=[rampValues_rgba, rampValues_intensity])
| 10,369 | Python | 38.132075 | 146 | 0.582409 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/colormap_properties_widget.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 carb
import omni.ui as ui
import omni.usd as ou
from pxr import Sdf
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from ..presets import ColormapPresets
from .index_properties_base_widget import IndexPropertiesBaseWidget
from .colormap import ColorMap
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame
class ColormapPropertiesWidget(IndexPropertiesBaseWidget):
USD_RENDERSETTINGS = 'nvindex.renderSettings'
def __init__(self):
super().__init__("IndeX Colormap", "Colormap")
self.colormap_source_combo_box = None
def switch_colormap_source(self, value):
key = "colormapSource"
self.request_rebuild() # update UI to change mode
self.store_value(key, value, "colormapValues")
def load_colormap_preset(self, prim, preset_name, colormapSource):
if prim and preset_name:
if colormapSource == "rgbaPoints":
(xPoints, rgbaPoints) = ColormapPresets.generate(preset_name, colormap_source=colormapSource)
xPoints_attr = prim.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray)
xPoints_attr.Set(xPoints)
rgbaPoints_attr = prim.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array)
rgbaPoints_attr.Set(rgbaPoints)
else:
colormap_data = ColormapPresets.generate(preset_name)
colormap_attr = prim.CreateAttribute("colormapValues", Sdf.ValueTypeNames.Color4fArray)
colormap_attr.Set(colormap_data)
def build_properties(self, stage, prim, prim_path):
with ui.VStack(spacing=5):
stage = ou.get_context().get_stage()
node_prim_path = self._payload[-1]
#TODO: Make this explicit to handle missing attributes
self.domain_model = UsdPropertiesWidgetBuilder._vec2_per_channel_builder(
stage,
"domain",
Sdf.ValueTypeNames.Float2,
{ Sdf.PropertySpec.DisplayNameKey: 'Domain' }, # metadata
[ node_prim_path ]
)
with ui.HStack():
key = "domainBoundaryMode"
with ui.HStack():
self.build_label("Domain Boundary Mode")
value = prim.GetAttribute(key).Get() or ""
self.domain_boundary_mode_combo_box = ui.ComboBox(self.create_combo_list_model(value, ['clampToEdge', 'clampToTransparent']), name=key)
self.domain_boundary_mode_combo_box.model.add_item_changed_fn(lambda m, i: self.store_value("domainBoundaryMode", m.get_current_string(), 'clampToEdge', Sdf.ValueTypeNames.Token))
with ui.HStack():
key = "colormapSource"
with ui.HStack():
self.build_label("Colormap Source")
value = prim.GetAttribute(key).Get() or ""
self.colormap_source_combo_box = ui.ComboBox(self.create_combo_list_model(value, ['colormapValues', 'rgbaPoints']), name=key)
self.colormap_source_combo_box.model.add_item_changed_fn(lambda m, i: self.switch_colormap_source(m.get_current_string()))
colormapSource = prim.GetAttribute("colormapSource").Get() or "colormapValues"
if colormapSource == "rgbaPoints":
# adding custom colormap editor
frame = CustomLayoutFrame(hide_extra=True)
with frame:
colormap_frame = ui.Frame(height=0)
with colormap_frame:
ColorMap(frame, prim, ["xPoints", "rgbaPoints"])
with ui.HStack():
self.build_label("Load Colormap Preset")
preset_combo_box = ui.ComboBox(self.create_combo_list_model('', [''] + ColormapPresets.get_labels()), name='loadColormapPreset')
preset_combo_box.model.add_item_changed_fn(lambda model, i: self.load_colormap_preset(prim, model.get_current_string(), colormapSource))
| 4,502 | Python | 46.904255 | 199 | 0.639938 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/tests/__init__.py | from .test_settings import TestIndeXSettingsUI
from .test_properties import TestIndeXPropertiesUI
| 98 | Python | 31.999989 | 50 | 0.877551 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/tests/test_properties.py | #!/usr/bin/env python3
# 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.usd
from omni.kit import ui_test
from pxr import Sdf, UsdShade
# Test custom properties UI for NVIDIA IndeX
class TestIndeXPropertiesUI(omni.kit.test.AsyncTestCase):
async def setUp(self):
super().setUp()
self._usd_context = omni.usd.get_context()
from omni.hydra.index.tests import USD_DIR
test_file_path = USD_DIR.joinpath("torus-settings.usda").absolute()
await self._usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
self._stage = self._usd_context.get_stage()
self.assertIsNotNone(self._stage)
def _print_sub_widget(self, parent):
for w in parent.find_all("**"):
print("-", w, w.realpath)
if hasattr(w.widget, 'identifier') and w.widget.identifier:
print(" id =", w.widget.identifier)
if hasattr(w.widget, 'name') and w.widget.name:
print(" name =", w.widget.name)
if hasattr(w.widget, 'title') and w.widget.title:
print(" title =", w.widget.title)
# Test "IndeX Volume" properties of UsdVolume prims
async def test_volume_properties(self):
prim = self._stage.GetPrimAtPath("/World/Volume")
self.assertTrue(prim.IsValid())
# Select the prim.
self._usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True)
# Need to wait for additional frames for omni.ui rebuild to take effect
await ui_test.wait_n_updates(20)
index_volume = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='IndeX Volume'")
self.assertTrue(index_volume)
custom_data = prim.GetCustomData()
self.assertTrue('nvindex.renderSettings' in custom_data)
render_settings = custom_data['nvindex.renderSettings']
filter_mode_widget = index_volume.find("**/ComboBox[0].name=='filterMode'")
self.assertTrue(filter_mode_widget)
self.assertEqual(filter_mode_widget.model.get_current_string(), render_settings['filterMode'])
sampling_distance_widget = index_volume.find("**/FloatField[0].name=='samplingDistance'")
self.assertTrue(sampling_distance_widget)
self.assertEqual(sampling_distance_widget.model.get_value_as_float(), render_settings['samplingDistance'])
# Modify values in UI and check if USD is updated
filter_mode_widget.model.set_current_index(0) # set to default filter
# await sampling_distance_widget.input(str(2.345)) # This doesn't seem to work
sampling_distance_widget.model.set_value(2.345)
await ui_test.wait_n_updates(2)
custom_data = prim.GetCustomData()
render_settings = custom_data['nvindex.renderSettings']
self.assertTrue('filterMode' not in render_settings) # default value will not be stored
self.assertEqual(sampling_distance_widget.model.get_value_as_float(), render_settings['samplingDistance'])
# Now modify the USD and check if UI is updated
new_filter_mode = "nearest"
new_sampling_distance = 1.2345
prim.SetCustomDataByKey("nvindex.renderSettings:filterMode", new_filter_mode)
prim.SetCustomDataByKey("nvindex.renderSettings:samplingDistance", new_sampling_distance)
await omni.kit.app.get_app().next_update_async()
custom_data = prim.GetCustomData()
# Need to reacquire widgets after rebuild
filter_mode_widget = index_volume.find("**/ComboBox[0].name=='filterMode'")
self.assertTrue(filter_mode_widget)
self.assertEqual(filter_mode_widget.model.get_current_string(), new_filter_mode)
sampling_distance_widget = index_volume.find("**/FloatField[0].name=='samplingDistance'")
self.assertTrue(sampling_distance_widget)
self.assertEqual(sampling_distance_widget.model.get_value_as_float(), new_sampling_distance)
# Test "IndeX Colormap" properties of (custom) Colormap prims
async def test_colormap_properties(self):
prim = self._stage.GetPrimAtPath("/World/Volume/mat/Colormap")
self.assertTrue(prim.IsValid())
self._usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True)
await ui_test.wait_n_updates(20)
index_colormap = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='IndeX Colormap'")
self.assertTrue(index_colormap)
# Colormap domain
domain_group = index_colormap.find("**/drag_per_channel_domain")
self.assertTrue(domain_group)
domain_value = []
for float_drag in domain_group.find_all("**/FloatDrag[0]"):
domain_value.append(float_drag.widget.model.get_value_as_float())
self.assertEqual(domain_value, prim.GetAttribute("domain").Get())
# Colormap domain boundary mode
domain_boundary_mode_widget = index_colormap.find("**/ComboBox[0].name=='domainBoundaryMode'")
self.assertTrue(domain_boundary_mode_widget)
self.assertEqual(domain_boundary_mode_widget.model.get_current_string(), prim.GetAttribute("domainBoundaryMode").Get())
# Colormap source
colormap_source_widget = index_colormap.find("**/ComboBox[0].name=='colormapSource'")
self.assertTrue(colormap_source_widget)
self.assertEqual(colormap_source_widget.model.get_current_string(), "colormapValues")
# Set a simple rgbaValues colormap
prim.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray).Set([0.5, 0.7, 1.0])
prim.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array).Set([(0, 1, 0, 0.14), (1, 0, 0, 0.25), (1, 1, 0, 0.25)])
# Switch colormap source
colormap_source_widget = index_colormap.find("**/ComboBox[0].name=='colormapSource'")
colormap_source_widget.model.set_current_index(1)
await ui_test.wait_n_updates(2)
# Verify values of the first control point in colormap editor
colormap_point_position_widget = index_colormap.find("**/FloatDrag[*].name=='colormapPointPosition'")
self.assertTrue(colormap_point_position_widget)
self.assertEqual(colormap_point_position_widget.model.get_value_as_float(), prim.GetAttribute("xPoints").Get()[0])
colormap_point_color_widget = index_colormap.find("**/ColorWidget[*].name=='colormapPointColor'")
self.assertTrue(colormap_point_color_widget)
color_model = colormap_point_color_widget.model
sub_models = color_model.get_item_children(None)
rgba_value = [ color_model.get_item_value_model(s).get_value_as_float() for s in sub_models ]
colormap_point_opacity_widget = index_colormap.find("**/FloatDrag[*].name=='colormapPointOpacity'")
self.assertTrue(colormap_point_opacity_widget)
rgba_value.append(colormap_point_opacity_widget.model.get_value_as_float())
self.assertEqual(rgba_value, prim.GetAttribute("rgbaPoints").Get()[0])
# Modify values in UI and check if USD is updated
colormap_point_position_widget.model.set_value(0.2)
for s, v in zip(sub_models, [0.1, 0.2, 0.3]):
color_model.get_item_value_model(s).set_value(v)
colormap_point_opacity_widget.model.set_value(0.4)
await ui_test.wait_n_updates(2)
self.assertEqual(colormap_point_position_widget.model.get_value_as_float(), prim.GetAttribute("xPoints").Get()[0])
self.assertEqual(colormap_point_opacity_widget.model.get_value_as_float(), prim.GetAttribute("rgbaPoints").Get()[0][3])
# Load a colormap preset
load_colormap_preset_widget = index_colormap.find("**/ComboBox[0].name=='loadColormapPreset'")
self.assertTrue(load_colormap_preset_widget)
preset_name = "Green Ramp"
presets = load_colormap_preset_widget.model.get_item_list()
self.assertTrue(preset_name in presets)
load_colormap_preset_widget.model.set_current_index(presets.index(preset_name))
await ui_test.wait_n_updates(2)
self.assertEqual(prim.GetAttribute("rgbaPoints").Get()[0], [0, 1, 0, 0]) # check that USD was updated
# Test "IndeX Shader" properties of UsdShader prims
async def test_shader_properties(self):
prim = self._stage.GetPrimAtPath("/World/Volume/mat/VolumeShader")
self.assertTrue(prim.IsValid())
self._usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True)
await ui_test.wait_n_updates(20)
index_shader = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='IndeX Shader'")
self.assertTrue(index_shader)
# Shader implementation source
implementation_source_widget = index_shader.find("**/ComboBox[0].name=='info:implementationSource'")
self.assertTrue(implementation_source_widget)
self.assertEqual(implementation_source_widget.model.get_current_string(), "id")
# Provide shader from asset
implementation_source_widget.model.set_current_index(implementation_source_widget.model.get_item_list().index("sourceAsset"))
await ui_test.wait_n_updates(2)
source_asset_widget = index_shader.find("**/sdf_asset_info:xac:sourceAsset.identifier=='sdf_asset_info:xac:sourceAsset'")
self.assertTrue(source_asset_widget)
source_asset_widget.model.set_value("./torus-shader.cu")
await ui_test.wait_n_updates(2)
shader = UsdShade.Shader(prim)
self.assertTrue(shader.GetSourceAsset('xac'))
# Integrate the asset
integrate_asset_widget = index_shader.find("**/Button[*].name=='integrateAssetContents'")
self.assertTrue(integrate_asset_widget)
await integrate_asset_widget.click()
await ui_test.wait_n_updates(2)
self.assertTrue(shader.GetSourceCode('xac').startswith("NV_IDX_XAC_VERSION_1_0"))
# Edit the code
source_code_widget = index_shader.find("**/StringField[*].name=='info:xac:sourceCode'")
self.assertTrue(source_code_widget)
source_code = source_code_widget.model.get_value_as_string() + "// foo bar baz!"
source_code_widget.model.set_value(source_code)
await ui_test.wait_n_updates(2)
self.assertNotEqual(shader.GetSourceCode('xac'), source_code) # not saved yet
save_compile_widget = index_shader.find("**/Button[*].name=='saveAndCompile'")
self.assertTrue(save_compile_widget)
await save_compile_widget.click()
await ui_test.wait_n_updates(2)
self.assertEqual(shader.GetSourceCode('xac'), source_code)
# Load a shader preset
load_shader_preset_widget = index_shader.find("**/ComboBox[0].name=='loadShaderPreset'")
self.assertTrue(load_shader_preset_widget)
preset_name = "Minimal Volume Shader"
presets = load_shader_preset_widget.model.get_item_list()
self.assertTrue(preset_name in presets)
load_shader_preset_widget.model.set_current_index(presets.index(preset_name))
await ui_test.wait_n_updates(2)
self.assertTrue(shader.GetSourceCode('xac').startswith("NV_IDX_XAC_VERSION_1_0"))
self.assertTrue("foo bar baz" not in shader.GetSourceCode('xac'))
# Test the "Create Volume Material" button in "IndeX Volume" properties of UsdVolume prims
async def test_create_volume_material(self):
prim = self._stage.GetPrimAtPath("/World/Volume")
self.assertTrue(prim.IsValid())
self._usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True)
await ui_test.wait_n_updates(20)
index_volume = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='IndeX Volume'")
self.assertTrue(index_volume)
old_material = UsdShade.MaterialBindingAPI(prim).GetDirectBinding().GetMaterial()
self.assertTrue(old_material)
# Create new volume material
create_material_widget = index_volume.find("**/Button[*].name=='createVolumeMaterial'")
self.assertTrue(create_material_widget)
await create_material_widget.click()
await ui_test.wait_n_updates(2)
# Check that the material was created and bound
new_material = UsdShade.MaterialBindingAPI(prim).GetDirectBinding().GetMaterial()
self.assertTrue(new_material)
self.assertEqual(new_material.GetPath(), str(prim.GetPath()) + "/Material")
# Restore previous material
UsdShade.MaterialBindingAPI(prim).Bind(old_material)
| 12,948 | Python | 48.613027 | 133 | 0.678638 |
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/tests/test_settings.py | #!/usr/bin/env python3
# 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 carb
import omni.kit.test
import omni.usd
from omni.kit import ui_test
settings = carb.settings.get_settings()
class TestIndeXSettingsUI(omni.kit.test.AsyncTestCase):
async def setUp(self):
super().setUp()
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
def get_render_setings_window(self):
render_settings_window = ui_test.find("Render Settings")
render_settings_window.widget.height = 600
render_settings_window.widget.width = 600
render_settings_window.widget.visible = True
return render_settings_window
def assertSetting(self, setting_name, setting_value):
self.assertTrue(settings.get(setting_name) == setting_value)
async def test_settings(self):
# Set initial state
roi_min_org = [0, 0, 0]
roi_max_org = [10, 10, 10]
settings.set("/nvindex/dataBboxMin", roi_min_org)
settings.set("/nvindex/dataBboxMax", roi_max_org)
settings.set("/rtx/index/regionOfInterestMin", roi_min_org)
settings.set("/rtx/index/regionOfInterestMax", roi_max_org)
render_settings_window = self.get_render_setings_window()
self.assertTrue(render_settings_window)
# Select IndeX "Cluster" settings in the global "Render Settings" tab
button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]")
self.assertTrue(button)
await button.click()
# Cluster / Cluster Compositing Settings
collapsable_frame = render_settings_window.find("**/Cluster Compositing Settings")
self.assertTrue(collapsable_frame)
collapsable_frame.widget.collapsed = False
await omni.kit.app.get_app().next_update_async()
# Select IndeX "Common" settings in the global "Render Settings" tab
button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[1]")
self.assertTrue(button)
await button.click()
# Common / Scene Settings
collapsable_frame = render_settings_window.find("**/Scene Settings")
self.assertTrue(collapsable_frame)
collapsable_frame.widget.collapsed = False
await omni.kit.app.get_app().next_update_async()
setting_name = "/rtx/index/regionOfInterest"
roi_min_org = settings.get(setting_name + "Min")
roi_max_org = settings.get(setting_name + "Max")
setting_hstack = collapsable_frame.find("/**/HStack_Region_of_Interest_Min")
self.assertTrue(isinstance(setting_hstack.widget, omni.ui.HStack))
setting_hstack = collapsable_frame.find("/**/HStack_Region_of_Interest_Max")
self.assertTrue(isinstance(setting_hstack.widget, omni.ui.HStack))
settings.set(setting_name + "Max", [5, 10, 10])
await omni.kit.app.get_app().next_update_async()
self.assertSetting(setting_name + "Min", roi_min_org)
self.assertSetting(setting_name + "Max", [5, 10, 10])
button = collapsable_frame.find("/**/Button[0]")
self.assertTrue(button)
await button.click();
self.assertSetting(setting_name + "Min", roi_min_org)
self.assertSetting(setting_name + "Max", roi_max_org)
# Common / Render Settings
collapsable_frame = render_settings_window.find("**/Render Settings")
self.assertTrue(collapsable_frame)
collapsable_frame.widget.collapsed = False
await omni.kit.app.get_app().next_update_async()
setting_hstack = collapsable_frame.find("/**/HStack_Background_Color")
self.assertTrue(isinstance(setting_hstack.widget, omni.ui.HStack))
# Background color
setting_name = "/rtx/index/backgroundColor"
self.assertSetting(setting_name, [0.0, 0.0, 0.0]) # default
background_color_field = setting_hstack.find("**/MultiFloatDragField[0]")
self.assertTrue(background_color_field)
color_model = background_color_field.model
sub_models = color_model.get_item_children(None)
color_model.get_item_value_model(sub_models[0]).set_value(1.0)
color_model.get_item_value_model(sub_models[2]).set_value(0.25)
await omni.kit.app.get_app().next_update_async()
self.assertSetting(setting_name, [1.0, 0.0, 0.25])
| 4,792 | Python | 40.318965 | 98 | 0.673831 |
omniverse-code/kit/exts/omni.index.settings.core/docs/index.rst | omni.index.settings.core
###########################
.. toctree::
:maxdepth: 1
| 84 | reStructuredText | 11.142856 | 27 | 0.440476 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_portable.py | import omni.kit.test
from .test_base import KitLaunchTest
class TestPortable(KitLaunchTest):
async def test_kit_portable(self):
# empty kit file
kit_file = "[dependencies]\n"
# script to check portable location is as passed in
script = """
import omni.kit.app
import carb.tokens
from pathlib import Path
data = Path(carb.tokens.get_tokens_interface().resolve("${{data}}")).resolve()
portable_path = Path(r'{0}').resolve()
def is_subpath(path, root):
return root in path.parents
if not is_subpath(data, portable_path):
print(f"Fail, expected portable path: {{(portable_path)}}")
omni.kit.app.get_app().post_quit(-1)
"""
# kit.portable:
portable_file = f"{self._temp_folder}/kit.portable"
with open(portable_file, "w") as f:
f.write("foo")
portable_path = f"{self._temp_folder}/foo"
await self._run_kit_with_script(
script.format(portable_path), args=[], kit_file=kit_file, portable=False, kit_file_name="test_bar.kit"
)
# test_bar.portable (like app name) (overrides kit.portable too)
portable_file = f"{self._temp_folder}/test_bar.portable"
with open(portable_file, "w") as f:
f.write("wow")
portable_path = f"{self._temp_folder}/wow"
await self._run_kit_with_script(
script.format(portable_path), args=[], kit_file=kit_file, portable=False, kit_file_name="test_bar.kit"
)
# arg: `--portable-root` (overrides everything)
portable_path = f"{self._temp_folder}/lake"
await self._run_kit_with_script(
script.format(portable_path),
args=["--portable-root", portable_path],
kit_file=kit_file,
portable=False,
kit_file_name="test_bar.kit",
)
| 1,832 | Python | 31.157894 | 114 | 0.608079 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_non_ascii_cmd_params.py | import omni.kit.test
import omni.kit.app
from pathlib import Path
from .test_base import KitLaunchTest
class TestNonAsciiCmdParams(KitLaunchTest):
async def test_kit_app_with_only_core_exts(self):
# Disabling tests untill OM-39027 is resolved
return
kit_file = "[dependencies]\n"
kit_file += '"omni.kit.loop-default" = {}\n'
script = """
import carb.settings
import omni.kit.app
s = carb.settings.get_settings()
def check(path, expected):
v = s.get(path)
if v != expected:
print(f"[Test Fail] setting path: {path}, expected: {expected}, got: {v}")
omni.kit.app.get_app().post_quit(-1)
"""
testParamPaths = ["/my/test/unicode_param", "/my/test/usual_param", "/my/test/unicode_param2"]
testParamValues = ["\U0001F44D", "test", "\u0627\u1F600"]
# Adding checks if unicode params were properly set into settings
script += "".join(map(lambda x, y: f"check(\"{x}\", \"{y}\")\n", testParamPaths, testParamValues))
# Making sure the executed script has proper unicode symbols
script += f"""
test_unicode_char = \"{testParamValues[0]}\"
test_char_code = ord(test_unicode_char)
expected_code = 128077
if test_char_code != expected_code:
print(f"[Test Fail] Wrong tested unicode character code: {{test_unicode_char}}, expected: {{expected_code}}, got: {{test_char_code}}")
omni.kit.app.get_app().post_quit(-1)
"""
# Adding necessary command line arguments
additional_args = [*map(lambda x, y: f"--{x}={y}", testParamPaths, testParamValues)]
await self._run_kit_with_script(script, args=["--/app/quitAfter=10", *additional_args], kit_file=kit_file)
| 1,697 | Python | 33.653061 | 138 | 0.647613 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_default_stage.py | import omni.kit.test
from .test_base import KitLaunchTest
from pathlib import Path
import omni
class TestDefaultStage(KitLaunchTest):
async def test_default_stage(self):
"""Test to ensure a default stage is created when it's requested."""
kit_file = "[dependencies]\n"
kit_file += '"omni.usd" = {}\n'
kit_file += '"omni.kit.loop-default" = {}\n'
kit_file += '"omni.kit.stage_templates" = {}\n'
kit_file += """
# Register extension folder from this repo in kit
[settings.app.exts]
folders.'++' = ["${app}/../exts" ]
[settings.app.extensions]
enabledDeprecated = [
]
"""
script = f"""
import omni.usd
import omni.kit.app
import asyncio
from pxr import Sdf, Usd
async def main():
for i in range(10):
await omni.kit.app.get_app().next_update_async()
usd_context = omni.usd.get_context()
# Gets stage to see if a default stage is created.
stage = usd_context.get_stage()
stage.DefinePrim("/test")
asyncio.ensure_future(main())
"""
await self._run_kit_with_script(
script,
args=["--no-window", "--/app/quitAfter=20", "--/app/content/emptyStageOnStart=True"],
kit_file=kit_file
)
| 1,293 | Python | 24.372549 | 97 | 0.584687 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_runloop.py | import omni.kit.test
from .test_base import KitLaunchTest
class TestKitRunLoop(KitLaunchTest):
async def test_kit_runloop(self):
# Build kit file
kit_file = "[dependencies]\n"
kit_file += '"omni.kit.loop-default" = {}\n'
kit_file += "[settings.app.runLoops]\n"
LOOPS = [("loop60", 60), ("loop30", 30), ("main", 300)]
for loop, freq in LOOPS:
kit_file += f"{loop}.rateLimitEnabled = true\n"
kit_file += f"{loop}.rateLimitFrequency = {freq}\n"
kit_file += f"{loop}.rateLimitUseBusyLoop = true\n"
# Subscribe to update events, count them. Validate count and thread ids. Measure time. Overall test code should
# take 1 second = 300 main updates.
script = f"""
from collections import defaultdict
import threading
import time
import omni.kit.app
app = omni.kit.app.get_app()
def simple_assert(v, message):
if not v:
print(f"[error] simple_assert failure: {{message}}")
omni.kit.app.get_app().post_quit(123)
subs = []
cnt = defaultdict(int)
threads = {{}}
start_t = time.time()
for loop, freq in {LOOPS}:
def on_update(e, loop=loop):
cnt[loop] += 1
# Check thread id
tid = threading.get_ident()
if loop not in threads:
threads[loop] = tid
simple_assert(threads[loop] == tid, f"runloop: {{loop}}, thread id is incorrect")
if loop == "main" and cnt[loop] >= 300:
# validate count
for loop, freq in {LOOPS}:
f = cnt[loop] / freq
simple_assert(f >= 0.80 and f <= 1.20, f"runloop: {{loop}}, expected: {{freq}}, result: {{cnt[loop]}}")
dt = time.time() - start_t
simple_assert(dt >= 0.8 and dt <= 1.2, f"test took longer than expected: {{dt}}")
omni.kit.app.get_app().post_quit(0)
subs.append(app.get_update_event_stream(loop).create_subscription_to_pop(
on_update
))
"""
await self._run_kit_with_script(script, args=["--/app/quitAfter=10000"], kit_file=kit_file)
| 2,086 | Python | 31.107692 | 119 | 0.580537 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_ext_api.py | import omni.kit.app
import omni.kit.test
import os
from pathlib import Path
class TestExtAPI(omni.kit.test.AsyncTestCase):
async def test_ext_helpers(self):
manager = omni.kit.app.get_app().get_extension_manager()
# Enable ext id
my_id = manager.get_enabled_extension_id("omni.kit.core.tests")
self.assertEqual(my_id.split("-")[0], "omni.kit.core.tests")
# Ext name
self.assertEqual(omni.ext.get_extension_name(my_id), "omni.kit.core.tests")
self.assertEqual(omni.ext.get_extension_name("omni.kit.some_ext_id"), "omni.kit.some_ext_id")
self.assertEqual(omni.ext.get_extension_name("omni.kit.some_ext_id-1.0.0"), "omni.kit.some_ext_id")
self.assertEqual(omni.ext.get_extension_name("omni.kit.some_ext_id-variant-1.0.0"), "omni.kit.some_ext_id-variant")
# Ext id from module
self.assertEqual(manager.get_extension_id_by_module(__name__), my_id)
self.assertEqual(manager.get_extension_id_by_module("omni.kit.core.tests"), my_id)
self.assertEqual(manager.get_extension_id_by_module("omni.kit.core.tests.test_base"), my_id)
self.assertEqual(manager.get_extension_id_by_module("omni.kit.core"), None)
# Ext path
root = Path(os.path.dirname(__file__)).parent.parent.parent.parent
self.assertEqual(root, Path(manager.get_extension_path(my_id)))
self.assertEqual(root, Path(manager.get_extension_path_by_module(__name__)))
self.assertEqual(root, Path(manager.get_extension_path_by_module("omni.kit.core.tests")))
self.assertEqual(root, Path(manager.get_extension_path_by_module("omni.kit.core.tests.test_base")))
self.assertEqual(manager.get_extension_path_by_module("omni.kit.core"), None)
async def test_solve_extensions(self):
manager = omni.kit.app.get_app().get_extension_manager()
expected_sequence = ["omni.kit.actions.core", "omni.kit.commands"]
# pass by name
result, exts, err = manager.solve_extensions(["omni.kit.commands"], add_enabled=False, return_only_disabled=False)
self.assertTrue(result)
self.assertListEqual([e["name"] for e in exts], expected_sequence)
self.assertEqual(err, "")
commands_ext_id = exts[1]["id"]
# pass by id
result, exts, err = manager.solve_extensions([commands_ext_id], add_enabled=False, return_only_disabled=False)
self.assertTrue(result)
self.assertListEqual([e["name"] for e in exts], expected_sequence)
self.assertEqual(err, "")
# pass both
result, exts, err = manager.solve_extensions(expected_sequence, add_enabled=False, return_only_disabled=False)
self.assertTrue(result)
self.assertListEqual([e["name"] for e in exts], expected_sequence)
self.assertEqual(err, "")
# pass wrong version
result, exts, err = manager.solve_extensions(["omni.kit.actions.core-55.5.5", "omni.kit.commands"], add_enabled=False, return_only_disabled=False)
self.assertFalse(result)
self.assertTrue(len(err) > 0)
# do not return enabled
result, exts, err = manager.solve_extensions(["omni.kit.core.tests"], add_enabled=False, return_only_disabled=True)
self.assertTrue(result)
self.assertTrue(len(exts) == 0)
| 3,325 | Python | 45.194444 | 154 | 0.664662 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/__init__.py | from .test_core_only import *
from .test_ext_api import *
from .test_app_api import *
from .test_runloop import *
from .test_portable import *
from .test_persistent_settings import *
from .test_post_quit_hang import *
from .test_non_ascii_cmd_params import *
from .test_script_exec import *
from .test_extensions import *
from .test_python_bat import *
from .test_default_stage import *
# Expose our public functions
__all__ = ["validate_extensions_load", "validate_extensions_tests", "app_startup_time", "app_startup_warning_count"]
from .scripts.extensions_load import validate_extensions_load
from .scripts.extensions_tests import validate_extensions_tests
from .scripts.app_startup import app_startup_time, app_startup_warning_count
| 738 | Python | 37.894735 | 116 | 0.772358 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_python_bat.py | import carb.tokens
import omni.kit.test
import os
from .test_base import run_process
class TestPythonBat(omni.kit.test.AsyncTestCase):
async def test_python_bat(self):
resolve = carb.tokens.get_tokens_interface().resolve
python_path = resolve("${kit}/python${shell_ext}")
self.assertTrue(os.path.exists(python_path))
async def _run_python_and_check(args, timeout=30):
launch_args = [python_path] + args
code, err_messages, *_ = await run_process(launch_args, timeout)
if len(err_messages) > 0:
print(err_messages)
self.assertEqual(len(err_messages), 0, msg=err_messages)
self.assertEqual(code, 0)
# smoke test and it even runs python ok
await _run_python_and_check(["-c", "import sys"])
# check that we can import a few popular modules
await _run_python_and_check(["-c", "import carb; import omni.kit.app"])
await _run_python_and_check(["-c", "import omni.usd"])
await _run_python_and_check(["-c", "import omni.ui"])
| 1,084 | Python | 35.166665 | 79 | 0.621771 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_persistent_settings.py | import omni.kit.test
from .test_base import KitLaunchTest
# fmt: off
class TestPersistentSettings(KitLaunchTest):
async def test_persistent_settings(self):
kit_file_name = "test_persistent_settings.kit"
# In total in that test we have 3 setting values: regular, persistent set in kit file, persistent new
kit_file = """
[settings]
test_banana.just_some_value = 2
persistent.test_banana.saved_thing = 10
"""
# Functions / header to use in all scripts
script_base = """
import carb.settings
s = carb.settings.get_settings()
def check(path, expected):
v = s.get(path)
if v != expected:
print(f"[Test Fail] setting path: {path}, expected: {expected}, got: {v}")
omni.kit.app.get_app().post_quit(-1)
"""
# Clean start, set a bunch of settings persistent or not
script = script_base + """
check("/test_banana/just_some_value", 2)
check("/persistent/test_banana/saved_thing", 10)
s.set("/test_banana/just_some_value", 3)
s.set("/persistent/test_banana/saved_thing", 1515)
s.set("/persistent/test_banana/another_saved_thing", 78)
"""
await self._run_kit_with_script(script, args=["--reset-user"], kit_file=kit_file, kit_file_name=kit_file_name)
# Check persistent kept
script = script_base + """
check("/test_banana/just_some_value", 2)
check("/persistent/test_banana/saved_thing", 1515)
check("/persistent/test_banana/another_saved_thing", 78)
"""
await self._run_kit_with_script(script, args=[], kit_file=kit_file, kit_file_name=kit_file_name)
# Check that in different app or with different config path they are not loaded:
script = script_base + """
check("/test_banana/just_some_value", 2)
check("/persistent/test_banana/saved_thing", 10)
check("/persistent/test_banana/another_saved_thing", None)
"""
await self._run_kit_with_script(script, args=[], kit_file=kit_file, kit_file_name="test_persistent_settings_other_app.kit")
await self._run_kit_with_script(script, args=["--/app/userConfigPath='${data}/lol.json'"], kit_file=kit_file, kit_file_name=kit_file_name)
# Check we can override them with cmd
script = script_base + """
check("/test_banana/just_some_value", 333)
check("/persistent/test_banana/saved_thing", 888)
check("/persistent/test_banana/another_saved_thing", 999)
"""
args = [
"--/persistent/test_banana/saved_thing=888",
"--/persistent/test_banana/another_saved_thing=999",
"--/test_banana/just_some_value=333"
]
await self._run_kit_with_script(script, args=args, kit_file=kit_file, kit_file_name=kit_file_name)
# Run without args to check that persistent kept
script = script_base + """
check("/test_banana/just_some_value", 2)
check("/persistent/test_banana/saved_thing", 888)
check("/persistent/test_banana/another_saved_thing", 999)
"""
await self._run_kit_with_script(script, args=[], kit_file=kit_file, kit_file_name=kit_file_name)
# Reset settings
script = script_base + """
check("/test_banana/just_some_value", 2)
check("/persistent/test_banana/saved_thing", 10)
check("/persistent/test_banana/another_saved_thing", None)
"""
await self._run_kit_with_script(script, args=["--reset-user"], kit_file=kit_file, kit_file_name=kit_file_name)
# fmt: on
| 3,363 | Python | 38.57647 | 146 | 0.663098 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_script_exec.py | import omni.kit.test
import os
from pathlib import Path
from .test_base import KitLaunchTest
class TestScriptExec(KitLaunchTest):
async def test_script_exec(self):
kit_file = "\n"
script_base = """
import omni.kit.app
import sys
def check(v, expected):
if v != expected:
print(f"[Test Fail] expected: {expected}, got: {v}")
omni.kit.app.get_app().post_quit(-1)
"""
# Regular run
script = script_base + """
check(len(sys.argv), 1)
"""
await self._run_kit_with_script(script, kit_file=kit_file)
# Pass args
script = script_base + """
check(len(sys.argv), 3)
check(sys.argv[1], "abc")
check(sys.argv[2], "42")
"""
await self._run_kit_with_script(script, kit_file=kit_file, script_extra_args=" \"abc\" 42")
# Subfolder with a space in path
subfolder = f"{self._temp_folder}/abc def"
os.makedirs(subfolder)
script = script_base + """
check(len(sys.argv), 1)
"""
script_file = f"\"{subfolder}/script_1.py\""
await self._run_kit_with_script(script, kit_file=kit_file, script_file=script_file)
# Subfolder with a space in path + args
script = script_base + """
check(len(sys.argv), 3)
check(sys.argv[1], "abc")
check(sys.argv[2], "42")
"""
script_file = f"\"{subfolder}/script_2.py\""
await self._run_kit_with_script(script, kit_file=kit_file, script_file=script_file, script_extra_args=" \"abc\" 42")
| 1,502 | Python | 27.903846 | 124 | 0.595206 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_core_only.py | import omni.kit.test
import omni.kit.app
from pathlib import Path
from .test_base import KitLaunchTest
class TestCoreOnlyConfiguration(KitLaunchTest):
async def test_kit_app_with_only_core_exts(self):
manager = omni.kit.app.get_app().get_extension_manager()
core_exts = []
for ext in manager.get_extensions():
info = manager.get_extension_dict(ext["id"])
ext_folder_name = Path(info["path"]).parts[-2]
if ext_folder_name == "extscore":
core_exts.append(ext["name"])
self.assertTrue(info["isCore"])
self.assertGreater(len(core_exts), 0)
# Enable only core exts:
kit_file = "[dependencies]\n"
for ext in core_exts:
kit_file += '"{0}" = {{}}\n'.format(ext)
kit_file += "\n[settings.app.exts]\n"
kit_file += r'folders = ["${kit}/extscore"]'
# Check all extensions enabled
script = f"""
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
core_exts = {core_exts}
for ext in core_exts:
if not manager.is_extension_enabled(ext):
print("failed to enable extension: " + ext)
omni.kit.app.get_app().post_quit(-1)
"""
await self._run_kit_with_script(script, args=["--/app/quitAfter=10"], kit_file=kit_file)
| 1,337 | Python | 31.634146 | 96 | 0.598355 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_app_api.py | import carb.tokens
import omni.kit.app
import omni.kit.test
import os
import sys
from pathlib import Path
class TestAppAPI(omni.kit.test.AsyncTestCase):
async def test_tokens(self):
resolve = carb.tokens.get_tokens_interface().resolve
ABS_TOKENS = ["${cache}", "${kit}", "${data}", "${logs}", "${app}", "${temp}"]
for t in ABS_TOKENS:
path = resolve(t)
self.assertTrue(os.path.isabs(path))
self.assertTrue(os.path.exists(path))
python_exe = sys.prefix + "/" + ("python.exe" if sys.platform == "win32" else "bin/python3")
self.assertEqual(os.path.normpath(resolve("${python}")), os.path.normpath(python_exe))
| 693 | Python | 30.545453 | 100 | 0.623377 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_extensions.py | import omni.kit.test
from .test_base import KitLaunchTest
from .scripts import extensions_load, extensions_tests
import inspect
import sys
class TestExtensions(KitLaunchTest):
async def setUp(self):
await super().setUp()
self.app_to_test = "omni.app.full"
# basic kit file with additional test dependencies
# Note we need to manually add some [[test]] dependencies (could be automated)
self.kit_file = f"""
[dependencies]
"{self.app_to_test}" = {{}}
"omni.kit.ui_test" = {{}} # test dependency from omni.app.full.kit
"omni.kit.test_suite.helpers" = {{}} # test dependency from omni.app.full.kit
"omni.kit.test_helpers_gfx" = {{}} # test dependency from omni.renderer.core
"omni.kit.hydra_texture" = {{}} # test dependency from omni.kit.viewport.legacy_gizmos
"omni.rtx.tests" = {{}} # test dependency from omni.hydra.scene_api
"""
async def test_l1_extensions_have_tests(self):
# This list should be empty or near empty ideally
EXCLUSION_LIST = [
"omni.physx.cct",
"omni.kit.widget.live",
"omni.mdl",
"omni.mdl.neuraylib",
]
# These extensions only run tests on win32 for now
if sys.platform != "win32":
EXCLUSION_LIST.append("omni.hydra.scene_api")
EXCLUSION_LIST.append("omni.rtx.tests")
script = inspect.getsource(extensions_tests)
script = script.replace("EXCLUSION_LIST = []", f"EXCLUSION_LIST = {EXCLUSION_LIST}")
# when it fails it will assert with the number of extensions that have no tests, scroll up in the log to find them
await self._run_kit_with_script(
script,
args=[
"--/app/extensions/disableStartup=1", # extensions startup is disabled
"--/app/extensions/registryEnabled=0",
"--/app/quitAfter=10",
"--/crashreporter/gatherUserStory=0", # don't pop up the GUI on crash
"--no-window",
],
kit_file=self.kit_file,
timeout=60,
)
async def test_l1_extensions_load(self):
script = inspect.getsource(extensions_load)
await self._run_kit_with_script(
script,
args=[
"--/app/extensions/disableStartup=1", # extensions startup is disabled
"--/app/extensions/registryEnabled=0",
"--/app/quitAfter=10",
"--/crashreporter/gatherUserStory=0", # don't pop up the GUI on crash
],
kit_file=self.kit_file,
timeout=60,
)
| 2,677 | Python | 37.811594 | 122 | 0.581621 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_base.py | import carb
import asyncio
import shutil
import sys
import os
import subprocess
import tempfile
from time import time
import omni.kit.test
async def run_process(args, timeout, capture_output=False):
returncode = 0
fail_messages = []
proc = None
stdout = None
try:
cmd = " ".join(args)
print(f">>> running process: {cmd}\n")
async def run_proc():
nonlocal proc
proc = await asyncio.create_subprocess_exec(
*args,
stdout=subprocess.PIPE if capture_output else None,
stderr=subprocess.STDOUT,
bufsize=0,
)
await proc.wait()
nonlocal returncode, stdout
returncode = proc.returncode
if capture_output:
stdout = []
async for line in proc.stdout:
stdout.append(line.decode(errors="replace").replace("\r\n", "\n").replace("\r", "\n"))
proc = None
await asyncio.wait_for(run_proc(), timeout)
except subprocess.CalledProcessError as e:
returncode = e.returncode
fail_messages.append(f"subprocess.CalledProcessError was raised: {e.output}")
except asyncio.TimeoutError:
fail_messages.append(f"Process timed out (timeout: {timeout}). Terminating.")
if proc:
proc.terminate()
# return code failure check
if returncode != 0:
fail_messages.append(f"Process return code: {returncode} != 0.")
return (returncode, fail_messages, stdout)
class KitLaunchTest(omni.kit.test.AsyncTestCase):
def __init__(self, tests=()):
super().__init__(tests)
async def _run_kit(self, args, portable=True, timeout=180, **kwargs):
launch_args = [sys.argv[0]] + args
launch_args += ["--/log/flushStandardStreamOutput=1", "--/app/fastShutdown=1", "--/crashreporter/gatherUserStory=0"]
if portable:
launch_args += ["--portable"]
return await run_process(launch_args, timeout, **kwargs)
async def _run_kit_and_check(self, args, portable=True, timeout=180):
code, err_messages, stdout = await self._run_kit(args, portable, timeout)
if len(err_messages) > 0:
print(err_messages)
self.assertEqual(len(err_messages), 0, msg=err_messages)
self.assertEqual(code, 0)
async def _run_kit_and_capture_stdout(self, args, portable=True, timeout=180, expect_errors=[], expect_success=True):
code, err_messages, stdout = await self._run_kit(args, portable, timeout, capture_output=True)
left_errors = list(expect_errors)
# Check that all expected errors are present in the output
# Replace [Error] with [SkippedError] to avoid main test failure
for line in stdout:
if "[Error]" in line:
line = line.replace("[Error]", "[SkippedError]")
for err in left_errors:
if err in line:
left_errors.remove(err)
sys.stdout.write(line)
self.assertTrue(len(left_errors) == 0, f"Expected errors not found: {left_errors}")
if expect_success:
self.assertEqual(code, 0)
else:
self.assertNotEqual(code, 0)
async def _run_kit_with_script(
self,
script_content,
args=[],
kit_file=None,
add_exec_check=True,
portable=True,
kit_file_name=None,
script_file=None,
script_extra_args="",
timeout=180,
):
ts = int(time())
# Touch special file and check after running kit that file exist. This way we can communicate failure to execute a script.
exec_check_file = f"{self._temp_folder}/exec_ok_{ts}"
if add_exec_check:
script_content += "\n"
script_content += "from pathlib import Path\n"
script_content += f"Path(r'{exec_check_file}').touch()\n"
if not script_file:
script_file = f"{self._temp_folder}/script_{ts}.py"
with open(script_file.strip('"'), "w") as f:
f.write(script_content)
carb.log_info(f"dump '{script_file}':\n{script_content}")
launch_args = []
# Optionally build kit file
if kit_file:
if not kit_file_name:
kit_file_name = f"test_{ts}.kit"
kit_file_path = f"{self._temp_folder}/{kit_file_name}"
with open(kit_file_path, "w") as f:
f.write(kit_file)
launch_args += [kit_file_path]
carb.log_info(f"dump '{kit_file_path}':\n{kit_file}")
launch_args += args
launch_args += ["--exec", script_file + script_extra_args]
await self._run_kit_and_check(launch_args, portable, timeout)
if add_exec_check:
self.assertTrue(os.path.exists(exec_check_file), "Script was not fully executed.")
async def setUp(self):
self._temp_folder = tempfile.mkdtemp()
async def tearDown(self):
shutil.rmtree(self._temp_folder)
| 5,083 | Python | 33.351351 | 130 | 0.581743 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_post_quit_hang.py | import omni.kit.test
from .test_base import KitLaunchTest
from pathlib import Path
import omni
class TestPostQuitHang(KitLaunchTest):
"""Test for https://nvidia-omniverse.atlassian.net/browse/OM-34203"""
async def test_post_quit_api(self):
kit_file = "[dependencies]\n"
kit_file += '"omni.usd" = {}\n'
kit_file += '"omni.kit.renderer.core" = {}\n'
kit_file += '"omni.kit.loop-default" = {}\n'
kit_file += '"omni.kit.mainwindow" = {}\n'
kit_file += '"omni.kit.uiapp" = {}\n'
kit_file += '"omni.kit.menu.file" = {}\n'
kit_file += '"omni.kit.selection" = {}\n'
kit_file += '"omni.kit.stage_templates" = {}\n'
kit_file += """
# Register extension folder from this repo in kit
[settings.app.exts]
folders.'++' = ["${app}/../exts" ]
[settings.app.extensions]
enabledDeprecated = [
]
"""
script = f"""
import omni.usd
import omni.kit.app
import asyncio
from pxr import Sdf, Usd
async def main():
usd_context = omni.usd.get_context()
for i in range(10):
root_layer = Sdf.Layer.CreateAnonymous("test.usd")
stage = Usd.Stage.Open(root_layer)
await usd_context.attach_stage_async(stage)
stage = usd_context.get_stage()
if stage:
prim = stage.DefinePrim("/World")
stage.SetDefaultPrim(prim)
prim = stage.GetDefaultPrim()
prim.CreateAttribute("testing", Sdf.ValueTypeNames.String).Set("test")
await usd_context.save_stage_async()
omni.kit.app.get_app().post_quit()
asyncio.ensure_future(main())
"""
await self._run_kit_with_script(script, args=["--no-window"], kit_file=kit_file)
| 1,765 | Python | 29.982456 | 88 | 0.580737 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/scripts/app_startup.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["app_startup_time", "app_startup_warning_count"]
import json
import time
from typing import Tuple
import carb
import carb.settings
import omni.kit.app
def app_startup_time(test_id: str) -> float:
"""Get startup time - send to nvdf"""
test_start_time = time.time()
startup_time = omni.kit.app.get_app().get_time_since_start_s()
test_result = {"startup_time_s": startup_time}
print(f"App Startup time: {startup_time}")
_post_to_nvdf(test_id, test_result, time.time() - test_start_time)
return startup_time
def app_startup_warning_count(test_id: str) -> Tuple[int, int]:
"""Get the count of warnings during startup - send to nvdf"""
test_start_time = time.time()
warning_count = 0
error_count = 0
log_file_path = carb.settings.get_settings().get("/log/file")
with open(log_file_path, "r") as file:
for line in file:
if "[Warning]" in line:
warning_count += 1
elif "[Error]" in line:
error_count += 1
test_result = {"startup_warning_count": warning_count, "startup_error_count": error_count}
print(f"App Startup Warning count: {warning_count}")
print(f"App Startup Error count: {error_count}")
_post_to_nvdf(test_id, test_result, time.time() - test_start_time)
return warning_count, error_count
# TODO: should call proper API from Kit
def _post_to_nvdf(test_id: str, test_result: dict, test_duration: float):
"""Send results to nvdf"""
try:
from omni.kit.test.nvdf import _can_post_to_nvdf, _get_ci_info, _post_json, get_app_info, to_nvdf_form
if not _can_post_to_nvdf():
return
data = {}
data["ts_created"] = int(time.time() * 1000)
data["app"] = get_app_info()
data["ci"] = _get_ci_info()
data["test"] = {
"passed": True,
"skipped": False,
"unreliable": False,
"duration": test_duration,
"test_id": test_id,
"ext_test_id": "omni.create.tests",
"test_type": "unittest",
}
data["test"].update(test_result)
project = "omniverse-kit-tests-results-v2"
json_str = json.dumps(to_nvdf_form(data), skipkeys=True)
_post_json(project, json_str)
# print(json_str) # uncomment to debug
except Exception as e:
carb.log_warn(f"Exception occurred: {e}")
if __name__ == "__main__":
app_startup_time()
app_startup_warning_count()
omni.kit.app.get_app().post_quit(0)
| 2,969 | Python | 32.75 | 110 | 0.626474 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/scripts/extensions_load.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["validate_extensions_load"]
import omni.kit.app
import omni.kit.test
def validate_extensions_load():
failures = []
manager = omni.kit.app.get_app().get_extension_manager()
for ext in manager.get_extensions():
ext_id = ext["id"]
ext_name = ext["name"]
info = manager.get_extension_dict(ext_id)
enabled = ext.get("enabled", False)
if not enabled:
continue
failed = info.get("state/failed", False)
if failed:
failures.append(ext_name)
if len(failures) == 0:
print("\n[success] All extensions loaded successfuly!\n")
else:
print("")
print(f"[error] Found {len(failures)} extensions that could not load:")
for count, ext in enumerate(failures):
print(f" {count+1}: {ext}")
print("")
return len(failures)
if __name__ == "__main__":
result = validate_extensions_load()
omni.kit.app.get_app().post_quit(result)
| 1,415 | Python | 29.782608 | 79 | 0.650883 |
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/scripts/extensions_tests.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["validate_extensions_tests"]
import omni.kit.app
import omni.kit.test
import carb.settings
EXCLUSION_LIST = []
def validate_extensions_tests(exclusion_list=[]):
"""Return the number of enabled extensions without python tests"""
failures = []
EXCLUSION_LIST.extend(exclusion_list)
settings = carb.settings.get_settings()
manager = omni.kit.app.get_app().get_extension_manager()
for ext in manager.get_extensions():
ext_id = ext["id"]
ext_name = ext["name"]
info = manager.get_extension_dict(ext_id)
# No apps
if info.get("isKitFile", False):
print(f"[ ok ] {ext_name} is an app")
continue
# Exclusion list
if ext_name in EXCLUSION_LIST:
print(f"[ ok ] {ext_name} is in the exclusion list")
continue
waiver = False
reason = ""
cpp_tests = False
test_info = info.get("test", None)
if isinstance(test_info, list) or isinstance(test_info, tuple):
for t in test_info:
if "waiver" in t:
reason = t.get("waiver", "")
waiver = True
if "cppTests" in t:
cpp_tests = True
if waiver:
print(f"[ ok ] {ext_name} has a waiver: {reason}")
continue
enabled = ext.get("enabled", False)
if not enabled:
print(f"[ ok ] {ext_name} is not enabled")
continue
# another test will report that the extension failed to load
failed = info.get("state/failed", False)
if failed:
print(f"[ !! ] {ext_name} failed to load")
continue
include_tests = []
python_dict = info.get("python", {})
python_modules = python_dict.get("module", []) + python_dict.get("modules", [])
for m in python_modules:
module = m.get("name")
if module:
include_tests.append("{}.*".format(module))
settings.set("/exts/omni.kit.test/includeTests", include_tests)
print(f"[ .. ] {ext_name} get tests...")
test_count = omni.kit.test.get_tests()
if len(test_count) > 0:
print(f"[ ok ] {ext_name} has {len(test_count)} tests")
elif cpp_tests:
print(f"[ ok ] {ext_name} has cpp tests")
else:
failures.append(ext_name)
print(f"[fail] {ext_name} has {len(test_count)} tests")
if len(failures) == 0:
print("\n[success] All extensions have tests or waiver!\n")
else:
print("")
print(f"[error] Found {len(failures)} extensions without tests or waiver:")
for count, ext in enumerate(failures):
print(f" {count+1}: {ext}")
print("")
return len(failures)
if __name__ == "__main__":
result = validate_extensions_tests()
omni.kit.app.get_app().post_quit(result)
| 3,375 | Python | 32.425742 | 87 | 0.576593 |
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/PACKAGE-LICENSES/omni.kit.window.audio.oscilloscope-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/config/extension.toml | [package]
title = "Audio Oscilloscope"
category = "Audio"
feature = true
version = "0.1.0"
description = "Displays the waveform of Kit's audio output."
authors = ["NVIDIA"]
keywords = ["audio", "debug"]
[dependencies]
"carb.audio" = {}
"omni.usd.libs" = {}
"omni.usd" = {}
"omni.ui" = {}
"omni.usd.schema.semantics" = {}
"omni.usd.schema.audio" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.kit.window.audio.oscilloscope"
[[python.module]]
name = "omni.kit.audio.oscilloscope"
[[test]]
# Just go with default timeout unless you're testing locally.
# What takes 3 seconds locally could take 3 minutes in CI.
#timeout = 30
args = [
# Use the null device backend so we have a consistent backend channel count,
# since that'll affect the generated image.
"--/audio/deviceBackend=null",
# This is needed or `omni.kit.ui_test.get_menubar().find_menu("Window")`
# will return `None`.
"--/app/menu/legacy_mode=false",
# omni.kit.property.audio causes kit to add a "do you want to save your changes"
# dialogue when kit is exiting unless this option is specified.
"--/app/file/ignoreUnsavedOnExit=true",
# disable DPI scaling & use no-window
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.property.audio", # needed for the (manual) USD test
"omni.kit.mainwindow", # needed for omni.kit.ui_test
"omni.kit.ui_test",
]
stdoutFailPatterns.exclude = [
"*" # I don't want these but OmniUiTest forces me to use them, so ignore all!
]
| 1,589 | TOML | 26.413793 | 84 | 0.670233 |
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/__init__.py | from .oscilloscope import *
| 28 | Python | 13.499993 | 27 | 0.785714 |
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/oscilloscope.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.audio
import omni.kit.audio.oscilloscope
import omni.kit.ui
import omni.ui
import threading
import time
import re
import asyncio
class OscilloscopeWindowExtension(omni.ext.IExt):
"""Audio Recorder Window Extension"""
def _menu_callback(self, a, b):
self._window.visible = not self._window.visible
def _read_callback(self, event):
img = self._oscilloscope.get_image();
self._waveform_image_provider.set_bytes_data(img, [self._waveform_width, self._waveform_height])
def _record_clicked(self):
if self._recording:
self._record_button.set_style({"image_url": "resources/glyphs/audio_record.svg"})
self._recording = False;
self._oscilloscope.stop()
else:
self._record_button.set_style({"image_url": "resources/glyphs/timeline_stop.svg"})
self._recording = True
self._oscilloscope.start()
def on_startup(self):
self._timer = None
self._waveform_width = 512;
self._waveform_height = 460;
try:
self._oscilloscope = omni.kit.audio.oscilloscope.create_oscilloscope(self._waveform_width, self._waveform_height);
except Exception as e:
return;
self._window = omni.ui.Window("Audio Oscilloscope", width=512, height=540)
self._recording = False
with self._window.frame:
with omni.ui.VStack(height=0, spacing=8):
# waveform
with omni.ui.HStack(height=460):
omni.ui.Spacer()
self._waveform_image_provider = omni.ui.ByteImageProvider()
self._waveform_image = omni.ui.ImageWithProvider(
self._waveform_image_provider,
width=omni.ui.Percent(100),
height=omni.ui.Percent(100),
fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH,
)
omni.ui.Spacer()
# buttons
with omni.ui.HStack():
omni.ui.Spacer()
self._record_button = omni.ui.Button(
width=32,
height=32,
clicked_fn=self._record_clicked,
style={"image_url": "resources/glyphs/audio_record.svg"},
)
omni.ui.Spacer()
self._sub = self._oscilloscope.get_event_stream().create_subscription_to_pop(self._read_callback)
self._menuEntry = omni.kit.ui.get_editor_menu().add_item("Window/Oscilloscope", self._menu_callback)
self._window.visible = False
def on_shutdown(self): # pragma: no cover
self._sub = None
self._recorder = None
self._window = None
self._menuEntry = None
self._oscilloscope = None
menu = omni.kit.ui.get_editor_menu()
if menu is not None:
menu.remove_item("Window/Oscilloscope")
| 3,436 | Python | 37.188888 | 126 | 0.592549 |
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/tests/test_window_audio_oscilloscope.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
import omni.kit.test
import omni.kit.ui_test
import omni.ui as ui
import omni.usd
import omni.timeline
import carb.tokens
import omni.usd.audio
from omni.ui.tests.test_base import OmniUiTest
import pathlib
import asyncio;
class TestOscilloscopeWindow(OmniUiTest): # pragma: no cover
async def _dock_window(self):
await self.docked_test_window(
window=self._win.window,
width=512,
height=540)
# Before running each test
async def setUp(self):
await super().setUp()
import omni.kit.material.library
# wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
await omni.kit.material.library.get_mdl_list_async()
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.window.audio.oscilloscope}")
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
self._golden_img_dir = self._test_path.joinpath("golden")
# open the dropdown
window_menu = omni.kit.ui_test.get_menubar().find_menu("Window")
self.assertIsNotNone(window_menu)
await window_menu.click()
# click the oscilloscope window to open it
oscilloscope_menu = omni.kit.ui_test.get_menubar().find_menu("Oscilloscope")
self.assertIsNotNone(oscilloscope_menu)
await oscilloscope_menu.click()
self._win = omni.kit.ui_test.find("Audio Oscilloscope")
self.assertIsNotNone(self._win)
self._record_button = self._win.find("**/Button[*]")
self.assertIsNotNone(self._record_button)
# After running each test
async def tearDown(self):
self._win = None
await super().tearDown()
async def _test_just_opened(self):
await self._dock_window()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_just_opened.png")
async def _test_recording(self):
# docking the window breaks the UI system entirely for some reason
#await self._dock_window()
await self._record_button.click() # the user hit the record button
await asyncio.sleep(4.0) # wait for the bar to fill up
await self._dock_window()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_recording.png")
await self._record_button.click() # the user hit stop
await asyncio.sleep(0.25) # wait so the window will be updated
await self._dock_window()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_stopped.png")
async def _test_real_audio(self):
# Comment this out to run the test.
# Since this test is timing dependent, it'll never work 100% and we don't
# have any sort of smart comparison that could handle a shift in the image.
# It works about 80% of the time.
return
context = omni.usd.get_context()
self.assertIsNotNone(context)
context.new_stage()
stage = context.get_stage()
self.assertIsNotNone(stage)
audio = omni.usd.audio.get_stage_audio_interface()
self.assertIsNotNone(audio)
prim_path = "/test_sound"
prim = stage.DefinePrim(prim_path, "OmniSound")
self.assertIsNotNone(prim)
prim.GetAttribute("filePath").Set(str(self._test_path / "1hz.oga"))
prim.GetAttribute("auralMode").Set("nonSpatial")
i = 0
while audio.get_sound_asset_status(prim) == omni.usd.audio.AssetLoadStatus.IN_PROGRESS:
await asyncio.sleep(0.001)
if i > 5000:
raise Exception("asset load timed out")
i += 1
await self._record_button.click() # the user hit the record button
# use a voice to bypass the timeline
voice = audio.spawn_voice(prim)
i = 0
while voice.is_playing():
await asyncio.sleep(0.001)
i += 1
if (i == 5000):
self.assertFalse("test timed out")
await self._dock_window()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_real_audio.png")
# tests need to be run sequentially, so we can only have 1 test function in this module
async def test_all(self):
await self._test_just_opened()
await self._test_recording()
await self._test_real_audio()
| 4,929 | Python | 34.724637 | 109 | 0.653479 |
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/tests/__init__.py | from .test_window_audio_oscilloscope import * # pragma: no cover
| 66 | Python | 32.499984 | 65 | 0.757576 |
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/audio/oscilloscope/__init__.py | from ._oscilloscope import *
| 29 | Python | 13.999993 | 28 | 0.758621 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/PACKAGE-LICENSES/omni.kit.test_suite.viewport-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.7"
category = "Internal"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "omni.kit.test_suite.viewport"
description="omni.kit.test_suite.viewport"
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "ui", "test"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog = "docs/CHANGELOG.md"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
[[python.module]]
name = "omni.kit.test_suite.viewport"
[dependencies]
"omni.kit.test" = {}
"omni.kit.test_helpers_gfx" = {}
"omni.kit.renderer.capture" = {}
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/file/ignoreUnsavedOnExit=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=false",
"--/persistent/app/stage/dragDropImport='reference'",
"--/persistent/app/material/dragDropMaterialPath='absolute'",
"--no-window"
]
dependencies = [
"omni.usd",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers",
"omni.kit.window.stage",
"omni.kit.property.bundle",
"omni.kit.window.status_bar",
"omni.hydra.pxr",
"omni.kit.viewport.utility",
"omni.kit.window.viewport",
"omni.kit.window.content_browser",
]
| 1,976 | TOML | 28.507462 | 94 | 0.690789 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/__init__.py | from .scripts import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/drag_drop_path.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 os
import omni.kit.app
import omni.usd
import carb
from omni.kit.test.teamcity import is_running_in_teamcity
import sys
import unittest
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class DragDropFileViewportPath(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "empty_stage.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
async def test_l1_drag_drop_path_viewport_absolute(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
viewport_window = ui_test.find("Viewport")
await viewport_window.focus()
# drag/drop from content browser to stage window
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "materials/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=viewport_window.center)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertTrue(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_viewport_relative(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
viewport_window = ui_test.find("Viewport")
await viewport_window.focus()
# drag/drop from content browser to stage window
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "materials/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=viewport_window.center)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertFalse(os.path.isabs(asset.path))
@unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020")
async def test_l1_drag_drop_hilighting(self):
from pathlib import Path
import omni.kit.test
from omni.kit.viewport.utility.tests.capture import capture_viewport_and_compare
from carb.input import MouseEventType
from carb.tokens import get_tokens_interface
await ui_test.find("Content").focus()
viewport_window = ui_test.find("Viewport")
await viewport_window.focus()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
async with ContentBrowserTestHelper() as content_browser_helper:
usd_path = get_test_data_path(__name__, "shapes").replace("\\", "/")
await content_browser_helper.toggle_grid_view_async(False)
selections = await content_browser_helper.select_items_async(usd_path, ["basic_cube.usda"])
self.assertIsNotNone(selections)
widget = await content_browser_helper.get_treeview_item_async(selections[-1].name)
self.assertIsNotNone(widget)
start_pos = widget.center
pos_0 = viewport_window.center
pos_1 = ui_test.Vec2(50, pos_0.y + 75)
pos_2 = ui_test.Vec2(viewport_window.size.x - 50, pos_0.y - 25)
wait_delay = 4
drag_delay = 12
await ui_test.input.emulate_mouse(MouseEventType.MOVE, start_pos)
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN)
await ui_test.human_delay(wait_delay)
await ui_test.input.emulate_mouse_slow_move(start_pos, pos_0, human_delay_speed=drag_delay)
await ui_test.human_delay(wait_delay)
await ui_test.input.emulate_mouse_slow_move(pos_0, pos_1, human_delay_speed=drag_delay)
await ui_test.human_delay(wait_delay)
await ui_test.input.emulate_mouse_slow_move(pos_1, pos_2, human_delay_speed=drag_delay)
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP)
await ui_test.human_delay(wait_delay)
EXTENSION_ROOT = Path(get_tokens_interface().resolve("${omni.kit.test_suite.viewport}")).resolve().absolute()
GOLDEN_IMAGES = EXTENSION_ROOT.joinpath("data", "tests", "images")
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
passed, fail_msg = await capture_viewport_and_compare(image_name="test_l1_drag_drop_hilighting.png",
output_img_dir=OUTPUTS_DIR,
golden_img_dir=GOLDEN_IMAGES)
self.assertTrue(passed, msg=fail_msg)
| 6,013 | Python | 46.730158 | 119 | 0.673374 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/drag_drop_material_viewport.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
delete_prim_path_children,
arrange_windows
)
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropMaterialViewport(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
def _verify_material(self, stage, mtl_name, to_select):
# verify material created
prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()]
self.assertTrue(f"/World/Looks/{mtl_name}" in prim_paths)
self.assertTrue(f"/World/Looks/{mtl_name}/Shader" in prim_paths)
# verify bound material
if to_select:
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == f"/World/Looks/{mtl_name}")
# NOTE: This crashes in hydra so disabled
async def __test_l1_drag_drop_material_viewport(self):
await ui_test.find("Content").focus()
await ui_test.find("Stage").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"]
await wait_stage_loading()
# drag to center of viewport window
# NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used
content_browser_helper = ContentBrowserTestHelper()
material_test_helper = MaterialLibraryTestHelper()
viewport_window = ui_test.find("Viewport")
await viewport_window.focus()
drag_target = viewport_window.center
mdl_list = await omni.kit.material.library.get_mdl_list_async()
for mtl_name, mdl_path, submenu in mdl_list:
# delete anything in Looks
await delete_prim_path_children("/World/Looks")
# select prim
await select_prims(to_select)
# wait for UI to update
await ui_test.human_delay()
# drag/drop
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# handle create material dialog
await material_test_helper.handle_create_material_dialog(mdl_path, mtl_name)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify material
self._verify_material(stage, mtl_name, [])
| 3,738 | Python | 39.641304 | 126 | 0.665597 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/__init__.py | from .viewport_assign_material_single import *
from .viewport_assign_material_multi import *
from .select_bound_objects_viewport import *
from .drag_drop_material_viewport import *
from .drag_drop_usd_viewport_item import *
from .viewport_setup import *
from .drag_drop_path import *
from .drag_drop_external_audio_viewport import *
| 333 | Python | 36.111107 | 48 | 0.786787 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/viewport_assign_material_single.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, wait_for_window, handle_assign_material_dialog, arrange_windows
class ViewportAssignMaterialSingle(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
DATA = [["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"],
["", "/World/Looks/OmniGlass", "/World/Looks/OmniPBR", "/World/Looks/OmniSurface_Plastic"]]
async def test_l1_viewport_assign_material_single(self):
await ui_test.find("Stage").focus()
await ui_test.find("Viewport").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
for to_select in self.DATA[0]:
for index, mtl_path in enumerate(self.DATA[1]):
# select prim
await select_prims([to_select])
# wait for material to load & UI to refresh
await wait_stage_loading()
# right click on viewport
await ui_test.find("Viewport").right_click()
await ui_test.human_delay(50)
# click context menu "Assign Material"
await ui_test.select_context_menu("Assign Material")
# use assign material dialog
await handle_assign_material_dialog(index)
# verify binding
prim = stage.GetPrimAtPath(to_select)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == mtl_path)
| 2,455 | Python | 39.262294 | 169 | 0.657026 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/viewport_setup.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportSetup"]
import omni.kit.test
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
import carb
from pxr import UsdGeom
class ViewportSetup(AsyncTestCase):
# Before running each test
async def setUp(self):
super().setUp()
async def test_camera_startup_values(self):
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
stage = usd_context.get_stage()
self.assertIsNotNone(stage)
persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp')
self.assertIsNotNone(persp)
self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 18.147562, places=5)
self.assertEqual(persp.GetFStopAttr().Get(), 0)
top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top')
self.assertIsNotNone(top)
self.assertEqual(top.GetHorizontalApertureAttr().Get(), 5000)
# Legacy Viewport does some legacy hi-jinks based on resolution
# self.assertEqual(top.GetVerticalApertureAttr().Get(), 5000)
# Test typed-defaults and creation
settings = carb.settings.get_settings()
try:
perps_key = '/persistent/app/primCreation/typedDefaults/camera'
ortho_key = '/persistent/app/primCreation/typedDefaults/orthoCamera'
settings.set(perps_key + '/focalLength', 150)
settings.set(perps_key + '/fStop', 22)
settings.set(perps_key + '/horizontalAperture', 1234)
settings.set(ortho_key + '/horizontalAperture', 1000)
settings.set(ortho_key + '/verticalAperture', 2000)
await usd_context.new_stage_async()
stage = usd_context.get_stage()
self.assertIsNotNone(stage)
persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp')
self.assertIsNotNone(persp)
self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 150)
self.assertAlmostEqual(persp.GetFStopAttr().Get(), 22)
self.assertAlmostEqual(persp.GetHorizontalApertureAttr().Get(), 1234)
# Legacy Viewport does some legacy hi-jinks based on resolution
# self.assertFalse(persp.GetVerticalApertureAttr().IsAuthored())
top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top')
self.assertIsNotNone(top)
# Legacy Viewport does some legacy hi-jinks based on resolution
# self.assertAlmostEqual(top.GetHorizontalApertureAttr().Get(), 1000)
# self.assertAlmostEqual(top.GetVerticalApertureAttr().Get(), 2000)
finally:
# Reset now for all other tests
settings.destroy_item(perps_key)
settings.destroy_item(ortho_key)
| 3,154 | Python | 40.513157 | 85 | 0.671528 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/select_bound_objects_viewport.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import platform
import unittest
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class SelectBoundObjectsViewport(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
DATA = [
("/World/Looks/OmniPBR", {"/World/Cone", "/World/Cylinder"}),
("/World/Looks/OmniGlass", {"/World/Cube", "/World/Sphere"}),
]
async def test_l1_select_bound_objects_viewport(self):
usd_context = omni.usd.get_context()
for to_select, to_verify in self.DATA:
# select prim
await select_prims([to_select])
# wait for material to load & UI to refresh
await wait_stage_loading()
# right click on viewport
await ui_test.find("Viewport").right_click()
# click context menu "Select Bound Objects"
await ui_test.select_context_menu("Select Bound Objects")
# veirfy new selection
selected = usd_context.get_selection().get_selected_prim_paths()
self.assertSetEqual(set(selected), to_verify)
| 1,920 | Python | 33.303571 | 121 | 0.679687 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/drag_drop_external_audio_viewport.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 os
import carb
import omni.usd
import omni.kit.app
from os import listdir
from os.path import isfile, join
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, get_prims, arrange_windows
class ExternalDragDropUsdViewportAudio(AsyncTestCase):
# Before running each test
async def setUp(self):
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
await arrange_windows("Stage", 512)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
async def test_l1_external_drag_drop_audio_viewport_item(self):
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
audio_list = []
audio_path = get_test_data_path(__name__, f"media/")
prims = get_prims(stage)
for item_path in [join(audio_path, f) for f in listdir(audio_path) if isfile(join(audio_path, f))]:
# position mouse
await ui_test.find("Viewport").click()
await ui_test.human_delay()
# simulate drag/drop
omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': [item_path]})
await ui_test.human_delay(50)
prim_list = get_prims(stage, prims)
self.assertEqual(len(prim_list), 1)
audio_list.append([prim_list[0], os.path.relpath(item_path, audio_path)])
prims.append(prim_list[0])
# verify
self.assertEqual(len(audio_list), 5)
for prim, audio_file in audio_list:
asset_path = prim.GetAttribute('filePath').Get()
self.assertTrue(asset_path.resolvedPath.endswith(audio_file))
| 2,565 | Python | 39.093749 | 118 | 0.676413 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/drag_drop_usd_viewport_item.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import asyncio
import os
import carb
import omni.usd
import omni.kit.app
from omni.kit.async_engine import run_coroutine
import concurrent.futures
from typing import List
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Tf, Usd, Sdf
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
wait_stage_loading,
delete_prim_path_children,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropUsdViewportItem(AsyncTestCase):
# Before running each test
async def setUp(self):
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
await arrange_windows("Stage", 512)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
await delete_prim_path_children("/World")
self._usd_path = get_test_data_path(__name__, "shapes").replace("\\", "/")
# After running each test
async def tearDown(self):
await wait_stage_loading()
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
def assertPathsEqual(self, path_a: str, path_b: str):
# Make drive comparison case insensitive on Windows
drive_a, path_a = os.path.splitdrive(path_a)
drive_b, path_b = os.path.splitdrive(path_b)
self.assertEqual(path_a, path_b)
self.assertEqual(drive_a.lower(), drive_b.lower())
async def wait_for_import(self, stage, prim_paths, drag_drop_fn):
# create future
future_test = asyncio.Future()
all_expected_prim_paths = set(prim_paths)
def on_objects_changed(notice, sender, future_test):
for p in notice.GetResyncedPaths():
if p.pathString in all_expected_prim_paths:
all_expected_prim_paths.discard(p.pathString)
if not all_expected_prim_paths:
async def future_test_complete(future_test):
await omni.kit.app.get_app().next_update_async()
future_test.set_result(True)
if not self._test_complete:
self._test_complete = run_coroutine(future_test_complete(future_test))
break
async def wait_for_event(future_test):
await future_test
# create listener
self._test_complete = None
listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, lambda n, s, : on_objects_changed(n, s, future_test), stage)
# do drag/drop
if asyncio.isfuture(drag_drop_fn()):
await drag_drop_fn()
else:
concurrent.futures.wait(drag_drop_fn())
# wait for Tf.Notice event
try:
await asyncio.wait_for(wait_for_event(future_test), timeout=30.0)
except asyncio.TimeoutError:
carb.log_error(f"wait_for_import timeout")
# release listener
listener.Revoke()
def _verify(self, stage, prim_path, usd, reference):
prim = stage.GetPrimAtPath(prim_path)
self.assertIsNotNone(prim)
payloads = omni.usd.get_composed_payloads_from_prim(prim)
references = omni.usd.get_composed_references_from_prim(prim)
if reference:
items = references
self.assertEqual(payloads, [])
self.assertEqual(len(references), 1)
else:
items = payloads
self.assertEqual(len(payloads), 1)
self.assertEqual(references, [])
for (ref, layer) in items:
# unlike stage_window this ref.assetPath is not absoloute
abs_path = get_test_data_path(__name__, f"{ref.assetPath}").replace("\\", "/")
self.assertPathsEqual(abs_path, usd)
async def _drag_drop_usd_items(self, usd_path: str, usd_names: List[str], reference: bool = False):
await ui_test.find("Content").focus()
viewport_window = ui_test.find("Viewport")
await viewport_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
# set dragDropImport
import_method = "reference" if reference else "payload"
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", import_method)
all_expected_prim_paths = []
for usd_name in usd_names:
prim_name, _ = os.path.splitext(os.path.basename(usd_name))
all_expected_prim_paths.append(f"/World/{prim_name}")
# drag/drop
content_browser_helper = ContentBrowserTestHelper()
await self.wait_for_import(stage, all_expected_prim_paths,
lambda: run_coroutine(content_browser_helper.drag_and_drop_tree_view(
usd_path, names=usd_names, drag_target=viewport_window.center
))
)
await wait_stage_loading()
# verify
for usd_name, prim_path in zip(usd_names, all_expected_prim_paths):
self._verify(stage, prim_path, f"{usd_path}/{usd_name}", reference)
async def test_l1_drag_drop_usd_stage_item_reference(self):
await self._drag_drop_usd_items(self._usd_path, ["basic_sphere.usda"], reference=True)
async def test_l1_drag_drop_usd_viewport_item_payload(self):
await self._drag_drop_usd_items(self._usd_path, ["basic_cone.usda"], reference=False)
async def test_l1_drag_drop_multiple_usd_stage_items_reference(self):
usd_names = ["basic_cube.usda", "basic_cone.usda", "basic_sphere.usda"]
await self._drag_drop_usd_items(self._usd_path, usd_names, reference=True)
async def test_l1_drag_drop_multiple_usd_viewport_items_payload(self):
usd_names = ["basic_cube.usda", "basic_cone.usda", "basic_sphere.usda"]
await self._drag_drop_usd_items(self._usd_path, usd_names, reference=False)
| 6,423 | Python | 39.658228 | 125 | 0.640822 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/viewport_assign_material_multi.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, wait_for_window, handle_assign_material_dialog, arrange_windows
class ViewportAssignMaterialMulti(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
DATA = [["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"],
["", "/World/Looks/OmniGlass", "/World/Looks/OmniPBR", "/World/Looks/OmniSurface_Plastic"]]
async def test_l1_viewport_assign_material_multi(self):
await ui_test.find("Stage").focus()
await ui_test.find("Viewport").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = self.DATA[0]
for index, mtl_path in enumerate(self.DATA[1]):
# select prim
await select_prims(to_select)
# wait for material to load & UI to refresh
await wait_stage_loading()
# right click on viewport
await ui_test.find("Viewport").right_click()
await ui_test.human_delay(50)
# click context menu "Assign Material"
await ui_test.select_context_menu("Assign Material")
# use assign material dialog
await handle_assign_material_dialog(index)
# verify binding
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == mtl_path)
| 2,433 | Python | 38.258064 | 169 | 0.668722 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.7] - 2022-09-21
### Added
- Test for drag drop usd file across mulitple objects in Viewport
## [1.0.6] - 2022-08-03
### Changes
- Added external drag/drop audio file tests
## [1.0.5] - 2022-07-25
### Changes
- Refactored unittests to make use of content_browser test helpers
## [1.0.4] - 2022-06-14
### Added
- Fixed drag/drop test for viewport next
## [1.0.3] - 2022-06-09
### Added
- Test new default startup values
## [1.0.2] - 2022-06-04
### Changes
- Make path comparisons case insensitive for Windows drive
- Remove extra timeout for tests not running with RTX
## [1.0.1] - 2022-05-23
### Changes
- Add missing explicit dependencies
## [1.0.0] - 2022-02-09
### Changes
- Created
| 796 | Markdown | 20.54054 | 80 | 0.674623 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/docs/README.md | # omni.kit.test_suite.viewport
## omni.kit.test_suite.viewport
Test Suite
| 78 | Markdown | 8.874999 | 31 | 0.730769 |
omniverse-code/kit/exts/omni.kit.test_suite.viewport/docs/index.rst | omni.kit.test_suite.viewport
############################
viewport tests
.. toctree::
:maxdepth: 1
CHANGELOG
| 118 | reStructuredText | 10.899999 | 28 | 0.525424 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/capture.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.kit.app
import asyncio
from typing import Any, Callable, Sequence
class Capture:
'''Base capture delegate'''
def __init__(self, *args, **kwargs):
self.__future = asyncio.Future()
def capture(self, aov_map, frame_info, hydra_texture, result_handle):
carb.log_error(f'Capture used, but capture was not overriden')
async def wait_for_result(self, completion_frames: int = 2):
await self.__future
while completion_frames:
await omni.kit.app.get_app().next_update_async()
completion_frames = completion_frames - 1
return self.__future.result()
def _set_completed(self, value: Any = True):
if not self.__future.done():
self.__future.set_result(value)
class RenderCapture(Capture):
'''Viewport capturing delegate that iterates over multiple aovs and calls user defined capture_aov method for all of interest'''
def __init__(self, aov_names: Sequence[str], per_aov_data: Sequence[Any] = None, *args, **kwargs):
super().__init__(*args, **kwargs)
# Accept a 1:1 mapping a 1:0 mapping or a N:1 mapping of AOV to data
if per_aov_data is None:
self.__aov_mapping = {aov:None for aov in aov_names}
elif len(aov_names) == len(per_aov_data):
self.__aov_mapping = {aov:data for aov, data in zip(aov_names, per_aov_data)}
else:
if len(per_aov_data) != 1:
assert len(aov_names) == len(per_aov_data), f'Mismatch between {len(aov_names)} aovs and {len(per_aov_data)} per_aov_data'
self.__aov_mapping = {aov:per_aov_data for aov in aov_names}
self.__frame_info = None
self.__hydra_texture = None
self.__result_handle = None
self.__render_capture = None
@property
def aov_data(self):
return self.__aov_mapping.values()
@property
def aov_names(self):
return self.__aov_mapping.keys()
@property
def resolution(self):
return self.__frame_info.get('resolution')
@property
def view(self):
return self.__frame_info.get('view')
@property
def projection(self):
return self.__frame_info.get('projection')
@property
def frame_number(self):
return self.__frame_info.get('frame_number')
@property
def viewport_handle(self):
return self.__frame_info.get('viewport_handle')
@property
def hydra_texture(self):
return self.__hydra_texture
@property
def result_handle(self):
return self.__result_handle
@property
def frame_info(self):
return self.__frame_info
@property
def render_capture(self):
if not self.__render_capture:
try:
import omni.renderer_capture
self.__render_capture = omni.renderer_capture.acquire_renderer_capture_interface()
except ImportError:
carb.log_error(f'omni.renderer_capture extension must be loaded to use this interface')
raise
return self.__render_capture
def capture(self, aov_map, frame_info, hydra_texture, result_handle):
try:
self.__hydra_texture = hydra_texture
self.__result_handle = result_handle
self.__frame_info = frame_info
color_data, color_data_set = None, False
completed = []
for aov_name, user_data in self.__aov_mapping.items():
aov_data = aov_map.get(aov_name)
if aov_data:
self.capture_aov(user_data, aov_data)
completed.append(aov_name)
elif aov_name == '':
color_data, color_data_set = user_data, True
if color_data_set:
aov_name = 'LdrColor'
aov_data = aov_map.get(aov_name)
if aov_data is None:
aov_name = 'HdrColor'
aov_data = aov_map.get(aov_name)
if aov_data:
self.capture_aov(color_data, aov_data)
completed.append(aov_name)
except:
raise
finally:
self.__hydra_texture = None
self.__result_handle = None
self.__render_capture = None
self._set_completed(completed)
def capture_aov(self, user_data, aov: dict):
carb.log_error('RenderCapture used, but capture_aov was not overriden')
def save_aov_to_file(self, file_path: str, aov: dict, format_desc: dict = None):
if format_desc:
if hasattr(self.render_capture, 'capture_next_frame_rp_resource_to_file'):
self.render_capture.capture_next_frame_rp_resource_to_file(file_path, aov['texture']['rp_resource'],
format_desc=format_desc,
metadata = self.__frame_info.get('metadata'))
return
carb.log_error('Format description provided to capture, but not honored')
self.render_capture.capture_next_frame_rp_resource(file_path, aov['texture']['rp_resource'], metadata = self.__frame_info.get('metadata'))
def deliver_aov_buffer(self, callback_fn: Callable, aov: dict):
self.render_capture.capture_next_frame_rp_resource_callback(callback_fn, aov['texture']['rp_resource'], metadata = self.__frame_info.get('metadata'))
def save_product_to_file(self, file_path: str, render_product: str):
self.render_capture.capture_next_frame_using_render_product(self.viewport_handle, file_path, render_product)
class MultiAOVFileCapture(RenderCapture):
'''Class to capture multiple AOVs into multiple files'''
def __init__(self, aov_names: Sequence[str], file_paths: Sequence[str], format_desc: dict = None, *args, **kwargs):
super().__init__(aov_names, file_paths, *args, **kwargs)
self.__format_desc = format_desc
@property
def format_desc(self):
return self.__format_desc
@format_desc.setter
def format_desc(self, value: dict):
self.__format_desc = value
def capture_aov(self, file_path: str, aov: dict, format_desc: dict = None):
self.save_aov_to_file(file_path, aov, self.__format_desc)
class MultiAOVByteCapture(RenderCapture):
'''Class to deliver multiple AOVs buffer/bytes to a callback function'''
def __init__(self, aov_names: Sequence[str], callback_fns: Sequence[Callable] = None, *args, **kwargs):
super().__init__(aov_names, callback_fns, *args, **kwargs)
def capture_aov(self, callback_fn: Callable, aov: dict):
self.deliver_aov_buffer(callback_fn or self.on_capture_completed, aov)
def on_capture_completed(buffer, buffer_size, width, height, format):
pass
class FileCapture(MultiAOVFileCapture):
'''Class to capture a single AOVs (defaulting to color) into one file'''
def __init__(self, file_path: str, aov_name: str = '', *args, **kwargs):
super().__init__([aov_name], [file_path], *args, **kwargs)
class ByteCapture(MultiAOVByteCapture):
'''Class to capture a single AOVs (defaulting to color) to a user callback'''
def __init__(self, callback_fn: Callable = None, aov_name: str = '', *args, **kwargs):
super().__init__([aov_name], [callback_fn], *args, **kwargs)
| 7,872 | Python | 38.365 | 157 | 0.609756 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/extension.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ['ViewportWidgetExtension']
import omni.ext
class ViewportWidgetExtension(omni.ext.IExt):
def on_startup(self):
pass
def on_shutdown(self):
from .widget import ViewportWidget
from .impl.utility import _report_error
for instance in ViewportWidget.get_instances(): # pragma: no cover
try:
instance.destroy()
except Exception:
_report_error()
| 884 | Python | 33.03846 | 76 | 0.704751 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/__init__.py | from .extension import ViewportWidgetExtension
# Expose our public classes for from omni.kit.widget.viewport import ViewportWidget
__all__ = ['ViewportWidget']
from .widget import ViewportWidget
| 197 | Python | 27.28571 | 83 | 0.807107 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/api.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ['ViewportAPI']
import omni.usd
import carb
from .impl.utility import _report_error
from .capture import Capture
from pxr import Usd, UsdGeom, Sdf, Gf, CameraUtil
from typing import Callable, Optional, Sequence, Tuple, Union
import weakref
import asyncio
class ViewportAPI():
class __ViewportSubscription:
def __init__(self, fn: Callable, callback_container: set):
self.__callback_container = callback_container
self.__callback = fn
self.__callback_container.add(self.__callback)
def destroy(self):
if not self.__callback_container:
return
# Clear out self of references early, and then operate on the re-scoped objects
scoped_container = self.__callback_container
scoped_callback = self.__callback
self.__callback_container, self.__callback = None, None
try:
scoped_container.remove(scoped_callback)
except KeyError: # pragma: no cover
pass
def __del__(self):
self.destroy()
def __init__(self, usd_context_name: str, viewport_id: str, viewport_changed_fn: Optional[Callable]):
self.__usd_context_name = usd_context_name
self.__viewport_id = viewport_id
self.__viewport_changed = viewport_changed_fn
self.__viewport_texture, self.__hydra_texture = None, None
self.__aspect_ratios = (1, 1)
self.__projection = Gf.Matrix4d(1)
self.__flat_rendered_projection = self.__flatten_matrix(self.__projection)
self.__transform = Gf.Matrix4d(1)
self.__view = Gf.Matrix4d(1)
self.__ndc_to_world = None
self.__world_to_ndc = None
self.__time = Usd.TimeCode.Default()
self.__view_changed = set()
self.__frame_changed = set()
self.__render_settings_changed = set()
self.__fill_frame = False
self.__lock_to_render_result = True
self.__first_synch = True
self.__updates_enabled = True
self.__freeze_frame = False
self.__scene_views = []
# Attribute to store the requirement status of the scene camera model.
# We initialize it to None and will only fetch the status when needed.
self.__requires_scene_camera_model = None
# Attribute to flag whether importing the SceneCameraModel failed or not.
# We use this to avoid continuously trying to import an unavailable or failing module.
self.__scene_camera_model_import_failed = False
# This stores the instance of SceneCameraModel if it's required and successfully imported.
# We initialize it to None as we don't need it immediately at initialization time.
self.__scene_camera_model = None
settings = carb.settings.get_settings()
self.__accelerate_rtx_picking = bool(settings.get("/exts/omni.kit.widget.viewport/picking/rtx/accelerate"))
self.__accelerate_rtx_picking_sub = settings.subscribe_to_node_change_events(
"/exts/omni.kit.widget.viewport/picking/rtx/accelerate", self.__accelerate_rtx_changed
)
def __del__(self):
sub, self.__accelerate_rtx_picking_sub = self.__accelerate_rtx_picking_sub, None
if sub:
settings = carb.settings.get_settings()
settings.unsubscribe_to_change_events(sub)
def add_scene_view(self, scene_view):
'''Add an omni.ui.scene.SceneView to push view and projection changes to.
The provided scene_view will be saved as a weak-ref.'''
if not scene_view: # pragma: no cover
raise RuntimeError('Provided scene_view is invalid')
self.__clean_weak_views()
self.__scene_views.append(weakref.ref(scene_view, self.__clean_weak_views))
_scene_camera_model = self._scene_camera_model
if _scene_camera_model:
scene_view.model = _scene_camera_model
# Sync the model immediately
model = scene_view.model
model.set_floats('view', self.__flatten_matrix(self.__view))
model.set_floats('projection', self.__flatten_matrix(self.__projection))
def remove_scene_view(self, scene_view):
'''Remove an omni.ui.scene.SceneView that was receiving view and projection changes.'''
if not scene_view:
raise RuntimeError('Provided scene_view is invalid')
for sv in self.__scene_views:
if sv() == scene_view:
self.__scene_views.remove(sv)
break
self.__clean_weak_views()
def subscribe_to_view_change(self, callback: Callable):
return self.__subscribe_to_change(callback, self.__view_changed, 'subscribe_to_view_change')
def subscribe_to_frame_change(self, callback: Callable):
return self.__subscribe_to_change(callback, self.__frame_changed, 'subscribe_to_frame_change')
def subscribe_to_render_settings_change(self, callback: Callable):
return self.__subscribe_to_change(callback, self.__render_settings_changed, 'subscribe_to_render_settings_change')
def request_pick(self, *args, **kwargs):
return self.__hydra_texture.request_pick(*args, **kwargs) if self.__hydra_texture else None
def request_query(self, mouse, *args, **kwargs):
if self.__accelerate_rtx_picking and kwargs.get("view") is None:
# If using scene_camera_model, pull view and projection from that and
# avoid the flattening stage as well.
if False: # self.__scene_camera_model:
kwargs["view"] = self.__scene_camera_model.view
kwargs["projection"] = self.__scene_camera_model.projection
else:
kwargs["view"] = self.__flatten_matrix(self.__view)
kwargs["projection"] = self.__flat_rendered_projection
return self.__hydra_texture.request_query(mouse, *args, **kwargs) if self.__hydra_texture else None
def schedule_capture(self, delegate: Capture) -> Capture:
if self.__viewport_texture:
return self.__viewport_texture.schedule_capture(delegate)
async def wait_for_render_settings_change(self):
future = asyncio.Future()
def rs_changed(*args):
nonlocal scoped_sub
scoped_sub = None
if not future.done():
future.set_result(True)
scoped_sub = self.subscribe_to_render_settings_change(rs_changed)
return await future
async def wait_for_rendered_frames(self, additional_frames: int = 0):
future = asyncio.Future()
def frame_changed(*args):
nonlocal additional_frames, scoped_sub
additional_frames = additional_frames - 1
if (additional_frames <= 0) and (not future.done()):
future.set_result(True)
scoped_sub = None
scoped_sub = self.subscribe_to_frame_change(frame_changed)
return await future
# Deprecated
def pick(self, *args, **kwargs): # pragma: no cover
carb.log_warn('ViewportAPI.pick is deprecated, use request_pick')
return self.__hydra_texture.pick(*args, **kwargs) if self.__hydra_texture else None
def query(self, mouse, *args, **kwargs): # pragma: no cover
carb.log_warn('ViewportAPI.query is deprecated, use request_query')
return self.__hydra_texture.query(mouse, *args, **kwargs) if self.__hydra_texture else None
def set_updates_enabled(self, enabled: bool = True): # pragma: no cover
carb.log_warn('ViewportAPI.set_updates_enabled is deprecated, use updates_enabled')
self.updates_enabled = enabled
@property
def hydra_engine(self):
'''Get the name of the active omni.hydra.engine for this Viewport'''
return self.__viewport_texture.hydra_engine if self.__viewport_texture else None
@hydra_engine.setter
def hydra_engine(self, hd_engine: str):
'''Set the name of the active omni.hydra.engine for this Viewport'''
if self.__viewport_texture:
self.__viewport_texture.hydra_engine = hd_engine
@property
def render_mode(self):
'''Get the render-mode for the active omni.hydra.engine used in this Viewport'''
return self.__viewport_texture.render_mode if self.__viewport_texture else None
@render_mode.setter
def render_mode(self, render_mode: str):
'''Set the render-mode for the active omni.hydra.engine used in this Viewport'''
if self.__viewport_texture:
self.__viewport_texture.render_mode = render_mode
@property
def set_hd_engine(self):
'''Set the active omni.hydra.engine for this Viewport, and optionally its render-mode'''
return self.__viewport_texture.set_hd_engine if self.__viewport_texture else None
@property
def camera_path(self) -> Sdf.Path:
'''Return an Sdf.Path to the active rendering camera'''
return self.__viewport_texture.camera_path if self.__viewport_texture else None
@camera_path.setter
def camera_path(self, camera_path: Union[Sdf.Path, str]):
'''Set the active rendering camera from an Sdf.Path'''
if self.__viewport_texture:
self.__viewport_texture.camera_path = camera_path
@property
def resolution(self) -> Tuple[float, float]:
'''Return a tuple of (resolution_x, resolution_y) this Viewport is rendering at, accounting for scale.'''
return self.__viewport_texture.resolution if self.__viewport_texture else None
@resolution.setter
def resolution(self, value: Tuple[float, float]):
'''Set the resolution to render with (resolution_x, resolution_y).
The provided resolution should be full resolution, as any texture scaling will be applied to it.'''
if self.__viewport_texture:
self.__viewport_texture.resolution = value
@property
def resolution_scale(self) -> float:
'''Get the scaling factor for the Viewport's render resolution.'''
return self.__viewport_texture.resolution_scale if self.__viewport_texture else None
@resolution_scale.setter
def resolution_scale(self, value: float):
'''Set the scaling factor for the Viewport's render resolution.'''
if self.__viewport_texture:
self.__viewport_texture.resolution_scale = value
@property
def full_resolution(self) -> Tuple[float, float]:
'''Return a tuple of the full (full_resolution_x, full_resolution_y) this Viewport is rendering at, not accounting for scale.'''
return self.__viewport_texture.full_resolution if self.__viewport_texture else None
@property
def render_product_path(self) -> str:
'''Return a string to the UsdRender.Product used by the Viewport'''
if self.__hydra_texture:
render_product = self.__hydra_texture.get_render_product_path()
if render_product and (not render_product.startswith('/')):
render_product = '/Render/RenderProduct_' + render_product
return render_product
@render_product_path.setter
def render_product_path(self, prim_path: str):
'''Set the UsdRender.Product used by the Viewport with a string'''
if self.__hydra_texture:
prim_path = str(prim_path)
name = self.__hydra_texture.get_name()
if prim_path == f'/Render/RenderProduct_{name}':
prim_path = name
return self.__hydra_texture.set_render_product_path(prim_path)
@property
def fps(self) -> float:
'''Return the frames-per-second this Viewport is running at'''
return self.frame_info.get('fps', 0)
@property
def frame_info(self) -> dict:
return self.__viewport_texture.frame_info if self.__viewport_texture else {}
@property
def fill_frame(self) -> bool:
return self.__fill_frame
@fill_frame.setter
def fill_frame(self, value: bool):
value = bool(value)
if self.__fill_frame != value:
self.__fill_frame = value
stage = self.stage
if stage:
self.viewport_changed(self.camera_path, stage)
@property
def lock_to_render_result(self) -> bool:
return self.__lock_to_render_result
@lock_to_render_result.setter
def lock_to_render_result(self, value: bool):
value = bool(value)
if self.__lock_to_render_result != value:
self.__lock_to_render_result = value
if self.__viewport_texture:
self.__viewport_texture._render_settings_changed()
@property
def freeze_frame(self) -> bool:
return self.__freeze_frame
@freeze_frame.setter
def freeze_frame(self, value: bool):
self.__freeze_frame = bool(value)
@property
def updates_enabled(self) -> bool:
return self.__updates_enabled
@updates_enabled.setter
def updates_enabled(self, value: bool):
value = bool(value)
if self.__updates_enabled != value:
self.__updates_enabled = value
if self.__hydra_texture:
self.__hydra_texture.set_updates_enabled(value)
@property
def viewport_changed(self):
return self.__viewport_changed if self.__viewport_changed else lambda c, s: None
@property
def id(self) -> str:
return self.__viewport_id
@property
def usd_context_name(self) -> str:
'''Return the name of the omni.usd.UsdContext this Viewport is attached to'''
return self.__usd_context_name
@property
def usd_context(self):
'''Return the omni.usd.UsdContext this Viewport is attached to'''
return omni.usd.get_context(self.__usd_context_name)
@property
def stage(self) -> Usd.Stage:
'''Return the Usd.Stage of the omni.usd.UsdContext this Viewport is attached to'''
return self.usd_context.get_stage()
@property
def projection(self) -> Gf.Matrix4d:
'''Return the projection of the UsdCamera in terms of the ui element it sits in.'''
return Gf.Matrix4d(self.__projection)
@property
def transform(self) -> Gf.Matrix4d:
'''Return the world-space transform of the UsdGeom.Camera being used to render'''
return Gf.Matrix4d(self.__transform)
@property
def view(self) -> Gf.Matrix4d:
'''Return the inverse of the world-space transform of the UsdGeom.Camera being used to render'''
return Gf.Matrix4d(self.__view)
@property
def time(self) -> Usd.TimeCode:
'''Return the Usd.TimeCode this Viewport is using'''
return self.__time
@property
def world_to_ndc(self) -> Gf.Matrix4d:
if not self.__world_to_ndc:
self.__world_to_ndc = self.view * self.projection
return Gf.Matrix4d(self.__world_to_ndc)
@property
def ndc_to_world(self) -> Gf.Matrix4d:
if not self.__ndc_to_world:
self.__ndc_to_world = self.world_to_ndc.GetInverse()
return Gf.Matrix4d(self.__ndc_to_world)
@property
def _scene_camera_model(self) -> "SceneCameraModel":
"""
This property fetches and returns the instance of SceneCameraModel.
If the instance has not been fetched before, it fetches and stores it.
If the instance was fetched previously, it retrieves it from the cache.
Returns:
Instance of SceneCameraModel, or None if it fails to fetch or not required.
"""
if self.__scene_camera_model is None:
self.__scene_camera_model = self.__create_scene_camera_model()
return self.__scene_camera_model
def __create_scene_camera_model(self) -> "SceneCameraModel":
"""
Creates SceneCameraModel based on the requirement from app settings.
If a scene camera model is required, it imports and initializes the SceneCameraModel.
Returns:
Instance of SceneCameraModel if required and successfully imported, else None.
"""
if self.__is_requires_scene_camera_model() and not self.__scene_camera_model_import_failed:
# Determine viewport handle by checking if __viewport_texture exists
# and has a viewport_handle attribute.
if not self.__viewport_texture or not self.__viewport_texture.viewport_handle:
viewport_handle = -1
else:
viewport_handle = self.__viewport_texture.viewport_handle
try:
from omni.kit.viewport.scene_camera_model import SceneCameraModel
return SceneCameraModel(self.usd_context_name, viewport_handle)
except ImportError: # pragma: no cover
carb.log_error("omni.kit.viewport.scene_camera_model must be enabled for singleCameraModel")
self.__scene_camera_model_import_failed = True
return None
def __is_requires_scene_camera_model(self) -> bool:
"""
Determines if the SceneCameraModel is required based on app settings.
If the setting has not been checked before, it fetches from the app settings
and stores the boolean value.
Returns:
Boolean indicating whether or not the SceneCameraModel is required.
"""
if self.__requires_scene_camera_model is None:
settings = carb.settings.acquire_settings_interface()
self.__requires_scene_camera_model = bool(
settings.get("/ext/omni.kit.widget.viewport/sceneView/singleCameraModel/enabled")
)
return self.__requires_scene_camera_model
def map_ndc_to_texture(self, mouse: Sequence[float]) -> Tuple[Tuple[float, float], 'ViewportAPI']:
ratios = self.__aspect_ratios
# Move into viewport's NDC-space: [-1, 1] bound by viewport
mouse = (mouse[0] / ratios[0], mouse[1] / ratios[1])
# Move from NDC space to texture-space [-1, 1] to [0, 1]
def check_bounds(coord): return coord >= -1 and coord <= 1
return tuple((x + 1.0) * 0.5 for x in mouse), self if (check_bounds(mouse[0]) and check_bounds(mouse[1])) else None
def map_ndc_to_texture_pixel(self, mouse: Sequence[float]) -> Tuple[Tuple[float, float], 'ViewportAPI']:
# Move into viewport's uv-space: [0, 1]
mouse, viewport = self.map_ndc_to_texture(mouse)
# Then scale by resolution flipping-y
resolution = self.resolution
return (int(mouse[0] * resolution[0]), int((1.0 - mouse[1]) * resolution[1])), viewport
def __get_conform_policy(self):
'''
TODO: Need python exposure via UsdContext or HydraTexture
import carb
conform_setting = carb.settings.get_settings().get("/app/hydra/aperture/conform")
if (conform_setting is None) or (conform_setting == 1) or (conform_setting == 'horizontal'):
return CameraUtil.MatchHorizontally
if (conform_setting == 0) or (conform_setting == 'vertical'):
return CameraUtil.MatchVertically
if (conform_setting == 2) or (conform_setting == 'fit'):
return CameraUtil.Fit
if (conform_setting == 3) or (conform_setting == 'crop'):
return CameraUtil.Crop
if (conform_setting == 4) or (conform_setting == 'stretch'):
return CameraUtil.DontConform
'''
return CameraUtil.MatchHorizontally
def _conform_projection(self, policy, camera: UsdGeom.Camera, image_aspect: float, canvas_aspect: float, projection: Sequence[float] = None):
'''For the given camera (or possible incoming projection) return a projection matrix that matches the rendered image
but keeps NDC co-ordinates for the texture bound to [-1, 1]'''
if projection is None:
# If no projection is provided, conform the camera based on settings
# This wil adjust apertures on the gf_camera
gf_camera = camera.GetCamera(self.__time)
if policy == CameraUtil.DontConform:
# For DontConform, still have to conform for the final canvas
if image_aspect < canvas_aspect:
gf_camera.horizontalAperture = gf_camera.horizontalAperture * (canvas_aspect / image_aspect)
else:
gf_camera.verticalAperture = gf_camera.verticalAperture * (image_aspect / canvas_aspect)
else:
CameraUtil.ConformWindow(gf_camera, policy, image_aspect)
projection = gf_camera.frustum.ComputeProjectionMatrix()
self.__flat_rendered_projection = self.__flatten_matrix(projection)
else:
self.__flat_rendered_projection = projection
projection = Gf.Matrix4d(*projection)
# projection now has the rendered image projection
# Conform again based on canvas size so projection extends with the Viewport sits in the UI
if image_aspect < canvas_aspect:
self.__aspect_ratios = (image_aspect / canvas_aspect, 1)
policy2 = CameraUtil.MatchVertically
else:
self.__aspect_ratios = (1, canvas_aspect / image_aspect)
policy2 = CameraUtil.MatchHorizontally
if policy != CameraUtil.DontConform:
projection = CameraUtil.ConformedWindow(projection, policy2, canvas_aspect)
return projection
def _sync_viewport_api(self, camera: UsdGeom.Camera, canvas_size: Sequence[int],
time: Usd.TimeCode = Usd.TimeCode.Default(),
view: Sequence[float] = None, projection: Sequence[float] = None,
force_update: bool = False):
'''Sync the ui and viewport state, and inform any view-scubscribers if a change occured'''
# Early exit if the Viewport is locked to a rendered image, not updates to SceneViews or internal state
if not self.__updates_enabled or self.__freeze_frame:
return
# Store the current time
if time:
self.__time = time
# When locking to render, allow one update to push initial USD state into Viewport
# Otherwise, if locking to render results and no View provided, wait for next frame to deliver it.
if self.__first_synch:
self.__first_synch = False
elif not force_update and (self.__lock_to_render_result and not view):
return
# If forcing UI resolution to match Viewport, set the resolution now if it needs to be updated.
# Early exit in this case as it will trigger a subsequent UI -> Viewport sync.
resolution = self.full_resolution
canvas_size = (int(canvas_size[0]), int(canvas_size[1]))
# We want to be careful not to resize to 0, 0 in the case the canvas is 0, 0
if self.__fill_frame and (canvas_size[0] and canvas_size[1]):
if (resolution[0] != canvas_size[0]) or (resolution[1] != canvas_size[1]):
self.resolution = canvas_size
return
prev_xform, prev_proj = self.__transform, self.__projection
if view:
self.__view = Gf.Matrix4d(*view)
self.__transform = self.__view.GetInverse()
else:
self.__transform = camera.ComputeLocalToWorldTransform(self.__time)
self.__view = self.__transform.GetInverse()
image_aspect = resolution[0] / resolution[1] if resolution[1] else 1
canvas_aspect = canvas_size[0] / canvas_size[1] if canvas_size[1] else 1
policy = self.__get_conform_policy()
self.__projection = self._conform_projection(policy, camera, image_aspect, canvas_aspect, projection)
view_changed = self.__transform != prev_xform
proj_changed = self.__projection != prev_proj
if view_changed or proj_changed:
self.__ndc_to_world = None
self.__world_to_ndc = None
self.__notify_scene_views(view_changed, proj_changed)
self.__notify_objects(self.__view_changed)
return True
# Legacy methods that we also support
def get_active_camera(self) -> Sdf.Path:
'''Return an Sdf.Path to the active rendering camera'''
return self.camera_path
def set_active_camera(self, camera_path: Sdf.Path):
'''Set the active rendering camera from an Sdf.Path'''
self.camera_path = camera_path
def get_render_product_path(self) -> str:
'''Return a string to the UsdRender.Product used by the Viewport'''
return self.render_product_path
def set_render_product_path(self, product_path: str):
'''Set the UsdRender.Product used by the Viewport with a string'''
self.render_product_path = product_path
def get_texture_resolution(self) -> Tuple[float, float]:
'''Return a tuple of (resolution_x, resolution_y)'''
return self.resolution
def set_texture_resolution(self, value: Tuple[float, float]):
'''Set the resolution to render with (resolution_x, resolution_y)'''
self.resolution = value
def get_texture_resolution_scale(self) -> float:
'''Get the scaling factor for the Viewport's render resolution.'''
return self.resolution_scale
def set_texture_resolution_scale(self, value: float):
'''Set the scaling factor for the Viewport's render resolution.'''
self.resolution_scale = value
def get_full_texture_resolution(self) -> Tuple[float, float]:
'''Return a tuple of (full_resolution_x, full_resolution_y)'''
return self.full_resolution
# Semi Private access, do not assume these will always be available by guarding usage and access.
@property
def display_render_var(self) -> str:
if self.__viewport_texture:
return self.__viewport_texture.display_render_var
@display_render_var.setter
def display_render_var(self, name: str):
if self.__viewport_texture:
self.__viewport_texture.display_render_var = str(name)
@property
def _settings_path(self) -> str:
return self.__hydra_texture.get_settings_path() if self.__hydra_texture else None
@property
def _hydra_texture(self):
return self.__hydra_texture
@property
def _viewport_texture(self):
return self.__viewport_texture
def _notify_frame_change(self):
self.__notify_objects(self.__frame_changed)
def _notify_render_settings_change(self):
self.__notify_objects(self.__render_settings_changed)
# Very Private methods
def __set_hydra_texture(self, viewport_texture, hydra_texture):
# Transfer any local state this instance is carying
if hydra_texture:
hydra_texture.set_updates_enabled(self.__updates_enabled)
_scene_camera_model = self._scene_camera_model
if _scene_camera_model:
if not viewport_texture or not viewport_texture.viewport_handle:
_scene_camera_model.set_viewport_handle(-1)
else:
_scene_camera_model.set_viewport_handle(viewport_texture.viewport_handle)
# Replace the references this instance has
self.__viewport_texture = viewport_texture
self.__hydra_texture = hydra_texture
def __callback_args(self, fn_container: Sequence):
# Send a proxy so nobody can retain the instance directly
vp_api = weakref.proxy(self)
if id(fn_container) == id(self.__render_settings_changed):
return (self.camera_path, self.resolution, vp_api)
return (vp_api,)
def __subscribe_to_change(self, callback: Callable, container: set, name: str):
if not callable(callback):
raise ValueError(f'ViewportAPI {name} requires a callable object')
# If we're in a valid state, invoke the callback now.
# If it throws we leave it up to the caller to figure out why and re-subscribe
if self.__viewport_texture and self.__hydra_texture:
callback(*self.__callback_args(container))
return ViewportAPI.__ViewportSubscription(callback, container)
def __notify_objects(self, fn_container: Sequence):
if fn_container:
args = self.__callback_args(fn_container)
for fn in fn_container.copy():
try:
fn(*args)
except Exception: # pragma: no cover
_report_error()
def __notify_scene_views(self, view: bool, proj: bool):
if not self.__scene_views:
return
# Since these are weak-refs, prune any objects that may have gone out of date
active_views = []
# Flatten these once for the loop below
if view:
view = [self.__view[0][0], self.__view[0][1], self.__view[0][2], self.__view[0][3], self.__view[1][0], self.__view[1][1], self.__view[1][2], self.__view[1][3], self.__view[2][0], self.__view[2][1], self.__view[2][2], self.__view[2][3], self.__view[3][0], self.__view[3][1], self.__view[3][2], self.__view[3][3]]
if proj:
proj = [self.__projection[0][0], self.__projection[0][1], self.__projection[0][2], self.__projection[0][3], self.__projection[1][0], self.__projection[1][1], self.__projection[1][2], self.__projection[1][3], self.__projection[2][0], self.__projection[2][1], self.__projection[2][2], self.__projection[2][3], self.__projection[3][0], self.__projection[3][1], self.__projection[3][2], self.__projection[3][3]]
for sv_ref in self.__scene_views:
scene_view = sv_ref()
if scene_view:
active_views.append(sv_ref)
try:
sv_model = scene_view.model
view_item, proj_item = None, None
_scene_camera_model = self._scene_camera_model
if _scene_camera_model is None and view:
view_item = sv_model.get_item('view')
sv_model.set_floats(view_item, view)
if proj:
proj_item = sv_model.get_item('projection')
sv_model.set_floats(proj_item, proj)
# Update both or just a single item
sv_model._item_changed(None if (view_item and proj_item) else (view_item or proj_item))
except Exception: # pragma: no cover
_report_error()
self.__scene_views = active_views
def __clean_weak_views(self, *args):
self.__scene_views = [sv for sv in self.__scene_views if sv()]
def __accelerate_rtx_changed(self, *args, **kwargs):
settings = carb.settings.get_settings()
self.__accelerate_rtx_picking = bool(settings.get("/exts/omni.kit.widget.viewport/picking/rtx/accelerate"))
@staticmethod
def __flatten_matrix(m):
# Pull individual Gf.Vec4 for each row, then index each component of those individually.
m0, m1, m2, m3 = m[0], m[1], m[2], m[3]
return [m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3]]
| 31,558 | Python | 43.701133 | 419 | 0.627575 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/display_delegate.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ['ViewportDisplayDelegate']
import omni.ui as ui
class ViewportDisplayDelegate:
def __init__(self, viewport_api):
self.__zstack = None
self.__image_provider = None
self.__image = None
def __del__(self):
self.destroy()
def destroy(self):
if self.__zstack:
self.__zstack.clear()
self.__zstack.destroy()
self.__zstack = None
if self.__image:
self.__image.destroy()
self.__image = None
if self.__image_provider:
self.__image_provider = None
@property
def image_provider(self):
return self.__image_provider
@image_provider.setter
def image_provider(self, image_provider: ui.ImageProvider):
if not isinstance(image_provider, ui.ImageProvider):
raise RuntimeError('ViewportDisplayDelegate.image_provider must be an omni.ui.ImageProvider')
# Clear any existing ui.ImageWithProvider
# XXX: ui.ImageWithProvider should have a method to swap this out
if self.__image:
self.__image.destroy()
self.__image = None
self.__image_provider = image_provider
self.__image = ui.ImageWithProvider(self.__image_provider,
style_type_name_override='ViewportImage',
name='Color')
def create(self, ui_frame, prev_delegate, *args, **kwargs):
# Save the previous ImageProvider early to keep it alive
image_provider = prev_delegate.image_provider if prev_delegate else None
self.destroy()
with ui_frame:
self.__zstack = ui.ZStack()
with self.__zstack:
if not image_provider:
image_provider = ui.ImageProvider(name='ViewportImageProvider')
self.image_provider = image_provider
return self.__zstack
def update(self, viewport_api, texture, view, projection, presentation_key=None):
self.__image_provider.set_image_data(texture, presentation_key=presentation_key)
return self.size
@property
def size(self):
return (int(self.__image.computed_width), int(self.__image.computed_height))
class OverlayViewportDisplayDelegate(ViewportDisplayDelegate):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__overlay_image = None
self.__overlay_provider = None
def __del__(self):
self.destroy()
def destroy(self):
if self.__overlay_image:
self.__overlay_image.destroy()
self.__overlay_image = None
if self.__overlay_provider:
self.__overlay_provider = None
super().destroy()
def create(self, ui_frame, prev_delegate, *args, **kwargs):
# Grab the last image and put to push as the last element in the parent ui.Stack
prev_provider = prev_delegate.image_provider if prev_delegate else None
# Build the default ui for the Viewports display, but don't pass along any previous delegate/image
ui_stack = super().create(ui_frame, None, *args, **kwargs)
if ui_stack and prev_provider:
with ui_stack:
self.__overlay_provider = prev_provider
self.__overlay_image = ui.ImageWithProvider(self.__overlay_provider,
style_type_name_override='ViewportImageOverlay',
name='Overlay')
return ui_stack
def set_overlay_alpha(self, overlay_alpha: float):
self.__overlay_image.set_style({
'ViewportImageOverlay': {
'color': ui.color(1.0, 1.0, 1.0, overlay_alpha)
}
})
| 4,262 | Python | 36.725663 | 108 | 0.600657 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/widget.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ['ViewportWidget']
from .api import ViewportAPI
from .impl.texture import ViewportTexture
from .impl.utility import init_settings, save_implicit_cameras, StageAxis
from .display_delegate import ViewportDisplayDelegate
from omni.kit.async_engine import run_coroutine
import omni.ui as ui
import omni.usd
import carb.events
import carb.settings
from pxr import Usd, UsdGeom, Sdf, Tf
from typing import Optional, Tuple, Union
import weakref
import asyncio
import concurrent.futures
class ViewportWidget:
"""The Viewport Widget
Simplest implementation of a viewport which you must control 100%
"""
__g_instances = []
@classmethod
def get_instances(cls):
for inst in cls.__g_instances:
yield inst
@classmethod
def __clean_instances(cls, dead, self=None):
active = []
for p in ViewportWidget.__g_instances:
try:
if p and p != self:
active.append(p)
except ReferenceError:
pass
ViewportWidget.__g_instances = active
@property
def viewport_api(self):
return self.__proxy_api
@property
def name(self):
return self.__ui_frame.name
@property
def visible(self):
return self.__ui_frame.visible
@visible.setter
def visible(self, value):
self.__ui_frame.visible = bool(value)
def __init__(self,
usd_context_name: str = '',
camera_path: Optional[str] = None,
resolution: Optional[tuple] = None,
hd_engine: Optional[str] = None,
viewport_api: Union[ViewportAPI, str, None] = None,
hydra_engine_options: Optional[dict] = None,
*ui_args, **ui_kwargs):
"""ViewportWidget contructor
Args:
usd_context_name (str): The name of a UsdContext this Viewport will be viewing.
camera_path (str): The path to a UsdGeom.Camera to render with.
resolution: (x,y): The size of the backing texture that is rendered into (or 'fill_frame' to lock to UI size).
viewport_api: (ViewportAPI, str) A ViewportAPI instance that users have access to via .viewport_api property
or a unique string id used to create a default ViewportAPI instance.
"""
self.__ui_frame: ui.Frame = ui.Frame(*ui_args, **ui_kwargs)
self.__viewport_texture: Optional[ViewportTexture] = None
self.__display_delegate: Optional[ViewportDisplayDelegate] = None
self.__g_instances.append(weakref.proxy(self, ViewportWidget.__clean_instances))
self.__stage_listener = None
self.__rsettings_changed = None
if not viewport_api or not isinstance(viewport_api, ViewportAPI):
viewport_id = viewport_api if viewport_api else str(id(self))
self.__vp_api: ViewportAPI = ViewportAPI(usd_context_name, viewport_id, self._viewport_changed)
else:
self.__vp_api: ViewportAPI = viewport_api
# This object or it's parent-scope instantiator own the API, so hand out a weak-ref proxy
self.__proxy_api = weakref.proxy(self.__vp_api)
self.__update_api_texture = self.__vp_api._ViewportAPI__set_hydra_texture
self.__stage_up: Optional[StageAxis] = None
self.__size_changed: bool = False
self.__resize_future: Optional[asyncio.Future] = None
self.__resize_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None
self.__push_ui_to_viewport: bool = False
self.__expand_viewport_to_ui: bool = False
self.__full_resolution: Tuple[float, float] = (0.0, 0.0)
# Whether to account for DPI when driving the Viewport resolution
self.__resolution_uses_dpi: bool = True
resolution = self.__resolve_resolution(resolution)
# Save any arguments to send to HydraTexture in a local kwargs dict
self.__hydra_engine_options = hydra_engine_options
# TODO: Defer ui creation until stage open
self.__build_ui(usd_context_name, camera_path, resolution, hd_engine)
def on_usd_context_event(event: carb.events.IEvent):
if event.type == int(omni.usd.StageEventType.OPENED):
self.__on_stage_opened(self.__ensure_usd_stage(), camera_path, resolution, hd_engine)
elif event.type == int(omni.usd.StageEventType.CLOSING):
self.__remove_notifications()
elif event.type == int(omni.usd.StageEventType.SETTINGS_SAVING):
# XXX: This might be better handled at a higher level or allow opt into implicit camera saving
if carb.settings.get_settings().get("/app/omni.usd/storeCameraSettingsToUsdStage"):
if self.__vp_api:
time, camera = self.__vp_api.time, str(self.__vp_api.camera_path)
else:
time, camera = None, None
save_implicit_cameras(self.__ensure_usd_stage(), time, camera)
usd_context = self.__ensure_usd_context()
self.__stage_subscription = usd_context.get_stage_event_stream().create_subscription_to_pop(
on_usd_context_event, name=f'ViewportWidget {self.name} on_usd_context_event'
)
stage = usd_context.get_stage()
if stage:
self.__on_stage_opened(stage, camera_path, resolution, hd_engine)
elif usd_context and carb.settings.get_settings().get("/exts/omni.kit.widget.viewport/autoAttach/mode") == 2:
# Initialize the auto-attach now, but watch for all excpetions so that constructor returns properly and this
# ViewportWidget is valid and fully constructed in order to try and re-setup on next stage open
try:
resolution, tx_resolution = self.__get_texture_resolution(resolution)
self.__viewport_texture = ViewportTexture(usd_context_name, camera_path, tx_resolution, hd_engine,
hydra_engine_options=self.__hydra_engine_options,
update_api_texture=self.__update_api_texture)
self.__update_api_texture(self.__viewport_texture, None)
self.__viewport_texture._on_stage_opened(self.__set_image_data, camera_path, self.__is_first_instance())
except Exception:
import traceback
carb.log_error(traceback.format_exc())
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
# Clean ourself from the instance list
ViewportWidget.__clean_instances(None, self)
self.__stage_subscription = None
self.__remove_notifications()
if self.__vp_api:
clear_engine = self.__vp_api.set_hd_engine
if clear_engine:
clear_engine(None)
self.__update_api_texture(None, None)
self.__destroy_ui()
self.__vp_api = None
self.__proxy_api = None
self.__resize_task_or_future = None
@property
def usd_context_name(self):
return self.__vp_api.usd_context_name
@property
def display_delegate(self):
return self.__display_delegate
@display_delegate.setter
def display_delegate(self, display_delegate: ViewportDisplayDelegate):
if not isinstance(display_delegate, ViewportDisplayDelegate):
raise RuntimeError('display_delegate must be a ViewportDisplayDelegate, {display_delegate} is not')
# Store the previous delegate for return value and comparison wtether anything is actually changing
prev_delegate = self.__display_delegate
# If the delegate is different, call the create method and change this instance's value if succesful
if prev_delegate != display_delegate:
self.__ui_frame.clear()
display_delegate.create(self.__ui_frame, prev_delegate)
self.__display_delegate = display_delegate
# Return the previous delegate so callers can swap and restore
return prev_delegate
def _viewport_changed(self, camera_path: Sdf.Path, stage: Usd.Stage, time: Usd.TimeCode = Usd.TimeCode.Default()):
# During re-open camera_path can wind up in an empty state, so be careful around getting the UsdGeom.Camera
prim = stage.GetPrimAtPath(camera_path) if (camera_path and stage) else None
camera = UsdGeom.Camera(prim) if prim else None
if not camera:
return None, None, None
canvas_size = self.__display_delegate.size
force_update = self.__size_changed
self.__vp_api._sync_viewport_api(camera, canvas_size, time, force_update=force_update)
return camera, canvas_size, time
def __ensure_usd_context(self, usd_context: omni.usd.UsdContext = None):
if not usd_context:
usd_context = self.__vp_api.usd_context
if not usd_context:
raise RuntimeError(f'omni.usd.UsdContext "{self.usd_context_name}" does not exist')
return usd_context
def __ensure_usd_stage(self, usd_context: omni.usd.UsdContext = None):
stage = self.__ensure_usd_context(usd_context).get_stage()
if stage:
return stage
raise RuntimeError(f'omni.usd.UsdContext "{self.usd_context_name}" has no stage')
def __remove_notifications(self):
# Remove notifications that are -transient- or related to a stage and can be easily setup
if self.__stage_listener:
self.__stage_listener.Revoke()
self.__stage_listener = None
if self.__rsettings_changed and self.__viewport_texture:
self.__viewport_texture._remove_render_settings_changed_fn(self.__rsettings_changed)
self.__rsettings_changed = None
if self.__ui_frame:
self.__ui_frame.set_computed_content_size_changed_fn(None)
# self.set_build_fn(None)
def __setup_notifications(self, stage: Usd.Stage, hydra_texture):
# Remove previous -soft- notifications
self.__remove_notifications()
# Proxy these two object so as not to extend their lifetime the API object
if hydra_texture and not isinstance(hydra_texture, weakref.ProxyType):
hydra_texture = weakref.proxy(hydra_texture)
assert hydra_texture is None or isinstance(hydra_texture, weakref.ProxyType), "Not sending a proxied object"
self.__update_api_texture(weakref.proxy(self.__viewport_texture), hydra_texture)
# Stage changed notification (Tf.Notice)
def stage_changed_notice(notice, sender):
camera_path = self.__vp_api.camera_path
if not camera_path:
return
first_instance = self.__is_first_instance()
camera_path_str = camera_path.pathString
for p in notice.GetChangedInfoOnlyPaths():
if p == Sdf.Path.absoluteRootPath:
if self.__stage_up.update(sender, self.__vp_api.time, self.usd_context_name, first_instance):
self.__vp_api.viewport_changed(camera_path, self.__ensure_usd_stage())
break
prim_path = p.GetPrimPath()
# If it is the camera path, assume any property change can affect view/projection
if prim_path != camera_path:
# Not the camera path, but any transform change to any parent also affects view
is_child = camera_path_str.startswith(prim_path.pathString)
if not is_child or not UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name):
continue
self.__vp_api.viewport_changed(camera_path, self.__ensure_usd_stage())
break
# omni.ui notification that the widget size has changed
def update_size():
try:
self.__size_changed = True
self.__root_size_changed()
self.__vp_api.viewport_changed(self.__vp_api.camera_path, self.__ensure_usd_stage())
finally:
self.__size_changed = False
# async version to ellide intermediate resize event
async def resize_future(n_frames: int, mouse_wait: int, mouse_up: bool, update_projection: bool = False):
import omni.appwindow
import omni.kit.app
import carb.input
if update_projection:
prim = stage.GetPrimAtPath(self.__vp_api.camera_path)
camera = UsdGeom.Camera(prim) if prim else None
if not camera:
update_projection = False
app = omni.kit.app.get_app()
async def skip_frame():
await app.next_update_async()
if update_projection:
self.__vp_api._sync_viewport_api(camera, self.__display_delegate.size, force_update=True)
if mouse_wait or mouse_up:
iinput = carb.input.acquire_input_interface()
app_window = omni.appwindow.get_default_app_window()
mouse = app_window.get_mouse()
mouse_value = iinput.get_mouse_value(mouse, carb.input.MouseInput.LEFT_BUTTON)
frames_waited, mouse_static, prev_mouse = 0, 0, None
while mouse_value:
await skip_frame()
frames_waited = frames_waited + 1
# Check mouse up no matter what, up cancels even if waiting for mouse paused
mouse_value = iinput.get_mouse_value(mouse, carb.input.MouseInput.LEFT_BUTTON)
if mouse_wait and mouse_value:
if mouse_static > mouse_wait:
# Else if the mouse has been on same pixel for more than required time, done
break
else:
# Compare current and previous mouse locations
cur_mouse = iinput.get_mouse_coords_pixel(mouse)
if prev_mouse:
if (cur_mouse[0] == prev_mouse[0]) and (cur_mouse[1] == prev_mouse[1]):
mouse_static = mouse_static + 1
else:
mouse_static = 0
prev_mouse = cur_mouse
# Make sure to wait the miniumum nuber of frames as well
if n_frames:
n_frames = max(0, n_frames - frames_waited)
for _ in range(n_frames):
await skip_frame()
# Check it hasn't been handled alredy once more
if self.__resize_future.done():
return
# Finally flag it as handled and push the size change
self.__resize_future.set_result(True)
update_size()
def size_changed_notification(*args, **kwargs):
# Ellide intermediate resize events when pushing ui size to Viewport
if self.__push_ui_to_viewport or self.__expand_viewport_to_ui or self.__vp_api.fill_frame:
if self.__resize_future and not self.__resize_future.done():
return
# Setting that controls the number of ui-frame delay
settings = carb.settings.get_settings()
f_delay = settings.get("/exts/omni.kit.widget.viewport/resize/textureFrameDelay")
mouse_pause = settings.get("/exts/omni.kit.widget.viewport/resize/waitForMousePaused")
mouse_up = settings.get("/exts/omni.kit.widget.viewport/resize/waitForMouseUp")
update_proj = settings.get("/exts/omni.kit.widget.viewport/resize/updateProjection")
if f_delay or mouse_pause or mouse_up:
self.__resize_future = asyncio.Future()
self.__resize_task_or_future = run_coroutine(resize_future(f_delay, mouse_pause, mouse_up, update_proj))
return
update_size()
# hydra_texture notification that the render-settings have changed (we only care about camera and resolution)
def render_settings_changed(camera_path, resolution):
# Notify everything else in the chain
self.__vp_api.viewport_changed(camera_path, self.__ensure_usd_stage())
self.__vp_api._notify_render_settings_change()
self.__stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, lambda n, s: stage_changed_notice(n, s), stage)
self.__rsettings_changed = self.__viewport_texture._add_render_settings_changed_fn(render_settings_changed)
self.__ui_frame.set_computed_content_size_changed_fn(size_changed_notification)
# self.set_build_fn(update_size)
# Update now if the widget is layed out
if self.__ui_frame.computed_height:
update_size()
def __resolve_resolution(self, resolution):
# XXX: ViewportWindow handles the de-serialization of saved Viewport resolution.
# This means clients of ViewportWidget only must handle startup resolution themselves.
if resolution is None:
# Support legacy settings to force fit-viewport
settings = carb.settings.get_settings()
width, height = settings.get('/app/renderer/resolution/width'), settings.get('/app/renderer/resolution/height')
# If both are set to values above 0, that is the default resolution for a Viewport
# If either of these being zero or below causes autmoatic resolution to fill the UI frame
if ((width is not None) and (width > 0)) and ((height is not None) and (height > 0)):
resolution = (width, height)
elif ((width is not None) and (width <= 0)) or ((height is not None) and (height <= 0)):
resolution = 'fill_frame'
# Allow a 'fill_frame' constant to be used for resolution
# Any constant zero or below also fills frame (support legacy behavior)
if (resolution is not None) and ((isinstance(resolution, str) and resolution == 'fill_frame') or int(resolution[0]) <= 0 or int(resolution[1]) <= 0):
resolution = 'fill_frame'
self.__vp_api.fill_frame = True
# Allow a 'fill_frame' constant to be used for resolution
# Any constant zero or below also fills frame (support legacy behavior)
if (resolution is not None):
if (isinstance(resolution, str) and resolution == 'fill_frame') or int(resolution[0]) <= 0 or int(resolution[1]) <= 0:
resolution = 'fill_frame'
self.__push_ui_to_viewport = True
self.__vp_api.fill_frame = True
else:
self.__full_resolution = resolution
return resolution
def __get_texture_resolution(self, resolution: Union[str, tuple]):
# Don't pass 'fill_frame' to ViewportTexture if it was requested, that will be done during layout anyway
if resolution == 'fill_frame':
return ((0, 0), None)
return resolution, resolution
def __build_ui(self, usd_context_name: str, camera_path: str, resolution: Union[str, tuple], hd_engine: str):
# Required for a lot of things (like selection-color) to work!
init_settings()
resolution, tx_resolution = self.__get_texture_resolution(resolution)
# the viewport texture is the base background inmage that is drive by the Hydra_Texture object
self.__viewport_texture = ViewportTexture(usd_context_name, camera_path, tx_resolution, hd_engine,
hydra_engine_options=self.__hydra_engine_options,
update_api_texture=self.__update_api_texture)
self.__update_api_texture(self.__viewport_texture, None)
self.display_delegate = ViewportDisplayDelegate(self.__proxy_api)
# Pull the current Viewport full resolution now (will call __root_size_changed)
self.set_resolution(resolution)
def __destroy_ui(self):
self.__display_delegate.destroy()
if self.__viewport_texture:
self.__viewport_texture.destroy()
self.__viewport_texture = None
if self.__ui_frame:
self.__ui_frame.destroy()
self.__ui_frame = None
def __is_first_instance(self) -> bool:
for vp_instance in self.__g_instances:
if vp_instance == self:
# vpinstance is this object, and no other instances attached to named UsdContext has been seen
return True
elif vp_instance.usd_context_name == self.usd_context_name:
# vpinstance is NOT this object, but vpinstance is attached to same UsdContext
return False
# Should be unreachable, but would be True in the event neither case above was triggered
return True
def __set_image_data(self, texture, presentation_key = 0):
vp_api = self.__vp_api
prim = self.__ensure_usd_stage().GetPrimAtPath(vp_api.camera_path)
camera = UsdGeom.Camera(prim) if prim else None
frame_info = vp_api.frame_info
lock_to_render = vp_api.lock_to_render_result
view = frame_info.get('view', None) if lock_to_render else None
# omni.ui.scene may not handle RTX projection yet, so calculate from USD camera
projection = None # frame_info.get('projection', None) if lock_to_render else None
canvas_size = self.__display_delegate.update(viewport_api=vp_api, texture=texture, view=view, projection=projection, presentation_key=presentation_key)
vp_api._sync_viewport_api(camera, canvas_size, vp_api.time, view, projection, force_update=True)
vp_api._notify_frame_change()
def __on_stage_opened(self, stage: Usd.Stage, camera_path: str, resolution: tuple, hd_engine: str):
"""Called when opening a new stage"""
# We support creation of ViewportWidget with an explicit path.
# If that path was not given or does not exists, fall-back to ov-metadata
if camera_path:
cam_prim = stage.GetPrimAtPath(camera_path)
if not cam_prim or not UsdGeom.Camera(cam_prim):
camera_path = False
if not camera_path:
# TODO: 104 Put in proper namespace and per viewport
# camera_path = stage.GetMetadataByDictKey("customLayerData", f"cameraSettings:{self.__vp_api.id}:boundCamera") or
# Fallback to < 103.1 boundCamera
try:
# Wrap in a try-catch so failure reading metadata does not cascade to caller.
camera_path = stage.GetMetadataByDictKey("customLayerData", "cameraSettings:boundCamera")
except Tf.ErrorException as e:
carb.log_error(f"Error reading Usd.Stage's boundCamera metadata {e}")
# Cache the known up-axis to watch for changes
self.__stage_up = StageAxis(stage)
if self.__viewport_texture is None:
self.__build_ui(self.usd_context_name, camera_path, resolution, hd_engine)
else:
self.__viewport_texture.camera_path = camera_path
hydra_texture = self.__viewport_texture._on_stage_opened(self.__set_image_data, camera_path, self.__is_first_instance())
self.__setup_notifications(stage, hydra_texture)
# XXX: Temporary API for driving Viewport resolution based on UI. These may be removed.
@property
def resolution_uses_dpi(self) -> bool:
"""Whether to account for DPI when driving the Viewport texture resolution"""
return self.__resolution_uses_dpi
@property
def fill_frame(self) -> bool:
"""Whether the ui object containing the Viewport texture expands both dimensions of resolution based on the ui size"""
return self.__push_ui_to_viewport
@property
def expand_viewport(self) -> bool:
"""Whether the ui object containing the Viewport texture expands one dimension of resolution to cover the full ui size"""
return self.__expand_viewport_to_ui
@resolution_uses_dpi.setter
def resolution_uses_dpi(self, value: bool) -> None:
"""Tell the ui object whether to use DPI scale when driving the Viewport texture resolution"""
value = bool(value)
if self.__resolution_uses_dpi != value:
self.__resolution_uses_dpi = value
self.__root_size_changed()
@fill_frame.setter
def fill_frame(self, value: bool) -> None:
"""Tell the ui object containing the Viewport texture to expand both dimensions of resolution based on the ui size"""
value = bool(value)
if self.__push_ui_to_viewport != value:
self.__push_ui_to_viewport = value
if not self.__root_size_changed():
self.__vp_api.resolution = self.__full_resolution
@expand_viewport.setter
def expand_viewport(self, value: bool) -> None:
"""Tell the ui object containing the Viewport texture to expand one dimension of resolution to cover the full ui size"""
value = bool(value)
if self.__expand_viewport_to_ui != value:
self.__expand_viewport_to_ui = value
if not self.__root_size_changed():
self.__vp_api.resolution = self.__full_resolution
def set_resolution(self, resolution: Tuple[float, float]) -> None:
self.__full_resolution = resolution
# When resolution is <= 0, that means ui.Frame drives Viewport resolution
self.__push_ui_to_viewport = (resolution is None) or (resolution[0] <= 0) or (resolution[1] <= 0)
if not self.__root_size_changed():
# If neither option is enabled, then just set the resolution directly
self.__vp_api.resolution = resolution
@property
def resolution(self) -> Tuple[float, float]:
return self.__vp_api.resolution
@resolution.setter
def resolution(self, resolution: Tuple[float, float]):
self.set_resolution(resolution)
@property
def full_resolution(self):
return self.__full_resolution
def __root_size_changed(self, *args, **kwargs):
# If neither options are enabled, then do nothing to the Viewport's resolution
if not self.__push_ui_to_viewport and not self.__expand_viewport_to_ui:
return False
# Match the legacy Viewport resolution and fit
# XXX: Note for a downsampled constant resolution, that is expanded to the Viewport dimensions
# the order of operation is off if one expectes 512 x 512 @ 1 to 1024 x 1024 @ 0.5 to exapnd to the same result
# Get the omni.ui.Widget computed size
ui_frame = self.__ui_frame
res_x, res_y = int(ui_frame.computed_width), int(ui_frame.computed_height)
# Scale by DPI as legacy Viewport (to match legacy Viewport calculations)
dpi_scale = ui.Workspace.get_dpi_scale() if self.__resolution_uses_dpi else 1.0
res_x, res_y = res_x * dpi_scale, res_y * dpi_scale
# Full resolution width and hight
fres_x, fres_y = self.__full_resolution if self.__full_resolution else (res_x, res_y)
if self.__expand_viewport_to_ui and (fres_y > 0) and (res_y > 0):
tex_ratio = fres_x / fres_y
ui_ratio = res_x / res_y
if tex_ratio < ui_ratio:
fres_x = fres_x * (ui_ratio / tex_ratio)
else:
fres_y = fres_y * (tex_ratio / ui_ratio)
# Limit the resolution to not grow too large
res_x, res_y = min(res_x, fres_x), min(res_y, fres_y)
self.__vp_api.resolution = res_x, res_y
return True
| 28,492 | Python | 48.125862 | 159 | 0.615752 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_scene_view_integration.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.
##
__all__ = ["TestSceneViewIntegration"]
from omni.kit.widget.viewport import ViewportWidget
from omni.ui.tests.test_base import OmniUiTest
import omni.usd
from pathlib import Path
import carb
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve()
TEST_FILES_DIR = CURRENT_PATH.joinpath('tests')
USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd')
TEST_WIDTH, TEST_HEIGHT = 360, 240
class TestSceneViewIntegration(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
await omni.usd.get_context().new_stage_async()
# After running each test
async def tearDown(self):
await super().tearDown()
await self.linux_gpu_shutdown_workaround()
async def linux_gpu_shutdown_workaround(self, usd_context_name : str = ''):
await self.wait_n_updates(10)
omni.usd.release_all_hydra_engines(omni.usd.get_context(usd_context_name))
await self.wait_n_updates(10)
async def open_usd_file(self, filename: str, resolved: bool = False):
usd_context = omni.usd.get_context()
usd_path = str(USD_FILES_DIR.joinpath(filename) if not resolved else filename)
await usd_context.open_stage_async(usd_path)
return usd_context
def assertAlmostEqual(self, a, b, places: int = 4):
if isinstance(a, float) or isinstance(a, int):
super().assertAlmostEqual(a, b, places)
else:
for i in range(len(b)):
super().assertAlmostEqual(a[i], b[i], places)
async def test_scene_view_compositing(self):
"""Test adding a SceneView to the Viewport will draw correctly"""
await self.open_usd_file("cube.usda")
import omni.ui
import omni.ui.scene
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
# Need a Window otherwise the ui size calculations won't run
window_flags = omni.ui.WINDOW_FLAGS_NO_RESIZE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR
style = {"border_width": 0}
window = omni.ui.Window("Test", width=TEST_WIDTH, height=TEST_HEIGHT, flags=window_flags, padding_x=0, padding_y=0)
with window.frame:
window.frame.set_style(style)
with omni.ui.ZStack():
viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT), style=style)
scene_view = omni.ui.scene.SceneView(style=style)
with scene_view.scene:
size = 50
vertex_indices = [0, 1, 3, 2, 4, 6, 7, 5, 6, 2, 3, 7, 4, 5, 1, 0, 4, 0, 2, 6, 5, 7, 3, 1]
points = [(-size, -size, size), (size, -size, size), (-size, size, size),
(size, size, size), (-size, -size, -size), (size, -size, -size),
(-size, size, -size), (size, size, -size)]
omni.ui.scene.PolygonMesh(points,
[[1.0, 0.0, 1.0, 0.5]] * len(vertex_indices),
vertex_counts=[4] * 6,
vertex_indices=vertex_indices,
wireframe=True,
thicknesses=[2] * len(vertex_indices))
viewport_widget.viewport_api.add_scene_view(scene_view)
await self.wait_n_updates(32)
await self.finalize_test(golden_img_dir=TEST_FILES_DIR, golden_img_name="test_scene_view_compositing.png")
viewport_widget.viewport_api.remove_scene_view(scene_view)
viewport_widget.destroy()
del viewport_widget
| 4,183 | Python | 42.583333 | 125 | 0.608654 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_widget.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.
##
__all__ = ["TestWidgetAPI"]
import omni.kit.test
from omni.kit.widget.viewport import ViewportWidget
from omni.kit.widget.viewport.display_delegate import ViewportDisplayDelegate, OverlayViewportDisplayDelegate
from omni.kit.test import get_test_output_path
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.commands
import omni.usd
import carb
from pxr import Gf, Sdf, Usd, UsdGeom
from pathlib import Path
import traceback
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve()
TEST_FILES_DIR = CURRENT_PATH.joinpath('tests')
USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd')
OUTPUTS_DIR = Path(get_test_output_path())
TEST_WIDTH, TEST_HEIGHT = 360, 240
class TestWidgetAPI(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
await omni.usd.get_context().new_stage_async()
# After running each test
async def tearDown(self):
await super().tearDown()
await self.linux_gpu_shutdown_workaround()
async def linux_gpu_shutdown_workaround(self, usd_context_name : str = ''):
await self.wait_n_updates(10)
omni.usd.release_all_hydra_engines(omni.usd.get_context(usd_context_name))
await self.wait_n_updates(10)
async def open_usd_file(self, filename: str, resolved: bool = False):
usd_context = omni.usd.get_context()
usd_path = str(USD_FILES_DIR.joinpath(filename) if not resolved else filename)
await usd_context.open_stage_async(usd_path)
return usd_context
def assertAlmostEqual(self, a, b, places: int = 4):
if isinstance(a, float) or isinstance(a, int):
super().assertAlmostEqual(a, b, places)
else:
for i in range(len(b)):
super().assertAlmostEqual(a[i], b[i], places)
async def test_widget_pre_open(self):
"""Test ViewportWidget creation with existing UsdContext and Usd.Stage and startup resolutin settings"""
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
usd_context = await self.open_usd_file('cube.usda')
self.assertIsNotNone(usd_context.get_stage())
usd_context_stage = usd_context.get_stage()
settings = carb.settings.get_settings()
viewport_widget = None
try:
settings.set("/app/renderer/resolution/width", 400)
settings.set("/app/renderer/resolution/height", 400)
await self.wait_n_updates(6)
viewport_widget = ViewportWidget()
viewport_api = viewport_widget.viewport_api
# Test omni.usd.UsdContext and Usd.Stage properties
self.assertEqual(viewport_api.usd_context, usd_context)
self.assertEqual(viewport_api.stage, usd_context_stage)
self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp'))
# Test startup resolution
self.assertEqual(viewport_api.resolution, (400, 400))
self.assertEqual(viewport_api.resolution_scale, 1.0)
# Test deprecated resolution API methods (not properties)
self.assertEqual(viewport_api.resolution, viewport_api.get_texture_resolution())
viewport_api.set_texture_resolution((200, 200))
self.assertEqual(viewport_api.resolution, (200, 200))
# Test deprecated camera API methods (not properties)
self.assertEqual(viewport_api.camera_path, viewport_api.get_active_camera())
viewport_api.set_active_camera(Sdf.Path('/OmniverseKit_Top'))
self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Top'))
finally:
settings.destroy_item("/app/renderer/resolution/width")
settings.destroy_item("/app/renderer/resolution/height")
if viewport_widget:
viewport_widget.destroy()
del viewport_widget
await self.wait_n_updates(6)
await self.finalize_test_no_image()
async def test_widget_post_open(self):
"""Test ViewportWidget adopts a change to the Usd.Stage after it is visible and startup resolution scale setting"""
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
settings = carb.settings.get_settings()
viewport_widget = None
try:
settings.set("/app/renderer/resolution/width", 400)
settings.set("/app/renderer/resolution/height", 400)
settings.set("/app/renderer/resolution/multiplier", 0.5)
await self.wait_n_updates(6)
viewport_widget = ViewportWidget()
viewport_api = viewport_widget.viewport_api
# Test omni.usd.UsdContext and Usd.Stage properties
usd_context = await self.open_usd_file('sphere.usda')
self.assertIsNotNone(usd_context.get_stage())
usd_context_stage = usd_context.get_stage()
# Test display-delegate API
await self.__test_display_delegate(viewport_widget)
self.assertEqual(viewport_api.usd_context, usd_context)
self.assertEqual(viewport_api.stage, usd_context_stage)
self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp'))
# Test startup resolution
self.assertEqual(viewport_api.resolution, (200, 200))
self.assertEqual(viewport_api.resolution_scale, 0.5)
finally:
settings.destroy_item("/app/renderer/resolution/width")
settings.destroy_item("/app/renderer/resolution/height")
settings.destroy_item("/app/renderer/resolution/multiplier")
if viewport_widget:
viewport_widget.destroy()
del viewport_widget
await self.wait_n_updates(6)
await self.finalize_test_no_image()
async def test_widget_custom_camera_saved(self):
"""Test ViewportWidget will absorb the stored Kit bound camera"""
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
usd_context = await self.open_usd_file('custom_camera.usda')
self.assertIsNotNone(usd_context.get_stage())
usd_context_stage = usd_context.get_stage()
viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT))
viewport_api = viewport_widget.viewport_api
self.assertEqual(viewport_api.usd_context, usd_context)
self.assertEqual(viewport_api.stage, usd_context_stage)
self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera'))
cam_prim = viewport_api.stage.GetPrimAtPath(viewport_api.camera_path)
self.assertTrue(bool(cam_prim))
cam_geom = UsdGeom.Camera(cam_prim)
self.assertTrue(bool(cam_geom))
coi_prop = cam_prim.GetProperty('omni:kit:centerOfInterest')
self.assertTrue(bool(coi_prop))
coi_prop.Get()
world_pos = viewport_api.transform.Transform(Gf.Vec3d(0, 0, 0))
self.assertAlmostEqual(world_pos, Gf.Vec3d(250, 825, 800))
self.assertAlmostEqual(coi_prop.Get(), Gf.Vec3d(0, 0, -1176.0633486339075))
viewport_widget.destroy()
del viewport_widget
await self.finalize_test_no_image()
async def test_widget_custom_camera_contructor(self):
"""Test ViewportWidget can be contructed with a specified Camera"""
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
usd_context = await self.open_usd_file('custom_camera.usda')
self.assertIsNotNone(usd_context.get_stage())
usd_context_stage = usd_context.get_stage()
viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT), camera_path='/World/Camera_01')
viewport_api = viewport_widget.viewport_api
self.assertEqual(viewport_api.usd_context, usd_context)
self.assertEqual(viewport_api.stage, usd_context_stage)
self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera_01'))
cam_prim = viewport_api.stage.GetPrimAtPath(viewport_api.camera_path)
self.assertTrue(bool(cam_prim))
cam_geom = UsdGeom.Camera(cam_prim)
self.assertTrue(bool(cam_geom))
coi_prop = cam_prim.GetProperty('omni:kit:centerOfInterest')
self.assertTrue(bool(coi_prop))
coi_prop.Get()
world_pos = viewport_api.transform.Transform(Gf.Vec3d(0, 0, 0))
self.assertAlmostEqual(world_pos, Gf.Vec3d(350, 650, -900))
self.assertAlmostEqual(coi_prop.Get(), Gf.Vec3d(0, 0, -1164.0446726822815))
viewport_widget.destroy()
del viewport_widget
await self.finalize_test_no_image()
async def test_implicit_cameras(self):
"""Test ViewportWidget creation with existing UsdContext and Usd.Stage"""
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
usd_context = await self.open_usd_file('cube.usda')
self.assertIsNotNone(usd_context.get_stage())
usd_context_stage = usd_context.get_stage()
viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT))
viewport_api = viewport_widget.viewport_api
self.assertEqual(viewport_api.usd_context, usd_context)
self.assertEqual(viewport_api.stage, usd_context_stage)
self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp'))
time = Usd.TimeCode.Default()
def test_default_camera_position(cam_path: str, expected_pos: Gf.Vec3d, expected_rot: Gf.Vec3d = None):
prim = usd_context.get_stage().GetPrimAtPath(cam_path)
camera = UsdGeom.Camera(prim) if prim else None
self.assertTrue(bool(camera))
world_xform = camera.ComputeLocalToWorldTransform(time)
world_pos = world_xform.Transform(Gf.Vec3d(0, 0, 0))
self.assertAlmostEqual(world_pos, expected_pos)
if expected_rot:
rot_prop = prim.GetProperty('xformOp:rotateXYZ')
self.assertIsNotNone(rot_prop)
rot_value = rot_prop.Get()
self.assertAlmostEqual(rot_value, expected_rot)
test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500), Gf.Vec3d(-35.26439, 45, 0))
test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 50000), Gf.Vec3d(0, 0, 0))
test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0), Gf.Vec3d(90, 0, 180))
test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0), Gf.Vec3d(0, -90, 0))
output_file = str(OUTPUTS_DIR.joinpath('implicit_cameras_same.usda'))
(result, err, saved_layers) = await usd_context.save_as_stage_async(output_file)
self.assertTrue(result)
await omni.usd.get_context().new_stage_async()
await usd_context.open_stage_async(output_file)
test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500))
test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 50000))
test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0))
test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0))
# Change OmniverseKit_Persp location
omni.kit.commands.create(
'TransformPrimCommand',
path='/OmniverseKit_Persp',
new_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(-100, -200, -300)),
old_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(500, 500, 500)),
time_code=time,
).do()
# Change OmniverseKit_Front location
omni.kit.commands.create(
'TransformPrimCommand',
path='/OmniverseKit_Front',
new_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(0, 0, 56789)),
old_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(0, 0, 50000)),
time_code=time,
).do()
# Change OmniverseKit_Top aperture
UsdGeom.Camera(usd_context.get_stage().GetPrimAtPath('/OmniverseKit_Top')).GetHorizontalApertureAttr().Set(50000)
output_file = str(OUTPUTS_DIR.joinpath('implicit_cameras_changed.usda'))
(result, err, saved_layers) = await usd_context.save_as_stage_async(output_file)
self.assertTrue(result)
await omni.usd.get_context().new_stage_async()
await usd_context.open_stage_async(output_file)
test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(-100, -200, -300))
test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 56789))
# These haven't changed and should be default
test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0))
test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0))
# Test ortho aperture change is picked up
horiz_ap = UsdGeom.Camera(usd_context.get_stage().GetPrimAtPath('/OmniverseKit_Top')).GetHorizontalApertureAttr().Get()
self.assertAlmostEqual(horiz_ap, 50000)
# Test implicit camera creation for existing Z-Up scene
#
usd_context = await self.open_usd_file('implicit_cams_z_up.usda')
self.assertIsNotNone(usd_context.get_stage())
usd_context_stage = usd_context.get_stage()
self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Top'))
test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500), Gf.Vec3d(54.73561, 0, 135))
test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(500, 0, 0), Gf.Vec3d(90, 0, 90))
test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 0, 25), Gf.Vec3d(0, 0, -90))
test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(0, -50000, 0), Gf.Vec3d(90, 0, 0))
# Test that creation of another ViewportWidget doesn't affect existing implict caameras
viewport_widget_2 = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT))
test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500), Gf.Vec3d(54.73561, 0, 135))
viewport_widget_2.destroy()
del viewport_widget_2
# Test saving metadata to usd, so copy the input files to writeable temp files
from shutil import copyfile
tmp_layers = str(OUTPUTS_DIR.joinpath('layers.usda'))
copyfile(str(USD_FILES_DIR.joinpath('layers.usda')), tmp_layers)
copyfile(str(USD_FILES_DIR.joinpath('sublayer.usda')), str(OUTPUTS_DIR.joinpath('sublayer.usda')))
# Open the copy and validate the default camera
usd_context = await self.open_usd_file(tmp_layers, True)
self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp'))
# Switch to a known camera and re-validate
viewport_api.camera_path = '/World/Camera'
self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera'))
# Save the file and re-open it
# XXX: Need to dirty something in the stage for save to take affect
stage = usd_context.get_stage()
stage.GetPrimAtPath(viewport_api.camera_path).GetAttribute('focalLength').Set(51)
# Move the target layer to a sub-layer and then attmept the save
with Usd.EditContext(stage, stage.GetLayerStack()[-1]):
await usd_context.save_stage_async()
await omni.kit.app.get_app().next_update_async()
await omni.usd.get_context().new_stage_async()
# Re-open
usd_context = await self.open_usd_file(tmp_layers, True)
# Camera should match what was just saved
self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera'))
# Test dynmically switching Stage up-axis
async def set_stage_axis(stage, cam_prim, up_axis: str, wait: int = 2):
stage.SetMetadata(UsdGeom.Tokens.upAxis, up_axis)
for i in range(wait):
await omni.kit.app.get_app().next_update_async()
return UsdGeom.Xformable(cam_prim).GetLocalTransformation()
await omni.usd.get_context().new_stage_async()
usd_context = omni.usd.get_context()
self.assertIsNotNone(usd_context)
stage = usd_context.get_stage()
self.assertIsNotNone(stage)
cam_prim = stage.GetPrimAtPath(viewport_api.camera_path)
self.assertIsNotNone(cam_prim)
cam_xformable = UsdGeom.Xformable(cam_prim)
self.assertIsNotNone(cam_xformable)
self.assertEqual(cam_prim.GetPath().pathString, '/OmniverseKit_Persp')
xform_y = await set_stage_axis(stage, cam_prim, 'Y')
xform_y1 = cam_xformable.GetLocalTransformation()
self.assertEqual(xform_y, xform_y1)
self.assertAlmostEqual(xform_y.ExtractRotation().GetAxis(), Gf.Vec3d(-0.59028449177967, 0.7692737418738016, 0.24450384215364918))
xform_z = await set_stage_axis(stage, cam_prim, 'Z')
self.assertNotEqual(xform_y, xform_z)
self.assertAlmostEqual(xform_z.ExtractRotation().GetAxis(), Gf.Vec3d(0.1870534627395223, 0.4515870066346049, 0.8723990930279281))
xform_x = await set_stage_axis(stage, cam_prim, 'X')
self.assertNotEqual(xform_x, xform_z)
self.assertNotEqual(xform_x, xform_y)
self.assertAlmostEqual(xform_x.ExtractRotation().GetAxis(), Gf.Vec3d(0.541766002079245, 0.07132485246922922, 0.8374976802423478))
texture_pixel, vp_api = viewport_api.map_ndc_to_texture((0, 0))
self.assertAlmostEqual(texture_pixel, (0.5, 0.5))
self.assertEqual(vp_api, viewport_api)
# Test return of Viewport is None when NDC is out of bounds
texture_pixel, vp_api = viewport_api.map_ndc_to_texture((-2, -2))
self.assertIsNone(vp_api)
# Test return of Viewport is None when NDC is out of bounds
texture_pixel, vp_api = viewport_api.map_ndc_to_texture((2, 2))
self.assertIsNone(vp_api)
# Test camera is correctly positioned/labeled with new stage and Z or Y setting
settings = carb.settings.get_settings()
async def new_stage_with_up_setting(up_axis: str, wait: int = 2):
settings.set('/persistent/app/stage/upAxis', up_axis)
for i in range(wait):
await omni.kit.app.get_app().next_update_async()
await omni.usd.get_context().new_stage_async()
usd_context = omni.usd.get_context()
self.assertIsNotNone(usd_context)
stage = usd_context.get_stage()
self.assertIsNotNone(stage)
cam_prim = stage.GetPrimAtPath(viewport_api.camera_path)
return UsdGeom.Xformable(cam_prim).GetLocalTransformation()
# Switch to new stage as Z-up and test against values from previous Z-up
try:
xform_z = await new_stage_with_up_setting('Z')
self.assertNotEqual(xform_y, xform_z)
self.assertAlmostEqual(xform_z.ExtractRotation().GetAxis(), Gf.Vec3d(0.1870534627395223, 0.4515870066346049, 0.8723990930279281))
finally:
settings.destroy_item('/persistent/app/stage/upAxis')
try:
# Test again against default up as Y
xform_y1 = await new_stage_with_up_setting('Y')
self.assertEqual(xform_y, xform_y1)
self.assertAlmostEqual(xform_y.ExtractRotation().GetAxis(), Gf.Vec3d(-0.59028449177967, 0.7692737418738016, 0.24450384215364918))
finally:
settings.destroy_item('/persistent/app/stage/upAxis')
# Test opeinig a file with implicit cameras saved into it works properly
usd_context = await self.open_usd_file('implcit_precision.usda')
self.assertIsNotNone(usd_context.get_stage())
test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(-1500, 400, 500), Gf.Vec3d(-15, 751, 0))
test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 50000), Gf.Vec3d(0, 0, 0))
test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0), Gf.Vec3d(90, 0, 180))
test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0), Gf.Vec3d(0, -90, 0))
await self.__test_camera_startup_values(viewport_widget)
await self.__test_camera_target_settings(viewport_widget)
def get_tr(stage: Usd.Stage, cam: str):
xf = UsdGeom.Camera(stage.GetPrimAtPath(f'/OmniverseKit_{cam}')).ComputeLocalToWorldTransform(0)
return xf.ExtractTranslation()
def get_rot(stage: Usd.Stage, cam: str):
xf = UsdGeom.Camera(stage.GetPrimAtPath(f'/OmniverseKit_{cam}')).ComputeLocalToWorldTransform(0)
decomp = (Gf.Vec3d(-1, 0, 0), Gf.Vec3d(0, -1, 0), Gf.Vec3d(0, 0, 1))
rotation = xf.ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis())
return rotation
# Test re-opening ortho cameras keep orthogonal rotations
usd_context = await self.open_usd_file('ortho_y.usda')
stage = omni.usd.get_context().get_stage()
self.assertTrue(Gf.IsClose(get_rot(stage, 'Top'), Gf.Vec3d(-90, 0, -180), 0.00001))
self.assertTrue(Gf.IsClose(get_rot(stage, 'Front'), Gf.Vec3d(0, 0, 0), 0.00001))
self.assertTrue(Gf.IsClose(get_rot(stage, 'Right'), Gf.Vec3d(0, -90, 0), 0.00001))
usd_context = await self.open_usd_file('ortho_z.usda')
stage = omni.usd.get_context().get_stage()
self.assertTrue(Gf.IsClose(get_rot(stage, 'Top'), Gf.Vec3d(0, 0, -90), 0.00001))
self.assertTrue(Gf.IsClose(get_rot(stage, 'Front'), Gf.Vec3d(90, 90, 0), 0.00001))
self.assertTrue(Gf.IsClose(get_rot(stage, 'Right'), Gf.Vec3d(90, 0, 0), 0.00001))
usd_context = await self.open_usd_file('cam_prop_declaration_only.usda')
stage = omni.usd.get_context().get_stage()
self.assertTrue(Gf.IsClose(get_tr(stage, 'Persp'), Gf.Vec3d(-417, 100, -110), 0.00001))
self.assertTrue(Gf.IsClose(get_tr(stage, 'Top'), Gf.Vec3d(0, 50000, 0), 0.00001))
self.assertTrue(Gf.IsClose(get_tr(stage, 'Front'), Gf.Vec3d(0, 0, 50000), 0.00001))
self.assertTrue(Gf.IsClose(get_tr(stage, 'Right'), Gf.Vec3d(-50000, 0, 0), 0.00001))
viewport_widget.destroy()
del viewport_widget
await self.finalize_test_no_image()
async def test_dont_save_implicit_cameras(self):
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
self.assertIsNotNone(usd_context.get_stage())
settings = carb.settings.get_settings()
# Save current state so it restored
shouldsave = settings.get("/app/omni.usd/storeCameraSettingsToUsdStage")
try:
settings.set("/app/omni.usd/storeCameraSettingsToUsdStage", False)
output_file = str(OUTPUTS_DIR.joinpath('dont_save_implicit_cameras.usda'))
(result, err, saved_layers) = await usd_context.save_as_stage_async(output_file)
self.assertTrue(result)
usd_context = await self.open_usd_file(output_file, True)
stage = usd_context.get_stage()
self.assertFalse(stage.HasMetadataDictKey("customLayerData", "cameraSettings"))
except Exception as e:
raise e
finally:
settings.set("/app/omni.usd/storeCameraSettingsToUsdStage", shouldsave)
await self.finalize_test_no_image()
async def __test_camera_startup_values(self, viewport_widget):
# await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
# viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT))
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
stage = usd_context.get_stage()
self.assertIsNotNone(stage)
persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp')
self.assertIsNotNone(persp)
self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 18.147562, places=5)
self.assertEqual(persp.GetFStopAttr().Get(), 0)
top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top')
self.assertIsNotNone(top)
self.assertEqual(top.GetHorizontalApertureAttr().Get(), 5000)
self.assertEqual(top.GetVerticalApertureAttr().Get(), 5000)
# Test typed-defaults and creation
settings = carb.settings.get_settings()
try:
perps_key = '/persistent/app/primCreation/typedDefaults/camera'
ortho_key = '/persistent/app/primCreation/typedDefaults/orthoCamera'
settings.set(perps_key + '/focalLength', 150)
settings.set(perps_key + '/fStop', 22)
settings.set(perps_key + '/clippingRange', (200, 2000))
settings.set(perps_key + '/horizontalAperture', 1234)
settings.set(ortho_key + '/horizontalAperture', 1000)
settings.set(ortho_key + '/verticalAperture', 2000)
settings.set(ortho_key + '/clippingRange', (20000.0, 10000000.0))
await usd_context.new_stage_async()
stage = usd_context.get_stage()
self.assertIsNotNone(stage)
persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp')
self.assertIsNotNone(persp)
self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 150)
self.assertAlmostEqual(persp.GetFStopAttr().Get(), 22)
self.assertAlmostEqual(persp.GetHorizontalApertureAttr().Get(), 1234)
self.assertAlmostEqual(persp.GetClippingRangeAttr().Get(), Gf.Vec2f(200, 2000))
self.assertFalse(persp.GetVerticalApertureAttr().IsAuthored())
top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top')
self.assertIsNotNone(top)
self.assertAlmostEqual(top.GetHorizontalApertureAttr().Get(), 1000)
self.assertAlmostEqual(top.GetVerticalApertureAttr().Get(), 2000)
# Test that the extension.toml default is used
self.assertAlmostEqual(top.GetClippingRangeAttr().Get(), Gf.Vec2f(20000.0, 10000000.0))
finally:
# Reset now for all other tests
settings.destroy_item(perps_key)
settings.destroy_item(ortho_key)
# viewport_widget.destroy()
# del viewport_widget
async def __test_camera_target_settings(self, viewport_widget):
"""Test /app/viewport/defaultCamera/target/distance settings values"""
settings = carb.settings.get_settings()
# These all have no defaults (as feature is disabled until set)
enabled_key = "/app/viewport/defaultCamera/target/distance/enabled"
value_key = "/app/viewport/defaultCamera/target/distance/value"
unit_key = "/app/viewport/defaultCamera/target/distance/units"
async def test_stage_open(filepath: str, expected_coi: Gf.Vec3d):
usd_context = await self.open_usd_file(filepath)
stage = usd_context.get_stage()
await self.wait_n_updates(3)
persp_cam = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp')
self.assertTrue(bool(persp_cam.GetPrim().IsValid()))
coi_prop = persp_cam.GetPrim().GetProperty('omni:kit:centerOfInterest')
self.assertTrue(bool(coi_prop.IsValid()))
self.assertAlmostEqual(coi_prop.Get(), expected_coi)
async def set_target_distance(value, unit):
settings.set(enabled_key, True)
settings.set(value_key, value)
settings.set(unit_key, unit)
await self.wait_n_updates(3)
try:
await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -1732.0508))
await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -1732.0508))
await set_target_distance(5, "stage")
await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -0.04999))
await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -50))
await set_target_distance(5, "meters")
await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -500))
await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -0.5))
await set_target_distance(5, 1)
await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -5))
await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -5))
finally:
# Make sure to clear the keys for remainig tests
settings.destroy_item(enabled_key)
settings.destroy_item(value_key)
settings.destroy_item(unit_key)
async def __test_display_delegate(self, viewport_widget):
self.assertIsNotNone(viewport_widget.display_delegate)
self.assertTrue(isinstance(viewport_widget.display_delegate, ViewportDisplayDelegate))
def test_set_display_delegate(display_delegate):
success = False
try:
viewport_widget.display_delegate = display_delegate
success = True
except RuntimeError:
pass
return success
result = test_set_display_delegate(None)
self.assertFalse(result)
result = test_set_display_delegate(32)
self.assertFalse(result)
result = test_set_display_delegate(OverlayViewportDisplayDelegate(viewport_widget.viewport_api))
self.assertTrue(result)
async def test_ui_driven_resolution(self):
"""Test ViewportWidget driving the underlying Viewport texture resolution"""
import omni.ui
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
# Need a Window otherwise the ui size calculations won't run
window_flags = omni.ui.WINDOW_FLAGS_NO_RESIZE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR
style = {"border_width": 0}
window = omni.ui.Window("Test", width=TEST_WIDTH, height=TEST_HEIGHT, flags=window_flags, padding_x=0, padding_y=0)
startup_resolution = TEST_WIDTH * 0.5, TEST_HEIGHT * 0.25
with window.frame:
window.frame.set_style(style)
viewport_widget = ViewportWidget(resolution=startup_resolution, style=style)
await self.wait_n_updates(8)
current_res = viewport_widget.viewport_api.resolution
self.assertEqual(current_res[0], startup_resolution[0])
self.assertEqual(current_res[1], startup_resolution[1])
viewport_widget.fill_frame = True
await self.wait_n_updates(8)
# Should match the ui.Frame which should be filling the ui.Window
current_res = viewport_widget.viewport_api.resolution
self.assertEqual(current_res[0], window.frame.computed_width)
self.assertEqual(current_res[1], window.frame.computed_height)
viewport_widget.fill_frame = False
viewport_widget.expand_viewport = True
await self.wait_n_updates(8)
current_res = viewport_widget.viewport_api.resolution
# Some-what arbitrary numbers from implementation that are know to be correct for 360, 240 ui.Frame
self.assertEqual(current_res[0], 180)
self.assertEqual(current_res[1], 120)
full_resolution = viewport_widget.full_resolution
self.assertEqual(full_resolution[0], startup_resolution[0])
self.assertEqual(full_resolution[1], startup_resolution[1])
# Test reversion to no fill or exapnd returns back to the resolution explicitly specified.
viewport_widget.fill_frame = False
viewport_widget.expand_viewport = False
await self.wait_n_updates(8)
current_res = viewport_widget.viewport_api.resolution
self.assertEqual(current_res[0], startup_resolution[0])
self.assertEqual(current_res[1], startup_resolution[1])
# Set render resolution to x3
viewport_widget.resolution = (TEST_WIDTH * 2.5, TEST_HEIGHT * 2.5)
viewport_widget.expand_viewport = True
# Set Window size to x2
two_x_res = TEST_WIDTH * 2, TEST_HEIGHT * 2
window.width, window.height = two_x_res
await self.wait_n_updates(8)
current_res = viewport_widget.viewport_api.resolution
self.assertEqual(current_res[0], two_x_res[0])
self.assertEqual(current_res[1], two_x_res[1])
viewport_widget.destroy()
del viewport_widget
window.destroy()
del window
await self.finalize_test_no_image()
async def __test_engine_creation_arguments(self, hydra_engine_options, verify_engine):
viewport_widget, window = None, None
try:
import omni.ui
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
# Need a Window otherwise the ui size calculations won't run
window = omni.ui.Window("Test", width=TEST_WIDTH, height=TEST_HEIGHT)
startup_resolution = TEST_WIDTH * 0.5, TEST_HEIGHT * 0.25
with window.frame:
viewport_widget = ViewportWidget(resolution=startup_resolution, width=TEST_WIDTH, height=TEST_HEIGHT,
hydra_engine_options=hydra_engine_options)
await self.wait_n_updates(5)
await verify_engine(viewport_widget.viewport_api._hydra_texture)
finally:
if viewport_widget is not None:
viewport_widget.destroy()
del viewport_widget
if window is not None:
window.destroy()
del window
await self.finalize_test_no_image()
async def test_engine_creation_default_arguments(self):
"""Test default engine creation arguments"""
hydra_engine_options = {}
async def verify_engine(hydra_texture):
settings = carb.settings.get_settings()
tick_rate = settings.get(f"{hydra_texture.get_settings_path()}hydraTickRate")
is_async = settings.get(f"{hydra_texture.get_settings_path()}async")
is_async_ll = settings.get(f"{hydra_texture.get_settings_path()}asyncLowLatency")
self.assertEqual(is_async, bool(settings.get("/app/asyncRendering")))
self.assertEqual(is_async_ll, bool(settings.get("/app/asyncRenderingLowLatency")))
self.assertEqual(tick_rate, int(settings.get("/persistent/app/viewport/defaults/tickRate")))
await self.__test_engine_creation_arguments(hydra_engine_options, verify_engine)
async def test_engine_creation_forward_arguments(self):
"""Test forwarding of engine creation arguments"""
settings = carb.settings.get_settings()
# Make sure the defaults are in a state that overrides from hydra_engine_options can be tested
self.assertFalse(bool(settings.get("/app/asyncRendering")))
self.assertFalse(bool(settings.get("/app/asyncRenderingLowLatency")))
self.assertNotEqual(30, int(settings.get("/persistent/app/viewport/defaults/tickRate")))
try:
hydra_engine_options = {
"is_async": True,
"is_async_low_latency": True,
"hydra_tick_rate": 30
}
async def verify_engine(hydra_texture):
tick_rate = settings.get(f"{hydra_texture.get_settings_path()}hydraTickRate")
is_async = settings.get(f"{hydra_texture.get_settings_path()}async")
is_async_ll = settings.get(f"{hydra_texture.get_settings_path()}asyncLowLatency")
self.assertEqual(is_async, hydra_engine_options.get("is_async"))
self.assertEqual(is_async_ll, hydra_engine_options.get("is_async_low_latency"))
self.assertEqual(tick_rate, hydra_engine_options.get("hydra_tick_rate"))
await self.__test_engine_creation_arguments(hydra_engine_options, verify_engine)
finally:
settings.set("/app/asyncRendering", False)
settings.destroy_item("/app/asyncRenderingLowLatency")
| 36,413 | Python | 46.414062 | 141 | 0.649411 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/__init__.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .test_capture import *
from .test_widget import *
from .test_ray_query import *
from .test_scene_view_integration import *
| 557 | Python | 38.85714 | 76 | 0.795332 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_capture.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.
##
__all__ = ["TestCaptureAPI"]
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from omni.ui.tests.compare_utils import OUTPUTS_DIR, compare, CompareError
import omni.usd
import omni.ui as ui
from omni.kit.widget.viewport import ViewportWidget
from omni.kit.widget.viewport.capture import *
from omni.kit.test_helpers_gfx.compare_utils import compare as gfx_compare
from omni.kit.test.teamcity import teamcity_publish_image_artifact
import carb
import traceback
from pathlib import Path
import os
from pxr import Usd, UsdRender
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve()
TEST_FILES_DIR = CURRENT_PATH.joinpath('tests')
USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd')
TEST_WIDTH, TEST_HEIGHT = 360, 240
NUM_DEFAULT_WINDOWS = 0
# XXX: Make this more accessible in compare_utils
#
def compare_images(image_name, threshold = 10):
image1 = OUTPUTS_DIR.joinpath(image_name)
image2 = TEST_FILES_DIR.joinpath(image_name)
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image_name).stem}.diffmap.png")
gfx_compare(image1, image2, image_diffmap)
class TestByteCapture(ByteCapture):
def __init__(self, test, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__test = test
self.__complete = False
def on_capture_completed(self, buffer, buffer_size, width, height, format):
self.__test.assertEqual(width, TEST_WIDTH)
self.__test.assertEqual(height, TEST_HEIGHT)
self.__test.assertEqual(format, ui.TextureFormat.RGBA8_UNORM)
class TestCaptureAPI(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
# After running each test
async def tearDown(self):
await super().tearDown()
async def merged_test_capture_file(self):
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
usd_path = str(TEST_FILES_DIR.joinpath('usd/sphere.usda'))
image_name = f'sphere.png'
image_path = str(OUTPUTS_DIR.joinpath(image_name))
usd_context = omni.usd.get_context()
await usd_context.open_stage_async(usd_path)
self.assertIsNotNone(usd_context.get_stage())
vp_window = ui.Window('test_capture_file', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR)
self.assertIsNotNone(vp_window)
with vp_window.frame:
vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT))
self.assertIsNotNone(vp_widget)
capture = vp_widget.viewport_api.schedule_capture(FileCapture(image_path))
captured_aovs = await capture.wait_for_result()
self.assertEqual(captured_aovs, ['LdrColor'])
# Test the frame's metadata is available
self.assertIsNotNone(capture.view)
self.assertIsNotNone(capture.projection)
self.assertEqual(capture.resolution, (TEST_WIDTH, TEST_HEIGHT))
# Test the viewport_handle is also available for usets that
self.assertIsNotNone(capture.viewport_handle)
compare_images(image_name)
vp_widget.destroy()
vp_window.destroy()
del vp_window
async def merged_test_capture_file_with_format(self):
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
usd_path = str(TEST_FILES_DIR.joinpath('usd/sphere.usda'))
image_name = f'sphere_rle.exr'
image_path = str(OUTPUTS_DIR.joinpath(image_name))
usd_context = omni.usd.get_context()
await usd_context.open_stage_async(usd_path)
self.assertIsNotNone(usd_context.get_stage())
vp_window = ui.Window('test_capture_file_with_format', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR)
self.assertIsNotNone(vp_window)
with vp_window.frame:
vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT))
self.assertIsNotNone(vp_widget)
format_desc = {}
format_desc["format"] = "exr"
format_desc["compression"] = "rle"
capture = vp_widget.viewport_api.schedule_capture(FileCapture(image_path, format_desc=format_desc))
captured_aovs = await capture.wait_for_result()
self.assertEqual(captured_aovs, ['LdrColor'])
# Test the frame's metadata is available
self.assertIsNotNone(capture.view)
self.assertIsNotNone(capture.projection)
self.assertEqual(capture.resolution, (TEST_WIDTH, TEST_HEIGHT))
# Test the viewport_handle is also available for usets that
self.assertIsNotNone(capture.viewport_handle)
self.assertIsNotNone(capture.format_desc)
# Cannot compare EXR images for testing yet
# compare_images(image_name)
vp_widget.destroy()
vp_window.destroy()
del vp_window
async def merged_test_capture_bytes_free_func_hdr(self):
# 1030: Doesn't have the ability to set render_product_path and this test will fail
import omni.hydratexture
if not hasattr(omni.hydratexture.IHydraTexture, 'set_render_product_path'):
return
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
aov_name = 'HdrColor'
image_name = f'cube_{aov_name}.exr'
image_path = str(OUTPUTS_DIR.joinpath(image_name))
usd_path = str(TEST_FILES_DIR.joinpath('usd/cube.usda'))
usd_context = omni.usd.get_context()
await usd_context.open_stage_async(usd_path)
self.assertIsNotNone(usd_context.get_stage())
num_calls = 0
def on_capture_completed(buffer, buffer_size, width, height, format):
nonlocal num_calls
num_calls = num_calls + 1
self.assertEqual(width, TEST_WIDTH)
self.assertEqual(height, TEST_HEIGHT)
# Note the RGBA16_SFLOAT format!
self.assertEqual(format, ui.TextureFormat.RGBA16_SFLOAT)
vp_window = ui.Window('test_capture_bytes_free_func', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR)
self.assertIsNotNone(vp_window)
with vp_window.frame:
vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT))
self.assertIsNotNone(vp_widget)
# Edit the RenderProduct to output HdrColor
render_product_path = vp_widget.viewport_api.render_product_path
if render_product_path[0] != '/':
render_product_path = f'/Render/RenderProduct_{render_product_path}'
stage = usd_context.get_stage()
with Usd.EditContext(stage, stage.GetSessionLayer()):
prim = usd_context.get_stage().GetPrimAtPath(render_product_path)
self.assertTrue(prim.IsValid())
self.assertTrue(prim.IsA(UsdRender.Product))
product = UsdRender.Product(prim)
targets = product.GetOrderedVarsRel().GetForwardedTargets()
self.assertEqual(1, len(targets))
prim = usd_context.get_stage().GetPrimAtPath(targets[0])
self.assertTrue(prim.IsValid())
self.assertTrue(prim.IsA(UsdRender.Var))
render_var = UsdRender.Var(prim)
value_set = render_var.GetSourceNameAttr().Set(aov_name)
self.assertTrue(value_set)
# Trigger the texture to update the render, and wait for the change to funnel back to us
vp_widget.viewport_api.render_product_path = render_product_path
settings_changed = await vp_widget.viewport_api.wait_for_render_settings_change()
self.assertTrue(settings_changed)
# Now that the settings have changed, so the capture of 'HdrColor'
captured_aovs = await vp_widget.viewport_api.schedule_capture(ByteCapture(on_capture_completed, aov_name=aov_name)).wait_for_result()
self.assertTrue(aov_name in captured_aovs)
# Since we requested one AOV, test that on_capture_completed was only called once
# Currently RTX will deliver 'HdrColor' and 'LdrColor' when 'HdrColor' is requested
# If that changes these two don't neccessarily need to be tested.
self.assertEqual(len(captured_aovs), 1)
self.assertEqual(num_calls, 1)
captured_aovs = await vp_widget.viewport_api.schedule_capture(FileCapture(image_path, aov_name=aov_name)).wait_for_result()
self.assertTrue(aov_name in captured_aovs)
# XXX cannot compare EXR
# compare_images(image_name)
# So test it exists and publish the image
self.assertTrue(os.path.exists(image_path))
teamcity_publish_image_artifact(image_path, "results")
vp_widget.destroy()
vp_window.destroy()
del vp_window
async def merged_test_capture_bytes_subclass(self):
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
usd_path = str(TEST_FILES_DIR.joinpath('usd/cube.usda'))
usd_context = omni.usd.get_context()
await usd_context.open_stage_async(usd_path)
self.assertIsNotNone(usd_context.get_stage())
capture = TestByteCapture(self)
vp_window = ui.Window('test_capture_bytes_subclass', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR)
self.assertIsNotNone(vp_window)
with vp_window.frame:
vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT))
self.assertIsNotNone(vp_widget)
vp_widget.viewport_api.schedule_capture(capture)
captured_aovs = await capture.wait_for_result()
self.assertEqual(captured_aovs, ['LdrColor'])
vp_widget.destroy()
vp_window.destroy()
del vp_window
async def test_3_capture_tests_merged_for_linux(self):
try:
await self.merged_test_capture_file()
await self.wait_n_updates(10)
await self.merged_test_capture_bytes_free_func_hdr()
await self.wait_n_updates(10)
await self.merged_test_capture_bytes_subclass()
await self.wait_n_updates(10)
await self.merged_test_capture_file_with_format()
await self.wait_n_updates(10)
finally:
await self.finalize_test_no_image()
| 10,923 | Python | 41.177606 | 145 | 0.656596 |
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_ray_query.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__ = ["TestRayQuery"]
from omni.kit.widget.viewport import ViewportWidget
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
import omni.usd
from pathlib import Path
import carb
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve()
TEST_FILES_DIR = CURRENT_PATH.joinpath('tests')
USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd')
TEST_WIDTH, TEST_HEIGHT = 320, 180
class TestRayQuery(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
# After running each test
async def tearDown(self):
await super().tearDown()
await self.linux_gpu_shutdown_workaround()
async def linux_gpu_shutdown_workaround(self, usd_context_name : str = ''):
await self.wait_n_updates(10)
omni.usd.release_all_hydra_engines(omni.usd.get_context(usd_context_name))
await self.wait_n_updates(10)
async def open_usd_file(self, filename: str, resolved: bool = False):
usd_context = omni.usd.get_context()
usd_path = str(USD_FILES_DIR.joinpath(filename) if not resolved else filename)
await usd_context.open_stage_async(usd_path)
return usd_context
async def __test_ray_query(self, camera_path: str):
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False)
usd_context = await self.open_usd_file('ray_query.usda')
self.assertIsNotNone(usd_context.get_stage())
usd_context_stage = usd_context.get_stage()
window_flags = omni.ui.WINDOW_FLAGS_NO_COLLAPSE
window_flags |= omni.ui.WINDOW_FLAGS_NO_RESIZE
window_flags |= omni.ui.WINDOW_FLAGS_NO_CLOSE
window_flags |= omni.ui.WINDOW_FLAGS_NO_SCROLLBAR
window_flags |= omni.ui.WINDOW_FLAGS_NO_TITLE_BAR
vp_window, viewport_widget = None, None
try:
vp_window = omni.ui.Window("Viewport", width=TEST_WIDTH, height=TEST_HEIGHT, flags=window_flags)
with vp_window.frame:
viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT))
results = []
def query_completed(*args):
results.append(args)
viewport_api = viewport_widget.viewport_api
viewport_api.camera_path = camera_path
# 1:1 conform of render and viewport
await self.wait_n_updates(5)
viewport_api.request_query((193, 123), query_completed)
await self.wait_n_updates(15)
# test with half height
viewport_api.resolution = TEST_WIDTH, TEST_HEIGHT * 0.5
await self.wait_n_updates(5)
viewport_api.request_query((193, 78), query_completed)
await self.wait_n_updates(15)
# test with half width
viewport_api.resolution = TEST_WIDTH * 0.5, TEST_HEIGHT
await self.wait_n_updates(5)
viewport_api.request_query((96, 106), query_completed)
await self.wait_n_updates(15)
self.assertEqual(len(results), 3)
for args in results:
self.assertEqual(args[0], "/World/Xform/FG")
# Compare integer in a sane range that must be toward the lower-right corner of the object
iworld_pos = [int(v) for v in args[1]]
self.assertTrue(iworld_pos[0] >= 46 and iworld_pos[0] <= 50)
self.assertTrue(iworld_pos[1] >= -50 and iworld_pos[1] <= -46)
self.assertTrue(iworld_pos[2] == 0)
finally:
if viewport_widget:
viewport_widget.destroy()
viewport_widget = None
if vp_window:
vp_window.destroy()
vp_window = None
await self.finalize_test_no_image()
async def test_perspective_ray_query(self):
'''Test request_query API with a perpective camera'''
await self.__test_ray_query("/World/Xform/Camera")
async def test_orthographic_ray_query(self):
'''Test request_query API with an orthographic camera'''
await self.__test_ray_query("/OmniverseKit_Front")
| 4,631 | Python | 39.99115 | 120 | 0.638523 |
omniverse-code/kit/exts/omni.kit.widget.viewport/docs/index.rst | omni.kit.widget.viewport
###########################
Viewport Widget
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule:: omni.kit.widget.viewport
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
| 293 | reStructuredText | 12.999999 | 43 | 0.600683 |
omniverse-code/kit/exts/omni.kit.window.drop_support/PACKAGE-LICENSES/omni.kit.window.drop_support-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.window.drop_support/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.1"
category = "Internal"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "External Drag & Drop"
description="Drag & Drop support from outside kit"
# URL of the extension source repository.
repository = ""
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Keywords for the extension
keywords = ["kit", "drag", "drop"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
[dependencies]
"omni.appwindow" = {}
"omni.ui" = {}
[[python.module]]
name = "omni.kit.window.drop_support"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/file/ignoreUnsavedStage=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.window.stage",
"omni.kit.window.file",
"omni.hydra.pxr",
"omni.kit.window.viewport",
]
stdoutFailPatterns.exclude = [
"*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop
"*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available
]
| 1,933 | TOML | 28.753846 | 122 | 0.697879 |
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/drop_support.py | import os
import asyncio
import carb.events
import carb.input
import omni.appwindow
import omni.ui as ui
class ExternalDragDrop():
def __init__(self, window_name: str, drag_drop_fn: callable):
self._window_name = window_name
self._drag_drop_fn = drag_drop_fn
# subscribe to external drag/drop events
app_window = omni.appwindow.get_default_app_window()
self._dropsub = app_window.get_window_drop_event_stream().create_subscription_to_pop(
self._on_drag_drop_external, name="ExternalDragDrop event", order=0
)
def destroy(self):
self._drag_drop_fn = None
self._dropsub = None
def get_current_mouse_coords(self):
app_window = omni.appwindow.get_default_app_window()
input = carb.input.acquire_input_interface()
dpi_scale = ui.Workspace.get_dpi_scale()
pos_x, pos_y = input.get_mouse_coords_pixel(app_window.get_mouse())
return pos_x / dpi_scale, pos_y / dpi_scale
def is_window_hovered(self, pos_x, pos_y, window_name):
window = ui.Workspace.get_window(window_name)
# if window hasn't been drawn yet docked may not be valid, so check dock_id also
if not window or not window.visible or ((window.docked or window.dock_id != 0) and not window.is_selected_in_dock()):
return False
if (pos_x > window.position_x and
pos_y > window.position_y and
pos_x < window.position_x + window.width and
pos_y < window.position_y + window.height
):
return True
return False
def _on_drag_drop_external(self, e: carb.events.IEvent):
# need to wait until next frame as otherwise mouse coords can be wrong
async def do_drag_drop():
await omni.kit.app.get_app().next_update_async()
mouse_x, mouse_y = self.get_current_mouse_coords()
if self.is_window_hovered(mouse_x, mouse_y, self._window_name):
self._drag_drop_fn(self, list(e.payload['paths']))
asyncio.ensure_future(do_drag_drop())
def expand_payload(self, payload):
new_payload = []
for file_path in payload:
if os.path.isdir(file_path):
for root, subdirs, files in os.walk(file_path):
for file in files:
new_payload.append(os.path.join(root, file))
else:
new_payload.append(file_path)
return new_payload
| 2,498 | Python | 37.446153 | 125 | 0.609287 |
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/__init__.py | from .drop_support import *
| 28 | Python | 13.499993 | 27 | 0.75 |
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/tests/test_drag_drop.py | import os
import unittest
import threading
import carb
import asyncio
import omni.kit.test
import omni.ui as ui
import omni.appwindow
import omni.client.utils as clientutils
from pathlib import Path
from omni.kit import ui_test
class TestExternalDragDropUtils(omni.kit.test.AsyncTestCase):
async def test_external_drag_drop(self):
# new stage
await omni.usd.get_context().new_stage_async()
await ui_test.human_delay(50)
# stage event
future_test = asyncio.Future()
def on_timeout():
nonlocal future_test
future_test.set_result(False)
carb.log_error(f"stage event omni.usd.StageEventType.OPENED hasn't been received")
timeout_timer = threading.Timer(30.0, on_timeout)
def on_stage_event(event):
if event.type == int(omni.usd.StageEventType.OPENED):
nonlocal timeout_timer
timeout_timer.cancel()
nonlocal future_test
future_test.set_result(True)
carb.log_info(f"stage event omni.usd.StageEventType.OPENED received")
stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(on_stage_event, name="omni.kit.window.drop_support")
timeout_timer.start()
# get file path
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
file_path = str(Path(extension_path).joinpath("data/tests/4Lights.usda")).replace("\\", "/")
# position mouse
await ui_test.find("Viewport").click()
await ui_test.human_delay()
# simulate drag/drop
omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': [file_path]})
await ui_test.human_delay(50)
# wait for stage event OPENED
await future_test
await ui_test.human_delay(50)
# verify
root_layer = omni.usd.get_context().get_stage().GetRootLayer()
self.assertTrue(clientutils.equal_urls(root_layer.identifier, file_path))
| 2,103 | Python | 34.661016 | 153 | 0.646695 |
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/tests/__init__.py | from .test_drag_drop import *
| 31 | Python | 9.666663 | 29 | 0.709677 |
omniverse-code/kit/exts/omni.kit.window.drop_support/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-09
### Changes
- Created
| 141 | Markdown | 16.749998 | 80 | 0.659574 |
omniverse-code/kit/exts/omni.kit.window.drop_support/docs/README.md | # omni.kit.window.drop_support
## Introduction
Library functions to allow drag & drop from outside kit
| 107 | Markdown | 12.499998 | 55 | 0.757009 |
omniverse-code/kit/exts/omni.kit.window.drop_support/docs/index.rst | omni.kit.window.drop_support
#############################
Drag and Drop support from outside kit
.. toctree::
:maxdepth: 1
CHANGELOG
.. automodule:: omni.kit.window.drop_support
:platform: Windows-x86_64, Linux-x86_64, Linux-aarch64
:members:
:undoc-members:
:imported-members:
| 306 | reStructuredText | 17.058823 | 58 | 0.624183 |
omniverse-code/kit/exts/omni.kit.numpy.common/PACKAGE-LICENSES/omni.kit.numpy.common-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.numpy.common/config/extension.toml | [package]
title = "Common Types Numpy Bindings"
description = "Numpy type bindings for common vector types"
readme ="docs/README.md"
preview_image = ""
version = "0.1.0"
[dependencies]
"omni.kit.pip_archive" = {}
[[python.module]]
name = "omni.kit.numpy.common"
[python.pipapi]
requirements = ["numpy"]
[[test]]
waiver = "Simple binding extension (carb types to numpy)" | 373 | TOML | 19.777777 | 59 | 0.707775 |
omniverse-code/kit/exts/omni.kit.numpy.common/omni/kit/numpy/common/_numpy_dtypes.pyi | from __future__ import annotations
import omni.kit.numpy.common._numpy_dtypes
import typing
__all__ = [
]
| 114 | unknown | 10.499999 | 42 | 0.675439 |
omniverse-code/kit/exts/omni.kit.numpy.common/omni/kit/numpy/common/__init__.py | __name__ = "Carb Primitive Numpy DTypes"
from ._numpy_dtypes import *
| 71 | Python | 16.999996 | 40 | 0.690141 |
omniverse-code/kit/exts/omni.kit.numpy.common/docs/README.md | # Usage
This extension is used when creating Python Bindings that returns a numpy array of common Carb types (e.g `carb::Float3`).
To use this extension, add `"omni.kit.numpy.common" = {}` to the `[dependencies]` section on the `config/extension.toml` file.
| 261 | Markdown | 42.66666 | 126 | 0.735632 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/PACKAGE-LICENSES/omni.kit.window.popup_dialog-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.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 omni.kit.window.popup_dialog import MessageDialog, InputDialog, FormDialog, OptionsDialog, OptionsMenu
class DemoApp:
def __init__(self):
self._window = None
self._popups = []
self._cur_popup_index = 0
self._build_ui()
def _build_ui(self):
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
self._window = ui.Window("DemoPopup", width=600, height=80, flags=window_flags)
with self._window.frame:
builders = [
("Message", self._build_message_popup),
("String Input", self._build_string_input),
("Form Dialog", self._build_form_dialog),
("Options Dialog", self._build_options_dialog),
("Options Menu", self._build_options_menu),
]
with ui.VStack(spacing=10):
with ui.HStack(height=30):
collection = ui.RadioCollection()
for i, builder in enumerate(builders):
button = ui.RadioButton(text=builder[0], radio_collection=collection, width=120)
self._popups.append(builder[1]())
button.set_clicked_fn(lambda i=i, parent=button: self._on_show_popup(i, parent))
ui.Spacer()
ui.Spacer()
def _build_message_popup(self) -> MessageDialog:
#BEGIN-DOC-message-dialog
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
dialog = MessageDialog(
title="Message",
message=message,
ok_handler=lambda dialog: print(f"Message acknowledged"),
)
#END-DOC-message-dialog
return dialog
def _build_string_input(self) -> InputDialog:
#BEGIN-DOC-input-dialog
dialog = InputDialog(
title="String Input",
message="Please enter a string value:",
pre_label="LDAP Name: ",
post_label="@nvidia.com",
ok_handler=lambda dialog: print(f"Input accepted: '{dialog.get_value()}'"),
)
#END-DOC-input-dialog
return dialog
def _build_form_dialog(self) -> FormDialog:
#BEGIN-DOC-form-dialog
field_defs = [
FormDialog.FieldDef("string", "String: ", ui.StringField, "default"),
FormDialog.FieldDef("int", "Integer: ", ui.IntField, 1),
FormDialog.FieldDef("float", "Float: ", ui.FloatField, 2.0),
FormDialog.FieldDef(
"tuple", "Tuple: ", lambda **kwargs: ui.MultiFloatField(column_count=3, h_spacing=2, **kwargs), None
),
FormDialog.FieldDef("slider", "Slider: ", lambda **kwargs: ui.FloatSlider(min=0, max=10, **kwargs), 3.5),
FormDialog.FieldDef("bool", "Boolean: ", ui.CheckBox, True),
]
dialog = FormDialog(
title="Form Dialog",
message="Please enter values for the following fields:",
field_defs=field_defs,
ok_handler=lambda dialog: print(f"Form accepted: '{dialog.get_values()}'"),
)
#END-DOC-form-dialog
return dialog
def _build_options_dialog(self) -> OptionsDialog:
#BEGIN-DOC-options-dialog
field_defs = [
OptionsDialog.FieldDef("hard", "Hard place", False),
OptionsDialog.FieldDef("harder", "Harder place", True),
OptionsDialog.FieldDef("hardest", "Hardest place", False),
]
dialog = OptionsDialog(
title="Options Dialog",
message="Please make your choice:",
field_defs=field_defs,
width=300,
radio_group=True,
ok_handler=lambda choice: print(f"Choice: '{dialog.get_choice()}'"),
)
#END-DOC-options-dialog
return dialog
def _build_options_menu(self) -> OptionsMenu:
#BEGIN-DOC-options-menu
field_defs = [
OptionsMenu.FieldDef("audio", "Audio", None, False),
OptionsMenu.FieldDef("materials", "Materials", None, True),
OptionsMenu.FieldDef("scripts", "Scripts", None, False),
OptionsMenu.FieldDef("textures", "Textures", None, False),
OptionsMenu.FieldDef("usd", "USD", None, True),
]
menu = OptionsMenu(
title="Options Menu",
field_defs=field_defs,
width=150,
value_changed_fn=lambda dialog, name: print(f"Value for '{name}' changed to {dialog.get_value(name)}"),
)
#END-DOC-options-menu
return menu
def _on_show_popup(self, popup_index: int, parent: ui.Widget):
self._popups[self._cur_popup_index].hide()
self._popups[popup_index].show(offset_x=-1, offset_y=26, parent=parent)
self._cur_popup_index = popup_index
if __name__ == "__main__":
app = DemoApp()
| 5,387 | Python | 40.767442 | 143 | 0.585112 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/config/extension.toml | [package]
title = "Simple Popup Dialogs with Input Fields"
version = "2.0.16"
description = "A variety of simple Popup Dialogs for taking in user inputs"
authors = ["NVIDIA"]
slackids = ["UQY4RMR3N"]
repository = ""
keywords = ["kit", "ui"]
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
[dependencies]
"omni.ui" = {}
[[python.module]]
name = "omni.kit.window.popup_dialog"
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
[[python.scriptFolder]]
path = "scripts"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false",
"--/renderer/multiGpu/maxGpuCount=1",
"--no-window",
]
dependencies = [
"omni.kit.renderer.core",
"omni.kit.renderer.capture",
]
pythonTests.unreliable = [
"*test_ui_layout", # OM-77232
"*test_one_button_layout", # OM-77232
]
| 1,019 | TOML | 20.25 | 75 | 0.652601 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/input_dialog.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
import omni.kit.app
import asyncio
from typing import Callable, Any, Optional
from .dialog import AbstractDialog, PopupDialog, get_field_value
from .style import get_style
class InputDialog(PopupDialog):
"""
A simple popup dialog with an input field and two buttons, OK and Cancel
Keyword Args:
title (str): Title of popup window. Default None.
message (str): Message to display.
input_cls (omni.ui.AbstractField): Type of input field specified by class name, e.g.
omni.ui.StringField, omni.ui.IntField, omni.ui.CheckBox. Default is omni.ui.StringField.
pre_label (str): Text displayed before input field. Default None.
post_label (str): Text displayed after input field. Default None.
default_value (str): Default value of the input field.
warning_message (Optional[str]): Warning message that will displayed in red with the warning glyph. Default None.
"""
def __init__(
self,
width: int=400,
parent: ui.Widget=None, # OBSOLETE
message: str=None,
title: str=None,
ok_handler: Callable[[AbstractDialog], None]=None,
cancel_handler: Callable[[AbstractDialog], None]=None,
ok_label: str="Ok",
cancel_label: str="Cancel",
input_cls: ui.AbstractField=None,
pre_label: str=None,
post_label: str=None,
default_value: str=None,
warning_message: Optional[str]=None
):
super().__init__(
width=width,
title=title,
ok_handler=ok_handler,
cancel_handler=cancel_handler,
ok_label=ok_label,
cancel_label=cancel_label,
modal=True,
warning_message=warning_message
)
with self._window.frame:
with ui.VStack():
self._build_warning_message()
self._widget = InputWidget(
message=message,
input_cls=input_cls or ui.StringField,
pre_label=pre_label,
post_label=post_label,
default_value=default_value)
self._build_ok_cancel_buttons()
self.hide()
def get_value(self) -> Any:
"""
Returns field value.
Returns:
Any, e.g. one of [str, int, float, bool]
"""
if self._widget:
return self._widget.get_value()
return None
def destroy(self):
if self._widget:
self._widget.destroy()
self._widget = None
super().destroy()
class InputWidget:
"""
A simple widget with an input field. As opposed to the dialog class, the widget can be combined
with other widget types in the same window.
Keyword Args:
message (str): Message to display.
input_cls (omni.ui.AbstractField): Class of the input field, e.g.
omni.ui.StringField, omni.ui.IntField, omni.ui.CheckBox. Default is omni.ui.StringField.
pre_label (str): Text displayed before input field. Default None.
post_label (str): Text displayed after input field. Default None.
default_value (str): Default value of the input field.
"""
def __init__(self,
message: str = None,
input_cls: ui.AbstractField = None,
pre_label: str = None,
post_label: str = None,
default_value: Any = None
):
self._input = None
self._build_ui(message, input_cls or ui.StringField, pre_label, post_label, default_value)
def _build_ui(self,
message: str,
input_cls: ui.AbstractField,
pre_label: str,
post_label: str,
default_value: Any,
):
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="Background")
with ui.VStack(style_type_name_override="Dialog", spacing=6):
if message:
ui.Label(message, height=20, word_wrap=True, style_type_name_override="Message")
with ui.HStack(height=0):
input_width = 100
if pre_label:
ui.Label(pre_label, style_type_name_override="Field.Label", name="prefix")
input_width -= 30
if post_label:
input_width -= 30
self._input = input_cls(
width=ui.Percent(input_width), height=20, style_type_name_override="Input"
)
if default_value:
self._input.model.set_value(default_value)
# OM-95817: Wait a frame to make sure it focus correctly
async def focus_field():
await omni.kit.app.get_app().next_update_async()
if self._input:
self._input.focus_keyboard()
asyncio.ensure_future(focus_field())
if post_label:
ui.Label(post_label, style_type_name_override="Field.Label", name="postfix")
def get_value(self) -> Any:
"""
Returns value of input field.
Returns:
Any
"""
if self._input:
return get_field_value(self._input)
return None
def destroy(self):
self._input = None
self._window = None | 5,888 | Python | 35.80625 | 121 | 0.573709 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/message_dialog.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 typing import Callable, Optional
from .dialog import AbstractDialog, PopupDialog
from .style import get_style
class MessageDialog(PopupDialog):
"""
This simplest of all popup dialogs displays a confirmation message before executing an action.
Keyword Args:
title (str): Title of popup window. Default None.
message (str): The displayed message. Default ''.
disable_cancel_button (bool): If True, then don't display 'Cancel' button. Default False.
warning_message (Optional[str]): Warning message that will displayed in red with the warning glyph. Default None.
"""
def __init__(
self,
width: int=400,
parent: ui.Widget=None, # OBSOLETE
message: str="",
title: str=None,
ok_handler: Callable[[AbstractDialog], None]=None,
cancel_handler: Callable[[AbstractDialog], None]=None,
ok_label: str="Ok",
cancel_label: str="Cancel",
disable_okay_button: bool=False,
disable_cancel_button: bool=False,
warning_message: Optional[str]=None,
):
super().__init__(
width=width,
title=title,
ok_handler=ok_handler,
cancel_handler=cancel_handler,
ok_label=ok_label,
cancel_label=cancel_label,
modal=True,
warning_message=warning_message,
)
with self._window.frame:
with ui.VStack():
self._widget = MessageWidget(message)
self._build_warning_message()
self._build_ok_cancel_buttons(disable_okay_button=disable_okay_button, disable_cancel_button=disable_cancel_button)
self.hide()
def set_message(self, message: str):
"""
Updates the message string.
Args:
message (str): The message string.
"""
if self._widget:
self._widget.set_message(message)
def destroy(self):
if self._widget:
self._widget.destroy()
self._widget = None
super().destroy()
class MessageWidget:
"""
This widget displays a custom message. As opposed to the dialog class, the widget can be combined
with other widget types in the same window.
Keyword Args:
message (str): The message string
"""
def __init__(self, message: str = ""):
self._message_label = None
self._build_ui(message)
def _build_ui(self, message: str):
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="Background")
with ui.VStack(style_type_name_override="Dialog", spacing=6):
with ui.HStack(height=0):
self._message_label = ui.Label(message, word_wrap=True, style_type_name_override="Message")
def set_message(self, message: str):
"""
Updates the message string.
Args:
message (str): The message string.
"""
self._message_label.text = message
def destroy(self):
self._message_label = None
| 3,552 | Python | 31.898148 | 131 | 0.619088 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/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
try:
THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle")
except Exception:
THEME = None
finally:
THEME = THEME or "NvidiaDark"
CURRENT_PATH = Path(__file__).parent.absolute()
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath(f"icons/{THEME}")
def get_style():
if THEME == "NvidiaLight":
style = {
"Button": {"background_color": 0xFFC9C9C9, "selected_color": 0xFFACACAF},
"Button.Label": {"color": 0xFF535354},
"Dialog": {"background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin_width": 6},
"Label": {"background_color": 0xFFC9C9C9, "color": 0xFF535354},
"Input": {
"background_color": 0xFFC9C9C9,
"selected_color": 0xFFACACAF,
"color": 0xFF535354,
"alignment": ui.Alignment.LEFT_CENTER,
},
"Rectangle": {"background_color": 0xFFC9C9C9, "border_radius": 3},
"Background": {"background_color": 0xFFE0E0E0, "border_radius": 2, "border_width": 0.5, "border_color": 0x55ADAC9F},
"Background::header": {"background_color": 0xFF535354, "corner_flag": ui.CornerFlag.TOP, "margin": 0},
"Dialog": {"background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin": 10},
"Message": {
"background_color": 0xFFC9C9C9,
"color": 0xFF535354,
"margin": 0,
"alignment": ui.Alignment.LEFT_CENTER,
"margin": 0,
},
"Button": {"background_color": 0xFFC9C9C9, "selected_color": 0xFFACACAF, "margin": 0},
"Button.Label": {"color": 0xFF535354},
"Field": {"background_color": 0xFF535354, "color": 0xFFD6D6D6},
"Field:pressed": {"background_color": 0xFF535354, "color": 0xFFD6D6D6},
"Field:selected": {"background_color": 0xFFBEBBAE, "color": 0xFFD6D6D6},
"Field.Label": {"background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin": 0},
"Field.Label::title": {"color": 0xFFD6D6D6},
"Field.Label::prefix": {"alignment": ui.Alignment.RIGHT_CENTER},
"Field.Label::postfix": {"alignment": ui.Alignment.LEFT_CENTER},
"Field.Label::reset_all": {"color": 0xFFB0703B, "alignment": ui.Alignment.RIGHT_CENTER},
"Input": {
"background_color": 0xFF535354,
"color": 0xFFD6D6D6,
"alignment": ui.Alignment.LEFT_CENTER,
"margin_height": 0,
},
"Menu.Item": {"margin_width": 6, "margin_height": 2},
"Menu.Header": {"margin": 6},
"Menu.CheckBox": {"background_color": 0xFF535354, "color": 0xFFD6D6D6},
"Menu.Separator": {"color": 0x889E9E9E},
"Options.Item": {"margin_width": 6, "margin_height": 0},
"Options.CheckBox": {"background_color": 0x0, "color": 0xFF23211F},
"Options.RadioButton": {"background_color": 0x0, "color": 0xFF9E9E9E},
"Rectangle.Warning": {"background_color": 0x440000FF, "border_radius": 3, "margin": 10},
}
else:
style = {
"BorderedBackground": {"background_color": 0x0, "border_width": .5, "border_color": 0x55ADAC9F},
"Background": {"background_color": 0x0},
"Background::header": {"background_color": 0xFF23211F, "corner_flag": ui.CornerFlag.TOP, "margin": 0},
"Dialog": {"background_color": 0x0, "color": 0xFF9E9E9E, "margin": 10},
"Message": {
"background_color": 0x0,
"color": 0xFF9E9E9E,
"margin": 0,
"alignment": ui.Alignment.LEFT_CENTER,
"margin": 0,
},
"Button": {"background_color": 0xFF23211F, "selected_color": 0xFF8A8777, "margin": 0},
"Button.Label": {"color": 0xFF9E9E9E},
"Field.Label": {"background_color": 0x0, "color": 0xFF9E9E9E, "margin": 0},
"Field.Label::prefix": {"alignment": ui.Alignment.RIGHT_CENTER},
"Field.Label::postfix": {"alignment": ui.Alignment.LEFT_CENTER},
"Field.Label::reset_all": {"color": 0xFFB0703B, "alignment": ui.Alignment.RIGHT_CENTER},
"Input": {
"background_color": 0xCC23211F,
"color": 0xFF9E9E9E,
"alignment": ui.Alignment.LEFT_CENTER,
"margin_height": 0,
},
"Menu.Item": {"margin_width": 6, "margin_height": 2},
"Menu.Header": {"margin": 6},
"Menu.CheckBox": {"background_color": 0xDD9E9E9E, "color": 0xFF23211F},
"Menu.Separator": {"color": 0x889E9E9E},
"Options.Item": {"margin_width": 6, "margin_height": 0},
"Options.CheckBox": {"background_color": 0xDD9E9E9E, "color": 0xFF23211F},
"Options.RadioButton": {"background_color": 0x0, "color": 0xFF9E9E9E},
"Rectangle.Warning": {"background_color": 0x440000FF, "border_radius": 3, "margin": 10},
}
return style
| 5,578 | Python | 51.140186 | 128 | 0.573682 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/__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.
#
"""
A set of simple popup dialogs with optional input fields and two buttons, OK and Cancel.
Example:
.. code-block:: python
dialog = InputDialog(
width=450,
pre_label="prefix",
post_label="postfix",
ok_handler=on_okay,
cancel_handler=on_cancel,
)
"""
__all__ = [
'MessageDialog', 'MessageWidget',
'InputDialog', 'InputWidget',
'FormDialog', 'FormWidget',
'OptionsDialog', 'OptionsWidget',
'OptionsMenu', 'OptionsMenuWidget',
'PopupDialog'
]
from .message_dialog import MessageDialog, MessageWidget
from .input_dialog import InputDialog, InputWidget
from .form_dialog import FormDialog, FormWidget
from .options_dialog import OptionsDialog, OptionsWidget
from .options_menu import OptionsMenu, OptionsMenuWidget
from .dialog import PopupDialog
| 1,255 | Python | 30.399999 | 88 | 0.738645 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/dialog.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 carb.input
import omni.ui as ui
from typing import Callable, Union, Optional
from .style import get_style
class AbstractDialog:
pass
class PopupDialog(AbstractDialog):
""" Base class for a simple popup dialog with two primary buttons, OK and Cancel."""
WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE
WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP
WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR
def __init__(
self,
width: int=400,
parent: ui.Widget=None, # OBSOLETE
title: str=None,
ok_handler: Callable[[AbstractDialog], None]=None,
cancel_handler: Callable[[AbstractDialog], None]=None,
ok_label: str="Ok",
cancel_label: str="Cancel",
hide_title_bar: bool=False,
modal: bool=False,
warning_message: Optional[str]=None,
):
"""
Inherited args from the base class.
Keyword Args:
width (int): Window width. Default 400.
title (str): Title to display. Default None.
ok_handler (Callable): Function to invoke when Ok button clicked. Function signature:
void okay_handler(dialog: PopupDialog)
cancel_handler (Callable): Function to invoke when Cancel button clicked. Function
signature: void cancel_handler(dialog: PopupDialog)
ok_label (str): Alternative text to display on 'Accept' button. Default 'Ok'.
cancel_label (str): Alternative text to display on 'Cancel' button. Default 'Cancel'.
warning_message (Optional[str]): Warning message that will displayed in red with the warning glyph. Default None.
parent (omni.ui.Widget): OBSOLETE.
"""
super().__init__()
self._title = title
self._click_okay_handler = ok_handler
self._click_cancel_handler = cancel_handler
self._okay_label = ok_label
self._okay_button = None
self._cancel_label = cancel_label
self._cancel_button = None
self._warning_message = warning_message
self._modal = modal
self._width = width
self._hide_title_bar = hide_title_bar
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_okay,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel
}
self._build_window()
def __del__(self):
self.destroy()
def show(self, offset_x: int = 0, offset_y: int = 0, parent: ui.Widget = None, recreate_window: bool = False):
"""
Shows this dialog, optionally offset from the parent widget, if any.
Keyword Args:
offset_x (int): X offset. Default 0.
offset_y (int): Y offset. Default 0.
parent (ui.Widget): Offset from this parent widget. Default None.
recreate_window (bool): Recreate popup window. Default False.
"""
if recreate_window:
# OM-42020: Always recreate window.
# Recreate to follow the parent window type (external window or main window) to make position right
# TODO: Only recreate when parent window external status changed. But there is no such notification now.
self._window = None
self._build_window()
if parent:
self._window.position_x = parent.screen_position_x + offset_x
self._window.position_y = parent.screen_position_y + offset_y
elif offset_x != 0 or offset_y != 0:
self._window.position_x = offset_x
self._window.position_y = offset_y
self._window.set_key_pressed_fn(self._on_key_pressed)
self._window.visible = True
def hide(self):
"""Hides this dialog."""
self._window.visible = False
@property
def position_x(self):
return self._window.position_x
@property
def position_y(self):
return self._window.position_y
@property
def window(self):
return self._window
def _build_window(self):
window_flags = self.WINDOW_FLAGS
if not self._title or self._hide_title_bar:
window_flags |= ui.WINDOW_FLAGS_NO_TITLE_BAR
if self._modal:
window_flags |= ui.WINDOW_FLAGS_MODAL
self._window = ui.Window(self._title or "", width=self._width, height=0, flags=window_flags)
self._build_widgets()
def _build_widgets(self):
pass
def _cancel_handler(self, dialog):
self.hide()
def _ok_handler(self, dialog):
pass
def _build_ok_cancel_buttons(self, disable_okay_button: bool = False, disable_cancel_button: bool = False):
if disable_okay_button and disable_cancel_button:
return
with ui.HStack(height=20, spacing=4):
ui.Spacer()
if not disable_okay_button:
self._okay_button = ui.Button(self._okay_label, width=100, clicked_fn=self._on_okay)
if not disable_cancel_button:
self._cancel_button = ui.Button(self._cancel_label, width=100, clicked_fn=self._on_cancel)
ui.Spacer()
def _build_warning_message(self, glyph_width=50, glyph_height=100):
if not self._warning_message:
return
with ui.ZStack(style=get_style(), height=0):
with ui.HStack(style={"margin": 15}):
ui.Image(
"resources/glyphs/Warning_Log.svg",
width=glyph_width,
height=glyph_height,
alignment=ui.Alignment.CENTER
)
ui.Label(self._warning_message, word_wrap=True, style_type_name_override="Message")
ui.Rectangle(style_type_name_override="Rectangle.Warning")
def _on_okay(self):
if self._click_okay_handler:
self._click_okay_handler(self)
def _on_cancel(self):
if self._click_cancel_handler:
self._click_cancel_handler(self)
else:
self.hide()
def _on_key_pressed(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func and mod in (0, ui.Widget.FLAG_WANT_CAPTURE_KEYBOARD):
func()
def set_okay_clicked_fn(self, ok_handler: Callable[[AbstractDialog], None]):
"""
Sets function to invoke when Okay button is clicked.
Args:
ok_handler (Callable): Callback with signature: void okay_handler(dialog: PopupDialog)
"""
self._click_okay_handler = ok_handler
def set_cancel_clicked_fn(self, cancel_handler: Callable[[AbstractDialog], None]):
"""
Sets function to invoke when Cancel button is clicked.
Args:
cancel_handler (Callable): Callback with signature: void cancel_handler(dialog: PopupDialog)
"""
self._click_cancel_handler = cancel_handler
def destroy(self):
self._window = None
self._click_okay_handler = None
self._click_cancel_handler = None
self._key_functions = None
self._okay_button = None
self._cancel_button = None
def get_field_value(field: ui.AbstractField) -> Union[str, int, float, bool]:
if not field:
return None
if isinstance(field, ui.StringField):
return field.model.get_value_as_string()
elif type(field) in [ui.IntField, ui.IntDrag, ui.IntSlider]:
return field.model.get_value_as_int()
elif type(field) in [ui.FloatField, ui.FloatDrag, ui.FloatSlider]:
return field.model.get_value_as_float()
elif isinstance(field, ui.CheckBox):
return field.model.get_value_as_bool()
else:
# TODO: Retrieve values for MultiField
return None
| 8,192 | Python | 34.777292 | 125 | 0.613403 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/options_menu.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 typing import List, Dict, Callable
from collections import namedtuple
from .dialog import AbstractDialog, PopupDialog
from .options_dialog import OptionsWidget
from .style import get_style
class OptionsMenu(PopupDialog):
"""
A simple checkbox menu with a set of options
Keyword Args:
title (str): Title of this menu. Default None.
field_defs ([OptionsMenu.FieldDef]): List of FieldDefs. Default [].
value_changed_fn (Callable): This callback is triggered on any value change.
Note:
OptionsMenu.FieldDef:
A namedtuple of (name, label, glyph, default) for describing the options field,
e.g. OptionsDialog.FieldDef("option", "Option", None, True).
"""
FieldDef = namedtuple("OptionsMenuFieldDef", "name label glyph default")
def __init__(
self,
width: int=400,
parent: ui.Widget=None,
title: str=None,
ok_handler: Callable[[AbstractDialog], None]=None,
cancel_handler: Callable[[AbstractDialog], None]=None,
ok_label: str="Ok",
cancel_label: str="Cancel",
field_defs: List[FieldDef]=None,
value_changed_fn: Callable=None,
):
self._widget = OptionsMenuWidget(title, field_defs, value_changed_fn, build_ui=False)
super().__init__(
width=width,
title=title,
ok_handler=ok_handler,
cancel_handler=cancel_handler,
ok_label=ok_label,
cancel_label=cancel_label,
hide_title_bar=True,
)
def get_values(self) -> dict:
"""
Returns all values in a dictionary.
Returns:
dict
"""
if self._widget:
return self._widget.get_values()
return {}
def get_value(self, name: str) -> bool:
"""
Returns value of the named field.
Args:
name (str): Name of the field.
Returns:
bool
"""
if self._widget:
return self._widget.get_value(name)
return False
def set_value(self, name: str, value: bool):
"""
Sets the value of the named field.
Args:
name (str): Name of the field.
value (bool): New value
"""
if self._widget:
self._widget.set_value(name, value)
return None
def reset_values(self):
"""Resets all values to their defaults."""
if self._widget:
self._widget.reset_values()
return None
def destroy(self):
"""Destructor"""
if self._widget:
self._widget.destroy()
self._widget = None
super().destroy()
def _build_widgets(self):
with self._window.frame:
with ui.VStack():
self._widget.build_ui()
self.hide()
class OptionsMenuWidget:
"""
A simple checkbox widget with a set of options. As opposed to the menu class, the widget can be combined
with other widget types in the same window.
Keyword Args:
title (str): Title of this menu. Default None.
field_defs ([OptionsDialog.FieldDef]): List of FieldDefs. Default [].
value_changed_fn (Callable): This callback is triggered on any value change.
build_ui (bool): Build ui when created.
Note:
OptionsMenu.FieldDef:
A namedtuple of (name, label, glyph, default) for describing the options field,
e.g. OptionsDialog.FieldDef("option", "Option", None, True).
"""
def __init__(self,
title: str = None,
field_defs: List[OptionsMenu.FieldDef] = [],
value_changed_fn: Callable = None,
build_ui: bool = True,
):
self._field_defs = field_defs
self._field_models: Dict[str, ui.AbstractValueModel] = {}
for field in field_defs:
self._field_models[field.name] = ui.SimpleBoolModel(field.default)
self._fields: Dict[str, ui.Widget] = {}
self._title = title
self._value_changed_fn = value_changed_fn
if build_ui:
self.build_ui()
def build_ui(self):
with ui.ZStack(height=0, style=get_style()):
ui.Rectangle(style_type_name_override="BorderedBackground")
with ui.VStack():
with ui.ZStack(height=0):
ui.Rectangle(name="header", style_type_name_override="Background")
with ui.HStack(style_type_name_override="Menu.Header"):
if self._title:
ui.Label(self._title, width=0, name="title", style_type_name_override="Field.Label")
ui.Spacer()
label = ui.Label(
"Reset All", width=0, name="reset_all", style_type_name_override="Field.Label"
)
ui.Spacer(width=6)
label.set_mouse_pressed_fn(lambda x, y, b, _: self.reset_values())
ui.Spacer(height=4)
for field_def in self._field_defs:
with ui.HStack(height=20, style_type_name_override="Menu.Item"):
check_box = ui.CheckBox(model=self._field_models[field_def.name], width=20, style_type_name_override="Menu.CheckBox")
# check_box.model.set_value(field_def.default)
check_box.model.add_value_changed_fn(
lambda _, name=field_def.name: self._value_changed_fn(self, name)
)
ui.Spacer(width=2)
ui.Label(field_def.label, width=0, style_type_name_override="Field.Label")
self._fields[field_def.name] = check_box
ui.Spacer(height=4)
def get_value(self, name: str) -> bool:
"""
Returns value of the named field.
Args:
name (str): Name of the field.
Returns:
bool
"""
if name and name in self._field_models:
model = self._field_models[name]
return model.get_value_as_bool()
return False
def get_values(self) -> dict:
"""
Returns all values in a dictionary.
Returns:
dict
"""
options = {}
for name, model in self._field_models.items():
options[name] = model.get_value_as_bool()
return options
def set_value(self, name: str, value: bool):
"""
Sets the value of the named field.
Args:
name (str): Name of the field.
value (bool): New value
"""
if name and name in self._field_models:
model = self._field_models[name]
model.set_value(value)
def reset_values(self):
"""Resets all values to their defaults."""
for field_def in self._field_defs:
model = self._field_models[field_def.name]
model.set_value(field_def.default)
def destroy(self):
self._field_defs = None
self._fields.clear()
self._field_models.clear()
| 7,633 | Python | 32.191304 | 141 | 0.562688 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/options_dialog.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 typing import List, Dict, Callable, Optional
from collections import namedtuple
from .dialog import AbstractDialog, PopupDialog
from .style import get_style, ICON_PATH
class OptionsDialog(PopupDialog):
"""
A simple checkbox dialog with a set options and two buttons, OK and Cancel
Keyword Args:
title (str): Title of popup window. Default None.
message (str): Message string.
field_defs ([OptionsDialog.FieldDef]): List of FieldDefs. Default [].
value_changed_fn (Callable): This callback is triggered on any value change.
radio_group (bool): If True, then only one option can be selected at a time.
Note:
OptionsDialog.FieldDef:
A namedtuple of (name, label, default) for describing the options field,
e.g. OptionsDialog.FieldDef("option", "Option", True).
"""
FieldDef = namedtuple("OptionsDialogFieldDef", "name label default")
def __init__(
self,
width: int=400,
parent: ui.Widget=None, # OBSOLETE
message: str=None,
title: str=None,
ok_handler: Callable[[AbstractDialog], None]=None,
cancel_handler: Callable[[AbstractDialog], None]=None,
ok_label: str="Ok",
cancel_label: str="Cancel",
field_defs: List[FieldDef]=None,
value_changed_fn: Callable=None,
radio_group: bool=False,
):
super().__init__(
width=width,
title=title,
ok_handler=ok_handler,
cancel_handler=cancel_handler,
ok_label=ok_label,
cancel_label=cancel_label,
hide_title_bar=True,
modal=True
)
with self._window.frame:
with ui.VStack():
self._widget = OptionsWidget(message, field_defs, value_changed_fn, radio_group)
self._build_ok_cancel_buttons()
self.hide()
def get_value(self, name: str) -> bool:
"""
Returns value of the named field.
Args:
name (str): Name of the field.
Returns:
bool
"""
if self._widget:
return self._widget.get_value(name)
return None
def get_values(self) -> Dict:
"""
Returns all values in a dictionary.
Returns:
Dict
"""
if self._widget:
return self._widget.get_values()
return {}
def get_choice(self) -> str:
"""
Returns name of chosen option.
Returns:
str
"""
if self._widget:
return self._widget.get_choice()
return None
def destroy(self):
if self._widget:
self._widget.destroy()
self._widget = None
super().destroy()
class OptionsWidget:
"""
A simple checkbox widget with a set options. As opposed to the dialog class, the widget can be combined
with other widget types in the same window.
Keyword Args:
message (str): Message string.
field_defs ([OptionsDialog.FieldDef]): List of FieldDefs. Default [].
value_changed_fn (Callable): This callback is triggered on any value change.
radio_group (bool): If True, then only one option can be selected at a time.
Note:
OptionsDialog.FieldDef:
A namedtuple of (name, label, default) for describing the options field,
e.g. OptionsDialog.FieldDef("option", "Option", True).
"""
def __init__(self,
message: str = None,
field_defs: List[OptionsDialog.FieldDef] = [],
value_changed_fn: Callable = None,
radio_group: bool = False
):
self._field_defs = field_defs
self._radio_group = ui.RadioCollection() if radio_group else None
self._fields: Dict[str, ui.Widget] = {}
self._build_ui(message, field_defs, value_changed_fn, self._radio_group)
def _build_ui(self, message: str, field_defs: List[OptionsDialog.FieldDef], value_changed_fn: Callable, radio_group: Optional[ui.RadioCollection]):
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="Background")
with ui.VStack(style_type_name_override="Dialog", spacing=0):
if message:
ui.Label(message, height=20, word_wrap=True, style_type_name_override="Message")
for field_def in field_defs:
with ui.HStack():
ui.Spacer(width=30)
with ui.HStack(height=20, style_type_name_override="Options.Item"):
if radio_group:
icon_style = {
"image_url": f"{ICON_PATH}/radio_off.svg",
":checked": {"image_url": f"{ICON_PATH}/radio_on.svg"},
}
field = ui.RadioButton(
radio_collection=radio_group,
width=26,
height=26,
style=icon_style,
style_type_name_override="Options.RadioButton",
)
else:
field = ui.CheckBox(width=20, style_type_name_override="Options.CheckBox")
field.model.set_value(field_def.default)
ui.Spacer(width=2)
ui.Label(field_def.label, width=0, style_type_name_override="Field.Label")
self._fields[field_def.name] = field
ui.Spacer()
#ui.Spacer(height=4)
def get_values(self) -> dict:
"""
Returns all values in a dictionary.
Returns:
dict
"""
options = {}
for name, field in self._fields.items():
options[name] = field.checked if isinstance(field, ui.RadioButton) else field.model.get_value_as_bool()
return options
def get_value(self, name: str) -> bool:
"""
Returns value of the named field.
Args:
name (str): Name of the field.
Returns:
bool
"""
if name and name in self._fields:
field = self._fields[name]
return field.checked if isinstance(field, ui.RadioButton) else field.model.get_value_as_bool()
return None
def get_choice(self) -> str:
"""
Returns name of chosen option.
Returns:
str
"""
if self._radio_group:
choice = self._radio_group.model.get_value_as_int()
return self._field_defs[choice].name
return None
def destroy(self):
self._field_defs = None
self._fields.clear()
self._radio_group = None
| 7,428 | Python | 33.235023 | 151 | 0.551158 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/form_dialog.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__ = ['FormDialog', 'FormWidget']
from omni.kit.async_engine import run_coroutine
import omni.ui as ui
import asyncio
from typing import List, Union, Callable
from collections import namedtuple
from .dialog import AbstractDialog, PopupDialog, get_field_value
from .style import get_style
class FormDialog(PopupDialog):
"""
A simple popup dialog with a set of input fields and two buttons, OK and Cancel
Keyword Args:
title (str): Title of popup window. Default None.
message (str): Message string.
field_defs ([FormDialog.FieldDef]): List of FieldDefs. Default [].
input_width (int): OBSOLETE.
Note:
FormDialog.FieldDef:
A namedtuple of (name, label, type, default value) for describing the input field,
e.g. FormDialog.FieldDef("name", "Name: ", omni.ui.StringField, "Bob").
"""
FieldDef = namedtuple("FormDialogFieldDef", "name label type default focused", defaults=[False])
def __init__(
self,
width: int=400,
parent: ui.Widget=None, # OBSOLETE
message: str=None,
title: str=None,
ok_handler: Callable[[AbstractDialog], None]=None,
cancel_handler: Callable[[AbstractDialog], None]=None,
ok_label: str="Ok",
cancel_label: str="Cancel",
field_defs: List[FieldDef]=None,
input_width: int=250 # OBSOLETE
):
super().__init__(
width=width,
title=title,
ok_handler=ok_handler,
cancel_handler=cancel_handler,
ok_label=ok_label,
cancel_label=cancel_label,
modal=True
)
with self._window.frame:
with ui.VStack(style=get_style(), style_type_name_override="Dialog"):
self._widget = FormWidget(message, field_defs)
self._build_ok_cancel_buttons()
self.hide()
def show(self, offset_x: int = 0, offset_y: int = 0, parent: ui.Widget = None):
"""
Shows this dialog, optionally offset from the parent widget, if any.
Keyword Args:
offset_x (int): X offset. Default 0.
offset_y (int): Y offset. Default 0.
parent (ui.Widget): Offset from this parent widget. Default None.
"""
# focus on show
self._widget.focus()
super().show(offset_x=offset_x, offset_y=offset_y, parent=parent)
def get_field(self, name: str) -> ui.AbstractField:
"""
Returns widget corresponding to named field.
Args:
name (str): Name of the field.
Returns:
omni.ui.AbstractField
"""
if self._widget:
return self._widget.get_field(name)
return None
def get_value(self, name: str) -> Union[str, int, float, bool]:
"""
Returns value of the named field.
Args:
name (str): Name of the field.
Returns:
Union[str, int, float, bool]
Note:
Doesn't currently return MultiFields correctly.
"""
if self._widget:
return self._widget.get_value(name)
return None
def get_values(self) -> dict:
"""
Returns all values in a dict.
Args:
name (str): Name of the field.
Returns:
dict
Note:
Doesn't currently return MultiFields correctly.
"""
if self._widget:
return self._widget.get_values()
return {}
def reset_values(self):
"""Resets all values to their defaults."""
if self._widget:
return self._widget.reset_values()
def destroy(self):
"""Destructor"""
if self._widget:
self._widget.destroy()
self._widget = None
super().destroy()
class FormWidget:
"""
A simple form widget with a set of input fields. As opposed to the dialog class, the widget can be combined
with other widget types in the same window.
Keyword Args:
message (str): Message string.
field_defs ([FormDialog.FieldDef]): List of FieldDefs. Default [].
Note:
FormDialog.FieldDef:
A namedtuple of (name, label, type, default value) for describing the input field,
e.g. FormDialog.FieldDef("name", "Name: ", omni.ui.StringField, "Bob").
"""
def __init__(self, message: str = None, field_defs: List[FormDialog.FieldDef] = []):
self._field_defs = field_defs
self._fields = {}
self._build_ui(message, field_defs)
def _build_ui(self, message: str, field_defs: List[FormDialog.FieldDef]):
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="Background")
with ui.VStack(style_type_name_override="Dialog", spacing=6):
if message:
ui.Label(message, height=20, word_wrap=True, style_type_name_override="Message")
for field_def in field_defs:
with ui.HStack(height=0):
ui.Label(field_def.label, style_type_name_override="Field.Label", name="prefix")
field = field_def.type(width=ui.Percent(70), height=20, style_type_name_override="Field")
if "set_value" in dir(field.model):
field.model.set_value(field_def.default)
self._fields[field_def.name] = field
def focus(self) -> None:
"""Focus fields for the current widget."""
# had to delay focus keyboard for one frame
async def delay_focus(field):
import omni.kit.app
await omni.kit.app.get_app().next_update_async()
field.focus_keyboard()
# OM-80009: Add ability to focus an input field for form dialog;
# When multiple fields are set to focused, then the last field will be the
# actual focused field.
for field_def in self._field_defs:
if field_def.focused:
field = self._fields[field_def.name]
run_coroutine(delay_focus(field))
def get_field(self, name: str) -> ui.AbstractField:
"""
Returns widget corresponding to named field.
Args:
name (str): Name of the field.
Returns:
omni.ui.AbstractField
"""
if name and name in self._fields:
return self._fields[name]
return None
def get_value(self, name: str) -> Union[str, int, float, bool]:
"""
Returns value of the named field.
Args:
name (str): Name of the field.
Returns:
Union[str, int, float, bool]
Note:
Doesn't currently return MultiFields correctly.
"""
if name and name in self._fields:
field = self._fields[name]
return get_field_value(field)
return None
def get_values(self) -> dict:
"""
Returns all values in a dict.
Args:
name (str): Name of the field.
Returns:
dict
Note:
Doesn't currently return MultiFields correctly.
"""
return {name: get_field_value(field) for name, field in self._fields.items()}
def reset_values(self):
"""Resets all values to their defaults."""
for field_def in self._field_defs:
if field_def.name in self._fields:
field = self._fields[field_def.name]
if "set_value" in dir(field.model):
field.model.set_value(field_def.default)
def destroy(self):
self._field_defs = None
self._fields.clear() | 8,184 | Python | 30.972656 | 113 | 0.577713 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/__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.
##
from .test_form_dialog import *
from .test_input_dialog import *
from .test_message_dialog import *
from .test_options_dialog import *
from .test_options_menu import * | 608 | Python | 45.84615 | 77 | 0.786184 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_input_dialog.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
import omni.kit.app
from pathlib import Path
from omni.ui.tests.test_base import OmniUiTest
from unittest.mock import Mock
from ..input_dialog import InputDialog, InputWidget
CURRENT_PATH = Path(__file__).parent.absolute()
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests")
class TestInputDialog(OmniUiTest):
"""Testing FormDialog"""
async def setUp(self):
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images")
async def tearDown(self):
pass
async def test_ui_layout(self):
"""Testing that the UI layout looks consistent"""
window = await self.create_test_window()
with window.frame:
InputWidget(
message="Please enter a username:",
pre_label="LDAP Name: ",
post_label="@nvidia.com",
default_value="user",
)
await omni.kit.app.get_app().next_update_async()
# Add a threshold for the focused field is not stable.
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="input_dialog.png", threshold=25)
async def test_okay_handler(self):
"""Test clicking okay button triggers the callback"""
mock_okay_handler = Mock()
under_test = InputDialog(
message="Please enter a string value:",
pre_label="LDAP Name: ",
post_label="@nvidia.com",
ok_handler=mock_okay_handler,
)
under_test.show()
under_test._on_okay()
await omni.kit.app.get_app().next_update_async()
mock_okay_handler.assert_called_once()
async def test_get_field_value(self):
"""Test that get_value returns the value of the input field"""
under_test = InputDialog(
message="Please enter a string value:",
pre_label="LDAP Name: ",
post_label="@nvidia.com",
default_value="user",
)
self.assertEqual("user", under_test.get_value())
| 2,503 | Python | 36.373134 | 119 | 0.644826 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_options_menu.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
import unittest
import asyncio
import omni.kit.app
from pathlib import Path
from omni.ui.tests.test_base import OmniUiTest
from unittest.mock import Mock
from ..options_menu import OptionsMenu, OptionsMenuWidget
CURRENT_PATH = Path(__file__).parent.absolute()
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests")
class TestOptionsMenu(OmniUiTest):
"""Testing FormDialog"""
async def setUp(self):
self._field_defs = [
OptionsMenu.FieldDef("audio", "Audio", None, False),
OptionsMenu.FieldDef("materials", "Materials", None, True),
OptionsMenu.FieldDef("scripts", "Scripts", None, False),
OptionsMenu.FieldDef("textures", "Textures", None, False),
OptionsMenu.FieldDef("usd", "USD", None, True),
]
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images")
async def tearDown(self):
pass
async def test_ui_layout(self):
"""Testing that the UI layout looks consistent"""
window = await self.create_test_window()
with window.frame:
OptionsMenuWidget(
title="Options",
field_defs=self._field_defs,
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="options_menu.png")
window.destroy()
# wait one frame so that widget is destroyed
await omni.kit.app.get_app().next_update_async()
async def test_okay_handler(self):
"""Test clicking okay button triggers the callback"""
mock_value_changed_fn = Mock()
under_test = OptionsMenu(
title="Options",
field_defs=self._field_defs,
value_changed_fn=mock_value_changed_fn,
)
under_test.show()
self.assertEqual(under_test.get_value('usd'), True)
under_test.destroy()
| 2,415 | Python | 37.349206 | 105 | 0.662112 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_message_dialog.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
import omni.kit.app
from pathlib import Path
from omni.ui.tests.test_base import OmniUiTest
from unittest.mock import Mock
from ..message_dialog import MessageWidget, MessageDialog
CURRENT_PATH = Path(__file__).parent.absolute()
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests")
class TestMessageDialog(OmniUiTest):
"""Testing FormDialog"""
async def setUp(self):
self._message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images")
async def tearDown(self):
pass
async def test_message_widget(self):
"""Testing the look of message widget"""
window = await self.create_test_window()
with window.frame:
under_test = MessageWidget()
under_test.set_message(self._message)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="message_dialog.png")
window.destroy()
# wait one frame so that widget is destroyed
await omni.kit.app.get_app().next_update_async()
async def test_messgae_dialog(self):
"""Testing the look of message dialog"""
mock_cancel_handler = Mock()
under_test = MessageDialog(title="Message", cancel_handler=mock_cancel_handler,)
under_test.set_message("Hello World")
under_test.show()
await omni.kit.app.get_app().next_update_async()
under_test._on_cancel()
mock_cancel_handler.assert_called_once()
under_test.destroy() | 2,155 | Python | 41.274509 | 149 | 0.703016 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_form_dialog.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
import omni.ui as ui
import omni.kit.app
from pathlib import Path
from omni.ui.tests.test_base import OmniUiTest
from unittest.mock import Mock
from ..form_dialog import FormDialog, FormWidget
CURRENT_PATH = Path(__file__).parent.absolute()
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests")
class TestFormDialog(OmniUiTest):
"""Testing FormDialog"""
async def setUp(self):
self._field_defs = [
FormDialog.FieldDef("string", "String: ", ui.StringField, "default"),
FormDialog.FieldDef("int", "Integer: ", ui.IntField, 1),
FormDialog.FieldDef("float", "Float: ", ui.FloatField, 2.0),
FormDialog.FieldDef(
"tuple", "Tuple: ", lambda **kwargs: ui.MultiFloatField(column_count=3, h_spacing=2, **kwargs), None
),
FormDialog.FieldDef("slider", "Slider: ", lambda **kwargs: ui.FloatSlider(min=0, max=10, **kwargs), 3.5),
FormDialog.FieldDef("bool", "Boolean: ", ui.CheckBox, True),
]
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images")
async def tearDown(self):
pass
async def test_ui_layout(self):
"""Testing that the UI layout looks consistent"""
window = await self.create_test_window()
with window.frame:
FormWidget(
message="Test fields:",
field_defs=self._field_defs,
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="form_dialog.png")
window.destroy()
# wait one frame so that widget is destroyed
await omni.kit.app.get_app().next_update_async()
async def test_okay_handler(self):
"""Test clicking okay button triggers the callback"""
mock_okay_handler = Mock()
under_test = FormDialog(
message="Test fields:",
field_defs=self._field_defs,
ok_handler=mock_okay_handler,
)
under_test.show()
under_test._on_okay()
await omni.kit.app.get_app().next_update_async()
mock_okay_handler.assert_called_once()
under_test.destroy()
async def test_get_field_value(self):
"""Test that get_value returns the value of the named field"""
under_test = FormDialog(
message="Test fields:",
field_defs=self._field_defs,
)
for field in self._field_defs:
name, label, _, default_value, focused = field
self.assertEqual(default_value, under_test.get_value(name))
under_test.destroy()
async def test_reset_dialog_value(self):
"""Test reset dialog value"""
under_test = FormDialog(
message="Test fields:",
field_defs=self._field_defs,
)
string_field = under_test.get_field("string")
string_field.model.set_value("test")
self.assertEqual(under_test.get_value("string"), "test")
under_test.reset_values()
self.assertEqual(under_test.get_value("string"), "default")
under_test.destroy() | 3,641 | Python | 39.021978 | 118 | 0.629223 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_options_dialog.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
import unittest
import asyncio
import omni.kit.app
from pathlib import Path
from omni.ui.tests.test_base import OmniUiTest
from unittest.mock import Mock
from ..options_dialog import OptionsDialog, OptionsWidget
CURRENT_PATH = Path(__file__).parent.absolute()
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests")
class TestOptionsDialog(OmniUiTest):
"""Testing FormDialog"""
async def setUp(self):
self._field_defs = [
OptionsDialog.FieldDef("hard", "Hard place", False),
OptionsDialog.FieldDef("harder", "Harder place", True),
OptionsDialog.FieldDef("hardest", "Hardest place", False),
]
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images")
async def tearDown(self):
pass
async def test_ui_layout(self):
"""Testing that the UI layout looks consistent"""
window = await self.create_test_window()
with window.frame:
OptionsWidget(
message="Please make your choice:",
field_defs=self._field_defs,
radio_group=False,
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="options_dialog.png")
window.destroy()
# wait one frame so that widget is destroyed
await omni.kit.app.get_app().next_update_async()
async def test_okay_handler(self):
"""Test clicking okay button triggers the callback"""
mock_okay_handler = Mock()
under_test = OptionsDialog(
message="Please make your choice:",
field_defs=self._field_defs,
width=300,
radio_group=False,
ok_handler=mock_okay_handler,
)
under_test.show()
await asyncio.sleep(1)
under_test._on_okay()
mock_okay_handler.assert_called_once()
# TODO:
# self.assertEqual(under_test.get_choice(), 'harder')
under_test.destroy()
| 2,523 | Python | 36.117647 | 107 | 0.653983 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [2.0.16] - 2023-01-31
### Fixed
- OM-79359: Ensure imput dialog auto focus when it has default value
## [2.0.15] - 2022-12-12
### Fixed
- Reverts popup flag, otherwise cannot click away the dialog
## [2.0.14] - 2022-12-08
### Fixed
- Removes popup flag from core dialog, which causes drawing issues when dialogs collide
## [2.0.13] - 2022-11-30
### Fixed
- Centre the okay or cancel button when either or both are enabled.
## [2.0.12] - 2022-11-17
### Changes
- Updated doc.
## [2.0.11] - 2022-11-04
### Changes
- Added warning_message kwarg to base dialog class, and ui build for the warning message.
## [2.0.10] - 2022-08-23
### Changes
- Added set_cancel_clicked_fn to base dialog class.
## [2.0.9] - 2022-07-06
### Changes
- Added title bar.
## [2.0.8] - 2022-05-26
### Changes
- Updated styling
## [2.0.7] - 2022-04-06
### Changes
- Fixes Filepicker delete items dialog.
## [2.0.6] - 2022-03-31
### Changes
- Added unittests and created separate widgets and dialogs.
## [2.0.5] - 2021-11-01
### Changes
- Added set_value method to programmatically set an options menu value.
## [2.0.4] - 2021-11-01
### Changes
- Add method to MessageDialog for updating the message text.
## [2.0.3] - 2021-09-07
### Changes
- Makes all dialog windows modal.
- Option to hide Okay button.
- Better control of window placement when showing it.
## [2.0.2] - 2021-06-29
### Changes
- Binds ENTER key to Okay button, and ESC key to Cancel button.
## [2.0.1] - 2021-06-07
### Changes
- More thorough destruction of class instances upon shutdown.
## [2.0.0] - 2021-05-05
### Changes
- Update `__init__` of the popup dialog to be explicit in supported arguments
- Renamed click_okay_handler and click_cancel_handler to ok_handler and cancel_handler
- Added support for `Enter` and `Esc` keys.
- Renamed okay_label to ok_label
## [1.0.1] - 2021-02-10
### Changes
- Updated StyleUI handling
## [1.0.0] - 2020-10-29
### Added
- Ported OptionsMenu from content browser
- New OptionsDialog derived from OptionsMenu
## [0.1.0] - 2020-09-24
### Added
- Initial commit to master.
| 2,172 | Markdown | 23.41573 | 89 | 0.680018 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/docs/index.rst | omni.kit.window.popup_dialog
#############################
Simple Popup Dialogs with Input Fields
.. toctree::
:maxdepth: 1
CHANGELOG
.. automodule:: omni.kit.window.popup_dialog
:platform: Windows-x86_64, Linux-x86_64
:members:
:show-inheritance:
:undoc-members:
:imported-members:
| 313 | reStructuredText | 17.470587 | 44 | 0.623003 |
omniverse-code/kit/exts/omni.kit.window.popup_dialog/docs/Overview.md | # Overview
A set of simple Popup Dialogs for passing user inputs. All of these dialogs subclass from the base PopupDialog,
which provides OK and Cancel buttons. The user is able to re-label these buttons as well as associate callbacks
that execute upon being clicked.
Why you should use the dialogs in this extension:
* Avoid duplicating UI code that you then have to maintain.
* Re-use dialogs that have standard look and feel to keep a consistent experience across the app.
* Inherit future improvements.
## Form Dialog
A form dialog can display a mixed set of input types.

Code for above:
```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py
---
language: python
start-after: BEGIN-DOC-form-dialog
end-before: END-DOC-form-dialog
dedent: 8
---
```
## Input Dialog
An input dialog allows one input field.

Code for above:
```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py
---
language: python
start-after: BEGIN-DOC-input-dialog
end-before: END-DOC-input-dialog
dedent: 8
---
```
## Message Dialog
A message dialog is the simplest of all popup dialogs; it displays a confirmation message before executing some action.

Code for above:
```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py
---
language: python
start-after: BEGIN-DOC-message-dialog
end-before: END-DOC-message-dialog
dedent: 8
---
```
## Options Dialog
An options dialog displays a set of checkboxes; the choices optionally belong to a radio group - meaning only one
choice is active at a given time.

Code for above:
```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py
---
language: python
start-after: BEGIN-DOC-options-dialog
end-before: END-DOC-options-dialog
dedent: 8
---
```
## Options Menu
Similar to the options dialog, but displayed in menu form.

Code for above:
```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py
---
language: python
start-after: BEGIN-DOC-options-menu
end-before: END-DOC-options-menu
dedent: 8
---
```
## Demo app
A complete demo, that includes the code snippets above, is included with this extension at "scripts/demo_popup_dialog.py". | 2,456 | Markdown | 23.326732 | 122 | 0.739821 |
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/PACKAGE-LICENSES/omni.kit.collaboration.channel_manager-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/config/extension.toml | [package]
title = "Channel Manager"
description = "The channel manager provides universal way to create/manage Omniverse Channel without caring about the state management but only message exchange between clients."
version = "1.0.9"
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
category = "Utility"
feature = true
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
[dependencies]
"omni.client" = {}
[[python.module]]
name = "omni.kit.collaboration.channel_manager"
[[test]]
args = [
"--/app/asyncRendering=false",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
pyCoverageOmit = [
"omni/kit/collaboration/channel_manager/tests/channel_manager_tests.py",
"omni/kit/collaboration/channel_manager/tests/test_base.py",
"omni/kit/collaboration/channel_manager/manager.py",
"omni/kit/collaboration/channel_manager/extension.py",
]
dependencies = []
stdoutFailPatterns.include = []
stdoutFailPatterns.exclude = []
[settings]
exts."omni.kit.collaboration.channel_manager".enable_server_tests = false
exts."omni.kit.collaboration.channel_manager".from_app = "Kit"
| 1,577 | TOML | 29.346153 | 178 | 0.740013 |
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/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.
#
__all__ = ["ChannelManagerExtension", "join_channel_async"]
import carb
import omni.ext
from .manager import Channel, ChannelManager
_global_instance = None
class ChannelManagerExtension(omni.ext.IExt): # pragma: no cover
def on_startup(self):
global _global_instance
_global_instance = self
self._channel_manager = ChannelManager()
self._channel_manager.on_startup()
def on_shutdown(self):
global _global_instance
_global_instance = None
self._channel_manager.on_shutdown()
self._channel_manager = None
async def join_channel_async(self, url, get_users_only) -> Channel:
channel = await self._channel_manager.join_channel_async(url, get_users_only)
return channel
def _has_channel(self, url) -> bool:
"""Internal for testing."""
return self._channel_manager.has_channel(url)
@staticmethod
def _get_instance():
global _global_instance
return _global_instance
async def join_channel_async(url: str, get_users_only=False) -> Channel:
"""
Joins a channel and starts listening. The typical life cycle is as follows of a channel session if get_users_only is False:
1. User joins and sends a JOIN message to the channel.
2. Other clients receive JOIN message will respond with HELLO to broadcast its existence.
3. Clients communicate with each other by sending MESSAGE to each other.
4. Clients send LEFT before quit this channel.
Args:
url (str): The channel url to join. The url could be stage url or url with `.__omni_channel__` or `.channel` suffix.
If the suffix is not provided, it will be appended internally with `.__omni_channel__` to be compatible with old
version.
get_users_only (bool): It will join channel without sending JOIN/HELLO/LEFT message but only receives message
from other clients. For example, it can be used to fetch user list without broadcasting its
existence. After joining, all users inside the channel will respond HELLO message.
Returns:
omni.kit.collaboration.channel_manager.Channel. The instance of channel that could be used to publish/subscribe
channel messages.
Examples:
>>> import omni.kit.collaboration.channel_manager as nm
>>>
>>> async join_channel_async(url):
>>> channel = await nm.join_channel_async(url)
>>> if channel:
>>> channel.add_subscriber(...)
>>> await channel.send_message_async(...)
>>> else:
>>> # Failed to join
>>> pass
"""
if not url.startswith("omniverse:"):
carb.log_warn(f"Only Omniverse URL supports to create channel: {url}.")
return None
if not ChannelManagerExtension._get_instance():
carb.log_warn(f"Channel Manager Extension is not enabled.")
return None
channel = await ChannelManagerExtension._get_instance().join_channel_async(url, get_users_only=get_users_only)
return channel
| 3,571 | Python | 38.252747 | 131 | 0.66508 |
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/__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.
#
from .extension import ChannelManagerExtension, join_channel_async
from .types import Message, MessageType, PeerUser
from .manager import Channel, ChannelSubscriber
| 598 | Python | 48.916663 | 76 | 0.819398 |
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/manager.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__ = ["Channel", "ChannelSubscriber"]
import asyncio
import concurrent.futures
import weakref
import json
import carb
import carb.settings
import omni.client
import omni.kit.app
import time
import omni.kit.collaboration.telemetry
import zlib
from typing import Callable, Dict, List
from .types import Message, MessageType, PeerUser
CHANNEL_PING_TIME_IN_SECONDS = 60 # Period to ping.
KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER = b'__OVUM__'
KIT_CHANNEL_MESSAGE_VERSION = "3.0"
OMNIVERSE_CHANNEL_URL_SUFFIX = ".__omni_channel__"
OMNIVERSE_CHANNEL_NEW_URL_SUFFIX = ".channel"
MESSAGE_VERSION_KEY = "version"
MESSAGE_FROM_USER_NAME_KEY = "from_user_name"
MESSAGE_CONTENT_KEY = "content"
MESSAGE_TYPE_KEY = "message_type"
MESSAGE_APP_KEY = "app"
def _get_app(): # pragma: no cover
settings = carb.settings.get_settings()
app_name = settings.get("/app/name") or "Kit"
if app_name.lower().endswith(".next"):
# FIXME: OM-55917: temp hack for Create.
return app_name[:-5]
return app_name
def _build_message_in_bytes(from_user, message_type, content): # pragma: no cover
content = {
MESSAGE_VERSION_KEY: KIT_CHANNEL_MESSAGE_VERSION,
MESSAGE_TYPE_KEY: message_type,
MESSAGE_FROM_USER_NAME_KEY: from_user,
MESSAGE_CONTENT_KEY: content,
MESSAGE_APP_KEY: _get_app(),
}
content_bytes = json.dumps(content).encode()
return KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER + content_bytes
class ChannelSubscriber: # pragma: no cover
"""Handler of subscription to a channel."""
def __init__(self, message_handler: Callable[[Message], None], channel: weakref) -> None:
"""
Constructor. Internal only.
Args:
message_handler (Callable[[Message], None]): Message handler to handle message.
channel (weakref): Weak holder of channel.
"""
self._channel = channel
self._message_handler = message_handler
def __del__(self):
self.unsubscribe()
def unsubscribe(self):
"""Stop subscribe."""
self._message_handler = None
if self._channel and self._channel():
self._channel()._remove_subscriber(self)
def _on_message(self, message: Message):
if self._message_handler:
self._message_handler(message)
class NativeChannelWrapper: # pragma: no cover
"""
Channel is the manager that manages message receive and distribution to MessageSubscriber. It works
in subscribe/publish pattern.
"""
def __init__(self, url: str, get_users_only):
"""
Constructor. Internal only.
"""
self._url = url
self._logged_user_name = ""
self._logged_user_id = ""
self._peer_users: Dict[str, PeerUser] = {}
self._channel_handler = None
self._subscribers = []
self._message_queue = []
self._stopped = False
self._get_users_only = get_users_only
self._stopping = False
self._last_ping_time = time.time()
self._last_user_response_time = {}
self._all_pending_tasks = []
self._joining = False
self._telemetry = omni.kit.collaboration.telemetry.Schema_omni_kit_collaboration_1_0()
def _track_asyncio_task(self, task):
self._all_pending_tasks.append(task)
def _remove_asyncio_task(self, task):
if task in self._all_pending_tasks:
self._all_pending_tasks.remove(task)
def _run_asyncio_task(self, func, *args):
task = asyncio.ensure_future(func(*args))
self._track_asyncio_task(task)
task.add_done_callback(lambda task: self._remove_asyncio_task(task))
return task
def _remove_all_tasks(self):
for task in self._all_pending_tasks:
task.cancel()
self._all_pending_tasks = []
def destroy(self):
self._remove_all_tasks()
self._telemetry = None
@property
def url(self) -> str:
"""Property. The channel url in Omniverse."""
return self._url
@property
def stopped(self) -> bool:
"""Property. If this channel is stopped already."""
return self._stopped or not self._channel_handler or self._channel_handler.is_finished()
@property
def stopping(self) -> bool:
return self._stopping
@property
def logged_user_name(self) -> str:
"""Property. The logged user name for this channel."""
return self._logged_user_name
@property
def logged_user_id(self) -> str:
"""Property. The unique logged user id."""
return self._logged_user_id
@property
def peer_users(self) -> Dict[str, PeerUser]:
"""Property. All the peer clients that joined to this channel."""
return self._peer_users
def _emit_channel_event(self, event_name:str):
"""
Generates a structured log event noting that a join or leave event has occurred. This event
is sent through the 'omni.kit.collaboration.telemetry' extension.
Args:
event_name: the name of the event to send. This must be either 'join' or 'leave'.
"""
# build up the event data to emit. Note that the live-edit session's URL will be hashed
# instead of exposed directly. This is because the URL contains both the USD stage name
# and potential PII in the session's name tag itself (ie: "Bob_session". Both of these
# are potentially considered either personal information or intellectual property and
# should not be exposed in telemetry events. The hashed value will at least be stable
# for any given URL.
event = omni.kit.collaboration.telemetry.Struct_liveEdit_liveEdit()
event.id = str(zlib.crc32(bytes(self.url, "utf-8")))
event.action = event_name
settings = carb.settings.get_settings()
cloud_link_id = settings.get("/cloud/cloudLinkId") or ""
self._telemetry.liveEdit_sendEvent(cloud_link_id, event)
async def join_channel_async(self):
"""
Async function. Join Omniverse Channel.
Args:
url: The url to create/join a channel.
get_users_only: Johns channel as a monitor only or not.
"""
if self._get_users_only:
carb.log_info(f"Getting users from channel: {self.url}")
else:
carb.log_info(f"Starting to join channel: {self.url}")
if self._channel_handler:
self._channel_handler.stop()
self._channel_handler = None
# Gets the logged user information.
try:
result, server_info = await omni.client.get_server_info_async(self.url)
if result != omni.client.Result.OK:
return False
self._logged_user_name = server_info.username
self._logged_user_id = server_info.connection_id
except Exception as e:
carb.log_error(f"Failed to join channel {self.url} since user token cannot be got: {str(e)}.")
return False
channel_connect_future = concurrent.futures.Future()
# TODO: Should this function be guarded with mutex?
# since it's called in another native thread.
def on_channel_message(
result: omni.client.Result, event_type: omni.client.ChannelEvent, from_user: str, content
):
if not channel_connect_future.done():
if not self._get_users_only:
carb.log_info(f"Join channel {self.url} successfully.")
self._emit_channel_event("join")
channel_connect_future.set_result(result == omni.client.Result.OK)
if result != omni.client.Result.OK:
carb.log_warn(f"Stop channel since it has errors: {result}.")
self._stopped = True
return
self._on_message(event_type, from_user, content)
self._joining = True
self._channel_handler = omni.client.join_channel_with_callback(self.url, on_channel_message)
result = channel_connect_future.result()
if result:
if self._get_users_only:
await self._send_message_internal_async(MessageType.GET_USERS, {})
else:
await self._send_message_internal_async(MessageType.JOIN, {})
self._joining = False
return result
def stop(self):
"""Stop this channel."""
if self._stopping or self.stopped:
return
if not self._get_users_only:
carb.log_info(f"Stopping channel {self.url}")
self._emit_channel_event("leave")
self._stopping = True
return self._run_asyncio_task(self._stop_async)
async def _stop_async(self):
if self._channel_handler and not self._channel_handler.is_finished():
if not self._get_users_only and not self._joining:
await self._send_message_internal_async(MessageType.LEFT, {})
self._channel_handler.stop()
self._channel_handler = None
self._stopped = True
self._stopping = False
self._subscribers.clear()
self._peer_users.clear()
self._last_user_response_time.clear()
def add_subscriber(self, on_message: Callable[[Message], None]) -> ChannelSubscriber:
subscriber = ChannelSubscriber(on_message, weakref.ref(self))
self._subscribers.append(weakref.ref(subscriber))
return subscriber
def _remove_subscriber(self, subscriber: ChannelSubscriber):
to_be_removed = []
for item in self._subscribers:
if not item() or item() == subscriber:
to_be_removed.append(item)
for item in to_be_removed:
self._subscribers.remove(item)
async def send_message_async(self, content: dict) -> omni.client.Request:
if self.stopped or self.stopping:
return
return await self._send_message_internal_async(MessageType.MESSAGE, content)
async def _send_message_internal_async(self, message_type: MessageType, content: dict):
carb.log_verbose(f"Send {message_type} message to channel {self.url}, content: {content}")
message = _build_message_in_bytes(self._logged_user_name, message_type, content)
return await omni.client.send_message_async(self._channel_handler.id, message)
def _update(self):
if self.stopped or self._stopping:
return
# FIXME: Is this a must?
pending_messages, self._message_queue = self._message_queue, []
for message in pending_messages:
self._handle_message(message[0], message[1], message[2])
current_time = time.time()
duration_in_seconds = current_time - self._last_ping_time
if duration_in_seconds > CHANNEL_PING_TIME_IN_SECONDS:
self._last_ping_time = current_time
carb.log_verbose("Ping all users...")
self._run_asyncio_task(self._send_message_internal_async, MessageType.GET_USERS, {})
dropped_users = []
for user_id, last_response_time in self._last_user_response_time.items():
duration = current_time - last_response_time
if duration > CHANNEL_PING_TIME_IN_SECONDS:
dropped_users.append(user_id)
for user_id in dropped_users:
peer_user = self._peer_users.pop(user_id, None)
if not peer_user:
continue
message = Message(peer_user, MessageType.LEFT, {})
self._broadcast_message(message)
def _broadcast_message(self, message: Message):
for subscriber in self._subscribers:
if subscriber():
subscriber()._on_message(message)
def _on_message(self, event_type: omni.client.ChannelEvent, from_user: str, content):
# Queue message handling to main looper.
self._message_queue.append((event_type, from_user, content))
def _handle_message(self, event_type: omni.client.ChannelEvent, from_user: str, content):
# Sent from me, skip them
if not from_user:
return
self._last_user_response_time[from_user] = time.time()
peer_user = None
payload = {}
message_type = None
new_user = False
if event_type == omni.client.ChannelEvent.JOIN:
# We don't use JOIN from server
pass
elif event_type == omni.client.ChannelEvent.LEFT:
peer_user = self._peer_users.pop(from_user, None)
if peer_user:
message_type = MessageType.LEFT
elif event_type == omni.client.ChannelEvent.DELETED:
self._channel_handler.stop()
self._channel_handler = None
elif event_type == omni.client.ChannelEvent.MESSAGE:
carb.log_verbose(f"Message received from user with id {from_user}.")
try:
header_len = len(KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER)
bytes = memoryview(content).tobytes()
if len(bytes) < header_len:
carb.log_error(f"Unsupported message received from user {from_user}.")
else:
bytes = bytes[header_len:]
message = json.loads(bytes)
except Exception:
carb.log_error(f"Failed to decode message sent from user {from_user}.")
return
version = message.get(MESSAGE_VERSION_KEY, None)
if not version or version != KIT_CHANNEL_MESSAGE_VERSION:
carb.log_warn(f"Message version sent from user {from_user} does not match expected one: {message}.")
return
from_user_name = message.get(MESSAGE_FROM_USER_NAME_KEY, None)
if not from_user_name:
carb.log_warn(f"Message sent from unknown user: {message}")
return
message_type = message.get(MESSAGE_TYPE_KEY, None)
if not message_type:
carb.log_warn(f"Message sent from user {from_user} does not include message type.")
return
if message_type == MessageType.GET_USERS:
carb.log_verbose(f"Fetch message from user with id {from_user}, name {from_user_name}.")
if not self._get_users_only:
self._run_asyncio_task(self._send_message_internal_async, MessageType.HELLO, {})
return
peer_user = self._peer_users.get(from_user, None)
if not peer_user:
# Don't handle non-recorded user's left.
if message_type == MessageType.LEFT:
carb.log_verbose(f"User {from_user}, name {from_user_name} left channel.")
return
else:
from_app = message.get(MESSAGE_APP_KEY, "Unknown")
peer_user = PeerUser(from_user, from_user_name, from_app)
self._peer_users[from_user] = peer_user
new_user = True
else:
new_user = False
if message_type == MessageType.HELLO:
carb.log_verbose(f"Hello message from user with id {from_user}, name {from_user_name}.")
if not new_user:
return
elif message_type == MessageType.JOIN:
carb.log_verbose(f"Join message from user with id {from_user}, name {from_user_name}.")
if not new_user:
return
if not self._get_users_only:
self._run_asyncio_task(self._send_message_internal_async, MessageType.HELLO, {})
elif message_type == MessageType.LEFT:
carb.log_verbose(f"Left message from user with id {from_user}, name {from_user_name}.")
self._peer_users.pop(from_user, None)
else:
message_content = message.get(MESSAGE_CONTENT_KEY, None)
if not message_content or not isinstance(message_content, dict):
carb.log_warn(f"Message content sent from user {from_user} is empty or invalid format: {message}.")
return
carb.log_verbose(f"Message received from user with id {from_user}: {message}.")
payload = message_content
message_type = MessageType.MESSAGE
if message_type and peer_user:
# It's possible that user blocks its main thread and hang over the duration time to reponse ping command.
# This is to notify user is back again.
if new_user and message_type != MessageType.HELLO and message_type != MessageType.JOIN:
message = Message(peer_user, MessageType.HELLO, {})
self._broadcast_message(message)
message = Message(peer_user, message_type, payload)
self._broadcast_message(message)
class Channel: # pragma: no cover
def __init__(self, handler: weakref, channel_manager: weakref) -> None:
self._handler = handler
self._channel_manager = channel_manager
if self._handler and self._handler():
self._url = self._handler().url
self._logged_user_name = self._handler().logged_user_name
self._logged_user_id = self._handler().logged_user_id
else:
self._url = ""
@property
def stopped(self):
return not self._handler or not self._handler() or self._handler().stopped
@property
def logged_user_name(self):
return self._logged_user_name
@property
def logged_user_id(self):
return self._logged_user_id
@property
def peer_users(self) -> Dict[str, PeerUser]:
"""Property. All the peer clients that joined to this channel."""
if self._handler and self._handler():
return self._handler().peer_users
return None
@property
def url(self):
return self._url
def stop(self) -> asyncio.Future:
if not self.stopped and self._channel_manager and self._channel_manager():
task = self._channel_manager()._stop_channel(self._handler())
else:
task = None
self._handler = None
return task
def add_subscriber(self, on_message: Callable[[Message], None]) -> ChannelSubscriber:
"""
Add subscriber.
Args:
on_message (Callable[[Message], None]): The message handler.
Returns:
Instance of ChannelSubscriber. The channel will be stopped if instance is release.
So it needs to hold the instance before it's stopped. You can manually call `stop`
to stop this channel, or set the returned instance to None.
"""
if not self.stopped:
return self._handler().add_subscriber(on_message)
return None
async def send_message_async(self, content: dict) -> omni.client.Request:
"""
Async function. Send message to all peer clients.
Args:
content (dict): The message composed in dictionary.
Return:
omni.client.Request.
"""
if not self.stopped:
return await self._handler().send_message_async(content)
return None
class ChannelManager: # pragma: no cover
def __init__(self) -> None:
self._all_channels: List[NativeChannelWrapper] = []
self._update_subscription = None
def on_startup(self):
carb.log_info("Starting Omniverse Channel Manager...")
self._all_channels.clear()
app = omni.kit.app.get_app()
self._update_subscription = app.get_update_event_stream().create_subscription_to_pop(
self._on_update, name="omni.kit.collaboration.channel_manager update"
)
def on_shutdown(self):
carb.log_info("Shutting down Omniverse Channel Manager...")
self._update_subscription = None
for channel in self._all_channels:
self._stop_channel(channel)
channel.destroy()
self._all_channels.clear()
def _stop_channel(self, channel: NativeChannelWrapper):
if channel and not channel.stopping:
task = channel.stop()
return task
return None
def _on_update(self, dt):
to_be_removed = []
for channel in self._all_channels:
if channel.stopped:
to_be_removed.append(channel)
else:
channel._update()
for channel in to_be_removed:
channel.destroy()
self._all_channels.remove(channel)
# Internal interface
def has_channel(self, url: str):
for channel in self._all_channels:
if url == channel:
return True
return False
async def join_channel_async(self, url: str, get_users_only: bool):
"""
Async function. Join Omniverse Channel.
Args:
url: The url to create/join a channel.
get_users_only: Joins channel as a monitor only or not.
"""
channel_wrapper = NativeChannelWrapper(url, get_users_only)
success = await channel_wrapper.join_channel_async()
if success:
self._all_channels.append(channel_wrapper)
channel = Channel(weakref.ref(channel_wrapper), weakref.ref(self))
else:
channel = None
return channel
| 21,927 | Python | 35.304636 | 119 | 0.602727 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.