file_path
stringlengths 32
153
| content
stringlengths 0
3.14M
|
---|---|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/capture_progress.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 os
from enum import Enum, IntEnum
import datetime
import subprocess
import carb
import omni.ui as ui
import omni.kit.app
class CaptureStatus(IntEnum):
NONE = 0
CAPTURING = 1
PAUSED = 2
FINISHING = 3
TO_START_ENCODING = 4
ENCODING = 5
CANCELLED = 6
class CaptureProgress:
def __init__(self):
self._init_internal()
def _init_internal(self, time_length=0, time_rate=24):
self._time_length = time_length
self._time_rate = time_rate
self._total_frames = int(self._time_length / self._time_rate)
# at least to capture 1 frame
if self._total_frames < 1:
self._total_frames = 1
self._capture_status = CaptureStatus.NONE
self._elapsed_time = 0.0
self._estimated_time_remaining = 0.0
self._current_frame_time = 0.0
self._average_time_per_frame = 0.0
self._encoding_time = 0.0
self._current_frame = 0
self._first_frame_num = 0
self._got_first_frame = False
self._progress = 0.0
self._current_subframe = -1
self._total_subframes = 1
self._subframe_time = 0.0
self._total_frame_time = 0.0
self._average_time_per_subframe = 0.0
self._total_preroll_frames = 0
self._prerolled_frames = 0
self._path_trace_iteration_num = 0
self._path_trace_subframe_num = 0
@property
def capture_status(self):
return self._capture_status
@capture_status.setter
def capture_status(self, value):
self._capture_status = value
@property
def elapsed_time(self):
return self._get_time_string(self._elapsed_time)
@property
def estimated_time_remaining(self):
return self._get_time_string(self._estimated_time_remaining)
@property
def current_frame_time(self):
return self._get_time_string(self._current_frame_time)
@property
def average_frame_time(self):
return self._get_time_string(self._average_time_per_frame)
@property
def encoding_time(self):
return self._get_time_string(self._encoding_time)
@property
def progress(self):
return self._progress
@property
def current_subframe(self):
return self._current_subframe
@property
def total_subframes(self):
return self._total_subframes
@property
def subframe_time(self):
return self._get_time_string(self._subframe_time)
@property
def average_time_per_subframe(self):
return self._get_time_string(self._average_time_per_subframe)
@property
def total_preroll_frames(self):
return self._total_preroll_frames
@total_preroll_frames.setter
def total_preroll_frames(self, value):
self._total_preroll_frames = value
@property
def prerolled_frames(self):
return self._prerolled_frames
@prerolled_frames.setter
def prerolled_frames(self, value):
self._prerolled_frames = value
@property
def path_trace_iteration_num(self):
return self._path_trace_iteration_num
@path_trace_iteration_num.setter
def path_trace_iteration_num(self, value):
self._path_trace_iteration_num = value
@property
def path_trace_subframe_num(self):
return self._path_trace_subframe_num
@path_trace_subframe_num.setter
def path_trace_subframe_num(self, value):
self._path_trace_subframe_num = value
def start_capturing(self, time_length, time_rate, preroll_frames=0):
self._init_internal(time_length, time_rate)
self._total_preroll_frames = preroll_frames
self._capture_status = CaptureStatus.CAPTURING
def finish_capturing(self):
self._init_internal()
def is_prerolling(self):
return (
(self._capture_status == CaptureStatus.CAPTURING or self._capture_status == CaptureStatus.PAUSED)
and self._total_preroll_frames > 0
and self._total_preroll_frames > self._prerolled_frames
)
def add_encoding_time(self, time):
if self._estimated_time_remaining > 0.0:
self._elapsed_time += self._estimated_time_remaining
self._estimated_time_remaining = 0.0
self._encoding_time += time
def add_frame_time(self, frame, time, pt_subframe_num=0, pt_iteration_num=0):
if not self._got_first_frame:
self._got_first_frame = True
self._first_frame_num = frame
self._current_frame = frame
self._path_trace_subframe_num = pt_subframe_num
self._path_trace_iteration_num = pt_iteration_num
self._elapsed_time += time
if self._current_frame != frame:
frames_captured = self._current_frame - self._first_frame_num + 1
self._average_time_per_frame = self._elapsed_time / frames_captured
self._current_frame = frame
self._current_frame_time = time
else:
self._current_frame_time += time
if frame == self._first_frame_num:
self._estimated_time_remaining = 0.0
self._progress = 0.0
else:
total_frame_time = self._average_time_per_frame * self._total_frames
# if users pause for long times, it's possible that elapsed time will be greater than estimated total time
# if this happens, estimate it again
if self._elapsed_time >= total_frame_time:
total_frame_time += time + self._average_time_per_frame
self._estimated_time_remaining = total_frame_time - self._elapsed_time
self._progress = self._elapsed_time / total_frame_time
def add_single_frame_capture_time(self, subframe, total_subframes, time):
self._total_subframes = total_subframes
self._elapsed_time += time
if self._current_subframe != subframe:
self._subframe_time = time
if self._current_subframe == -1:
self._average_time_per_subframe = self._elapsed_time
else:
self._average_time_per_subframe = self._elapsed_time / subframe
self._total_frame_time = self._average_time_per_subframe * total_subframes
else:
self._subframe_time += time
self._current_subframe = subframe
if self._current_subframe == 0:
self._estimated_time_remaining = 0.0
self._progress = 0.0
else:
if self._elapsed_time >= self._total_frame_time:
self._total_frame_time += time + self._average_time_per_subframe
self._estimated_time_remaining = self._total_frame_time - self._elapsed_time
self._progress = self._elapsed_time / self._total_frame_time
def _get_time_string(self, time_seconds):
hours = int(time_seconds / 3600)
minutes = int((time_seconds - hours*3600) / 60)
seconds = time_seconds - hours*3600 - minutes*60
time_string = ""
if hours > 0:
time_string += '{:d}h '.format(hours)
if minutes > 0:
time_string += '{:d}m '.format(minutes)
else:
if hours > 0:
time_string += "0m "
time_string += '{:.2f}s'.format(seconds)
return time_string
PROGRESS_WINDOW_WIDTH = 360
PROGRESS_WINDOW_HEIGHT = 260
PROGRESS_BAR_WIDTH = 216
PROGRESS_BAR_HEIGHT = 20
PROGRESS_BAR_HALF_HEIGHT = PROGRESS_BAR_HEIGHT / 2
TRIANGLE_WIDTH = 6
TRIANGLE_HEIGHT = 10
TRIANGLE_OFFSET_Y = 10
PROGRESS_WIN_DARK_STYLE = {
"Triangle::progress_marker": {"background_color": 0xFFD1981D},
"Rectangle::progress_bar_background": {
"border_width": 0.5,
"border_radius": PROGRESS_BAR_HALF_HEIGHT,
"background_color": 0xFF888888,
},
"Rectangle::progress_bar_full": {
"border_width": 0.5,
"border_radius": PROGRESS_BAR_HALF_HEIGHT,
"background_color": 0xFFD1981D,
},
"Rectangle::progress_bar": {
"background_color": 0xFFD1981D,
"border_radius": PROGRESS_BAR_HALF_HEIGHT,
"corner_flag": ui.CornerFlag.LEFT,
"alignment": ui.Alignment.LEFT,
},
}
PAUSE_BUTTON_STYLE = {
"NvidiaLight": {
"Button.Label::pause": {"color": 0xFF333333},
"Button.Label::pause:disabled": {"color": 0xFF666666},
},
"NvidiaDark": {
"Button.Label::pause": {"color": 0xFFCCCCCC},
"Button.Label::pause:disabled": {"color": 0xFF666666},
},
}
class CaptureProgressWindow:
def __init__(self):
self._app = omni.kit.app.get_app_interface()
self._update_sub = None
self._window_caption = "Capture Progress"
self._window = None
self._progress = None
self._progress_bar_len = PROGRESS_BAR_HALF_HEIGHT
self._progress_step = 0.5
self._is_single_frame_mode = False
self._show_pt_subframes = False
self._show_pt_iterations = False
self._support_pausing = True
def show(
self,
progress,
single_frame_mode: bool = False,
show_pt_subframes: bool = False,
show_pt_iterations: bool = False,
support_pausing: bool = True,
) -> None:
self._progress = progress
self._is_single_frame_mode = single_frame_mode
self._show_pt_subframes = show_pt_subframes
self._show_pt_iterations = show_pt_iterations
self._support_pausing = support_pausing
self._build_ui()
self._update_sub = self._app.get_update_event_stream().create_subscription_to_pop(
self._on_update, name="omni.kit.capure progress"
)
def close(self):
self._window = None
self._update_sub = None
def _build_progress_bar(self):
self._progress_bar_area.clear()
self._progress_bar_area.set_style(PROGRESS_WIN_DARK_STYLE)
with self._progress_bar_area:
with ui.Placer(offset_x=self._progress_bar_len - TRIANGLE_WIDTH / 2, offset_y=TRIANGLE_OFFSET_Y):
ui.Triangle(
name="progress_marker",
width=TRIANGLE_WIDTH,
height=TRIANGLE_HEIGHT,
alignment=ui.Alignment.CENTER_BOTTOM,
)
with ui.ZStack():
ui.Rectangle(name="progress_bar_background", width=PROGRESS_BAR_WIDTH, height=PROGRESS_BAR_HEIGHT)
ui.Rectangle(name="progress_bar", width=self._progress_bar_len, height=PROGRESS_BAR_HEIGHT)
def _build_ui_timer(self, text, init_value):
with ui.HStack():
with ui.HStack(width=ui.Percent(50)):
ui.Spacer()
ui.Label(text, width=0)
with ui.HStack(width=ui.Percent(50)):
ui.Spacer(width=15)
timer_label = ui.Label(init_value)
ui.Spacer()
return timer_label
def _build_multi_frames_capture_timers(self):
self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time)
self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining)
self._ui_current_frame_time = self._build_ui_timer("Current frame time", self._progress.current_frame_time)
if self._show_pt_subframes:
subframes_str = f"{self._progress.path_trace_subframe_num}"
self._ui_pt_subframes = self._build_ui_timer("Subframes", subframes_str)
if self._show_pt_iterations:
iter_str = f"{self._progress.path_trace_iteration_num}"
self._ui_pt_iterations = self._build_ui_timer("Iterations", iter_str)
self._ui_ave_frame_time = self._build_ui_timer("Average time per frame", self._progress.average_frame_time)
self._ui_encoding_time = self._build_ui_timer("Encoding", self._progress.encoding_time)
def _build_single_frame_capture_timers(self):
self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time)
self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining)
subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}"
self._ui_subframe_count = self._build_ui_timer("Subframe/Total frames", subframe_count)
self._ui_current_frame_time = self._build_ui_timer("Current subframe time", self._progress.subframe_time)
self._ui_ave_frame_time = self._build_ui_timer("Average time per subframe", self._progress.average_frame_time)
def _build_preroll_notification(self):
with ui.HStack():
ui.Spacer(width=ui.Percent(20))
self._preroll_frames_notification = ui.Label("Running preroll frames, please wait...")
ui.Spacer(width=ui.Percent(10))
def _build_ui(self):
if self._window is None:
style_settings = carb.settings.get_settings().get("/persistent/app/window/uiStyle")
if not style_settings:
style_settings = "NvidiaDark"
self._window = ui.Window(
self._window_caption,
width=PROGRESS_WINDOW_WIDTH,
height=PROGRESS_WINDOW_HEIGHT,
style=PROGRESS_WIN_DARK_STYLE,
)
with self._window.frame:
with ui.VStack():
with ui.HStack():
ui.Spacer(width=ui.Percent(20))
self._progress_bar_area = ui.VStack()
self._build_progress_bar()
ui.Spacer(width=ui.Percent(20))
ui.Spacer(height=5)
if self._is_single_frame_mode:
self._build_single_frame_capture_timers()
else:
self._build_multi_frames_capture_timers()
self._build_preroll_notification()
with ui.HStack():
with ui.HStack(width=ui.Percent(50)):
ui.Spacer()
self._ui_pause_button = ui.Button(
"Pause",
height=0,
clicked_fn=self._on_pause_clicked,
enabled=self._support_pausing,
style=PAUSE_BUTTON_STYLE[style_settings],
name="pause",
)
with ui.HStack(width=ui.Percent(50)):
ui.Spacer(width=15)
ui.Button("Cancel", height=0, clicked_fn=self._on_cancel_clicked)
ui.Spacer()
ui.Spacer()
self._window.visible = True
self._update_timers()
def _on_pause_clicked(self):
if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause":
self._progress.capture_status = CaptureStatus.PAUSED
self._ui_pause_button.text = "Resume"
elif self._progress.capture_status == CaptureStatus.PAUSED:
self._progress.capture_status = CaptureStatus.CAPTURING
self._ui_pause_button.text = "Pause"
def _on_cancel_clicked(self):
if (
self._progress.capture_status == CaptureStatus.CAPTURING
or self._progress.capture_status == CaptureStatus.PAUSED
):
self._progress.capture_status = CaptureStatus.CANCELLED
def _update_timers(self):
if self._is_single_frame_mode:
self._ui_elapsed_time.text = self._progress.elapsed_time
self._ui_remaining_time.text = self._progress.estimated_time_remaining
subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}"
self._ui_subframe_count.text = subframe_count
self._ui_current_frame_time.text = self._progress.subframe_time
self._ui_ave_frame_time.text = self._progress.average_time_per_subframe
else:
self._ui_elapsed_time.text = self._progress.elapsed_time
self._ui_remaining_time.text = self._progress.estimated_time_remaining
self._ui_current_frame_time.text = self._progress.current_frame_time
if self._show_pt_subframes:
subframes_str = f"{self._progress.path_trace_subframe_num}"
self._ui_pt_subframes.text = subframes_str
if self._show_pt_iterations:
iter_str = f"{self._progress.path_trace_iteration_num}"
self._ui_pt_iterations.text = iter_str
self._ui_ave_frame_time.text = self._progress.average_frame_time
self._ui_encoding_time.text = self._progress.encoding_time
def _update_preroll_frames(self):
if self._progress.is_prerolling():
msg = 'Running preroll frames {}/{}, please wait...'.format(
self._progress.prerolled_frames,
self._progress.total_preroll_frames
)
self._preroll_frames_notification.text = msg
else:
self._preroll_frames_notification.visible = False
def _on_update(self, event):
self._update_preroll_frames()
self._update_timers()
self._progress_bar_len = (
PROGRESS_BAR_WIDTH - PROGRESS_BAR_HEIGHT
) * self._progress.progress + PROGRESS_BAR_HALF_HEIGHT
self._build_progress_bar()
|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import math
import time
import datetime
import omni.ext
import carb
import omni.kit.app
import omni.timeline
import omni.usd
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file
from .capture_options import *
from .capture_progress import *
from .video_generation import VideoGenerationHelper
from .helper import get_num_pattern_file_path
VIDEO_FRAMES_DIR_NAME = "frames"
DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO = ".png"
capture_instance = None
class CaptureExtension(omni.ext.IExt):
def on_startup(self):
global capture_instance
capture_instance = self
self._options = CaptureOptions()
self._progress = CaptureProgress()
self._progress_window = CaptureProgressWindow()
self._renderer = None
import omni.renderer_capture
self._renderer = omni.renderer_capture.acquire_renderer_capture_interface()
self._viewport_api = None
self._app = omni.kit.app.get_app_interface()
self._timeline = omni.timeline.get_timeline_interface()
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._settings = carb.settings.get_settings()
self._show_default_progress_window = True
self._progress_update_fn = None
self._forward_one_frame_fn = None
self._capture_finished_fn = None
carb.log_warn("Deprecated notice: Please be noted that omni.kit.capture has been replaced with omni.kit.capture.viewport and will be removed in future releases. " \
"Please update the use of this extension to the new one.")
def on_shutdown(self):
self._progress = None
self._progress_window = None
global capture_instance
capture_instance = None
@property
def options(self):
return self._options
@options.setter
def options(self, value):
self._options = value
@property
def progress(self):
return self._progress
@property
def show_default_progress_window(self):
return self._show_default_progress_window
@show_default_progress_window.setter
def show_default_progress_window(self, value):
self._show_default_progress_window = value
@property
def progress_update_fn(self):
return self._progress_update_fn
@progress_update_fn.setter
def progress_update_fn(self, value):
self._progress_update_fn = value
@property
def forward_one_frame_fn(self):
return self._forward_one_frame_fn
@forward_one_frame_fn.setter
def forward_one_frame_fn(self, value):
self._forward_one_frame_fn = value
@property
def capture_finished_fn(self):
return self._capture_finished_fn
@capture_finished_fn.setter
def capture_finished_fn(self, value):
self._capture_finished_fn = value
def start(self):
self._prepare_folder_and_counters()
self._prepare_viewport()
self._start_internal()
def pause(self):
if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause":
self._progress.capture_status = CaptureStatus.PAUSED
def resume(self):
if self._progress.capture_status == CaptureStatus.PAUSED:
self._progress.capture_status = CaptureStatus.CAPTURING
def cancel(self):
if (
self._progress.capture_status == CaptureStatus.CAPTURING
or self._progress.capture_status == CaptureStatus.PAUSED
):
self._progress.capture_status = CaptureStatus.CANCELLED
def _update_progress_hook(self):
if self._progress_update_fn is not None:
self._progress_update_fn(
self._progress.capture_status,
self._progress.progress,
self._progress.elapsed_time,
self._progress.estimated_time_remaining,
self._progress.current_frame_time,
self._progress.average_frame_time,
self._progress.encoding_time,
self._frame_counter,
self._total_frame_count,
)
def _get_index_for_image(self, dir, file_name, image_suffix):
def is_int(string_val):
try:
v = int(string_val)
return True
except:
return False
images = os.listdir(dir)
name_len = len(file_name)
suffix_len = len(image_suffix)
max_index = 0
for item in images:
if item.startswith(file_name) and item.endswith(image_suffix):
num_part = item[name_len : (len(item) - suffix_len)]
if is_int(num_part):
num = int(num_part)
if max_index < num:
max_index = num
return max_index + 1
def _float_to_time(self, ft):
hour = int(ft)
ft = (ft - hour) * 60
minute = int(ft)
ft = (ft - minute) * 60
second = int(ft)
ft = (ft - second) * 1000000
microsecond = int(ft)
return datetime.time(hour, minute, second, microsecond)
def _is_environment_sunstudy_player(self):
if self._options.sunstudy_player is not None:
return type(self._options.sunstudy_player).__module__ == "omni.kit.environment.core.sunstudy_player.player"
else:
carb.log_warn("Sunstudy player type check is valid only when the player is available.")
return False
def _update_sunstudy_player_time(self):
if self._is_environment_sunstudy_player():
self._options.sunstudy_player.current_time = self._sunstudy_current_time
else:
self._options.sunstudy_player.update_time(self._sunstudy_current_time)
def _set_sunstudy_player_time(self, current_time):
if self._is_environment_sunstudy_player():
self._options.sunstudy_player.current_time = current_time
else:
date_time = self._options.sunstudy_player.get_date_time()
time_to_set = self._float_to_time(current_time)
new_date_time = datetime.datetime(
date_time.year, date_time.month, date_time.day,
time_to_set.hour, time_to_set.minute, time_to_set.second
)
self._options.sunstudy_player.set_date_time(new_date_time)
def _prepare_sunstudy_counters(self):
self._total_frame_count = self._options.fps * self._options.sunstudy_movie_length_in_seconds
duration = self._options.sunstudy_end_time - self._options.sunstudy_start_time
self._sunstudy_iterations_per_frame = self._options.ptmb_subframes_per_frame
self._sunstudy_delta_time_per_iteration = duration / float(self._total_frame_count * self._sunstudy_iterations_per_frame)
self._sunstudy_current_time = self._options.sunstudy_start_time
self._set_sunstudy_player_time(self._sunstudy_current_time)
def _prepare_folder_and_counters(self):
self._workset_dir = self._options.output_folder
if not self._make_sure_directory_existed(self._workset_dir):
carb.log_warn(f"Capture failed due to unable to create folder {self._workset_dir}")
self._finish()
return
if self._options.is_capturing_nth_frames():
if self._options.capture_every_Nth_frames == 1:
frames_folder = self._options.file_name + "_frames"
else:
frames_folder = self._options.file_name + "_" + str(self._options.capture_every_Nth_frames) + "th_frames"
self._nth_frames_dir = os.path.join(self._workset_dir, frames_folder)
if not self._make_sure_directory_existed(self._nth_frames_dir):
carb.log_warn(f"Capture failed due to unable to create folder {self._nth_frames_dir}")
self._finish()
return
if self._options.is_video():
self._frames_dir = os.path.join(self._workset_dir, self._options.file_name + "_" + VIDEO_FRAMES_DIR_NAME)
if not self._make_sure_directory_existed(self._frames_dir):
carb.log_warn(
f"Capture failed due to unable to create folder {self._workset_dir} to save frames of the video."
)
self._finish()
return
self._video_name = self._options.get_full_path()
self._frame_pattern_prefix = os.path.join(self._frames_dir, self._options.file_name)
if self._options.is_capturing_frame():
self._start_time = float(self._options.start_frame) / self._options.fps
self._end_time = float(self._options.end_frame + 1) / self._options.fps
self._time = self._start_time
self._frame = self._options.start_frame
self._start_number = self._frame
self._total_frame_count = round((self._end_time - self._start_time) * self._options.fps)
else:
self._start_time = self._options.start_time
self._end_time = self._options.end_time
self._time = self._options.start_time
self._frame = int(self._options.start_time * self._options.fps)
self._start_number = self._frame
self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._options.fps)
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._prepare_sunstudy_counters()
else:
if self._options.is_capturing_nth_frames():
self._frame_pattern_prefix = self._nth_frames_dir
if self._options.is_capturing_frame():
self._start_time = float(self._options.start_frame) / self._options.fps
self._end_time = float(self._options.end_frame + 1) / self._options.fps
self._time = self._start_time
self._frame = self._options.start_frame
self._start_number = self._frame
self._total_frame_count = round((self._end_time - self._start_time) * self._options.fps)
else:
self._start_time = self._options.start_time
self._end_time = self._options.end_time
self._time = self._options.start_time
self._frame = int(self._options.start_time * self._options.fps)
self._start_number = self._frame
self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._options.fps)
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._prepare_sunstudy_counters()
else:
index = self._get_index_for_image(self._workset_dir, self._options.file_name, self._options.file_type)
self._frame_pattern_prefix = os.path.join(self._workset_dir, self._options.file_name + str(index))
self._start_time = self._timeline.get_current_time()
self._end_time = self._timeline.get_current_time()
self._time = self._timeline.get_current_time()
self._frame = 1
self._start_number = self._frame
self._total_frame_count = 1
self._subframe = 0
self._sample_count = 0
self._frame_counter = 0
self._real_time_settle_latency_frames_done = 0
self._last_skipped_frame_path = ""
self._path_trace_iterations = 0
self._time_rate = 1.0 / self._options.fps
self._time_subframe_rate = (
self._time_rate * (self._options.ptmb_fsc - self._options.ptmb_fso) / self._options.ptmb_subframes_per_frame
)
def _prepare_viewport(self):
viewport_api = get_active_viewport()
if viewport_api is None:
return False
self._record_current_window_status(viewport_api)
viewport_api.camera_path = self._options.camera
viewport_api.resolution = (self._options.res_width, self._options.res_height)
self._settings.set_bool("/persistent/app/captureFrame/viewport", True)
self._settings.set_bool("/app/captureFrame/setAlphaTo1", not self._options.save_alpha)
if self._options.file_type == ".exr":
self._settings.set_bool("/app/captureFrame/hdr", self._options.hdr_output)
else:
self._settings.set_bool("/app/captureFrame/hdr", False)
if self._options.save_alpha:
self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", True)
self._settings.set_bool("/rtx/post/backgroundZeroAlpha/backgroundComposite", False)
self._selection.clear_selected_prim_paths()
if self._options.render_preset == CaptureRenderPreset.RAY_TRACE:
self._switch_renderer = not (self._saved_active_render == "rtx" and self._saved_render_mode == "RaytracedLighting")
if self._switch_renderer:
viewport_api.set_hd_engine("rtx", "RaytracedLighting")
carb.log_info("Switching to RayTracing Mode")
elif self._options.render_preset == CaptureRenderPreset.PATH_TRACE:
self._switch_renderer = not (self._saved_active_render == "rtx" and self._saved_render_mode == "PathTracing")
if self._switch_renderer:
viewport_api.set_hd_engine("rtx", "PathTracing")
carb.log_info("Switching to PathTracing Mode")
elif self._options.render_preset == CaptureRenderPreset.IRAY:
self._switch_renderer = not (self._saved_active_render == "iray" and self._saved_render_mode == "iray")
if self._switch_renderer:
viewport_api.set_hd_engine("iray", "iray")
carb.log_info("Switching to IRay Mode")
else:
self._switch_renderer = False
carb.log_info("Keeping current Render Mode")
if self._options.debug_material_type == CaptureDebugMaterialType.SHADED:
self._settings.set_int("/rtx/debugMaterialType", -1)
elif self._options.debug_material_type == CaptureDebugMaterialType.WHITE:
self._settings.set_int("/rtx/debugMaterialType", 0)
else:
carb.log_info("Keeping current debug mateiral type")
# set it to 0 to ensure we accumulate as many samples as requested even across subframes (for motion blur)
self._settings.set_int("/rtx/pathtracing/totalSpp", 0)
# don't show light and grid during capturing
self._settings.set_int("/persistent/app/viewport/displayOptions", 0)
# disable async rendering for capture, otherwise it won't capture images correctly
self._settings.set_bool("/app/asyncRendering", False)
self._settings.set_bool("/app/asyncRenderingLowLatency", False)
# Rendering to some image buffers additionally require explicitly setting `set_capture_sync(True)`, on top of
# disabling the `/app/asyncRendering` setting. This can otherwise cause images to hold corrupted buffer
# information by erroneously assuming a complete image buffer is available when only a first partial subframe
# has been renderer (as in the case of EXR):
self._renderer.set_capture_sync( self._options.file_type == ".exr" )
# frames to wait for the async settings above to be ready, they will need to be detected by viewport, and
# then viewport will notify the renderer not to do async rendering
self._frames_to_disable_async_rendering = 2
# Normally avoid using a high /rtx/pathtracing/spp setting since it causes GPU
# timeouts for large sample counts. But a value larger than 1 can be useful in Multi-GPU setups
self._settings.set_int(
"/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp)
)
# Setting resetPtAccumOnlyWhenExternalFrameCounterChanges ensures we control accumulation explicitly
# by simpling changing the /rtx/externalFrameCounter value
self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", True)
if self._options.render_preset == CaptureRenderPreset.IRAY:
self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._options.path_trace_spp)
# Enable syncLoads in materialDB and Hydra. This is needed to make sure texture updates finish before we start the rendering
self._settings.set("/rtx/materialDb/syncLoads", True)
self._settings.set("/rtx/hydra/materialSyncLoads", True)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", False)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", 0)
return True
def _show_progress_window(self):
return (
self._options.is_video() or self._options.is_capturing_nth_frames() or (self._options.show_single_frame_progress and self._options.is_capturing_pathtracing_single_frame())
) and self.show_default_progress_window
def _start_internal(self):
# If texture streaming is enabled, set the preroll to at least 1 frame
if self._settings.get("/rtx-transient/resourcemanager/enableTextureStreaming"):
self._options.preroll_frames = max(self._options.preroll_frames, 1)
# set usd time code second to target frame rate
self._saved_timecodes_per_second = self._timeline.get_time_codes_per_seconds()
self._timeline.set_time_codes_per_second(self._options.fps)
# if we want preroll, then set timeline's current time back with the preroll frames' time,
# and rely on timeline to do the preroll using the give timecode
if self._options.preroll_frames > 0:
self._timeline.set_current_time(self._start_time - self._options.preroll_frames / self._options.fps)
self._settings.set("/iray/current_frame_time", self._start_time - self._options.preroll_frames / self._options.fps)
else:
self._timeline.set_current_time(self._start_time)
self._settings.set("/iray/current_frame_time", self._start_time)
# change timeline to be in play state
self._timeline.play()
# disable automatic time update in timeline so that movie capture tool can control time step
self._timeline.set_auto_update(False)
self._update_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update, order=1000000)
)
self._progress.start_capturing(self._end_time - self._start_time, self._time_rate, self._options.preroll_frames)
# always show single frame capture progress for PT mode
self._options.show_single_frame_progress = True
if self._show_progress_window():
self._progress_window.show(
self._progress,
self._options.is_capturing_pathtracing_single_frame(),
show_pt_subframes=self._options.render_preset == CaptureRenderPreset.PATH_TRACE,
show_pt_iterations=self._options.render_preset == CaptureRenderPreset.IRAY
)
def _record_current_window_status(self, viewport_api):
assert viewport_api is not None, "No viewport to record to"
self._viewport_api = viewport_api
self._saved_camera = viewport_api.camera_path
self._saved_hydra_engine = viewport_api.hydra_engine
self._saved_render_mode = viewport_api.render_mode
resolution = viewport_api.resolution
self._saved_resolution_width = int(resolution[0])
self._saved_resolution_height = int(resolution[1])
self._saved_capture_frame_viewport = self._settings.get("/persistent/app/captureFrame/viewport")
self._saved_active_render = self._settings.get("/renderer/active")
self._saved_debug_material_type = self._settings.get("/rtx/debugMaterialType")
self._saved_total_spp = int(self._settings.get("/rtx/pathtracing/totalSpp"))
self._saved_spp = int(self._settings.get("/rtx/pathtracing/spp"))
self._saved_reset_pt_accum_only = self._settings.get("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges")
self._saved_display_options = self._settings.get("/persistent/app/viewport/displayOptions")
self._saved_async_rendering = self._settings.get("/app/asyncRendering")
self._saved_async_renderingLatency = self._settings.get("/app/asyncRenderingLowLatency")
self._saved_background_zero_alpha = self._settings.get("/rtx/post/backgroundZeroAlpha/enabled")
self._saved_background_zero_alpha_comp = self._settings.get("/rtx/post/backgroundZeroAlpha/backgroundComposite")
if self._options.render_preset == CaptureRenderPreset.IRAY:
self._saved_iray_sample_limit = int(self._settings.get("/rtx/iray/progressive_rendering_max_samples"))
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._saved_sunstudy_current_time = self._options.sunstudy_current_time
self._saved_timeline_current_time = self._timeline.get_current_time()
self._saved_rtx_sync_load_setting = self._settings.get("/rtx/materialDb/syncLoads")
self._saved_hydra_sync_load_setting = self._settings.get("/rtx/hydra/materialSyncLoads")
self._saved_async_texture_streaming = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/async")
self._saved_texture_streaming_budget = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB")
def _restore_window_status(self):
viewport_api, self._viewport_api = self._viewport_api, None
assert viewport_api is not None, "No viewport to restore to"
viewport_api.camera_path = self._saved_camera
viewport_api.resolution = (self._saved_resolution_width, self._saved_resolution_height)
if self._switch_renderer:
viewport_api.set_hd_engine(self._saved_hydra_engine, self._saved_render_mode)
self._settings.set_bool("/persistent/app/captureFrame/viewport", self._saved_capture_frame_viewport)
self._settings.set_int("/rtx/debugMaterialType", self._saved_debug_material_type)
self._settings.set_int("/rtx/pathtracing/totalSpp", self._saved_total_spp)
self._settings.set_int("/rtx/pathtracing/spp", self._saved_spp)
self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", self._saved_reset_pt_accum_only)
self._settings.set_int("/persistent/app/viewport/displayOptions", self._saved_display_options)
self._settings.set_bool("/app/asyncRendering", self._saved_async_rendering)
self._settings.set_bool("/app/asyncRenderingLowLatency", self._saved_async_renderingLatency)
self._renderer.set_capture_sync(not self._saved_async_rendering)
self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", self._saved_background_zero_alpha)
self._settings.set_bool(
"/rtx/post/backgroundZeroAlpha/backgroundComposite", self._saved_background_zero_alpha_comp
)
if self._options.render_preset == CaptureRenderPreset.IRAY:
self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._saved_iray_sample_limit)
if self._options.movie_type == CaptureMovieType.SUNSTUDY:
self._set_sunstudy_player_time(self._saved_sunstudy_current_time)
self._settings.set("/rtx/materialDb/syncLoads", self._saved_rtx_sync_load_setting)
self._settings.set("/rtx/hydra/materialSyncLoads", self._saved_hydra_sync_load_setting)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", self._saved_async_texture_streaming)
self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", self._saved_texture_streaming_budget)
self._settings.set("/app/captureFrame/hdr", False)
def _clean_pngs_in_directory(self, directory):
self._clean_files_in_directory(directory, ".png")
def _clean_files_in_directory(self, directory, suffix):
images = os.listdir(directory)
for item in images:
if item.endswith(suffix):
os.remove(os.path.join(directory, item))
def _make_sure_directory_existed(self, directory):
if not os.path.exists(directory):
try:
os.makedirs(directory, exist_ok=True)
except OSError as error:
carb.log_warn(f"Directory cannot be created: {dir}")
return False
return True
def _finish(self):
if (
self._progress.capture_status == CaptureStatus.FINISHING
or self._progress.capture_status == CaptureStatus.CANCELLED
):
self._update_sub = None
self._restore_window_status()
self._sample_count = 0
self._start_number = 0
self._frame_counter = 0
self._path_trace_iterations = 0
self._progress.capture_status = CaptureStatus.NONE
# restore timeline settings
# stop timeline, but re-enable auto update
timeline = self._timeline
timeline.set_auto_update(True)
timeline.stop()
timeline.set_time_codes_per_second(self._saved_timecodes_per_second)
self._timeline.set_current_time(self._saved_timeline_current_time)
self._settings.set("/iray/current_frame_time", self._saved_timeline_current_time)
if self._show_progress_window():
self._progress_window.close()
if self._capture_finished_fn is not None:
self._capture_finished_fn()
def _wait_for_image_writing(self):
# wait for the last frame is written to disk
# my tests of scenes of different complexity show a range of 0.2 to 1 seconds wait time
# so 5 second max time should be enough and we can early quit by checking the last
# frame every 0.1 seconds.
SECONDS_TO_WAIT = 5
SECONDS_EACH_TIME = 0.1
seconds_tried = 0.0
carb.log_info("Waiting for frames to be ready for encoding.")
while seconds_tried < SECONDS_TO_WAIT:
if os.path.isfile(self._frame_path) and os.access(self._frame_path, os.R_OK):
break
else:
time.sleep(SECONDS_EACH_TIME)
seconds_tried += SECONDS_EACH_TIME
if seconds_tried >= SECONDS_TO_WAIT:
carb.log_warn(f"Wait time out. To start encoding with images already have.")
def _capture_viewport(self, frame_path: str):
capture_viewport_to_file(self._viewport_api, file_path=frame_path)
carb.log_info(f"Capturing {frame_path}")
def _get_current_frame_output_path(self):
frame_path = ""
if self._options.is_video():
frame_path = get_num_pattern_file_path(
self._frames_dir,
self._options.file_name,
self._options.file_name_num_pattern,
self._frame,
DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO,
self._options.renumber_negative_frame_number_from_0,
abs(self._start_number)
)
else:
if self._options.is_capturing_nth_frames():
if self._frame_counter % self._options.capture_every_Nth_frames == 0:
frame_path = get_num_pattern_file_path(
self._frame_pattern_prefix,
self._options.file_name,
self._options.file_name_num_pattern,
self._frame,
self._options.file_type,
self._options.renumber_negative_frame_number_from_0,
abs(self._start_number)
)
else:
frame_path = self._frame_pattern_prefix + self._options.file_type
return frame_path
def _handle_skipping_frame(self, dt):
if not self._options.overwrite_existing_frames:
if os.path.exists(self._frame_path):
carb.log_warn(f"Frame {self._frame_path} exists, skip it...")
self._settings.set_int("/rtx/pathtracing/spp", 1)
self._subframe = 0
self._sample_count = 0
self._path_trace_iterations = 0
can_continue = True
if self._forward_one_frame_fn is not None:
can_continue = self._forward_one_frame_fn(dt)
elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \
(self._options.is_video() or self._options.is_capturing_nth_frames()):
self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration * self._sunstudy_iterations_per_frame
self._update_sunstudy_player_time()
else: # movie type is SEQUENCE
self._time = self._start_time + (self._frame - self._start_number) * self._time_rate
self._timeline.set_current_time(self._time)
self._settings.set("/iray/current_frame_time", self._time)
self._frame += 1
self._frame_counter += 1
# check if capture ends
if self._forward_one_frame_fn is not None:
if can_continue is False:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
else:
if self._time >= self._end_time or self._frame_counter >= self._total_frame_count:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
return True
else:
if os.path.exists(self._frame_path) and self._last_skipped_frame_path != self._frame_path:
carb.log_warn(f"Frame {self._frame_path} will be overwritten.")
self._last_skipped_frame_path = self._frame_path
return False
def _handle_real_time_capture_settle_latency(self):
if (self._options.render_preset == CaptureRenderPreset.RAY_TRACE
and self._options.real_time_settle_latency_frames > 0):
self._real_time_settle_latency_frames_done += 1
if self._real_time_settle_latency_frames_done > self._options.real_time_settle_latency_frames:
self._real_time_settle_latency_frames_done = 0
return False
else:
self._subframe = 0
self._sample_count = 0
return True
return False
def _on_update(self, e):
dt = e.payload["dt"]
if self._progress.capture_status == CaptureStatus.FINISHING:
self._finish()
self._update_progress_hook()
elif self._progress.capture_status == CaptureStatus.CANCELLED:
# carb.log_warn("video recording cancelled")
self._update_progress_hook()
self._finish()
elif self._progress.capture_status == CaptureStatus.ENCODING:
if VideoGenerationHelper().encoding_done:
self._progress.capture_status = CaptureStatus.FINISHING
self._update_progress_hook()
self._progress.add_encoding_time(dt)
elif self._progress.capture_status == CaptureStatus.TO_START_ENCODING:
if VideoGenerationHelper().is_encoding is False:
self._wait_for_image_writing()
if self._options.renumber_negative_frame_number_from_0 is True and self._start_number < 0:
video_frame_start_num = 0
else:
video_frame_start_num = self._start_number
started = VideoGenerationHelper().generating_video(
self._video_name,
self._frames_dir,
self._options.file_name,
self._options.file_name_num_pattern,
video_frame_start_num,
self._total_frame_count,
self._options.fps,
)
if started:
self._progress.capture_status = CaptureStatus.ENCODING
self._update_progress_hook()
self._progress.add_encoding_time(dt)
else:
carb.log_warn("Movie capture failed to encode the capture images.")
self._progress.capture_status = CaptureStatus.FINISHING
elif self._progress.capture_status == CaptureStatus.CAPTURING:
if self._frames_to_disable_async_rendering >= 0:
self._frames_to_disable_async_rendering -= 1
return
if self._progress.is_prerolling():
self._progress.prerolled_frames += 1
self._settings.set_int("/rtx/pathtracing/spp", 1)
left_preroll_frames = self._options.preroll_frames - self._progress.prerolled_frames
self._timeline.set_current_time(self._start_time - left_preroll_frames / self._options.fps)
self._settings.set("/iray/current_frame_time", self._start_time - left_preroll_frames / self._options.fps)
return
self._frame_path = self._get_current_frame_output_path()
if self._handle_skipping_frame(dt):
return
self._settings.set_int(
"/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp)
)
if self._options.render_preset == CaptureRenderPreset.IRAY:
iterations_done = int(self._settings.get("/iray/progression"))
self._path_trace_iterations = iterations_done
self._sample_count = iterations_done
else:
self._sample_count += self._options.spp_per_iteration
self._timeline.set_prerolling(False)
self._settings.set_int("/rtx/externalFrameCounter", self._frame)
# update progress timers
if self._options.is_capturing_pathtracing_single_frame():
self._progress.add_single_frame_capture_time(self._subframe, self._options.ptmb_subframes_per_frame, dt)
else:
self._progress.add_frame_time(self._frame, dt, self._subframe + 1, self._path_trace_iterations)
self._update_progress_hook()
# capture frame when we reach the sample count for this frame and are rendering the last subframe
# Note _sample_count can go over _samples_per_pixel when 'spp_per_iteration > 1'
if (self._sample_count >= self._options.path_trace_spp) and (
self._subframe == self._options.ptmb_subframes_per_frame - 1
):
if self._handle_real_time_capture_settle_latency():
return
if self._options.is_video():
self._capture_viewport(self._frame_path)
else:
if self._options.is_capturing_nth_frames():
if self._frame_counter % self._options.capture_every_Nth_frames == 0:
self._capture_viewport(self._frame_path)
else:
self._progress.capture_status = CaptureStatus.FINISHING
self._capture_viewport(self._frame_path)
# reset time the *next frame* (since otherwise we capture the first sample)
if self._sample_count >= self._options.path_trace_spp:
self._sample_count = 0
self._path_trace_iterations = 0
self._subframe += 1
if self._subframe == self._options.ptmb_subframes_per_frame:
self._subframe = 0
self._frame += 1
self._frame_counter += 1
self._time = self._start_time + (self._frame - self._start_number) * self._time_rate
can_continue = False
if self._forward_one_frame_fn is not None:
can_continue = self._forward_one_frame_fn(dt)
elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \
(self._options.is_video() or self._options.is_capturing_nth_frames()):
self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration
self._update_sunstudy_player_time()
else:
cur_time = (
self._time + (self._options.ptmb_fso * self._time_rate) + self._time_subframe_rate * self._subframe
)
self._timeline.set_current_time(cur_time)
self._settings.set("/iray/current_frame_time", cur_time)
if self._forward_one_frame_fn is not None:
if can_continue == False:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
else:
if self._time >= self._end_time or self._frame_counter >= self._total_frame_count:
if self._options.is_video():
self._progress.capture_status = CaptureStatus.TO_START_ENCODING
elif self._options.is_capturing_nth_frames():
self._progress.capture_status = CaptureStatus.FINISHING
@staticmethod
def get_instance():
global capture_instance
return capture_instance
|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/video_generation.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 os
import threading
import carb
from video_encoding import get_video_encoding_interface
from .singleton import Singleton
from .helper import get_num_pattern_file_path
g_video_encoding_api = get_video_encoding_interface()
@Singleton
class VideoGenerationHelper:
def __init__(self):
self._init_internal()
@property
def is_encoding(self):
return self._is_encoding
@property
def encoding_done(self):
return self._is_encoding == False and self._encoding_done == True
def generating_video(
self, video_name, frames_dir, filename_prefix, filename_num_pattern,
start_number, total_frames, frame_rate, image_type=".png"
):
carb.log_warn(f"Using videoencoding plugin to encode video ({video_name})")
global g_video_encoding_api
self._encoding_finished = False
if g_video_encoding_api is None:
carb.log_warn("Video encoding api not available; cannot encode video.")
return False
# acquire list of available frame image files, based on start_number and filename_pattern
next_frame = start_number
frame_count = 0
self._frame_filenames = []
while True:
frame_path = get_num_pattern_file_path(
frames_dir,
filename_prefix,
filename_num_pattern,
next_frame,
image_type
)
if os.path.isfile(frame_path) and os.access(frame_path, os.R_OK):
self._frame_filenames.append(frame_path)
next_frame += 1
frame_count += 1
if frame_count == total_frames:
break
else:
break
carb.log_warn(f"Found {len(self._frame_filenames)} frames to encode.")
if len(self._frame_filenames) == 0:
carb.log_warn(f"No frames to encode.")
return False
if not g_video_encoding_api.start_encoding(video_name, frame_rate, len(self._frame_filenames), True):
carb.log_warn(f"videoencoding plug failed to start encoding.")
return False
if self._encoding_thread == None:
self._encoding_thread = threading.Thread(target=self._encode_image_file_sequence, args=())
self._is_encoding = True
self._encoding_thread.start()
return True
def _init_internal(self):
self._video_generation_done_fn = None
self._frame_filenames = []
self._encoding_thread = None
self._is_encoding = False
self._encoding_done = False
def _encode_image_file_sequence(self):
global g_video_encoding_api
try:
for frame_filename in self._frame_filenames:
g_video_encoding_api.encode_next_frame_from_file(frame_filename)
except:
import traceback
carb.log_warn(traceback.format_exc())
finally:
g_video_encoding_api.finalize_encoding()
self._init_internal()
self._encoding_done = True
|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/__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 CaptureExtension
from .capture_options import *
from .capture_progress import *
|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/capture_options.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 os
from enum import Enum, IntEnum
class CaptureMovieType(IntEnum):
SEQUENCE = 0
SUNSTUDY = 1
PLAYLIST = 2
class CaptureRangeType(IntEnum):
FRAMES = 0
SECONDS = 1
class CaptureRenderPreset(IntEnum):
PATH_TRACE = 0
RAY_TRACE = 1
IRAY = 2
class CaptureDebugMaterialType(IntEnum):
SHADED = 0
WHITE = 1
class CaptureOptions:
""" All Capture options that will be used when capturing.
Note: When adding an attribute make sure it is exposed via the constructor.
Not doing this will cause erorrs when serializing and deserializing this object.
"""
def __init__(
self,
camera="camera",
range_type=CaptureRangeType.FRAMES,
capture_every_nth_frames=-1,
fps="24",
start_frame=1,
end_frame=40,
start_time=0,
end_time=10,
res_width=1920,
res_height=1080,
render_preset=CaptureRenderPreset.PATH_TRACE,
debug_material_type=CaptureDebugMaterialType.SHADED,
spp_per_iteration=1,
path_trace_spp=1,
ptmb_subframes_per_frame=1,
ptmb_fso=0.0,
ptmb_fsc=1.0,
output_folder="",
file_name="Capture",
file_name_num_pattern=".####",
file_type=".tga",
save_alpha=False,
hdr_output=False,
show_pathtracing_single_frame_progress=False,
preroll_frames=0,
overwrite_existing_frames=False,
movie_type=CaptureMovieType.SEQUENCE,
sunstudy_start_time=0.0,
sunstudy_current_time=0.0,
sunstudy_end_time=0.0,
sunstudy_movie_length_in_seconds=0,
sunstudy_player=None,
real_time_settle_latency_frames=0,
renumber_negative_frame_number_from_0=False
):
self._camera = camera
self._range_type = range_type
self._capture_every_nth_frames = capture_every_nth_frames
self._fps = fps
self._start_frame = start_frame
self._end_frame = end_frame
self._start_time = start_time
self._end_time = end_time
self._res_width = res_width
self._res_height = res_height
self._render_preset = render_preset
self._debug_material_type = debug_material_type
self._spp_per_iteration = spp_per_iteration
self._path_trace_spp = path_trace_spp
self._ptmb_subframes_per_frame = ptmb_subframes_per_frame
self._ptmb_fso = ptmb_fso
self._ptmb_fsc = ptmb_fsc
self._output_folder = output_folder
self._file_name = file_name
self._file_name_num_pattern = file_name_num_pattern
self._file_type = file_type
self._save_alpha = save_alpha
self._hdr_output = hdr_output
self._show_pathtracing_single_frame_progress = show_pathtracing_single_frame_progress
self._preroll_frames = preroll_frames
self._overwrite_existing_frames = overwrite_existing_frames
self._movie_type = movie_type
self._sunstudy_start_time = sunstudy_start_time
self._sunstudy_current_time = sunstudy_current_time
self._sunstudy_end_time = sunstudy_end_time
self._sunstudy_movie_length_in_seconds = sunstudy_movie_length_in_seconds
self._sunstudy_player = sunstudy_player
self._real_time_settle_latency_frames = real_time_settle_latency_frames
self._renumber_negative_frame_number_from_0 = renumber_negative_frame_number_from_0
def to_dict(self):
data = vars(self)
return {key.lstrip("_"): value for key, value in data.items()}
@classmethod
def from_dict(cls, options):
return cls(**options)
@property
def camera(self):
return self._camera
@camera.setter
def camera(self, value):
self._camera = value
@property
def range_type(self):
return self._range_type
@range_type.setter
def range_type(self, value):
self._range_type = value
@property
def capture_every_Nth_frames(self):
return self._capture_every_nth_frames
@capture_every_Nth_frames.setter
def capture_every_Nth_frames(self, value):
self._capture_every_nth_frames = value
@property
def fps(self):
return self._fps
@fps.setter
def fps(self, value):
self._fps = value
@property
def start_frame(self):
return self._start_frame
@start_frame.setter
def start_frame(self, value):
self._start_frame = value
@property
def end_frame(self):
return self._end_frame
@end_frame.setter
def end_frame(self, value):
self._end_frame = value
@property
def start_time(self):
return self._start_time
@start_time.setter
def start_time(self, value):
self._start_time = value
@property
def end_time(self):
return self._end_time
@end_time.setter
def end_time(self, value):
self._end_time = value
@property
def res_width(self):
return self._res_width
@res_width.setter
def res_width(self, value):
self._res_width = value
@property
def res_height(self):
return self._res_height
@res_height.setter
def res_height(self, value):
self._res_height = value
@property
def render_preset(self):
return self._render_preset
@render_preset.setter
def render_preset(self, value):
self._render_preset = value
@property
def debug_material_type(self):
return self._debug_material_type
@debug_material_type.setter
def debug_material_type(self, value):
self._debug_material_type = value
@property
def spp_per_iteration(self):
return self._spp_per_iteration
@spp_per_iteration.setter
def spp_per_iteration(self, value):
self._spp_per_iteration = value
@property
def path_trace_spp(self):
return self._path_trace_spp
@path_trace_spp.setter
def path_trace_spp(self, value):
self._path_trace_spp = value
@property
def ptmb_subframes_per_frame(self):
return self._ptmb_subframes_per_frame
@ptmb_subframes_per_frame.setter
def ptmb_subframes_per_frame(self, value):
self._ptmb_subframes_per_frame = value
@property
def ptmb_fso(self):
return self._ptmb_fso
@ptmb_fso.setter
def ptmb_fso(self, value):
self._ptmb_fso = value
@property
def ptmb_fsc(self):
return self._ptmb_fsc
@ptmb_fsc.setter
def ptmb_fsc(self, value):
self._ptmb_fsc = value
@property
def output_folder(self):
return self._output_folder
@output_folder.setter
def output_folder(self, value):
self._output_folder = value
@property
def file_name(self):
return self._file_name
@file_name.setter
def file_name(self, value):
self._file_name = value
@property
def file_name_num_pattern(self):
return self._file_name_num_pattern
@file_name_num_pattern.setter
def file_name_num_pattern(self, value):
self._file_name_num_pattern = value
@property
def file_type(self):
return self._file_type
@file_type.setter
def file_type(self, value):
self._file_type = value
@property
def save_alpha(self):
return self._save_alpha
@save_alpha.setter
def save_alpha(self, value):
self._save_alpha = value
@property
def hdr_output(self):
return self._hdr_output
@hdr_output.setter
def hdr_output(self, value):
self._hdr_output = value
@property
def show_pathtracing_single_frame_progress(self):
return self._show_pathtracing_single_frame_progress
@show_pathtracing_single_frame_progress.setter
def show_pathtracing_single_frame_progress(self, value):
self._show_pathtracing_single_frame_progress = value
@property
def preroll_frames(self):
return self._preroll_frames
@preroll_frames.setter
def preroll_frames(self, value):
self._preroll_frames = value
@property
def overwrite_existing_frames(self):
return self._overwrite_existing_frames
@overwrite_existing_frames.setter
def overwrite_existing_frames(self, value):
self._overwrite_existing_frames = value
@property
def movie_type(self):
return self._movie_type
@movie_type.setter
def movie_type(self, value):
self._movie_type = value
@property
def sunstudy_start_time(self):
return self._sunstudy_start_time
@sunstudy_start_time.setter
def sunstudy_start_time(self, value):
self._sunstudy_start_time = value
@property
def sunstudy_current_time(self):
return self._sunstudy_current_time
@sunstudy_current_time.setter
def sunstudy_current_time(self, value):
self._sunstudy_current_time = value
@property
def sunstudy_end_time(self):
return self._sunstudy_end_time
@sunstudy_end_time.setter
def sunstudy_end_time(self, value):
self._sunstudy_end_time = value
@property
def sunstudy_movie_length_in_seconds(self):
return self._sunstudy_movie_length_in_seconds
@sunstudy_movie_length_in_seconds.setter
def sunstudy_movie_length_in_seconds(self, value):
self._sunstudy_movie_length_in_seconds = value
@property
def sunstudy_player(self):
return self._sunstudy_player
@sunstudy_player.setter
def sunstudy_player(self, value):
self._sunstudy_player = value
@property
def real_time_settle_latency_frames(self):
return self._real_time_settle_latency_frames
@real_time_settle_latency_frames.setter
def real_time_settle_latency_frames(self, value):
self._real_time_settle_latency_frames = value
@property
def renumber_negative_frame_number_from_0(self):
return self._renumber_negative_frame_number_from_0
@renumber_negative_frame_number_from_0.setter
def renumber_negative_frame_number_from_0(self, value):
self._renumber_negative_frame_number_from_0 = value
def is_video(self):
return self.file_type == ".mp4"
def is_capturing_nth_frames(self):
return self._capture_every_nth_frames > 0
def is_capturing_pathtracing_single_frame(self):
return self.is_video() is False and self.is_capturing_nth_frames() is False and self.render_preset == CaptureRenderPreset.PATH_TRACE
def is_capturing_frame(self):
return self._range_type == CaptureRangeType.FRAMES
def get_full_path(self):
return os.path.join(self._output_folder, self._file_name + self._file_type)
|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/helper.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 os
def get_num_pattern_file_path(frames_dir, file_name, num_pattern, frame_num, file_type, renumber_frames=False, renumber_offset=0):
if renumber_frames:
renumbered_frames = frame_num + renumber_offset
else:
renumbered_frames = frame_num
abs_frame_num = abs(renumbered_frames)
padding_length = len(num_pattern.strip(".")[len(str(abs_frame_num)) :])
if renumbered_frames >= 0:
padded_string = "0" * padding_length + str(renumbered_frames)
else:
padded_string = "-" + "0" * padding_length + str(abs_frame_num)
filename = ".".join((file_name, padded_string, file_type.strip(".")))
frame_path = os.path.join(frames_dir, filename)
return frame_path
|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/singleton.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.
#
def Singleton(class_):
"""A singleton decorator"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/tests/__init__.py | from .test_capture_options import TestCaptureOptions
# from .test_capture_hdr import TestCaptureHdr
|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/tests/test_capture_hdr.py | from typing import Type
import os.path
import omni.kit.test
import carb
import carb.settings
import carb.tokens
import pathlib
import omni.kit.capture.capture_options as _capture_options
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file, create_viewport_window
OUTPUTS_DIR = omni.kit.test.get_test_output_path()
class TestCaptureHdr(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
settings = carb.settings.get_settings()
settings.set("/app/asyncRendering", False)
settings.set("/app/asyncRenderingLowLatency", False)
settings.set("/app/captureFrame/hdr", True)
# Setup viewport
self._usd_context = ''
await omni.usd.get_context(self._usd_context).new_stage_async()
async def test_hdr_capture(self):
viewport_api = get_active_viewport(self._usd_context)
if viewport_api is None:
return
# Wait until the viewport has valid resources
await viewport_api.wait_for_rendered_frames()
capture_filename = "capture.hdr_test.exr"
filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename)
capture_viewport_to_file(viewport_api, str(filePath))
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
assert os.path.isfile(str(filePath))
# Make sure we do not crash in the unsupported multi-view case
async def do_test_hdr_multiview_capture(self, test_legacy: bool):
viewport_api = get_active_viewport(self._usd_context)
if viewport_api is None:
return
# Wait until the viewport has valid resources
await viewport_api.wait_for_rendered_frames()
second_vp_window = create_viewport_window('Viewport 2', width=256, height=256)
await second_vp_window.viewport_api.wait_for_rendered_frames()
capture_filename = "capture.hdr_test.multiview.exr"
filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename)
# Multiview HDR output is not yet fully supported, confirm this exits gracefully
capture_viewport_to_file(viewport_api, str(filePath))
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
await omni.kit.app.get_app_interface().next_update_async()
assert os.path.isfile(str(filePath))
second_vp_window.destroy()
del second_vp_window
async def test_hdr_multiview_capture_legacy(self):
await self.do_test_hdr_multiview_capture(True)
async def test_hdr_multiview_capture(self):
await self.do_test_hdr_multiview_capture(False)
|
omniverse-code/kit/exts/omni.kit.capture/omni/kit/capture/tests/test_capture_options.py | from typing import Type
import omni.kit.test
import omni.kit.capture.capture_options as _capture_options
class TestCaptureOptions(omni.kit.test.AsyncTestCase):
async def test_capture_options_serialisation(self):
options = _capture_options.CaptureOptions()
data_dict = options.to_dict()
self.assertIsInstance(data_dict, dict)
async def test_capture_options_deserialisation(self):
options = _capture_options.CaptureOptions()
data_dict = options.to_dict()
regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict)
self.assertIsInstance(regenerated_options, _capture_options.CaptureOptions)
async def test_capture_options_values_persisted(self):
options = _capture_options.CaptureOptions(camera="my_camera")
data_dict = options.to_dict()
regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict)
self.assertEqual(regenerated_options.camera, "my_camera")
async def test_adding_random_attribute_fails(self):
""" Test that adding new attributes without making them configurable via the __init__ will raise an exception
"""
options = _capture_options.CaptureOptions()
options._my_new_value = "foo"
data_dict = options.to_dict()
with self.assertRaises(TypeError, msg="__init__() got an unexpected keyword argument 'my_new_value'"):
regnerated = _capture_options.CaptureOptions.from_dict(data_dict) |
omniverse-code/kit/exts/omni.kit.capture/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.5.1] - 2022-06-22
### Changed
- Add declaration of deprecation: this extension has been replaced with omni.kit.capture.viewport will be removed in future releases.
## [0.5.0] - 2022-05-23
### Changes
- Support legacy and new Viewport API
- Add dependency on omni.kit.viewport.utility
## [0.4.9] - 2021-11-27
### Changed
- Changed the way sunstudy updates its player by supporting the new player in environment.sunstudy
## [0.4.8] - 2021-09-08
### Changed
- Merge fixes from the release/102 branch; fixes includes:
- Fix the iray capture produces duplicated images issue
- Fix corrupted EXR image capture under certain circumstances, due to the rendering not behaving according to the value of the `asyncRendering` setting
- Backport required features of the plugin related to validation of frame counts and erroneous selection of Hydra engine when switching between RTX and Iray
- Add current frame index and total frame count to the notification system during frame capture
## [0.4.4] - 2021-07-05
### Added
- Added current frame index and total frame count to the notification system during frame capture.
## [0.4.3] - 2021-07-04
### Fixed
- Fixed the issue that can't switch to iray mode to capture images
## [0.4.2] - 2021-06-14
### Added
- Added support to renumber negative frame numbers from zero
### Changed
- Negative frame number format changed from ".00-x.png" to ".-000x.png"
## [0.4.1] - 2021-06-09
### Added
- Added the handling of path tracing iterations for capturing in Iray mode, also added a new entry to show number of iterations done on the progress window for Iray capturing
## [0.4.0] - 2021-05-25
### Fixed
- Fixed the issue that animation timeline's current time reset to zero after capture, now it's restored to the time before capture
## [0.3.9] - 2021-05-20
### Added
- Added a settle latency for capture in RTX real time mode to set the number of frames to be settled to improve image quality for each frame captured
## [0.3.8] - 2021-05-11
### Added
- Added support to the overwrite existing frame option; now if the frame path exists already, will warn either it will be skipped or it will be overwritten
- Added capture end callback in case users want it
### Fixed
- Fixed the issue that capture doesn't end in time if there are skipped frames
- Fixed the issue that all frames with number greater than start frame number in the output folder will be encoded into the final mp4 file, now only captured frames will be added.
## [0.3.7] - 2021-04-29
### Added
- Add support to new movie type sunstudy
## [0.3.6] - 2021-04-15
### Changed
- Change the name pattern of images of mp4 to be the same to capture Nth frames name pattern
## [0.3.5] - 2021-04-10
### Added
- Add support to skip existing frames at capturing sequence
## [0.3.4] - 2021-04-02
### Added
- Add preroll frames support so that it can run given frames before starting actual capturing. To save performance
for the preroll frames, "/rtx/pathtracing/spp" for path tracing will be set to 1
## [0.3.3] - 2021-03-01
### Added
- Add progress report of single frame capture in PT mode
- Update progress timers for video captures per iteration instead of per frame
## [0.3.2] - 2021-02-03
### Fixed
- Fix the time precision is a bit much issue
## [0.3.1] - 2021-02-03
### Fixed
- Fixed the PhysX and Flow simulation speed is much faster than normal in the captured movie issue
- Fixed the path tracing options are wrongly taken in the ray tracing mode during capture issue
## [0.3.0] - 2020-12-03
### Added
- Add support to capture in IRay mode
## [0.2.1] - 2020-11-30
### Removed
- Removed verbose warning during startup
## [0.2.0] - 2020-11-19
### Added
- Added functionality to capture with Kit Next
## [0.1.7] - 2020-10-19
### Fixed
- Hide lights and grid during capturing
## [0.1.6] - 2020-10-08
### Fixed
- Correct the update of motion blur subframe time
- Make sure frame count is right with when motion blur frame shutter open and close difference is not 1
## [0.1.5] - 2020-10-07
### Fixed
- Pass through the right file name
- Make sure padding is applied for files
|
omniverse-code/kit/exts/omni.kit.capture/docs/README.md | # Omniverse Kit Image and Video Capture
Extension to handle the capturing and recording of the viewport |
omniverse-code/kit/exts/omni.kit.window.splash_close_example/PACKAGE-LICENSES/omni.kit.window.splash_close_example-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. |
omniverse-code/kit/exts/omni.kit.window.splash_close_example/config/extension.toml | [package]
version = "0.2.0"
category = "Internal"
[core]
# Load as late as possible
order = 10000
[dependencies]
"omni.kit.window.splash" = { optional = true }
[[python.module]]
name = "omni.kit.window.splash_close_example"
[[test]]
waiver = "Simple example extension" # OM-48132
|
omniverse-code/kit/exts/omni.kit.window.splash_close_example/omni/kit/window/splash_close_example/extension.py | import carb
import omni.ext
class SplashCloseExtension(omni.ext.IExt):
def on_startup(self):
try:
import omni.splash
splash_iface = omni.splash.acquire_splash_screen_interface()
except (ImportError, ModuleNotFoundError):
splash_iface = None
if not splash_iface:
return
splash_iface.close_all()
def on_shutdown(self):
pass
|
omniverse-code/kit/exts/omni.kit.window.splash_close_example/omni/kit/window/splash_close_example/__init__.py | from .extension import *
|
omniverse-code/kit/exts/omni.kit.window.splash_close_example/docs/index.rst | omni.kit.window.splash_close_example: omni.kit.window.stats
############################################################
Window to display omni.stats
|
omniverse-code/kit/exts/omni.kit.property.light/PACKAGE-LICENSES/omni.kit.property.light-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. |
omniverse-code/kit/exts/omni.kit.property.light/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.6"
category = "Internal"
feature = true
# 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 = "Light Property Widget"
description="View and Edit Light Property Values"
# URL of the extension source repository.
repository = ""
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
# 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", "usd", "property", "light"]
# 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.usd" = {}
"omni.ui" = {}
"omni.kit.window.property" = {}
"omni.kit.property.usd" = {}
[[python.module]]
name = "omni.kit.property.light"
[[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/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/app/file/ignoreUnsavedOnExit=true",
"--/persistent/app/stage/dragDropImport='reference'",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=false",
"--no-window"
]
dependencies = [
"omni.usd",
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.material.library", # for omni_pbr...
"omni.kit.window.content_browser",
"omni.kit.window.stage",
"omni.kit.property.material",
"omni.kit.window.status_bar",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers",
"omni.kit.window.file",
"omni.hydra.pxr",
"omni.kit.window.viewport",
"omni.kit.window.content_browser"
]
stdoutFailPatterns.exclude = [
"*Failed to acquire interface*while unloading all plugins*"
]
|
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/__init__.py | from .scripts import *
|
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/scripts/light_properties.py | import os
import carb
import omni.ext
from pathlib import Path
from pxr import Sdf, UsdLux, Usd
TEST_DATA_PATH = ""
class LightPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from .prim_light_widget import LightSchemaAttributesWidget
w = p.get_window()
if w:
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
w.register_widget(
"prim",
"light",
LightSchemaAttributesWidget(
"Light",
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
UsdLux.LightAPI if hasattr(UsdLux, 'LightAPI') else UsdLux.Light,
[
UsdLux.CylinderLight,
UsdLux.DiskLight,
UsdLux.DistantLight,
UsdLux.DomeLight,
UsdLux.GeometryLight,
UsdLux.RectLight,
UsdLux.SphereLight,
UsdLux.ShapingAPI,
UsdLux.ShadowAPI,
UsdLux.LightFilter,
# https://github.com/PixarAnimationStudios/USD/commit/9eda37ec9e1692dd290efd9a26526e0d2c21bb03
UsdLux.PortalLight if hasattr(UsdLux, 'PortalLight') else UsdLux.LightPortal,
UsdLux.ListAPI,
],
[
"color",
"enableColorTemperature",
"colorTemperature",
"intensity",
"exposure",
"normalize",
"angle",
"radius",
"height",
"width",
"radius",
"length",
"texture:file",
"texture:format",
"diffuse",
"specular",
"shaping:focus",
"shaping:focusTint",
"shaping:cone:angle",
"shaping:cone:softness",
"shaping:ies:file",
"shaping:ies:angleScale",
"shaping:ies:normalize",
"collection:shadowLink:expansionRule",
"collection:shadowLink:excludes",
"collection:shadowLink:includes",
"collection:lightLink:expansionRule",
"collection:lightLink:excludes",
"collection:lightLink:includes",
"light:enableCaustics",
"visibleInPrimaryRay",
"disableFogInteraction",
"isProjector",
] \
# https://github.com/PixarAnimationStudios/USD/commit/c8cd344af6be342911e50d2350c228ed329be6b2
# USD v22.08 adds this to LightAPI as an API schema override of CollectionAPI
+ (["collection:lightLink:includeRoot"] if Usd.GetVersion() >= (0,22,8) else []),
[],
),
)
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "light")
self._registered = False
|
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/scripts/__init__.py | from .light_properties import *
|
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/scripts/prim_light_widget.py | # 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.
#
from typing import Set
import omni.ui as ui
import omni.usd
from omni.kit.property.usd.usd_property_widget import MultiSchemaPropertiesWidget, UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import create_primspec_bool
from pxr import Kind, Sdf, Usd, UsdLux
import carb
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class LightSchemaAttributesWidget(MultiSchemaPropertiesWidget):
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
self._settings = carb.settings.get_settings()
self._setting_path = PERSISTENT_SETTINGS_PREFIX + "/app/usd/usdLuxUnprefixedCompat"
self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change)
self.lux_attributes: Set[str] = set(['inputs:angle', 'inputs:color', 'inputs:temperature', 'inputs:diffuse', 'inputs:specular', 'inputs:enableColorTemperature',
'inputs:exposure', 'inputs:height', 'inputs:width', 'inputs:intensity', 'inputs:length',
'inputs:normalize', 'inputs:radius', 'inputs:shadow:color', 'inputs:shadow:distance', 'inputs:shadow:enable', 'inputs:shadow:falloff',
'inputs:shadow:falloffGamma', 'inputs:shaping:cone:angle', 'inputs:shaping:cone:softness', 'inputs:shaping:focus',
'inputs:shaping:focusTint', 'inputs:shaping:ies:angleScale', 'inputs:shaping:ies:file', 'inputs:shaping:ies:normalize', 'inputs:texture:format'])
# custom attributes
def is_prim_light_primary_visible_supported(prim):
return (
prim.IsA(UsdLux.DomeLight)
or prim.IsA(UsdLux.DiskLight)
or prim.IsA(UsdLux.RectLight)
or prim.IsA(UsdLux.SphereLight)
or prim.IsA(UsdLux.CylinderLight)
or prim.IsA(UsdLux.DistantLight)
)
def is_prim_light_disable_fog_interaction_supported(prim):
return (
prim.IsA(UsdLux.DomeLight)
or prim.IsA(UsdLux.DiskLight)
or prim.IsA(UsdLux.RectLight)
or prim.IsA(UsdLux.SphereLight)
or prim.IsA(UsdLux.CylinderLight)
or prim.IsA(UsdLux.DistantLight)
)
def is_prim_light_caustics_supported(prim):
return prim.IsA(UsdLux.DiskLight) or prim.IsA(UsdLux.RectLight) or prim.IsA(UsdLux.SphereLight)
def is_prim_light_is_projector_supported(prim):
return prim.IsA(UsdLux.RectLight)
def add_vipr(attribute_name, value_dict):
anchor_prim = self._get_prim(self._payload[-1])
if anchor_prim and (anchor_prim.IsA(UsdLux.DomeLight) or anchor_prim.IsA(UsdLux.DistantLight)):
return UsdPropertyUiEntry("visibleInPrimaryRay", "", create_primspec_bool(True), Usd.Attribute)
else:
return UsdPropertyUiEntry("visibleInPrimaryRay", "", create_primspec_bool(False), Usd.Attribute)
self.add_custom_schema_attribute("visibleInPrimaryRay", is_prim_light_primary_visible_supported, add_vipr, "", {})
self.add_custom_schema_attribute("disableFogInteraction", is_prim_light_disable_fog_interaction_supported, None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("light:enableCaustics", is_prim_light_caustics_supported, None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("isProjector", is_prim_light_is_projector_supported, None, "", create_primspec_bool(False))
def _on_change(self, item, event_type):
self.request_rebuild()
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
if self._schema().IsTyped() and not prim.IsA(self._schema):
return False
if self._schema().IsAPISchema() and not prim.HasAPI(self._schema):
return False
used += [attr for attr in prim.GetAttributes() if attr.GetName() in self._schema_attr_names and not attr.IsHidden()]
if self.is_custom_schema_attribute_used(prim):
used.append(None)
return used
def has_authored_inputs_attr(self, prim):
attrs = set([a.GetName() for a in prim.GetAuthoredAttributes()])
any_authored = attrs.intersection(self.lux_attributes)
return any_authored
def _customize_props_layout(self, attrs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.window.property.templates import (
SimplePropertyWidget,
LABEL_WIDTH,
LABEL_HEIGHT,
HORIZONTAL_SPACING,
)
self.add_custom_schema_attributes_to_props(attrs)
frame = CustomLayoutFrame(hide_extra=False)
anchor_prim = self._get_prim(self._payload[-1])
# TODO -
# add shadow values (Shadow Enable, Shadow Include, Shadow Exclude, Shadow Color, Shadow Distance, Shadow Falloff, Shadow Falloff Gamma)
# add UsdLux.DomeLight portals (see UsdLux.DomeLight GetPortalsRel)
# add filters (see UsdLux.Light / UsdLux.LightAPI GetFiltersRel)
self.usdLuxUnprefixedCompat = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/usd/usdLuxUnprefixedCompat")
has_authored_inputs = self.has_authored_inputs_attr(anchor_prim)
with frame:
with CustomLayoutGroup("Main"):
self._create_property("color", "Color", anchor_prim, has_authored_inputs)
self._create_property("enableColorTemperature", "Enable Color Temperature", anchor_prim, has_authored_inputs)
self._create_property("colorTemperature", "Color Temperature", anchor_prim, has_authored_inputs)
self._create_property("intensity", "Intensity", anchor_prim, has_authored_inputs)
self._create_property("exposure", "Exposure", anchor_prim, has_authored_inputs)
self._create_property("normalize", "Normalize Power", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.DistantLight):
self._create_property("angle", "Angle", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.DiskLight):
self._create_property("radius", "Radius", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.RectLight):
self._create_property("height", "Height", anchor_prim, has_authored_inputs)
self._create_property("width", "Width", anchor_prim, has_authored_inputs)
self._create_property("texture:file", "Texture File", anchor_prim, has_authored_inputs)
if anchor_prim and anchor_prim.IsA(UsdLux.SphereLight):
self._create_property("radius", "Radius", anchor_prim, has_authored_inputs)
CustomLayoutProperty("treatAsPoint", "Treat As Point")
if anchor_prim and anchor_prim.IsA(UsdLux.CylinderLight):
self._create_property("length", "Length", anchor_prim, has_authored_inputs)
self._create_property("radius", "Radius", anchor_prim, has_authored_inputs)
CustomLayoutProperty("treatAsLine", "Treat As Line")
if anchor_prim and anchor_prim.IsA(UsdLux.DomeLight):
self._create_property("texture:file", "Texture File", anchor_prim, has_authored_inputs)
self._create_property("texture:format", "Texture Format", anchor_prim, has_authored_inputs)
self._create_property("diffuse", "Diffuse Multiplier", anchor_prim, has_authored_inputs)
self._create_property("specular", "Specular Multiplier", anchor_prim, has_authored_inputs)
CustomLayoutProperty("visibleInPrimaryRay", "Visible In Primary Ray")
CustomLayoutProperty("disableFogInteraction", "Disable Fog Interaction")
CustomLayoutProperty("light:enableCaustics", "Enable Caustics")
CustomLayoutProperty("isProjector", "Projector light type")
with CustomLayoutGroup("Shaping", collapsed=True):
self._create_property("shaping:focus", "Focus", anchor_prim, has_authored_inputs)
self._create_property("shaping:focusTint", "Focus Tint", anchor_prim, has_authored_inputs)
self._create_property("shaping:cone:angle", "Cone Angle", anchor_prim, has_authored_inputs)
self._create_property("shaping:cone:softness", "Cone Softness", anchor_prim, has_authored_inputs)
self._create_property("shaping:ies:file", "File", anchor_prim, has_authored_inputs)
self._create_property("shaping:ies:angleScale", "AngleScale", anchor_prim, has_authored_inputs)
self._create_property("shaping:ies:normalize", "Normalize", anchor_prim, has_authored_inputs)
with CustomLayoutGroup("Light Link"):
CustomLayoutProperty("collection:lightLink:includeRoot", "Light Link Include Root")
CustomLayoutProperty("collection:lightLink:expansionRule", "Light Link Expansion Rule")
CustomLayoutProperty("collection:lightLink:includes", "Light Link Includes")
CustomLayoutProperty("collection:lightLink:excludes", "Light Link Excludes")
with CustomLayoutGroup("Shadow Link"):
CustomLayoutProperty("collection:shadowLink:includeRoot", "Shadow Link Include Root")
CustomLayoutProperty("collection:shadowLink:expansionRule", "Shadow Link Expansion Rule")
CustomLayoutProperty("collection:shadowLink:includes", "Shadow Link Includes")
CustomLayoutProperty("collection:shadowLink:excludes", "Shadow Link Excludes")
return frame.apply(attrs)
def _create_property(self, name: str, display_name: str, prim, has_authored_inputs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutProperty
)
if has_authored_inputs or not self.usdLuxUnprefixedCompat or not prim.HasAttribute(name):
prefixed_name = "inputs:" + name
return CustomLayoutProperty(prefixed_name, display_name)
return CustomLayoutProperty(name, display_name)
|
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/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_light import *
from .test_drag_drop_HDRI_property import *
|
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/tests/test_light.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 pathlib
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading
from pxr import Kind, Sdf, Gf
class TestLightWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
usd_path = pathlib.Path(get_test_data_path(__name__))
self._golden_img_dir = usd_path.absolute().joinpath("golden_img").absolute()
self._usd_path = usd_path.absolute()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
await super().tearDown()
await wait_stage_loading()
# Test(s)
async def test_light_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=650,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("light_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await wait_stage_loading()
# NOTE: cannot do DomeLight as it contains a file path which is build specific
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/DistantLight"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_light_ui.png")
|
omniverse-code/kit/exts/omni.kit.property.light/omni/kit/property/light/tests/test_drag_drop_HDRI_property.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.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
build_sdf_asset_frame_dictonary,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropHDRIProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "dome_light.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_drag_drop_HDRI_property(self):
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ["/World/DomeLight"]
# select prim
await select_prims(to_select)
# wait for material to load & UI to refresh
await wait_stage_loading()
# open all CollapsableFrames
for frame in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if frame.widget.title != "Raw USD Properties":
frame.widget.scroll_here_y(0.5)
frame.widget.collapsed = False
await ui_test.human_delay()
# prep content window for drag/drop
texture_path = get_test_data_path(__name__, "textures/sunflowers.hdr")
# NOTE: cannot keep using widget as they become stale as window refreshes due to set_value
# do tests
widget_table = await build_sdf_asset_frame_dictonary()
for frame_name in widget_table.keys():
if frame_name in ["Raw USD Properties", "Extra Properties"]:
continue
for field_name in widget_table[frame_name].keys():
# NOTE: sdf_asset_ could be used more than once, if so skip
if widget_table[frame_name][field_name] == 1:
def get_widget():
return ui_test.find(f"Property//Frame/**/CollapsableFrame[*].title=='{frame_name}'").find(f"**/StringField[*].identifier=='{field_name}'")
# scroll to widget
get_widget().widget.scroll_here_y(0.5)
await ui_test.human_delay()
# reset for test
get_widget().model.set_value("")
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.drag_and_drop_tree_view(texture_path, drag_target=get_widget().center)
# verify dragged item(s)
for prim_path in to_select:
prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
self.assertTrue(prim.IsValid())
attr = prim.GetAttribute(field_name[10:])
self.assertTrue(attr.IsValid())
asset_path = attr.Get()
self.assertTrue(asset_path != None)
self.assertTrue(asset_path.resolvedPath.replace("\\", "/").lower() == texture_path.replace("\\", "/").lower())
# reset for next test
get_widget().model.set_value("")
|
omniverse-code/kit/exts/omni.kit.property.light/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.6] - 2022-07-25
### Changes
- Refactored unittests to make use of content_browser test helpers
## [1.0.5] - 2022-01-10
### Changes
- Updated Shadow Link & Light Link. Now has include/exclude
## [1.0.4] - 2021-02-19
### Changes
- Added UI test
## [1.0.3] - 2021-01-11
### Changes
- visibleInPrimaryRay default value changed to True
## [1.0.2] - 2020-12-09
### Changes
- Added extension icon
- Added readme
- Updated preview image
## [1.0.1] - 2020-10-22
### Changes
- Improved layout
## [1.0.0] - 2020-09-17
### Changes
- Created
|
omniverse-code/kit/exts/omni.kit.property.light/docs/README.md | # omni.kit.property.light
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension supports editing of these Usd Types;
- UsdLux.CylinderLight
- UsdLux.DiskLight
- UsdLux.DistantLight
- UsdLux.DomeLight
- UsdLux.GeometryLight
- UsdLux.RectLight
- UsdLux.SphereLight
- UsdLux.ShapingAPI
- UsdLux.ShadowAPI
- UsdLux.LightFilter
- UsdLux.LightPortal
### and supports editing of these Usd APIs;
- UsdLux.ListAPI
|
omniverse-code/kit/exts/omni.kit.property.light/docs/index.rst | omni.kit.property.light
###########################
Property Light Values
.. toctree::
:maxdepth: 1
CHANGELOG
|
omniverse-code/kit/exts/omni.kit.property.light/data/tests/light_test.usda | #usda 1.0
(
customLayerData = {
dictionary cameraSettings = {
dictionary Front = {
double radius = 500
double3 target = (0, 0, 0)
}
dictionary Perspective = {
double3 position = (269597.88249153644, 269547.8824915365, 269597.8824915362)
double3 target = (0, -50, 0)
}
dictionary Right = {
double radius = 500
double3 target = (0, 0, 0)
}
dictionary Top = {
double radius = 500
double3 target = (0, 0, 0)
}
string boundCamera = "/OmniverseKit_Persp"
}
dictionary omni_layer = {
dictionary muteness = {
}
}
dictionary renderSettings = {
float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562
}
}
defaultPrim = "World"
endTimeCode = 100
metersPerUnit = 0.009999999776482582
startTimeCode = 0
timeCodesPerSecond = 24
upAxis = "Y"
)
def Xform "World"
{
def Scope "Looks"
{
def Material "GroundMat"
{
token outputs:mdl:displacement.connect = </World/Looks/GroundMat/Shader.outputs:out>
token outputs:mdl:surface.connect = </World/Looks/GroundMat/Shader.outputs:out>
token outputs:mdl:volume.connect = </World/Looks/GroundMat/Shader.outputs:out>
def Shader "Shader"
{
uniform token info:implementationSource = "sourceAsset"
uniform asset info:mdl:sourceAsset = @OmniPBR.mdl@
uniform token info:mdl:sourceAsset:subIdentifier = "OmniPBR"
color3f inputs:diffuse_color_constant = (0.08, 0.08, 0.08)
color3f inputs:diffuse_tint = (1, 1, 1)
float inputs:metallic_constant = 0
float inputs:reflection_roughness_constant = 0.36
float inputs:specular_level = 0.25 (
customData = {
double default = 0.5
dictionary range = {
double max = 1
double min = 0
}
}
displayGroup = "Reflectivity"
displayName = "Specular"
)
token outputs:out
}
}
}
def Cube "GroundCube"
{
float3[] extent = [(-50, -50, -50), (50, 50, 50)]
rel material:binding = </World/Looks/GroundMat> (
bindMaterialAs = "strongerThanDescendants"
)
bool primvars:doNotCastShadows = 1
double size = 100
double3 xformOp:rotateXYZ = (0, 0, 0)
double3 xformOp:scale = (2000, 1, 2000)
double3 xformOp:translate = (0, -50, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
}
def DistantLight "DistantLight" (
prepend apiSchemas = ["ShapingAPI"]
)
{
float inputs:angle = 1
color3f inputs:color = (1, 1, 1)
float inputs:intensity = 2000
float inputs:shaping:cone:angle = 180
float inputs:shaping:cone:softness
float inputs:shaping:focus
color3f inputs:shaping:focusTint
asset inputs:shaping:ies:file
double3 xformOp:rotateXYZ = (-113.97615051269531, 14.750445365905762, 29.791282653808594)
double3 xformOp:scale = (1, 1.0000003576278687, 1.0000003576278687)
double3 xformOp:translate = (0, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
}
def DomeLight "DomeLight" (
prepend apiSchemas = ["ShapingAPI"]
)
{
float inputs:intensity = 1000
float inputs:shaping:cone:angle = 180
float inputs:shaping:cone:softness
float inputs:shaping:focus = 0
color3f shaping:focusTint = (0, 0, 0)
asset inputs:shaping:ies:file
float inputs:specular = 1
asset inputs:texture:file = @textures/sunflowers.hdr@
token inputs:texture:format = "latlong"
token visibility = "inherited"
double3 xformOp:rotateXYZ = (270, 0, 0)
double3 xformOp:scale = (1, 1, 1)
double3 xformOp:translate = (0, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
}
}
|
omniverse-code/kit/exts/omni.kit.property.light/data/tests/dome_light.usda | #usda 1.0
(
customLayerData = {
dictionary cameraSettings = {
dictionary Front = {
double3 position = (0, 0, 50000)
double radius = 500
}
dictionary Perspective = {
double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998)
double3 target = (0, 0, 0)
}
dictionary Right = {
double3 position = (-50000, 0, -1.1102230246251565e-11)
double radius = 500
}
dictionary Top = {
double3 position = (-4.329780281177466e-12, 50000, 1.1102230246251565e-11)
double radius = 500
}
string boundCamera = "/OmniverseKit_Persp"
}
dictionary omni_layer = {
dictionary muteness = {
}
}
dictionary renderSettings = {
}
}
defaultPrim = "World"
endTimeCode = 100
metersPerUnit = 0.01
startTimeCode = 0
timeCodesPerSecond = 24
upAxis = "Y"
)
def Xform "World"
{
def DomeLight "DomeLight" (
prepend apiSchemas = ["ShapingAPI"]
)
{
float inputs:intensity = 1000
float inputs:shaping:cone:angle = 180
float inputs:shaping:cone:softness
float inputs:shaping:focus
color3f inputs:shaping:focusTint
asset inputs:shaping:ies:file
token inputs:texture:format = "latlong"
double3 xformOp:rotateXYZ = (270, 0, 0)
double3 xformOp:scale = (1, 1, 1)
double3 xformOp:translate = (0, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
}
}
|
omniverse-code/kit/exts/omni.kit.audiodeviceenum/PACKAGE-LICENSES/omni.kit.audiodeviceenum-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. |
omniverse-code/kit/exts/omni.kit.audiodeviceenum/config/extension.toml | [package]
title = "Kit Audio Device Enumerator"
category = "Audio"
feature = true
version = "1.0.0"
description = "An audio device enumeration API which is available from python and C++"
authors = ["NVIDIA"]
keywords = ["audio", "device"]
[dependencies]
"carb.audio" = {}
[[native.plugin]]
path = "bin/*.plugin"
[[python.module]]
name = "omni.kit.audiodeviceenum"
|
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/__init__.py | """
This module contains bindings to the C++ omni::audio::IAudioDeviceEnum
interface. This provides functionality for enumerating available audio devices
and collecting some basic information on each one.
Sound devices attached to the system may change at any point due to user
activity (ie: connecting or unplugging a USB audio device). When enumerating
devices, it is important to collect all device information directly instead
of caching it.
The device information is suitable to be used to display to a user in a menu
to allow them to choose a device to use by name.
"""
from ._audiodeviceenum import *
# Cached audio device enumerator instance pointer
def get_audio_device_enum_interface() -> IAudioDeviceEnum:
"""
helper method to retrieve a cached version of the IAudioDeviceEnum interface.
Returns:
The cached :class:`omni.kit.audiodeviceenum.IAudioDeviceEnum` interface. This will
only be retrieved on the first call. All subsequent calls will return the cached
interface object.
"""
if not hasattr(get_audio_device_enum_interface, "audio_device_enum"):
get_audio_device_enum_interface.audio_device_enum = acquire_audio_device_enum_interface()
return get_audio_device_enum_interface.audio_device_enum
|
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/_audio.pyi | """
This module contains bindings to the C++ omni::audio::IAudioDeviceEnum
interface. This provides functionality for enumerating available audio
devices and collecting some basic information on each one.
Sound devices attached to the system may change at any point due to user
activity (ie: connecting or unplugging a USB audio device). When enumerating
devices, it is important to collect all device information directly instead
of caching it.
The device information is suitable to be used to display to a user in a menu
to allow them to choose a device to use by name.
"""
import omni.kit.audiodeviceenum._audio
import typing
__all__ = [
"Direction",
"IAudioDeviceEnum",
"SampleType",
"acquire_audio_device_enum_interface"
]
class Direction():
"""
Members:
PLAYBACK : audio playback devices only.
CAPTURE : audio capture devices only.
"""
def __init__(self, arg0: int) -> None: ...
def __int__(self) -> int: ...
@property
def name(self) -> str:
"""
(self: handle) -> str
:type: str
"""
CAPTURE: omni.kit.audiodeviceenum._audio.Direction # value = Direction.CAPTURE
PLAYBACK: omni.kit.audiodeviceenum._audio.Direction # value = Direction.PLAYBACK
__members__: dict # value = {'PLAYBACK': Direction.PLAYBACK, 'CAPTURE': Direction.CAPTURE}
pass
class IAudioDeviceEnum():
"""
This interface contains functions for audio device enumeration. This is able to
enumerate all audio devices attached to the system at any given point and collect the
information for each device. This is only intended to collect the device information
needed to display to the user for device selection purposes. If a device is to be
chosen based on certain needs (ie: channel count, frame rate, etc), it should be done
directly through the audio playback or capture context during creation. This is able
to collect information for both playback and capture devices.
All the function in this interface are in omni.kit.audio.IAudioDeviceEnum class.
To retrieve this object, use get_audio_device_enum_interface() method:
>>> import omni.kit.audio
>>> dev = omni.kit.audio.get_audio_device_enum_interface()
>>> count = dev.get_device_count(PLAYBACK)
>>> desc = dev.get_device_description(PLAYBACK, 0)
"""
def get_device_channel_count(self, dir: Direction, index: int) -> int:
"""
Retrieves the maximum channel count for a requested device.
This retrieves the maximum channel count for a requested device. This count
is the maximum number of channels that the device can natively handle without
having to trim or reprocess the data. Using a device with a different channel
count than its maximum is allowed but will result in extra processing time to
upmix or downmix channels in the stream. Note that downmixing channel counts
(ie: 7.1 to stereo) will often result in multiple channels being blended
together and can result in an unexpected final signal in certain cases.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the maximum channel count for.
index: the index of the device to retrieve the channel count for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the maximum channel count of the requested device.
If the requested device is out of range of those connected to the system, 0
is returned.
"""
def get_device_count(self, dir: Direction) -> int:
"""
Retrieves the total number of devices attached to the system of a requested type.
Args:
dir: the audio direction to get the device count for.
Returns:
If successful, this returns the total number of connected audio devices of the
requested type.
If there are no devices of the requested type connected to the system, 0 is
returned.
"""
def get_device_description(self, dir: Direction, index: int) -> object:
"""
Retrieves a descriptive string for a requested audio device.
This retrieves a descriptive string for the requested device. This string is
suitable for display to a user in a menu or selection list.
Args:
dir: the audio direction to get the description string for.
index: the index of the device to retrieve the description for. This should be
between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns a python string describing the requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_frame_rate(self, dir: Direction, index: int) -> int:
"""
Retrieves the preferred frame rate of a requested device.
This retrieves the preferred frame rate of a requested device. The preferred
frame rate is the rate at which the device natively wants to process audio data.
Using the device at other frame rates may be possible but would require extra
processing time. Using a device at a different frame rate than its preferred
one may also result in degraded quality depending on what the processing versus
preferred frame rate is.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the preferred frame rate for.
index: the index of the device to retrieve the frame rate for. This should
be between 0 and one less than the most recent return value of
getDeviceCount().
Returns:
If successful, this returns the preferred frame rate of the requested device.
If the requested device was out of range of those connected to the system, 0
is returned.
"""
def get_device_id(self, dir: Direction, index: int) -> object:
"""
Retrieves the unique identifier for the requested device.
Args:
dir: the audio direction to get the device name for.
index: the index of the device to retrieve the identifier for. This
should be between 0 and one less than the most recent return
value of getDeviceCount().
Returns:
If successful, this returns a python string containing the unique identifier
of the requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_name(self, dir: Direction, index: int) -> object:
"""
Retrieves the friendly name of a requested device.
Args:
dir: the audio direction to get the device name for.
index: the index of the device to retrieve the name for. This should be between
0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns a python string containing the friendly name of the
requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_sample_size(self, dir: Direction, index: int) -> int:
"""
Retrieves the native sample size for a requested device.
This retrieves the bits per sample that a requested device prefers to process
its data at. It may be possible to use the device at a different sample size,
but that would likely result in extra processing time. Using a device at a
different sample rate than its native could degrade the quality of the final
signal.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the native sample size for.
index: the index of the device to retrieve the sample size for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the native sample size in bits per sample of the
requested device.
If the requested device is out of range of those connected to the system, 0
is returned.
"""
def get_device_sample_type(self, dir: Direction, index: int) -> SampleType:
"""
Retrieves the native sample data type for a requested device.
This retrieves the sample data type that a requested device prefers to process
its data in. It may be possible to use the device with a different data type,
but that would likely result in extra processing time. Using a device with a
different sample data type than its native could degrade the quality of the
final signal.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the native sample data type for.
index: the index of the device to retrieve the sample data type for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the native sample data type of the requested device.
If the requested device is out of range of those connected to the system,
UNKNOWN is returned.
"""
def is_direct_hardware_backend(self) -> bool:
"""
/** Check if the audio device backend uses direct hardware access.
*
* A direct hardware audio backend is capable of exclusively locking audio
* devices, so devices are not guaranteed to open successfully and opening
* devices to test their format may be disruptive to the system.
*
* ALSA is the only 'direct hardware' backend that's currently supported.
* Some devices under ALSA will exclusively lock the audio device; these
* may fail to open because they're busy.
* Additionally, some devices under ALSA can fail to open because they're
* misconfigured (Ubuntu's default ALSA configuration can contain
* misconfigured devices).
* In addition to this, opening some devices under ALSA can take a
* substantial amount of time (over 100ms).
* For these reasons, it is important to verify that you are not using a
* 'direct hardware' backend if you are going to call certain functions in
* this interface.
*
* Args:
* No arguments.
*
* Returns:
* This returns `True` if this backend has direct hardware access.
* This will be returned when ALSA is in use.
* This returns `False` if the backend is an audio mixing server.
* This will be returned when Pulse Audio or Window Audio Services
* are in use.
"""
pass
class SampleType():
"""
Members:
UNKNOWN : could not determine the same type or an invalid device index.
PCM_SIGNED_INTEGER : signed integer PCM samples.
PCM_UNSIGNED_INTEGER : unsigned integer PCM samples.
PCM_FLOAT : single precision floating point PCM samples.
COMPRESSED : a compressed sample format.
"""
def __init__(self, arg0: int) -> None: ...
def __int__(self) -> int: ...
@property
def name(self) -> str:
"""
(self: handle) -> str
:type: str
"""
COMPRESSED: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.COMPRESSED
PCM_FLOAT: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.PCM_FLOAT
PCM_SIGNED_INTEGER: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.PCM_SIGNED_INTEGER
PCM_UNSIGNED_INTEGER: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.PCM_UNSIGNED_INTEGER
UNKNOWN: omni.kit.audiodeviceenum._audio.SampleType # value = SampleType.UNKNOWN
__members__: dict # value = {'UNKNOWN': SampleType.UNKNOWN, 'PCM_SIGNED_INTEGER': SampleType.PCM_SIGNED_INTEGER, 'PCM_UNSIGNED_INTEGER': SampleType.PCM_UNSIGNED_INTEGER, 'PCM_FLOAT': SampleType.PCM_FLOAT, 'COMPRESSED': SampleType.COMPRESSED}
pass
def acquire_audio_device_enum_interface(plugin_name: str = None, library_path: str = None) -> IAudioDeviceEnum:
pass
|
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/_audiodeviceenum.pyi | """
This module contains bindings to the C++ omni::audio::IAudioDeviceEnum
interface. This provides functionality for enumerating available audio
devices and collecting some basic information on each one.
Sound devices attached to the system may change at any point due to user
activity (ie: connecting or unplugging a USB audio device). When enumerating
devices, it is important to collect all device information directly instead
of caching it.
The device information is suitable to be used to display to a user in a menu
to allow them to choose a device to use by name.
"""
from __future__ import annotations
import omni.kit.audiodeviceenum._audiodeviceenum
import typing
__all__ = [
"Direction",
"IAudioDeviceEnum",
"SampleType",
"acquire_audio_device_enum_interface"
]
class Direction():
"""
Members:
PLAYBACK : audio playback devices only.
CAPTURE : audio capture devices only.
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
CAPTURE: omni.kit.audiodeviceenum._audiodeviceenum.Direction # value = <Direction.CAPTURE: 1>
PLAYBACK: omni.kit.audiodeviceenum._audiodeviceenum.Direction # value = <Direction.PLAYBACK: 0>
__members__: dict # value = {'PLAYBACK': <Direction.PLAYBACK: 0>, 'CAPTURE': <Direction.CAPTURE: 1>}
pass
class IAudioDeviceEnum():
"""
This interface contains functions for audio device enumeration. This is able to
enumerate all audio devices attached to the system at any given point and collect the
information for each device. This is only intended to collect the device information
needed to display to the user for device selection purposes. If a device is to be
chosen based on certain needs (ie: channel count, frame rate, etc), it should be done
directly through the audio playback or capture context during creation. This is able
to collect information for both playback and capture devices.
All the function in this interface are in omni.kit.audio.IAudioDeviceEnum class.
To retrieve this object, use get_audio_device_enum_interface() method:
>>> import omni.kit.audio
>>> dev = omni.kit.audio.get_audio_device_enum_interface()
>>> count = dev.get_device_count(PLAYBACK)
>>> desc = dev.get_device_description(PLAYBACK, 0)
"""
def get_device_channel_count(self, dir: Direction, index: int) -> int:
"""
Retrieves the maximum channel count for a requested device.
This retrieves the maximum channel count for a requested device. This count
is the maximum number of channels that the device can natively handle without
having to trim or reprocess the data. Using a device with a different channel
count than its maximum is allowed but will result in extra processing time to
upmix or downmix channels in the stream. Note that downmixing channel counts
(ie: 7.1 to stereo) will often result in multiple channels being blended
together and can result in an unexpected final signal in certain cases.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the maximum channel count for.
index: the index of the device to retrieve the channel count for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the maximum channel count of the requested device.
If the requested device is out of range of those connected to the system, 0
is returned.
"""
def get_device_count(self, dir: Direction) -> int:
"""
Retrieves the total number of devices attached to the system of a requested type.
Args:
dir: the audio direction to get the device count for.
Returns:
If successful, this returns the total number of connected audio devices of the
requested type.
If there are no devices of the requested type connected to the system, 0 is
returned.
"""
def get_device_description(self, dir: Direction, index: int) -> object:
"""
Retrieves a descriptive string for a requested audio device.
This retrieves a descriptive string for the requested device. This string is
suitable for display to a user in a menu or selection list.
Args:
dir: the audio direction to get the description string for.
index: the index of the device to retrieve the description for. This should be
between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns a python string describing the requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_frame_rate(self, dir: Direction, index: int) -> int:
"""
Retrieves the preferred frame rate of a requested device.
This retrieves the preferred frame rate of a requested device. The preferred
frame rate is the rate at which the device natively wants to process audio data.
Using the device at other frame rates may be possible but would require extra
processing time. Using a device at a different frame rate than its preferred
one may also result in degraded quality depending on what the processing versus
preferred frame rate is.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the preferred frame rate for.
index: the index of the device to retrieve the frame rate for. This should
be between 0 and one less than the most recent return value of
getDeviceCount().
Returns:
If successful, this returns the preferred frame rate of the requested device.
If the requested device was out of range of those connected to the system, 0
is returned.
"""
def get_device_id(self, dir: Direction, index: int) -> object:
"""
Retrieves the unique identifier for the requested device.
Args:
dir: the audio direction to get the device name for.
index: the index of the device to retrieve the identifier for. This
should be between 0 and one less than the most recent return
value of getDeviceCount().
Returns:
If successful, this returns a python string containing the unique identifier
of the requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_name(self, dir: Direction, index: int) -> object:
"""
Retrieves the friendly name of a requested device.
Args:
dir: the audio direction to get the device name for.
index: the index of the device to retrieve the name for. This should be between
0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns a python string containing the friendly name of the
requested device.
If the requested device is out of range of those connected to the system, this
returns None.
"""
def get_device_sample_size(self, dir: Direction, index: int) -> int:
"""
Retrieves the native sample size for a requested device.
This retrieves the bits per sample that a requested device prefers to process
its data at. It may be possible to use the device at a different sample size,
but that would likely result in extra processing time. Using a device at a
different sample rate than its native could degrade the quality of the final
signal.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the native sample size for.
index: the index of the device to retrieve the sample size for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the native sample size in bits per sample of the
requested device.
If the requested device is out of range of those connected to the system, 0
is returned.
"""
def get_device_sample_type(self, dir: Direction, index: int) -> SampleType:
"""
Retrieves the native sample data type for a requested device.
This retrieves the sample data type that a requested device prefers to process
its data in. It may be possible to use the device with a different data type,
but that would likely result in extra processing time. Using a device with a
different sample data type than its native could degrade the quality of the
final signal.
This function will open the audio device to test on some systems. The
caller should ensure that isDirectHardwareBackend() returns false
before calling this.
Args:
dir: the audio direction to get the native sample data type for.
index: the index of the device to retrieve the sample data type for. This should
be between 0 and one less than the most recent return value of getDeviceCount().
Returns:
If successful, this returns the native sample data type of the requested device.
If the requested device is out of range of those connected to the system,
UNKNOWN is returned.
"""
def is_direct_hardware_backend(self) -> bool:
"""
/** Check if the audio device backend uses direct hardware access.
*
* A direct hardware audio backend is capable of exclusively locking audio
* devices, so devices are not guaranteed to open successfully and opening
* devices to test their format may be disruptive to the system.
*
* ALSA is the only 'direct hardware' backend that's currently supported.
* Some devices under ALSA will exclusively lock the audio device; these
* may fail to open because they're busy.
* Additionally, some devices under ALSA can fail to open because they're
* misconfigured (Ubuntu's default ALSA configuration can contain
* misconfigured devices).
* In addition to this, opening some devices under ALSA can take a
* substantial amount of time (over 100ms).
* For these reasons, it is important to verify that you are not using a
* 'direct hardware' backend if you are going to call certain functions in
* this interface.
*
* Args:
* No arguments.
*
* Returns:
* This returns `True` if this backend has direct hardware access.
* This will be returned when ALSA is in use.
* This returns `False` if the backend is an audio mixing server.
* This will be returned when Pulse Audio or Window Audio Services
* are in use.
"""
pass
class SampleType():
"""
Members:
UNKNOWN : could not determine the same type or an invalid device index.
PCM_SIGNED_INTEGER : signed integer PCM samples.
PCM_UNSIGNED_INTEGER : unsigned integer PCM samples.
PCM_FLOAT : single precision floating point PCM samples.
COMPRESSED : a compressed sample format.
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
COMPRESSED: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.COMPRESSED: 4>
PCM_FLOAT: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.PCM_FLOAT: 3>
PCM_SIGNED_INTEGER: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.PCM_SIGNED_INTEGER: 1>
PCM_UNSIGNED_INTEGER: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.PCM_UNSIGNED_INTEGER: 2>
UNKNOWN: omni.kit.audiodeviceenum._audiodeviceenum.SampleType # value = <SampleType.UNKNOWN: 0>
__members__: dict # value = {'UNKNOWN': <SampleType.UNKNOWN: 0>, 'PCM_SIGNED_INTEGER': <SampleType.PCM_SIGNED_INTEGER: 1>, 'PCM_UNSIGNED_INTEGER': <SampleType.PCM_UNSIGNED_INTEGER: 2>, 'PCM_FLOAT': <SampleType.PCM_FLOAT: 3>, 'COMPRESSED': <SampleType.COMPRESSED: 4>}
pass
def acquire_audio_device_enum_interface(plugin_name: str = None, library_path: str = None) -> IAudioDeviceEnum:
pass
|
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/tests/test_device.py | import omni.kit.test
import omni.kit.audiodeviceenum
def get_name_from_sample_type(sample_type): # pragma: no cover
if sample_type == omni.kit.audiodeviceenum.SampleType.UNKNOWN:
return "UNKNOWN"
if sample_type == omni.kit.audiodeviceenum.SampleType.PCM_SIGNED_INTEGER:
return "INT PCM"
if sample_type == omni.kit.audiodeviceenum.SampleType.PCM_UNSIGNED_INTEGER:
return "UINT PCM"
if sample_type == omni.kit.audiodeviceenum.SampleType.PCM_FLOAT:
return "FLOAT PCM"
if sample_type == omni.kit.audiodeviceenum.SampleType.COMPRESSED:
return "COMPRESSED"
class TestAudio(omni.kit.test.AsyncTestCase): # pragma: no cover
async def test_audio_device(self):
audio = omni.kit.audiodeviceenum.get_audio_device_enum_interface()
self.assertIsNotNone(audio)
count = audio.get_device_count(omni.kit.audiodeviceenum.Direction.PLAYBACK)
self.assertGreaterEqual(count, 0)
printDevices = 0
if printDevices != 0:
print("Found ", count, " Available Playback Devices:")
if count > 0:
for i in range(0, count):
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertIsNotNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertIsNotNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertIsNotNone(uniqueId)
if not audio.is_direct_hardware_backend():
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertGreater(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertGreater(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
self.assertGreater(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.PLAYBACK, i)
if printDevices != 0:
str_desc = " found the device '" + name + "' "
str_desc += "{" + str(channel_count) + " channels "
str_desc += "@ " + str(frame_rate) + "Hz "
str_desc += str(sample_size) + "-bit " + get_name_from_sample_type(sample_type)
print(str_desc)
print(" " + desc)
else:
if printDevices != 0:
print(" found the device '" + name + "' ")
print(" " + desc)
# make sure out of range values fail.
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertIsNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertIsNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertIsNone(uniqueId)
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.PLAYBACK, count)
self.assertEqual(sample_type, omni.kit.audiodeviceenum.SampleType.UNKNOWN)
count = audio.get_device_count(omni.kit.audiodeviceenum.Direction.CAPTURE)
self.assertGreaterEqual(count, 0)
if printDevices != 0:
print("\nFound ", count, " Available Capture Devices:")
if count > 0:
for i in range(0, count):
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertIsNotNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertIsNotNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertIsNotNone(uniqueId)
if not audio.is_direct_hardware_backend():
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertGreater(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertGreater(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
self.assertGreater(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.CAPTURE, i)
if printDevices != 0:
str_desc = " found the device '" + name + "' "
str_desc += "{" + str(channel_count) + " channels "
str_desc += "@ " + str(frame_rate) + "Hz "
str_desc += str(sample_size) + "-bit " + get_name_from_sample_type(sample_type)
print(str_desc)
print(" " + desc)
else:
if printDevices != 0:
print(" found the device '" + name + "' ")
print(" " + desc)
# make sure out of range values fail.
desc = audio.get_device_description(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertIsNone(desc)
name = audio.get_device_name(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertIsNone(name)
uniqueId = audio.get_device_id(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertIsNone(uniqueId)
frame_rate = audio.get_device_frame_rate(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(frame_rate, 0)
channel_count = audio.get_device_channel_count(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(channel_count, 0)
sample_size = audio.get_device_sample_size(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(sample_size, 0)
sample_type = audio.get_device_sample_type(omni.kit.audiodeviceenum.Direction.CAPTURE, count)
self.assertEqual(sample_type, omni.kit.audiodeviceenum.SampleType.UNKNOWN)
|
omniverse-code/kit/exts/omni.kit.audiodeviceenum/omni/kit/audiodeviceenum/tests/__init__.py | from .test_device import * # pragma: no cover
|
omniverse-code/kit/exts/omni.kit.window.cursor/PACKAGE-LICENSES/omni.kit.window.cursor-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. |
omniverse-code/kit/exts/omni.kit.window.cursor/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.1.1"
# 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 = "Window Cursor Extension"
description="Extension to manage main window cursor."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Internal"
# Keywords for the extension
keywords = ["kit", "cursor"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# We only depend on testing framework currently:
[dependencies]
"omni.appwindow" = {}
"omni.ui" = {}
# Main python module this extension provides, it will be publicly available as "import omni.example.hello".
[[python.module]]
name = "omni.kit.window.cursor"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
]
dependencies = [
"omni.kit.mainwindow"
]
|
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/cursor.py | # 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.
#
from pathlib import Path
from carb import windowing, log_warn
import omni.ext
import weakref
EXTEND_CURSOR_GRAB_OPEN = "Grab_open"
EXTEND_CURSOR_GRAB_CLOSE = "Grab_close"
EXTEND_CURSOR_PAN_FILE = "cursorPan.png"
EXTEND_CURSOR_PAN_CLOSE_FILE = "cursorPanClosed.png"
main_window_cursor = None
def get_main_window_cursor():
return main_window_cursor
def get_icon_path(path: str):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
icon_path = Path(extension_path).joinpath("data").joinpath("icons").joinpath(path)
return str(icon_path)
class WindowCursor(omni.ext.IExt):
def __init__(self):
self._imgui_renderer = None
self._app_window = None
super().__init__()
def on_startup(self, ext_id):
global main_window_cursor
main_window_cursor = weakref.proxy(self)
try:
import omni.kit.imgui_renderer
import omni.appwindow
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
self._app_window = omni.appwindow.get_default_app_window()
except Exception:
# Currently need both of these for further API usage, which can't happen now; so clear them both out
self._imgui_renderer, self._app_window = None, None
log_warn("omni.kit.window.cursor failed to initialize properly, changing cursor with it will not work")
import traceback
log_warn(f"{traceback.format_exc()}")
self._app_ready_sub = omni.kit.app.get_app().get_startup_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY,
self._on_app_ready,
)
def on_shutdown(self):
if self._imgui_renderer:
self._imgui_renderer.unregister_cursor_shape_extend(EXTEND_CURSOR_GRAB_OPEN)
self._imgui_renderer.unregister_cursor_shape_extend(EXTEND_CURSOR_GRAB_CLOSE)
global main_window_cursor
main_window_cursor = None
self._imgui_renderer = None
self._app_window = None
self._app_ready_sub = None
def _on_app_ready(self, event):
if self._imgui_renderer:
self._imgui_renderer.register_cursor_shape_extend(EXTEND_CURSOR_GRAB_OPEN, get_icon_path(EXTEND_CURSOR_PAN_FILE))
self._imgui_renderer.register_cursor_shape_extend(EXTEND_CURSOR_GRAB_CLOSE, get_icon_path(EXTEND_CURSOR_PAN_CLOSE_FILE))
def override_cursor_shape_extend(self, shape_name: str):
if self._app_window and self._imgui_renderer:
self._imgui_renderer.set_cursor_shape_override_extend(self._app_window, shape_name)
return True
return False
def override_cursor_shape(self, shape: windowing.CursorStandardShape):
if self._app_window and self._imgui_renderer:
self._imgui_renderer.set_cursor_shape_override(self._app_window, shape)
return True
return False
def clear_overridden_cursor_shape(self):
if self._app_window and self._imgui_renderer:
self._imgui_renderer.clear_cursor_shape_override(self._app_window)
return True
return False
def get_cursor_shape_override_extend(self):
if self._app_window and self._imgui_renderer:
return self._imgui_renderer.get_cursor_shape_override_extend(self._app_window)
return None
def get_cursor_shape_override(self):
if self._app_window and self._imgui_renderer:
return self._imgui_renderer.get_cursor_shape_override(self._app_window)
return None
|
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/__init__.py | from .cursor import *
|
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/tests/tests.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.imgui
import carb.input
import carb.windowing
import omni.appwindow
import omni.kit.app
import omni.kit.test
import omni.kit.window.cursor
import omni.kit.imgui_renderer
import omni.ui as ui
class TestCursorShape(omni.kit.test.AsyncTestCase):
async def setUp(self):
app_window = omni.appwindow.get_default_app_window()
self._mouse = app_window.get_mouse()
self._app = omni.kit.app.get_app()
self._cursor = omni.kit.window.cursor.get_main_window_cursor()
self._input_provider = carb.input.acquire_input_provider()
self._imgui = carb.imgui.acquire_imgui()
self._windowing = carb.windowing.acquire_windowing_interface()
self._os_window = app_window.get_window()
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
await self._build_test_windows()
async def tearDown(self):
self._os_window = None
self._windowing = None
self._imgui = None
self._window = None
self._dock_window_1 = None
self._dock_window_2 = None
self._imgui_renderer = None
async def test_cursor_shape(self):
main_dockspace = ui.Workspace.get_window("DockSpace")
width = main_dockspace.width
height = main_dockspace.height
await self._wait()
await self._move_and_test_cursor_shape((width / 2, 1), carb.imgui.MouseCursor.ARROW)
# Put on StringField and test IBeam shape
await self._move_and_test_cursor_shape((width / 2, height / 4), carb.imgui.MouseCursor.TEXT_INPUT)
# Put on vertical split and test HORIZONTAL_RESIZE
await self._move_and_test_cursor_shape(
(width / 2 + 1, height * 3 / 4),
carb.imgui.MouseCursor.RESIZE_EW,
)
# Put on horizontal split and test VERTICAL_RESIZE
await self._move_and_test_cursor_shape(
(width * 3 / 4, height / 2 + 1),
carb.imgui.MouseCursor.RESIZE_NS,
)
await self._wait()
# test override_cursor_shape_extend and get_cursor_shape_override_extend
test_extend_shapes = [
"IBeam",
"Grab_close",
"Crosshair",
"Grab_open",
]
for cursor_shape in test_extend_shapes:
self._cursor.override_cursor_shape_extend(cursor_shape)
await self._wait(100)
cur_cursor = self._cursor.get_cursor_shape_override_extend()
self.assertEqual(cur_cursor, cursor_shape)
# test override_cursor_shape and get_cursor_shape_override
test_shapes = [
carb.windowing.CursorStandardShape.CROSSHAIR,
carb.windowing.CursorStandardShape.IBEAM,
]
for cursor_shape in test_shapes:
self._cursor.override_cursor_shape(cursor_shape)
await self._wait(100)
cur_cursor = self._cursor.get_cursor_shape_override()
self.assertEqual(cur_cursor, cursor_shape)
all_shapes = self._imgui_renderer.get_all_cursor_shape_names()
print(all_shapes)
self._cursor.clear_overridden_cursor_shape()
await self._wait()
async def _move_and_test_cursor_shape(self, pos, cursor: carb.imgui.MouseCursor):
# Available options:
# carb.imgui.MouseCursor.ARROW: carb.windowing.CursorStandardShape.ARROW,
# carb.imgui.MouseCursor.TEXT_INPUT: carb.windowing.CursorStandardShape.IBEAM,
# carb.imgui.MouseCursor.RESIZE_NS: carb.windowing.CursorStandardShape.VERTICAL_RESIZE,
# carb.imgui.MouseCursor.RESIZE_EW: carb.windowing.CursorStandardShape.HORIZONTAL_RESIZE,
# carb.imgui.MouseCursor.HAND: carb.windowing.CursorStandardShape.HAND,
# carb.imgui.MouseCursor.CROSSHAIR: carb.windowing.CursorStandardShape.CROSSHAIR,
self._input_provider.buffer_mouse_event(self._mouse, carb.input.MouseEventType.MOVE, pos, 0, pos)
self._windowing.set_cursor_position(self._os_window, carb.Int2(*[int(p) for p in pos]))
await self._wait()
imgui_cursor = self._imgui.get_mouse_cursor()
self.assertEqual(cursor, imgui_cursor, f"Expect {cursor} but got {imgui_cursor}")
# build a dockspace with windows/widgets to test various cursor shape from imgui
async def _build_test_windows(self):
import omni.ui as ui
self._window = ui.Window("CursorShapeTest")
with self._window.frame:
with ui.ZStack():
with ui.Placer(offset_x=0, offset_y=10):
ui.StringField()
self._dock_window_1 = ui.Window("DockWindow1")
self._dock_window_2 = ui.Window("DockWindow2")
await self._app.next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window_handle = ui.Workspace.get_window("CursorShapeTest")
dock_window_handle1 = ui.Workspace.get_window("DockWindow1")
dock_window_handle2 = ui.Workspace.get_window("DockWindow2")
window_handle.dock_in(main_dockspace, ui.DockPosition.SAME)
dock_window_handle1.dock_in(window_handle, ui.DockPosition.BOTTOM, 0.5)
dock_window_handle2.dock_in(dock_window_handle1, ui.DockPosition.RIGHT, 0.5)
async def _wait(self, num=8):
for i in range(num):
await self._app.next_update_async() |
omniverse-code/kit/exts/omni.kit.window.cursor/omni/kit/window/cursor/tests/__init__.py | from .tests import *
|
omniverse-code/kit/exts/omni.kit.window.cursor/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.kit.window.cursor`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`.
## [1.1.1] - 2022-09-26
### Changed
- Store weakly referenced proxy to extension object.
- Handle possiblity of lower level API failure better.
- Return value of success for changing / restoring the cursor.
## [1.1.0] - 2022-05-06
### Changed
- Using `IImGuiRenderer` to override the mouse cursor
## [1.0.1] - 2021-03-01
### Added
- Added tests.
## [1.0.0] - 2020-11-06
### Added
- Initial extensions.
|
omniverse-code/kit/exts/omni.kit.window.cursor/docs/README.md | # Cursor Extension [omni.kit.window.cursor]
This is an extension to manager cursor shape.
|
omniverse-code/kit/exts/omni.kit.window.cursor/docs/index.rst | omni.kit.window.cursor
###########################
.. toctree::
:maxdepth: 1
CHANGELOG
|
omniverse-code/kit/exts/omni.kit.widget.live/PACKAGE-LICENSES/omni.kit.widget.live-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. |
omniverse-code/kit/exts/omni.kit.widget.live/config/extension.toml | [package]
version = "2.0.3"
title = "Kit Live Mode Control Widget"
category = "Internal"
changelog = "docs/CHANGELOG.md"
feature = true
keywords = ["live", "session"]
authors = ["NVIDIA"]
repository = ""
[dependencies]
"omni.usd" = {}
"omni.client" = {}
"omni.ui" = {}
"omni.kit.usd.layers" = {}
"omni.kit.menu.utils" = {}
"omni.kit.widget.live_session_management" = {}
[[python.module]]
name = "omni.kit.widget.live"
[settings]
exts."omni.kit.widget.live".enable_server_tests = false
[[test]]
args = [
"--/app/asyncRendering=false",
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/app/file/ignoreUnsavedOnExit=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=false",
"--no-window"
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.commands",
"omni.kit.selection",
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers"
]
stdoutFailPatterns.include = []
stdoutFailPatterns.exclude = [] |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/cache_state_menu.py | import asyncio
import aiohttp
import carb
import os
import toml
import time
import omni.client
import webbrowser
from omni.kit.menu.utils import MenuItemDescription, MenuAlignment
from omni import ui
from typing import Union
from .style import Styles
class CacheStateDelegate(ui.MenuDelegate):
def __init__(self, cache_enabled, **kwargs):
super().__init__(**kwargs)
self._cache_enabled = cache_enabled
self._cache_widget = None
def destroy(self):
self._cache_widget = None
def build_item(self, item: ui.MenuHelper):
with ui.HStack(width=0, style={"margin" : 0}):
ui.Spacer(width=5)
self._cache_widget = ui.HStack(content_clipping=1, width=0, style=Styles.CACHE_STATE_ITEM_STYLE)
ui.Spacer(width=10)
self.update_live_state(self._cache_enabled)
def get_menu_alignment(self):
return MenuAlignment.RIGHT
def update_menu_item(self, menu_item: Union[ui.Menu, ui.MenuItem], menu_refresh: bool):
if isinstance(menu_item, ui.MenuItem):
menu_item.visible = False
def update_live_state(self, cache_enabled):
if not self._cache_widget:
return
margin = 2
self._cache_enabled = cache_enabled
self._cache_widget.clear()
with self._cache_widget:
ui.Label("CACHE: ")
if cache_enabled:
ui.Label("ON", style={"color": 0xff00b86b})
else:
with ui.VStack():
ui.Spacer(height=margin)
with ui.ZStack(width=0):
with ui.HStack(width=20):
ui.Spacer()
ui.Label("OFF", name="offline", width=0)
ui.Spacer(width=margin)
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=14, height=14, name="doc")
ui.Spacer()
ui.Spacer()
button = ui.InvisibleButton(width=20)
button.set_clicked_fn(lambda: webbrowser.open('https://docs.omniverse.nvidia.com/nucleus/cache_troubleshoot.html', new=2))
ui.Spacer(height=margin)
class CacheStateMenu:
def __init__(self):
self._live_menu_name = "Cache State Widget"
self._menu_list = [MenuItemDescription(name="placeholder", show_fn=lambda: False)]
global_config_path = carb.tokens.get_tokens_interface().resolve("${omni_global_config}")
self._omniverse_config_path = os.path.join(global_config_path, "omniverse.toml").replace("\\", "/")
self._all_cache_apis = []
self._cache_enabled = False
self._last_time_check = 0
self._ping_cache_future = None
self._update_subscription = None
def _initialize(self):
if os.path.exists(self._omniverse_config_path):
try:
contents = toml.load(self._omniverse_config_path)
except Exception as e:
carb.log_error(f"Unable to parse {self._omniverse_config_path}. File corrupted?")
contents = None
if contents:
self._all_cache_apis = self._load_all_cache_server_apis(contents)
if self._all_cache_apis:
self._cache_enabled = True
self._update_subscription = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(
self._on_update, name="omni.kit.widget.live update"
)
else:
carb.log_warn("Unable to detect Omniverse Cache Server. Consider installing it for better IO performance.")
self._cache_enabled = False
else:
carb.log_warn(f"Unable to detect Omniverse Cache Server. File {self._omniverse_config_path} is not found."
f" Consider installing it for better IO performance.")
def register_menu_widgets(self):
self._initialize()
self._cache_state_delegate = CacheStateDelegate(self._cache_enabled)
omni.kit.menu.utils.add_menu_items(self._menu_list, name=self._live_menu_name, delegate=self._cache_state_delegate)
def unregister_menu_widgets(self):
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._live_menu_name)
if self._cache_state_delegate:
self._cache_state_delegate.destroy()
self._cache_state_delegate = None
self._menu_list = None
self._update_subscription = None
self._all_cache_apis = []
try:
if self._ping_cache_future and not self._ping_cache_future.done():
self._ping_cache_future.cancel()
self._ping_cache_future = None
except Exception:
self._ping_cache_future = None
def _on_update(self, dt):
if not self._cache_state_delegate or not self._all_cache_apis:
return
if not self._ping_cache_future or self._ping_cache_future.done():
now = time.time()
duration = now - self._last_time_check
# 30s
if duration < 30:
return
self._last_time_check = now
async def _ping_cache():
session = aiohttp.ClientSession()
cache_enabled = None
for cache_api in self._all_cache_apis:
try:
async with session.head(cache_api):
''' If we're here the service port is alive '''
cache_enabled = True
except Exception as e:
cache_enabled = False
break
await session.close()
if cache_enabled is not None and self._cache_enabled != cache_enabled:
self._cache_enabled = cache_enabled
if self._cache_state_delegate:
self._cache_state_delegate.update_live_state(self._cache_enabled)
self._ping_cache_future = asyncio.ensure_future(_ping_cache())
def _load_all_cache_server_apis(self, config_contents):
mapping = os.environ.get("OMNI_CONN_CACHE", None)
if mapping:
mapping = f"*#{mapping},f"
else:
mapping = os.environ.get("OMNI_CONN_REDIRECTION_DICT", None)
if not mapping:
mapping = os.environ.get("OM_REDIRECTION_DICT", None)
if not mapping:
connection_library_dict = config_contents.get("connection_library", None)
if connection_library_dict:
mapping = connection_library_dict.get("proxy_dict", None)
all_proxy_apis = set([])
if mapping:
mapping = mapping.lstrip("\"")
mapping = mapping.rstrip("\"")
mapping = mapping.lstrip("'")
mapping = mapping.rstrip("'")
redirections = mapping.split(";")
for redirection in redirections:
parts = redirection.split("#")
if not parts or len(parts) < 2:
continue
source, target = parts[0], parts[1]
targets = target.split(",")
if not targets:
continue
if len(targets) > 1:
proxy_address = targets[0]
else:
proxy_address = target
if not proxy_address.startswith("http://") and not proxy_address.startswith("https://"):
proxy_address_api = f"http://{proxy_address}/ping"
else:
if proxy_address.endswith("/"):
proxy_address_api = f"{proxy_address}ping"
else:
proxy_address_api = f"{proxy_address}/ping"
all_proxy_apis.add(proxy_address_api)
return all_proxy_apis
|
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/style.py | from .icons import Icons
class Styles:
CACHE_STATE_ITEM_STYLE = None
LIVE_STATE_ITEM_STYLE = None
@staticmethod
def on_startup():
# It needs to delay initialization of style as icons need to be initialized firstly.
Styles.CACHE_STATE_ITEM_STYLE = {
"Image::doc": {"image_url": Icons.get("docs"), "color": 0xB04B4BFF},
"Label::offline": {"color": 0xB04B4BFF},
"Rectangle::offline": {"border_radius": 2.0},
"Rectangle::offline": {"background_color": 0xff808080},
"Rectangle::offline:hovered": {"background_color": 0xFF9E9E9E},
}
Styles.LIVE_STATE_ITEM_STYLE = {
"Label": {"color": 0xffffffff},
"Image::lightning": {"image_url": Icons.get("lightning")},
"Image::arrow_down": {"image_url": Icons.get("arrow_down"), "color": 0xffffffff},
"Rectangle": {"border_radius": 2.0},
"Rectangle:hovered": {"background_color": 0xFF9E9E9E},
"Rectangle::offline": {"background_color": 0xff808080},
"Rectangle::live": {"background_color": 0xff00b86b}
}
|
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.usd
import omni.ext
import omni.kit.app
from .live_state_menu import LiveStateMenu
from .icons import Icons
from .style import Styles
class OmniLiveWidgetExtension(omni.ext.IExt):
def on_startup(self, ext_id):
extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
Icons.on_startup(extension_path)
Styles.on_startup()
usd_context = omni.usd.get_context()
self._live_state_menu = LiveStateMenu(usd_context)
self._live_state_menu.register_menu_widgets()
def on_shutdown(self):
self._live_state_menu.unregister_menu_widgets()
Icons.on_shutdown()
|
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/live_state_menu.py | import carb
import omni.usd
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.widget.live_session_management as lsm
from functools import partial
from omni.kit.menu.utils import MenuItemDescription, MenuAlignment
from omni.ui import color as cl
from typing import Union
from .style import Styles
class LiveStateDelegate(ui.MenuDelegate):
def __init__(self, layers_interface, **kwargs):
super().__init__(**kwargs)
self._layers = layers_interface
self._live_syncing = layers_interface.get_live_syncing()
self._usd_context = self._live_syncing.usd_context
self._live_background = None
self._drop_down_background = None
self._live_button = None
self._drop_down_button = None
self._live_session_user_list_widget = None
self._layers_event_subs = []
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
]:
layers_event_sub = self._layers.get_event_stream().create_subscription_to_pop_by_type(
event, self._on_layer_event, name=f"omni.kit.widget.live {str(event)}"
)
self._layers_event_subs.append(layers_event_sub)
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="omni.kit.widget.live stage event"
)
def destroy(self):
if self._live_button:
self._live_button.set_clicked_fn(None)
self._live_button = None
if self._drop_down_button:
self._drop_down_button.set_clicked_fn(None)
self._drop_down_button = None
if self._live_session_user_list_widget:
self._live_session_user_list_widget.destroy()
self._live_session_user_list_widget = None
self._live_syncing = None
self._layers_event_subs = []
self._stage_event_sub = None
def _on_layer_event(self, event: carb.events.IEvent):
payload = layers.get_layer_event_payload(event)
if not payload:
return
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self._usd_context.get_stage_url()):
return
self.__update_live_state()
elif (
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED or
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT
):
if not payload.is_layer_influenced(self._usd_context.get_stage_url()):
return
self.__update_live_tooltip()
def _on_stage_event(self, event: carb.events.IEvent):
if event.type == int(omni.usd.StageEventType.OPENED):
if self._live_session_user_list_widget:
self._live_session_user_list_widget.track_layer(self._usd_context.get_stage_url())
def _on_live_widget_button_clicked(self, button, show_options):
menu_widget = lsm.stop_or_show_live_session_widget(
self._live_syncing.usd_context,
not show_options,
False,
show_options
)
if not menu_widget:
return
# Try to align it with the button.
drop_down_x = button.screen_position_x
drop_down_y = button.screen_position_y
drop_down_height = button.computed_height
# FIXME: The width of context menu cannot be got. Using fixed width here.
menu_widget.show_at(
drop_down_x - 94,
drop_down_y + drop_down_height + 2
)
def build_item(self, item: ui.MenuHelper):
margin = 2
with ui.HStack(width=0, style={"margin" : 0}):
with ui.HStack(content_clipping=1, width=0, style=Styles.LIVE_STATE_ITEM_STYLE):
with ui.VStack():
ui.Spacer(height=margin)
self.__build_user_list()
ui.Spacer(height=margin)
ui.Spacer(width=2 * margin)
with ui.VStack():
ui.Spacer(height=margin)
with ui.ZStack(width=0):
self._live_background = ui.Rectangle(width=50, name="offline")
with ui.HStack(width=50):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=14, height=14, name="lightning")
ui.Spacer()
ui.Spacer(width=margin)
ui.Label("LIVE", width=0)
ui.Spacer()
self._live_button = ui.InvisibleButton(width=50, identifier="live_button")
self._live_button.set_clicked_fn(
partial(self._on_live_widget_button_clicked, self._live_button, False)
)
ui.Spacer(height=margin)
ui.Spacer(width=margin)
with ui.VStack():
ui.Spacer(height=margin)
with ui.ZStack(width=0):
self._drop_down_background = ui.Rectangle(width=16, name="offline")
with ui.HStack(width=16):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=14, height=14, name="arrow_down")
ui.Spacer()
ui.Spacer()
self._drop_down_button = ui.InvisibleButton(width=16, identifier="drop_down_button")
self._drop_down_button.set_clicked_fn(
partial(self._on_live_widget_button_clicked, self._drop_down_button, True)
)
ui.Spacer(height=margin)
ui.Spacer(width=8)
self.__update_live_state()
def get_menu_alignment(self):
return MenuAlignment.RIGHT
def update_menu_item(self, menu_item: Union[ui.Menu, ui.MenuItem], menu_refresh: bool):
if isinstance(menu_item, ui.MenuItem):
menu_item.visible = False
def __update_live_tooltip(self):
current_session = self._live_syncing.get_current_live_session()
if current_session:
peer_users_count = len(current_session.peer_users)
if peer_users_count > 0:
self._live_background.set_tooltip(
f"Leave Session {current_session.name}\n{peer_users_count + 1} Total Users in Session"
)
else:
self._live_background.set_tooltip(
f"Leave Session {current_session.name}"
)
def __update_live_state(self):
if self._live_background:
current_session = self._live_syncing.get_current_live_session()
if current_session:
self._live_background.name = "live"
self.__update_live_tooltip()
self._drop_down_background.name = "live"
else:
self._live_background.name = "offline"
self._live_background.set_tooltip("Start Session")
self._drop_down_background.name = "offline"
def __build_user_list(self):
def is_follow_enabled():
settings = carb.settings.get_settings()
enabled = settings.get(f"/app/liveSession/enableMenuFollowUser")
if enabled == True or enabled == False:
return enabled
return True
stage_url = self._usd_context.get_stage_url()
self._live_session_user_list_widget = lsm.LiveSessionUserList(
self._usd_context, stage_url,
follow_user_with_double_click=is_follow_enabled(),
allow_timeline_settings=True,
maximum_users=10
)
class LiveStateMenu:
def __init__(self, usd_context):
self._live_menu_name = "Live State Widget"
self._menu_list = [MenuItemDescription(name="placeholder", show_fn=lambda: False)]
self._usd_context = usd_context
self._layers = layers.get_layers(self._usd_context)
self._layer_state_delegate = None
def register_menu_widgets(self):
self._layer_state_delegate = LiveStateDelegate(self._layers)
omni.kit.menu.utils.add_menu_items(self._menu_list, name=self._live_menu_name, delegate=self._layer_state_delegate)
def unregister_menu_widgets(self):
omni.kit.menu.utils.remove_menu_items(self._menu_list, self._live_menu_name)
self._menu_list = None
if self._layer_state_delegate:
self._layer_state_delegate.destroy()
self._layer_state_delegate = None
self._layers = None
self._usd_context = None
|
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/__init__.py | from .extension import OmniLiveWidgetExtension |
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/icons.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
class Icons:
"""A singleton that scans the icon folder and returns the icon depending on the type"""
_icons = {}
@staticmethod
def on_startup(extension_path):
current_path = Path(extension_path)
icon_path = current_path.joinpath("icons")
# Read all the svg files in the directory
Icons._icons = {icon.stem: icon for icon in icon_path.glob("*.svg")}
@staticmethod
def on_shutdown():
Icons._icons = None
@staticmethod
def get(name, default=None):
"""Checks the icon cache and returns the icon if exists"""
found = Icons._icons.get(name)
if not found and default:
found = Icons._icons.get(default)
if found:
return str(found)
return None
|
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/tests/base.py | import carb
def enable_server_tests():
settings = carb.settings.get_settings()
return settings.get_as_bool("/exts/omni.kit.widget.live/enable_server_tests")
|
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/tests/test_live_widget.py | import omni.kit.test
from pathlib import Path
import omni.usd
import omni.client
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.kit.clipboard
from omni.ui.tests.test_base import OmniUiTest
from pxr import Usd, Sdf
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi, join_new_simulated_user, quit_simulated_user
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data")
class TestLiveWidget(OmniUiTest):
# Before running each test
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self.app = omni.kit.app.get_app()
self.usd_context = omni.usd.get_context()
self.layers = layers.get_layers(self.usd_context)
self.live_syncing = self.layers.get_live_syncing()
await omni.usd.get_context().new_stage_async()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self.simulated_user_names = []
self.simulated_user_ids = []
self.test_session_name = "test"
self.stage_url = "omniverse://__faked_omniverse_server__/test/live_session.usd"
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def wait(self, frames=10):
for i in range(frames):
await self.app.next_update_async()
async def __create_simulated_users(self, count=2):
for i in range(count):
user_name = f"test{i}"
user_id = user_name
self.simulated_user_names.append(user_name)
self.simulated_user_ids.append(user_id)
join_new_simulated_user(user_name, user_id)
await self.wait(2)
async def test_menu_setup(self):
import omni.kit.ui_test as ui_test
await self.usd_context.new_stage_async()
menu_widget = ui_test.get_menubar()
menu = menu_widget.find_menu("Live State Widget")
self.assertTrue(menu)
async def __create_fake_stage(self, join_test_session=True):
format = Sdf.FileFormat.FindByExtension(".usd")
# Sdf.Layer.New will not save layer so it won't fail.
# This can be used to test layer identifier with omniverse sheme without
# touching real server.
layer = Sdf.Layer.New(format, self.stage_url)
stage = Usd.Stage.Open(layer.identifier)
session = self.live_syncing.create_live_session(self.test_session_name, layer_identifier=layer.identifier)
self.assertTrue(session)
if join_test_session:
await self.usd_context.attach_stage_async(stage)
self.live_syncing.join_live_session(session)
return stage, layer
@MockLiveSyncingApi
async def test_open_stage_with_live_session(self):
import omni.kit.ui_test as ui_test
await self.usd_context.new_stage_async()
_, layer = await self.__create_fake_stage(False)
menu_widget = ui_test.get_menubar()
menu = menu_widget.find_menu("Live State Widget")
self.assertTrue(menu)
await menu.bring_to_front()
await menu.click(menu.center + ui_test.Vec2(50, 0), False, 10)
# hard code the position of click point, as the menu positon changes after running test_join_live_session_users
# don't know why the menu positon changes after running test_join_live_session_users
# await menu.click(ui_test.Vec2(1426, 5), False, 10)
await ui_test.human_delay(100)
await ui_test.select_context_menu("Join With Session Link")
stage_url_with_session = f"{layer.identifier}?live_session_name=test"
omni.kit.clipboard.copy(stage_url_with_session)
window = ui_test.find("JOIN LIVE SESSION WITH LINK")
self.assertTrue(window is not None)
input_field = window.find("**/StringField[*].name=='new_session_link_field'")
self.assertTrue(input_field)
confirm_button = window.find("**/Button[*].name=='confirm_button'")
self.assertTrue(confirm_button)
cancel_button = window.find("**/Button[*].name=='cancel_button'")
self.assertTrue(cancel_button)
# Invalid session name will fail to join
await ui_test.human_delay(100)
input_field.model.set_value("111111")
await confirm_button.click()
await ui_test.human_delay(100)
self.assertFalse(self.live_syncing.is_stage_in_live_session())
self.assertTrue(window.window.visible)
input_field.model.set_value("")
await confirm_button.click()
await ui_test.human_delay(100)
self.assertFalse(self.live_syncing.is_stage_in_live_session())
self.assertTrue(window.window.visible)
await cancel_button.click()
self.assertFalse(self.live_syncing.is_stage_in_live_session())
self.assertFalse(window.window.visible)
window.window.visible = True
await self.wait()
# Valid session link
paste_button = window.find("**/ToolButton[*].name=='paste_button'")
self.assertTrue(paste_button)
await paste_button.click()
self.assertEqual(input_field.model.get_value_as_string(), stage_url_with_session)
await confirm_button.click()
self.assertFalse(window.window.visible)
await ui_test.human_delay(300)
self.assertTrue(self.live_syncing.is_stage_in_live_session())
await menu.click(menu.center + ui_test.Vec2(70, 0), False, 10)
await ui_test.human_delay(100)
# Copy session link
omni.kit.clipboard.copy("unkonwn")
await ui_test.select_context_menu("Share Session Link")
window = ui_test.find("SHARE LIVE SESSION LINK")
self.assertTrue(window is not None)
confirm_button = window.find("**/InvisibleButton[*].name=='confirm_button'")
self.assertTrue(confirm_button)
await confirm_button.click()
stage_url_with_session = f"{layer.identifier}?live_session_name=test"
live_session_link = omni.kit.clipboard.paste()
self.assertTrue(live_session_link, stage_url_with_session)
self.assertFalse(window.window.visible)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_join_live_session_users(self):
await self.__create_fake_stage(join_test_session=True)
await self.wait()
await self.__create_simulated_users()
await self.wait()
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
hide_menu_bar = False,
threshold=1e-4
)
self.live_syncing.stop_all_live_sessions()
await self.wait()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_leave_live_session_users(self):
await self.__create_fake_stage(join_test_session=True)
await self.wait()
await self.__create_simulated_users()
await self.wait()
quit_simulated_user(self.simulated_user_ids[0])
await self.wait()
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
hide_menu_bar=False,
threshold=1e-4
)
self.live_syncing.stop_all_live_sessions()
await self.wait()
@MockLiveSyncingApi(user_name="test", user_id="test")
async def test_join_live_session_over_max_users(self):
await self.__create_fake_stage(join_test_session=True)
await self.wait()
await self.__create_simulated_users(26)
await self.wait()
await self.finalize_test(golden_img_dir=self._golden_img_dir, hide_menu_bar=False)
self.live_syncing.stop_all_live_sessions()
await self.wait()
|
omniverse-code/kit/exts/omni.kit.widget.live/omni/kit/widget/live/tests/__init__.py | from .test_live_widget import TestLiveWidget |
omniverse-code/kit/exts/omni.kit.widget.live/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [2.0.3] - 2022-09-29
- Use new omni.kit.usd.layers interfaces.
## [2.0.2] - 2022-08-30
### Changes
- Show menu options for join.
## [2.0.1] - 2022-07-19
### Changes
- Show app name for user in the live session.
## [2.0.0] - 2022-06-29
### Changes
- Refactoring live widget to move all code into python.
## [1.0.0] - 2022-06-13
### Changes
- Initialize live widget changelog. |
omniverse-code/kit/exts/omni.kit.widget.live/docs/index.rst | omni.kit.widget.live
####################
Omniverse Kit Live Mode Control Widget
|
omniverse-code/kit/exts/omni.kit.viewport.ready/PACKAGE-LICENSES/omni.kit.viewport.ready-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. |
omniverse-code/kit/exts/omni.kit.viewport.ready/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.2"
# 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 = "Viewport Ready"
description="Extension to inject a omni.ui element into the Viewport until rendering has begun"
# Keywords for the extension
keywords = ["kit", "viewport", "utility", "ready"]
# 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"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
category = "Viewport"
[dependencies]
"omni.ui" = {}
"omni.usd" = {}
"omni.kit.window.viewport" = {optional = true} # Load after legacy omni.kit.window.viewport, but don't require it
"omni.kit.viewport.window" = {optional = true} # Load after new omni.kit.viewport.window, but don't require it
# Main python module this extension provides, it will be publicly available as "import omni.kit.viewport.registry".
[[python.module]]
name = "omni.kit.viewport.ready"
[settings]
exts."omni.kit.viewport.ready".startup.enabled = true
exts."omni.kit.viewport.ready".startup.viewport = "Viewport"
exts."omni.kit.viewport.ready".startup.show_once = true
exts."omni.kit.viewport.ready".message = "RTX Loading"
exts."omni.kit.viewport.ready".font_size = 72
exts."omni.kit.viewport.ready".background_color = 0
[[test]]
args = [
"--/app/window/width=512",
"--/app/window/height=512",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture"
]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
|
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/extension.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.ext
import omni.kit.app
import carb
class ViewportReadyExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self.__vp_ready = None
self.__vp_extension_hooks = None
# Create a default ready-delegate when exts/omni.kit.viewport.ready/startup/enabled is set
if carb.settings.get_settings().get("exts/omni.kit.viewport.ready/startup/enabled"):
manager = omni.kit.app.get_app().get_extension_manager()
self.__vp_extension_hooks = (
manager.subscribe_to_extension_enable(
self._create_viewport_ready,
self._remove_viewport_ready,
ext_name="omni.kit.window.viewport",
hook_name="omni.kit.viewport.ready.LoadListener-1",
),
manager.subscribe_to_extension_enable(
self._create_viewport_ready,
self._remove_viewport_ready,
ext_name="omni.kit.viewport.window",
hook_name="omni.kit.viewport.ready.LoadListener-2",
)
)
def on_shutdown(self):
self._remove_viewport_ready()
def _create_viewport_ready(self, *args):
async def viewport_ready_ui():
# Honor setting to force this message to only ever show once in a session if requested.
# This needs to happen in the async loop as subscribe_to_extension_enable can call _create_viewport_ready
# before it has returned and assigend hooks to self.__vp_extension_hooks
settings = carb.settings.get_settings()
show_once = bool(settings.get("exts/omni.kit.viewport.ready/startup/show_once"))
if show_once:
self.__vp_extension_hooks = None
import omni.ui
from .viewport_ready import ViewportReady, ViewportReadyDelegate
max_wait = 100
viewport_name = settings.get("exts/omni.kit.viewport.ready/startup/viewport") or "Viewport"
viewport_window = omni.ui.Workspace.get_window(viewport_name)
while viewport_window is None and max_wait:
await omni.kit.app.get_app().next_update_async()
viewport_window = omni.ui.Workspace.get_window(viewport_name)
max_wait = max_wait - 1
# Create a simple delegate that responds to on_complete and clears the objects created
class DefaultDelegate(ViewportReadyDelegate):
def on_complete(delegate_self):
# self is ViewportReadyExtension instance
self.__vp_ready = None
super().on_complete()
self.__vp_ready = ViewportReady(DefaultDelegate())
import asyncio
asyncio.ensure_future(viewport_ready_ui())
def _remove_viewport_ready(self, *args):
self.__vp_ready = None
self.__vp_extension_hooks = None
|
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/__init__.py | from .extension import ViewportReadyExtension
|
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/viewport_ready.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__ = ['ViewportReadyProgressDelegate', 'ViewportReadyDelegate', 'ViewportReady']
import omni.ui
import omni.usd
import carb
class ViewportReadyProgressDelegate:
def __init__(self, settings: carb.settings.ISettings):
self.__progress = None
self.__label = None
self.__shader_count = None
self.__enabled_mask_id = None
self.setup_updates(settings)
def __del__(self):
self.destroy()
def setup_updates(self, settings: carb.settings.ISettings):
"""Setup the ViewportReadyProgressDelegate to get progress updates"""
try:
import re
import omni.activity.core
import omni.activity.profiler
self.__re_matcher = re.compile("^.*\.hlsl \(UID: [0-9]+\)")
persisted_shader_count = settings.get("/persistent/exts/omni.kit.viewport.ready/shader_count")
# Guard against divide by 0 error in activity_event which shouldn't happen but did once somehow.
self.__shader_count = (0, persisted_shader_count if persisted_shader_count else 1)
profiler = omni.activity.profiler.get_activity_profiler()
if profiler:
self.__enabled_mask_id = profiler.enable_capture_mask(omni.activity.profiler.CAPTURE_MASK_STARTUP)
activity = omni.activity.core.get_instance()
self.__activity = (activity, activity.create_callback_to_pop(self.activity_event))
except (ImportError, RuntimeError):
required_exts = "omni.activity.profiler and omni.activity.pump"
carb.log_error(f"{required_exts} must be enabled with /exts/omni.kit.viewport.ready/activity_progress=true")
def destroy(self):
self.__activity = None
progress, self.__progress = self.__progress, None
if progress:
progress.destroy()
label, self.__label = self.__label, None
if label:
label.destroy()
# Save the total number of shaders processed as the progress max hint for the next launch
if self.__shader_count:
carb.settings.get_settings().set("/persistent/exts/omni.kit.viewport.ready/shader_count", self.__shader_count[0])
# Restore the profile mask to whatever it was before
enabled_mask_id, self.__enabled_mask_id = self.__enabled_mask_id, None
if enabled_mask_id is not None:
profiler = omni.activity.profiler.get_activity_profiler()
profiler.disable_capture_mask(enabled_mask_id)
def activity_event(self, node, root_node: bool = True):
"""Event handler for omni.activity messages"""
# This is a rather delicate method relying on strings being constant to filter properly
node_name = node.name or ""
if not root_node:
if self.__re_matcher.search(node_name) is not None:
self.__shader_count = self.__shader_count[0] + 1, self.__shader_count[1]
self.set_progress(self.__shader_count[0] / self.__shader_count[1], f"Compiling: {node_name}")
elif node_name == "Ray Tracing Pipeline":
for node_id in range(node.child_count):
self.activity_event(node.get_child(node_id), False)
def set_progress(self, amount: float, message: str):
if self.__progress:
self.__progress.model.set_value(amount)
if self.__label:
self.__label.text = message
def build_ui(self, settings: carb.settings.ISettings, font_size: float, color: omni.ui.color):
"""Build the progress ui with font and color style hints"""
margin = settings.get("/exts/omni.kit.viewport.ready/activity_progress/margin")
margin = omni.ui.Percent(20 if margin is None else margin)
omni.ui.Spacer(width=margin)
with omni.ui.VStack():
omni.ui.Spacer(height=5)
self.__progress = omni.ui.ProgressBar(height=5,
alignment=omni.ui.Alignment.CENTER_BOTTOM,
style={"border_width": 2, "border_radius": 5,
"color": color})
omni.ui.Spacer(height=5)
self.__label = omni.ui.Label("", alignment=omni.ui.Alignment.CENTER_TOP, style={"font_size": font_size})
omni.ui.Spacer(width=margin)
class ViewportReadyDelegate:
def __init__(self, viewport_name: str = 'Viewport', usd_context_name: str = '', viewport_handle: int = None):
self.__viewport_name = viewport_name
self.__usd_context_name = usd_context_name
self.__viewport_handle = viewport_handle
self.__frame = None
# The signal RTX sends that first frame is ready could actually come before omni.ui has called the ui build fn
self.__destroyed = False
# Fill in some default based on carb.settings
settings = carb.settings.get_settings()
self.__message = settings.get("/exts/omni.kit.viewport.ready/message") or "RTX Loading"
self.__font_size = settings.get("/exts/omni.kit.viewport.ready/font_size") or 72
if settings.get("/exts/omni.kit.viewport.ready/activity_progress/enabled"):
self.__progress = ViewportReadyProgressDelegate(settings)
else:
self.__progress = None
@property
def message(self) -> str:
'''Return the string for the default omni.ui.Label.'''
if self.__message == "RTX Loading":
active = {
"rtx": "RTX",
"iray": "Iray",
"pxr": "Storm",
"index": "Index"
}.get(carb.settings.get_settings().get("/renderer/active"), None)
if active:
return f"{active} Loading"
return self.__message
@property
def font_size(self) -> float:
'''Return the font-size for the default omni.ui.Label.'''
return self.__font_size
@property
def usd_context_name(self) -> str:
'''Return the omni.usd.UsdContext name this delegate is waiting for completion on.'''
return self.__usd_context_name
@property
def viewport_name(self) -> str:
'''Return the name of the omni.ui.Window this delegate is waiting for completion on.'''
return self.__viewport_name
@property
def viewport_handle(self) -> int:
'''Return the ViewportHandle this delegate is waiting for completion on or None for any Viewport.'''
return self.__viewport_handle
def on_complete(self):
'''Callback function invoked when first rendered frame is delivered'''
# Make sure to always call destroy if any exception is thrown during log_complete
try:
self.log_complete()
finally:
self.destroy()
def log_complete(self, msg: str = None, prefix_time_since_start: bool = True):
'''Callback function that will log to info (and stdout if /app/enableStdoutOutput is enabled)'''
if msg is None:
msg = 'RTX ready'
if prefix_time_since_start:
import omni.kit.app
seconds = omni.kit.app.get_app().get_time_since_start_s()
msg = "[{0:.3f}s] ".format(seconds) + msg
if carb.settings.get_settings().get('/app/enableStdoutOutput'):
# Going to sys.stdout directly is cleaner when launched with -info
import sys
sys.stdout.write(msg + '\n')
else:
carb.log_info(msg)
def build_label(self) -> omni.ui.Widget:
'''Simple method to override the basic label showing progress.'''
return omni.ui.Label(self.message, alignment=omni.ui.Alignment.CENTER, style={"font_size": self.font_size})
def build_progress(self) -> None:
settings = carb.settings.get_settings()
color = settings.get("/exts/omni.kit.viewport.ready/activity_progress/color")
color = omni.ui.color("#76b900" if color is None else color)
font_size = settings.get("/exts/omni.kit.viewport.ready/activity_progress/font_size")
if font_size is None:
font_size = self.__font_size / 6
omni.ui.Spacer(height=5)
with omni.ui.HStack():
self.__progress.build_ui(settings, font_size, color)
def build_frame(self) -> None:
'''Method to override the basic frame showing progress.'''
# If RTX is ready before omni.ui is calling the build function, then do nothing
if self.__destroyed:
return
self.__frame = omni.ui.ZStack()
with self.__frame:
bg_color = carb.settings.get_settings().get('/exts/omni.kit.viewport.ready/background_color')
if bg_color:
omni.ui.Rectangle(style={"background_color": bg_color})
with omni.ui.VStack():
kwargs = {}
if self.__progress:
kwargs = {"height": omni.ui.Percent(35)}
omni.ui.Spacer(**kwargs)
self.build_label()
if self.__progress:
self.build_progress()
omni.ui.Spacer()
def build_ui(self) -> None:
'''Method to build the progress/info state in the Viewport window.'''
# If RTX is ready before build_ui is called then do nothing
if self.__destroyed:
return
if self.__frame is None:
viewport_window = omni.ui.Workspace.get_window(self.viewport_name)
if viewport_window:
frame = None
if hasattr(viewport_window, 'get_frame'):
frame = viewport_window.get_frame('omni.kit.viewport.ready.ViewportReadyDelegate')
else:
# TODO: Use omni.kit.viewport.utility get_viewport_window to manage omni.ui Wrapper on legacy viewport
if hasattr(viewport_window, 'frame'):
frame = viewport_window.frame
if frame:
frame.set_build_fn(self.build_frame)
def __del__(self):
self.destroy()
def destroy(self):
self.__destroyed = True
progress, self.__progress = self.__progress, None
if progress:
progress.destroy()
if self.__frame:
self.__frame.visible = False
if hasattr(self.__frame, 'clear'):
self.__frame.clear()
self.__frame.destroy()
self.__frame = None
class ViewportReady:
def __init__(self, viewport_ready: ViewportReadyDelegate = None):
self.__viewport_ready = viewport_ready if viewport_ready else ViewportReadyDelegate()
usd_context_name = self.__viewport_ready.usd_context_name
usd_context = omni.usd.get_context(usd_context_name)
if usd_context:
# Build the UI objects now
self.__viewport_ready.build_ui()
# Subscribe to the eent to wait for frame delivery
self.__new_frame_sub = usd_context.get_rendering_event_stream().create_subscription_to_push_by_type(
int(omni.usd.StageRenderingEventType.NEW_FRAME),
self.__on_event,
name=f"omni.kit.viewport.ready.ViewportReady"
)
else:
raise RuntimeError(f'No omni.usd.UsdContext found with name "{usd_context_name}"')
def __del__(self):
self.destroy()
def destroy(self):
self.__new_frame_sub = None
self.__viewport_ready = None
def __on_event(self, e: carb.events.IEvent):
waiting_for = self.__viewport_ready.viewport_handle
if (waiting_for is None) or (waiting_for == e.payload["viewport_handle"]):
if self.__viewport_complete():
# Avoid wrapping callback in try/catch by storing it first, destroying, then calling it
viewport_ready, self.__viewport_ready = self.__viewport_ready, None
self.destroy()
viewport_ready.on_complete()
del viewport_ready
def __viewport_complete(self):
usd_context_name = self.__viewport_ready.usd_context_name
window_name = self.__viewport_ready.viewport_name
try:
from omni.kit.viewport.window import get_viewport_window_instances
# Get every ViewportWindow, regardless of UsdContext it is attached to
for window in get_viewport_window_instances(usd_context_name):
if window.title == window_name:
return window.viewport_api.frame_info.get('viewport_handle', None) is not None
except ImportError:
pass
try:
import omni.kit.viewport_legacy as vp_legacy
vp_iface = vp_legacy.get_viewport_interface()
viewport_handle = vp_iface.get_instance(window_name)
if viewport_handle:
vp_window = vp_iface.get_viewport_window(viewport_handle)
if vp_window:
return bool(vp_window.get_drawable_ldr_resource() or vp_window.get_drawable_hdr_resource())
except ImportError:
pass
return False
|
omniverse-code/kit/exts/omni.kit.viewport.ready/omni/kit/viewport/ready/tests/__init__.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__ = ['TestViewportReady']
import omni.kit.test
from ..viewport_ready import ViewportReadyDelegate, ViewportReady
import omni.usd
import omni.ui
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
EXTENSION_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.ready}")).resolve().absolute()
TEST_PATH = EXTENSION_PATH.joinpath("data", "tests")
WIDTH, HEIGHT = 512, 512
class TestViewportReady(OmniUiTest):
async def setUp(self):
await super().setUp()
async def tearDown(self):
await super().tearDown()
@staticmethod
def __test_image_name(base_name: str):
settings = carb.settings.get_settings()
if settings.get("/exts/omni.kit.viewport.ready/activity_progress/enabled"):
base_name += "_progress"
if settings.get("/exts/omni.kit.viewport.window/startup/windowName"):
base_name += "_viewport"
return base_name + ".png"
async def test_ready_delegate_begin(self):
'''Test the Viewport readys status message is placed inside a ui.Window named Viewport'''
await self.create_test_area(WIDTH, HEIGHT)
test_window = omni.ui.Window(
"Viewport",
dockPreference=omni.ui.DockPreference.DISABLED,
flags=omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE,
width=WIDTH,
height=HEIGHT
)
await self.wait_n_updates()
delegate = ViewportReadyDelegate()
delegate.build_ui()
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_begin"))
async def test_ready_delegate_end(self):
'''Test the Viewport readys status message is removed from the Viewport'''
await self.create_test_area(WIDTH, HEIGHT)
test_window = omni.ui.Window(
"Viewport",
dockPreference=omni.ui.DockPreference.DISABLED,
flags=omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE,
width=WIDTH,
height=HEIGHT
)
await self.wait_n_updates()
delegate = ViewportReadyDelegate()
delegate.build_ui()
await self.wait_n_updates()
delegate.on_complete()
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_end"))
async def test_settings(self):
'''Test carb.settings usage for default delegate'''
# Make sure the values being set aren't the defaults!
delegate = ViewportReadyDelegate()
self.assertNotEqual(delegate.message, 'TEST MESSAGE')
self.assertNotEqual(delegate.font_size, 128)
import carb
settings = carb.settings.get_settings()
# Save all the defaults for restoration for later tests
preferences = [
'/exts/omni.kit.viewport.ready/message',
'/exts/omni.kit.viewport.ready/font_size',
]
defaults = {k: settings.get(k) for k in preferences}
try:
settings.set('/exts/omni.kit.viewport.ready/message', 'TEST MESSAGE')
settings.set('/exts/omni.kit.viewport.ready/font_size', 128)
delegate = ViewportReadyDelegate(viewport_name='Not a Viewport', usd_context_name='Not a UsdContext')
self.assertEqual(delegate.message, 'TEST MESSAGE')
self.assertEqual(delegate.font_size, 128)
self.assertEqual(delegate.viewport_name, 'Not a Viewport')
self.assertEqual(delegate.usd_context_name, 'Not a UsdContext')
except Exception as e:
raise e
finally:
# Restore the defaults
for k, v in defaults.items():
settings.set(k, v)
async def test_throw_in_log_message(self):
'''Test the Viewport readys status message is removed from the Viewport when log_message throws an Exception'''
await self.create_test_area(WIDTH, HEIGHT)
test_window = omni.ui.Window(
"Viewport",
dockPreference=omni.ui.DockPreference.DISABLED,
flags=omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE,
width=WIDTH,
height=HEIGHT
)
await self.wait_n_updates()
log_complete_threw = False
class LocalExpection(RuntimeError):
pass
class ThrowingViewportReadyDelegate(ViewportReadyDelegate):
def log_complete(self):
nonlocal log_complete_threw
log_complete_threw = True
raise LocalExpection("Expected to throw")
try:
delegate = ThrowingViewportReadyDelegate()
delegate.build_ui()
await self.wait_n_updates()
await self.capture_and_compare(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_threw_begin"))
delegate.on_complete()
except LocalExpection:
pass
self.assertTrue(log_complete_threw)
await self.wait_n_updates()
await self.finalize_test(golden_img_dir=TEST_PATH, golden_img_name=self.__test_image_name("test_ready_delegate_threw_end"))
|
omniverse-code/kit/exts/omni.kit.viewport.ready/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.kit.viewport.ready`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`_.
## [1.0.2] - 2022-10-28
### Fixed
- Possibility that RTX has sent a ready event before omni.ui has called the build_fn callback.
### Added
- Setting to force the message to only ever appear once in application session (on by default).
- Setting to specify a background color for the "RTX Loading" frame (transparent by default).
## [1.0.1] - 2022-04-22
### Added
- Log to stdout when requested
### Fixed
- Early exit wait loop after Viewport created
## [1.0.0] - 2022-04-12
### Added
- Initial release
|
omniverse-code/kit/exts/omni.kit.viewport.ready/docs/README.md | # Viewport Ready extension [omni.kit.viewport.ready]
Utility extension to place a message (or omni.ui objects) in the Viewport until a rendered frame has been delivered.
|
omniverse-code/kit/exts/omni.kit.viewport.ready/docs/index.rst | omni.kit.viewport.ready
###########################
Viewport Ready
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule:: omni.kit.viewport.ready
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
|
omniverse-code/kit/exts/omni.kit.viewport.ready/docs/Overview.md | # Overview
|
omniverse-code/kit/exts/omni.volume_nodes/ogn/docs/SaveVDB.rst | .. _omni_volume_SaveVDB_1:
.. _omni_volume_SaveVDB:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Save VDB
:keywords: lang-en omnigraph node Omni Volume WriteOnly volume save-v-d-b
Save VDB
========
.. <description>
Saves a VDB from file and puts it in a memory buffer.
.. </description>
Installation
------------
To use this node enable :ref:`omni.volume_nodes<ext_omni_volume_nodes>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:assetPath", "``token``", "Path to VDB file to save.", ""
"inputs:compressionMode", "``token``", "The compression mode to use when encoding", "None"
"", "*allowedTokens*", "None,Blosc,Zip", ""
"", "*default*", "None", ""
"inputs:data", "``uint[]``", "Data to save to file in NanoVDB or OpenVDB memory format.", "[]"
"inputs:execIn", "``execution``", "Input execution", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:execOut", "``execution``", "Output execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.volume.SaveVDB"
"Version", "1"
"Extension", "omni.volume_nodes"
"Has State?", "True"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"tags", "VDB"
"uiName", "Save VDB"
"__tokens", "{""none"": ""None"", ""blosc"": ""Blosc"", ""zip"": ""Zip""}"
"Categories", "Omni Volume"
"Generated Class Name", "SaveVDBDatabase"
"Python Module", "omni.volume_nodes"
|
omniverse-code/kit/exts/omni.volume_nodes/ogn/docs/LoadVDB.rst | .. _omni_volume_LoadVDB_1:
.. _omni_volume_LoadVDB:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Load VDB
:keywords: lang-en omnigraph node Omni Volume ReadOnly volume load-v-d-b
Load VDB
========
.. <description>
Loads a VDB from file and puts it in a memory buffer.
.. </description>
Installation
------------
To use this node enable :ref:`omni.volume_nodes<ext_omni_volume_nodes>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:assetPath", "``token``", "Path to VDB file to load.", ""
"inputs:execIn", "``execution``", "Input execution", "None"
"inputs:gridName", "``token``", "Optional name of the grid to extract. All grids are extracted if this is left empty.", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:data", "``uint[]``", "Data loaded from VDB file in NanoVDB memory format.", "None"
"outputs:execOut", "``execution``", "Output execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.volume.LoadVDB"
"Version", "1"
"Extension", "omni.volume_nodes"
"Has State?", "True"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"tags", "VDB"
"uiName", "Load VDB"
"__tokens", "{}"
"Categories", "Omni Volume"
"Generated Class Name", "LoadVDBDatabase"
"Python Module", "omni.volume_nodes"
|
omniverse-code/kit/exts/omni.volume_nodes/omni/volume_nodes/ogn/LoadVDBDatabase.py | """Support for simplified access to data on nodes of type omni.volume.LoadVDB
Loads a VDB from file and puts it in a memory buffer.
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class LoadVDBDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.volume.LoadVDB
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.assetPath
inputs.execIn
inputs.gridName
Outputs:
outputs.data
outputs.execOut
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:assetPath', 'token', 0, None, 'Path to VDB file to load.', {}, True, "", False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('inputs:gridName', 'token', 0, None, 'Optional name of the grid to extract. All grids are extracted if this is left empty.', {}, False, None, False, ''),
('outputs:data', 'uint[]', 0, None, 'Data loaded from VDB file in NanoVDB memory format.', {}, True, None, False, ''),
('outputs:execOut', 'execution', 0, None, 'Output execution', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def assetPath(self):
data_view = og.AttributeValueHelper(self._attributes.assetPath)
return data_view.get()
@assetPath.setter
def assetPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.assetPath)
data_view = og.AttributeValueHelper(self._attributes.assetPath)
data_view.set(value)
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
@property
def gridName(self):
data_view = og.AttributeValueHelper(self._attributes.gridName)
return data_view.get()
@gridName.setter
def gridName(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gridName)
data_view = og.AttributeValueHelper(self._attributes.gridName)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.data_size = None
self._batchedWriteValues = { }
@property
def data(self):
data_view = og.AttributeValueHelper(self._attributes.data)
return data_view.get(reserved_element_count=self.data_size)
@data.setter
def data(self, value):
data_view = og.AttributeValueHelper(self._attributes.data)
data_view.set(value)
self.data_size = data_view.get_array_size()
@property
def execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = LoadVDBDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = LoadVDBDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = LoadVDBDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
|
omniverse-code/kit/exts/omni.volume_nodes/omni/volume_nodes/ogn/SaveVDBDatabase.py | """Support for simplified access to data on nodes of type omni.volume.SaveVDB
Saves a VDB from file and puts it in a memory buffer.
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class SaveVDBDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.volume.SaveVDB
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.assetPath
inputs.compressionMode
inputs.data
inputs.execIn
Outputs:
outputs.execOut
Predefined Tokens:
tokens.none
tokens.blosc
tokens.zip
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:assetPath', 'token', 0, None, 'Path to VDB file to save.', {}, True, "", False, ''),
('inputs:compressionMode', 'token', 0, None, 'The compression mode to use when encoding', {ogn.MetadataKeys.ALLOWED_TOKENS: 'None,Blosc,Zip', 'default': 'None', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"none": "None", "blosc": "Blosc", "zip": "Zip"}'}, False, None, False, ''),
('inputs:data', 'uint[]', 0, None, 'Data to save to file in NanoVDB or OpenVDB memory format.', {}, True, [], False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('outputs:execOut', 'execution', 0, None, 'Output execution', {}, True, None, False, ''),
])
class tokens:
none = "None"
blosc = "Blosc"
zip = "Zip"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def assetPath(self):
data_view = og.AttributeValueHelper(self._attributes.assetPath)
return data_view.get()
@assetPath.setter
def assetPath(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.assetPath)
data_view = og.AttributeValueHelper(self._attributes.assetPath)
data_view.set(value)
@property
def compressionMode(self):
data_view = og.AttributeValueHelper(self._attributes.compressionMode)
return data_view.get()
@compressionMode.setter
def compressionMode(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.compressionMode)
data_view = og.AttributeValueHelper(self._attributes.compressionMode)
data_view.set(value)
@property
def data(self):
data_view = og.AttributeValueHelper(self._attributes.data)
return data_view.get()
@data.setter
def data(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.data)
data_view = og.AttributeValueHelper(self._attributes.data)
data_view.set(value)
self.data_size = data_view.get_array_size()
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = SaveVDBDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = SaveVDBDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = SaveVDBDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
|
omniverse-code/kit/exts/usdrt.gf.tests/PACKAGE-LICENSES/usdrt.gf.tests-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. |
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfRect.py | #!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and modified.
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfRect2i.py
from __future__ import division
import math
import sys
import unittest
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
from usdrt import Gf
class TestGfRect2i(TestClass):
def test_Constructor(self):
self.assertIsInstance(Gf.Rect2i(), Gf.Rect2i)
self.assertIsInstance(Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i()), Gf.Rect2i)
self.assertIsInstance(Gf.Rect2i(Gf.Vec2i(), 1, 1), Gf.Rect2i)
self.assertTrue(Gf.Rect2i().IsNull())
self.assertTrue(Gf.Rect2i().IsEmpty())
self.assertFalse(Gf.Rect2i().IsValid())
# further test of above.
r = Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i(-1, 0))
self.assertTrue(not r.IsNull() and r.IsEmpty())
self.assertEqual(
Gf.Rect2i(Gf.Vec2i(-1, 1), Gf.Vec2i(1, -1)).GetNormalized(), Gf.Rect2i(Gf.Vec2i(-1, -1), Gf.Vec2i(1, 1))
)
def test_Properties(self):
r = Gf.Rect2i()
r.max = Gf.Vec2i()
r.min = Gf.Vec2i(1, 1)
r.GetNormalized()
r.max = Gf.Vec2i(1, 1)
r.min = Gf.Vec2i()
r.GetNormalized()
r.min = Gf.Vec2i(3, 1)
self.assertEqual(r.min, Gf.Vec2i(3, 1))
r.max = Gf.Vec2i(4, 5)
self.assertEqual(r.max, Gf.Vec2i(4, 5))
r.minX = 10
self.assertEqual(r.minX, 10)
r.maxX = 20
self.assertEqual(r.maxX, 20)
r.minY = 30
self.assertEqual(r.minY, 30)
r.maxY = 40
self.assertEqual(r.maxY, 40)
r = Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i(10, 10))
self.assertEqual(r.GetCenter(), Gf.Vec2i(5, 5))
self.assertEqual(r.GetArea(), 121)
self.assertEqual(r.GetHeight(), 11)
self.assertEqual(r.GetWidth(), 11)
self.assertEqual(r.GetSize(), Gf.Vec2i(11, 11))
r.Translate(Gf.Vec2i(10, 10))
self.assertEqual(r, Gf.Rect2i(Gf.Vec2i(10, 10), Gf.Vec2i(20, 20)))
r1 = Gf.Rect2i()
r2 = Gf.Rect2i(Gf.Vec2i(), Gf.Vec2i(1, 1))
r1.GetIntersection(r2)
r2.GetIntersection(r1)
r1.GetIntersection(r1)
r1.GetUnion(r2)
r2.GetUnion(r1)
r1.GetUnion(r1)
r1 = Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(10, 10))
r2 = Gf.Rect2i(Gf.Vec2i(5, 5), Gf.Vec2i(15, 15))
self.assertEqual(r1.GetIntersection(r2), Gf.Rect2i(Gf.Vec2i(5, 5), Gf.Vec2i(10, 10)))
self.assertEqual(r1.GetUnion(r2), Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(15, 15)))
tmp = Gf.Rect2i(r1)
tmp += r2
self.assertEqual(tmp, Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(15, 15)))
self.assertTrue(r1.Contains(Gf.Vec2i(3, 3)) and not r1.Contains(Gf.Vec2i(11, 11)))
self.assertEqual(r1, Gf.Rect2i(Gf.Vec2i(0, 0), Gf.Vec2i(10, 10)))
self.assertTrue(r1 != r2)
self.assertEqual(r1, eval(repr(r1)))
self.assertTrue(len(str(Gf.Rect2i())))
if __name__ == "__main__":
unittest.main()
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/test_gf_quat_extras.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 copy
import math
import os
import platform
import sys
import time
import unittest
from . import TestRtScenegraph, tc_logger, update_path_and_load_usd
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
update_path_and_load_usd()
def get_quat_info():
"""Return list of tuples of class, scalar size, and format string"""
from usdrt import Gf
quat_info = [
(Gf.Quatd, 8, "d"),
(Gf.Quatf, 4, "f"),
(Gf.Quath, 2, "e"),
]
return quat_info
def get_quat_numpy_types():
import numpy
import usdrt
equivalent_types = {
usdrt.Gf.Quatd: numpy.double,
usdrt.Gf.Quatf: numpy.single,
usdrt.Gf.Quath: numpy.half,
}
return equivalent_types
class TestGfQuatBuffer(TestRtScenegraph):
"""Test buffer protocol for usdrt.Gf.Quat* classes"""
@tc_logger
def test_buffer_inspect(self):
"""Use memoryview to validate that buffer protocol is implemented"""
quat_info = get_quat_info()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
q = Quat(test_values[3], test_values[0], test_values[1], test_values[2])
view = memoryview(q)
self.assertEquals(view.itemsize, size)
self.assertEquals(view.ndim, 1)
self.assertEquals(view.shape, (4,))
self.assertEquals(view.format, fmt)
self.assertEquals(view.obj, Quat(test_values[3], test_values[0], test_values[1], test_values[2]))
@tc_logger
def test_buffer_init(self):
"""Validate initialization from an array using buffer protocol"""
import array
quat_info = get_quat_info()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
if fmt == "e":
# GfHalf not supported with array.array
continue
test_array = array.array(fmt, test_values)
test_quat = Quat(test_array)
self.assertEquals(test_quat, Quat(test_values[3], test_values[0], test_values[1], test_values[2]))
@tc_logger
def test_buffer_init_from_numpy_type(self):
"""Test initialization from numpy types"""
import numpy
quat_info = get_quat_info()
equivalent_types = get_quat_numpy_types()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
test_numpy_type = numpy.array(test_values, dtype=equivalent_types[Quat])
test_quat = Quat(test_numpy_type)
self.assertEquals(test_quat, Quat(test_values[3], test_values[0], test_values[1], test_values[2]))
@tc_logger
def test_buffer_init_wrong_type(self):
"""Verify that an exception is raised with initializing via buffer with different data type"""
import array
quat_info = get_quat_info()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
test_array = array.array("h", test_values)
with self.assertRaises(ValueError):
test_quat = Quat(test_array)
@tc_logger
def test_buffer_init_wrong_size(self):
"""Verify that an exception is raised with initializing via buffer with different data array length"""
import array
quat_info = get_quat_info()
test_values = [9, 8, 7, 6, 1]
for Quat, size, fmt in quat_info:
if fmt == "e":
# GfHalf not supported with array.array
continue
test_array = array.array(fmt, test_values)
with self.assertRaises(ValueError):
test_vec = Quat(test_array)
@tc_logger
def test_buffer_init_wrong_dimension(self):
"""Verify that an exception is raised with initializing via buffer with different data dimensions"""
import numpy
quat_info = get_quat_info()
equivalent_types = get_quat_numpy_types()
test_values = [9, 8, 7, 1]
for Quat, size, fmt in quat_info:
test_array = numpy.array([test_values, test_values], dtype=equivalent_types[Quat])
with self.assertRaises(ValueError):
test_quat = Quat(test_array)
class TestGfQuatGetSetItem(TestRtScenegraph):
"""Test item accessors for usdrt.Gf.Quat* classes"""
@tc_logger
def test_get_item(self):
"""Validate __getitem__ on GfQuat"""
from usdrt import Gf
for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]:
q = Quat(0.5, 1, 2, 3)
# Note that these are in memory layout order,
# which is different from constructor order
self.assertEqual(q[0], 1)
self.assertEqual(q[1], 2)
self.assertEqual(q[2], 3)
self.assertEqual(q[3], 0.5)
self.assertEqual(q[-4], 1)
self.assertEqual(q[-3], 2)
self.assertEqual(q[-2], 3)
self.assertEqual(q[-1], 0.5)
@tc_logger
def test_set_item(self):
"""Validate __setitem__ on GfQuat"""
from usdrt import Gf
for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]:
q = Quat()
self.assertEqual(q.imaginary[0], 0)
self.assertEqual(q.imaginary[1], 0)
self.assertEqual(q.imaginary[2], 0)
self.assertEqual(q.real, 0)
q[0] = 1
q[1] = 2
q[2] = 3
q[3] = 0.5
self.assertEqual(q.imaginary[0], 1)
self.assertEqual(q.imaginary[1], 2)
self.assertEqual(q.imaginary[2], 3)
self.assertEqual(q.real, 0.5)
@tc_logger
def test_get_item_slice(self):
"""Validate __getitem__ with a slice on GfQuat"""
from usdrt import Gf
for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]:
q = Quat(0.5, 1, 2, 3)
self.assertEqual(q[1:], [2, 3, 0.5])
@tc_logger
def test_set_item_slice(self):
"""Validate __setitem__ with a slice on GfQuat"""
from usdrt import Gf
for Quat in [Gf.Quatf, Gf.Quatd, Gf.Quath]:
q = Quat(0.5, 1, 2, 3)
self.assertEqual(q.imaginary[0], 1)
self.assertEqual(q.imaginary[1], 2)
self.assertEqual(q.imaginary[2], 3)
self.assertEqual(q.real, 0.5)
q[1:] = [5, 6, 7]
self.assertEqual(q.imaginary[0], 1)
self.assertEqual(q.imaginary[1], 5)
self.assertEqual(q.imaginary[2], 6)
self.assertEqual(q.real, 7)
class TestGfQuatCopy(TestRtScenegraph):
"""Test copy and deepcopy support for Gf.Quat* classes"""
@tc_logger
def test_copy(self):
"""Test __copy__"""
quat_info = get_quat_info()
for Quat, size, fmt in quat_info:
x = Quat()
y = x
self.assertTrue(y is x)
y[0] = 10
self.assertEqual(x[0], 10)
z = copy.copy(y)
self.assertFalse(z is y)
y[0] = 100
self.assertEqual(z[0], 10)
@tc_logger
def test_deepcopy(self):
"""Test __deepcopy__"""
quat_info = get_quat_info()
for Quat, size, fmt in quat_info:
x = Quat()
y = x
self.assertTrue(y is x)
y[0] = 10
self.assertEqual(x[0], 10)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y[0] = 100
self.assertEqual(z[0], 10)
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfVec.py | # Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and lightly modified
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfVec.py
from __future__ import division
__copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 platform
import sys
import time
import unittest
##### Uncomment for better assert messages
# if 'unittest.util' in __import__('sys').modules:
# # Show full diff in self.assertEqual.
# __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
import math
import sys
import unittest
def floatTypeRank(vec):
from usdrt import Gf
vecIntTypes = [Gf.Vec2i, Gf.Vec3i, Gf.Vec4i]
vecDoubleTypes = [Gf.Vec2d, Gf.Vec3d, Gf.Vec4d]
vecFloatTypes = [Gf.Vec2f, Gf.Vec3f, Gf.Vec4f]
vecHalfTypes = [Gf.Vec2h, Gf.Vec3h, Gf.Vec4h]
if vec in vecDoubleTypes:
return 3
elif vec in vecFloatTypes:
return 2
elif vec in vecHalfTypes:
return 1
def isFloatingPoint(vec):
from usdrt import Gf
vecIntTypes = [Gf.Vec2i, Gf.Vec3i, Gf.Vec4i]
vecDoubleTypes = [Gf.Vec2d, Gf.Vec3d, Gf.Vec4d]
vecFloatTypes = [Gf.Vec2f, Gf.Vec3f, Gf.Vec4f]
vecHalfTypes = [Gf.Vec2h, Gf.Vec3h, Gf.Vec4h]
return (vec in vecDoubleTypes) or (vec in vecFloatTypes) or (vec in vecHalfTypes)
def getEps(vec):
rank = floatTypeRank(vec)
if rank == 1:
return 1e-2
elif rank == 2:
return 1e-3
elif rank == 3:
return 1e-4
def vecWithType(vecType, type):
from usdrt import Gf
if vecType.dimension == 2:
if type == "d":
return Gf.Vec2d
elif type == "f":
return Gf.Vec2f
elif type == "h":
return Gf.Vec2h
elif type == "i":
return Gf.Vec2i
elif vecType.dimension == 3:
if type == "d":
return Gf.Vec3d
elif type == "f":
return Gf.Vec3f
elif type == "h":
return Gf.Vec3h
elif type == "i":
return Gf.Vec3i
elif vecType.dimension == 4:
if type == "d":
return Gf.Vec4d
elif type == "f":
return Gf.Vec4f
elif type == "h":
return Gf.Vec4h
elif type == "i":
return Gf.Vec4i
assert False, "No valid conversion for " + vecType + " to type " + type
return None
def checkVec(vec, values):
for i in range(len(vec)):
if vec[i] != values[i]:
return False
return True
def checkVecDot(v1, v2, dp):
if len(v1) != len(v2):
return False
checkdp = 0
for i in range(len(v1)):
checkdp += v1[i] * v2[i]
return checkdp == dp
def SetVec(vec, values):
for i in range(len(vec)):
vec[i] = values[i]
class TestGfVec(TestClass):
def ConstructorsTest(self, Vec):
# no arg constructor
self.assertIsInstance(Vec(), Vec)
# default constructor
v = Vec()
for x in v:
self.assertEqual(0, x)
# copy constructor
v = Vec()
for i in range(len(v)):
v[i] = i
v2 = Vec(v)
for i in range(len(v2)):
self.assertEqual(v[i], v2[i])
# explicit constructor
values = [3, 1, 4, 1]
if Vec.dimension == 2:
v = Vec(3, 1)
self.assertTrue(checkVec(v, values))
elif Vec.dimension == 3:
v = Vec(3, 1, 4)
self.assertTrue(checkVec(v, values))
elif Vec.dimension == 4:
v = Vec(3, 1, 4, 1)
self.assertTrue(checkVec(v, values))
else:
self.assertTrue(False, "No explicit constructor check for " + Vec)
# constructor taking single scalar value.
v = Vec(0)
self.assertTrue(all([x == 0 for x in v]))
v = Vec(1)
self.assertTrue(all([x == 1 for x in v]))
v = Vec(2)
self.assertTrue(all([x == 2 for x in v]))
# conversion from other types to this float type.
if isFloatingPoint(Vec):
for t in "dfih":
V = vecWithType(Vec, t)
self.assertTrue(Vec(V()))
# comparison to int type
Veci = vecWithType(Vec, "i")
vi = Veci()
SetVec(vi, (3, 1, 4, 1))
self.assertEqual(Vec(vi), vi)
if isFloatingPoint(Vec):
# Comparison to float type
for t in "dfh":
V = vecWithType(Vec, t)
v = V()
SetVec(v, (0.3, 0.1, 0.4, 0.1))
if floatTypeRank(Vec) >= floatTypeRank(V):
self.assertEqual(Vec(v), v)
else:
self.assertNotEqual(Vec(v), v)
def OperatorsTest(self, Vec):
from usdrt import Gf
v1 = Vec()
v2 = Vec()
# equality
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [3, 1, 4, 1])
self.assertEqual(v1, v2)
# inequality
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
self.assertNotEqual(v1, v2)
# component-wise addition
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
v3 = v1 + v2
v1 += v2
self.assertTrue(checkVec(v1, [8, 10, 6, 7]))
self.assertTrue(checkVec(v3, [8, 10, 6, 7]))
# component-wise subtraction
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
v3 = v1 - v2
v1 -= v2
self.assertTrue(checkVec(v1, [-2, -8, 2, -5]))
self.assertTrue(checkVec(v3, [-2, -8, 2, -5]))
# component-wise multiplication
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
v4 = v1 * 10
v5 = 10 * v1
v1 *= 10
self.assertTrue(checkVec(v1, [30, 10, 40, 10]))
self.assertTrue(checkVec(v4, [30, 10, 40, 10]))
self.assertTrue(checkVec(v5, [30, 10, 40, 10]))
# component-wise division
SetVec(v1, [3, 6, 9, 12])
v3 = v1 / 3
v1 /= 3
self.assertTrue(checkVec(v1, [1, 2, 3, 4]))
self.assertTrue(checkVec(v3, [1, 2, 3, 4]))
# dot product
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
dp = v1 * v2
dp2 = Gf.Dot(v1, v2)
dp3 = v1.GetDot(v2) # 2x compatibility
self.assertTrue(checkVecDot(v1, v2, dp))
self.assertTrue(checkVecDot(v1, v2, dp2))
self.assertTrue(checkVecDot(v1, v2, dp3))
# unary minus (negation)
SetVec(v1, [3, 1, 4, 1])
self.assertTrue(checkVec(-v1, [-3, -1, -4, -1]))
# repr
self.assertEqual(v1, eval(repr(v1)))
# string
self.assertTrue(len(str(Vec())) > 0)
# indexing
v = Vec()
for i in range(Vec.dimension):
v[i] = i + 1
self.assertEqual(v[-1], v[v.dimension - 1])
self.assertEqual(v[0], 1)
self.assertIn(v.dimension, v)
self.assertNotIn(v.dimension + 1, v)
with self.assertRaises(IndexError):
v[v.dimension + 1] = v.dimension + 1
# slicing
v = Vec()
value = [3, 1, 4, 1]
SetVec(v, value)
value = v[0 : v.dimension]
self.assertEqual(v[:], value)
self.assertEqual(v[:2], value[:2])
self.assertEqual(v[0:2], value[0:2])
self.assertEqual(v[-2:], value[-2:])
self.assertEqual(v[1:1], [])
if v.dimension > 2:
self.assertEqual(v[0:3:2], [3, 4])
v[:2] = (8, 9)
checkVec(v, [8, 9, 4, 1])
if v.dimension > 2:
v[:3:2] = [0, 1]
checkVec(v, [0, 9, 1, 1])
with self.assertRaises(ValueError):
# This should fail. Wrong length sequence
#
v[:2] = [1, 2, 3]
with self.assertRaises(TypeError):
# This should fail. Cannot use floats for indices
v[0.0:2.0] = [7, 7]
with self.assertRaises(TypeError):
# This should fail. Cannot convert None to vector data
#
v[:2] = [None, None]
def MethodsTest(self, Vec):
from usdrt import Gf
v1 = Vec()
v2 = Vec()
if isFloatingPoint(Vec):
eps = getEps(Vec)
# length
SetVec(v1, [3, 1, 4, 1])
l = Gf.GetLength(v1)
l2 = v1.GetLength()
self.assertTrue(Gf.IsClose(l, l2, eps), repr(l) + " " + repr(l2))
self.assertTrue(
Gf.IsClose(l, math.sqrt(Gf.Dot(v1, v1)), eps),
" ".join([repr(x) for x in [l, v1, math.sqrt(Gf.Dot(v1, v1))]]),
)
# Normalize...
SetVec(v1, [3, 1, 4, 1])
v2 = Vec(v1)
v2.Normalize()
nv = Gf.GetNormalized(v1)
nv2 = v1.GetNormalized()
nvcheck = v1 / Gf.GetLength(v1)
self.assertTrue(Gf.IsClose(nv, nvcheck, eps))
self.assertTrue(Gf.IsClose(nv2, nvcheck, eps))
self.assertTrue(Gf.IsClose(v2, nvcheck, eps))
SetVec(v1, [3, 1, 4, 1])
nv = v1.GetNormalized()
nvcheck = v1 / Gf.GetLength(v1)
self.assertTrue(Gf.IsClose(nv, nvcheck, eps)) # nv edit - linalg implementation not exactly equal
SetVec(v1, [0, 0, 0, 0])
v1.Normalize()
self.assertTrue(checkVec(v1, [0, 0, 0, 0]))
SetVec(v1, [2, 0, 0, 0])
Gf.Normalize(v1)
self.assertTrue(checkVec(v1, [1, 0, 0, 0]))
# projection
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
p1 = Gf.GetProjection(v1, v2)
p2 = v1.GetProjection(v2)
check = (v1 * v2) * v2
self.assertEqual(p1, check)
self.assertEqual(p2, check)
# complement
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
p1 = Gf.GetComplement(v1, v2)
p2 = v1.GetComplement(v2)
check = v1 - (v1 * v2) * v2
self.assertTrue((p1 == check) and (p2 == check))
# component-wise multiplication
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
v3 = Gf.CompMult(v1, v2)
self.assertTrue(checkVec(v3, [15, 9, 8, 6]))
# component-wise division
SetVec(v1, [3, 9, 18, 21])
SetVec(v2, [3, 3, 9, 7])
v3 = Gf.CompDiv(v1, v2)
self.assertTrue(checkVec(v3, [1, 3, 2, 3]))
# is close
SetVec(v1, [3, 1, 4, 1])
SetVec(v2, [5, 9, 2, 6])
self.assertTrue(Gf.IsClose(v1, v1, 0.1))
self.assertFalse(Gf.IsClose(v1, v2, 0.1))
# static Axis methods
for i in range(Vec.dimension):
v1 = Vec.Axis(i)
v2 = Vec()
v2[i] = 1
self.assertEqual(v1, v2)
v1 = Vec.XAxis()
self.assertTrue(checkVec(v1, [1, 0, 0, 0]))
v1 = Vec.YAxis()
self.assertTrue(checkVec(v1, [0, 1, 0, 0]))
if Vec.dimension != 2:
v1 = Vec.ZAxis()
self.assertTrue(checkVec(v1, [0, 0, 1, 0]))
if Vec.dimension == 3:
# cross product
SetVec(v1, [3, 1, 4, 0])
SetVec(v2, [5, 9, 2, 0])
v3 = Vec(Gf.Cross(v1, v2))
v4 = v1 ^ v2
v5 = v1.GetCross(v2) # 2x compatibility
check = Vec()
SetVec(check, [1 * 2 - 4 * 9, 4 * 5 - 3 * 2, 3 * 9 - 1 * 5, 0])
self.assertTrue(v3 == check and v4 == check and v5 == check)
# orthogonalize basis
# case 1: close to orthogonal, don't normalize
SetVec(v1, [1, 0, 0.1])
SetVec(v2, [0.1, 1, 0])
SetVec(v3, [0, 0.1, 1])
self.assertTrue(Vec.OrthogonalizeBasis(v1, v2, v3, False))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
# case 2: far from orthogonal, normalize
SetVec(v1, [1, 2, 3])
SetVec(v2, [-1, 2, 3])
SetVec(v3, [-1, -2, 3])
self.assertTrue(Vec.OrthogonalizeBasis(v1, v2, v3, True))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
self.assertTrue(Gf.IsClose(v1.GetLength(), 1, eps))
self.assertTrue(Gf.IsClose(v2.GetLength(), 1, eps))
self.assertTrue(Gf.IsClose(v3.GetLength(), 1, eps))
# case 3: already orthogonal - shouldn't change, even with large
# tolerance
SetVec(v1, [1, 0, 0])
SetVec(v2, [0, 1, 0])
SetVec(v3, [0, 0, 1])
vt1 = v1
vt2 = v2
vt3 = v3
self.assertTrue(Vec.OrthogonalizeBasis(v1, v2, v3, False)) # nv edit - no epsilon parameter
self.assertTrue(v1 == vt1)
self.assertTrue(v2 == vt2)
self.assertTrue(v3 == vt3)
# case 4: co-linear input vectors - should do nothing
SetVec(v1, [1, 0, 0])
SetVec(v2, [1, 0, 0])
SetVec(v3, [0, 0, 1])
vt1 = v1
vt2 = v2
vt3 = v3
self.assertFalse(Vec.OrthogonalizeBasis(v1, v2, v3, False)) # nv edit - no epsilon parameter
self.assertEqual(v1, vt1)
self.assertEqual(v2, vt2)
self.assertEqual(v3, vt3)
# build orthonormal frame
SetVec(v1, [1, 1, 1, 1])
(v2, v3) = v1.BuildOrthonormalFrame()
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
SetVec(v1, [0, 0, 0, 0])
(v2, v3) = v1.BuildOrthonormalFrame()
self.assertTrue(Gf.IsClose(v2, Vec(), eps))
self.assertTrue(Gf.IsClose(v3, Vec(), eps))
SetVec(v1, [1, 0, 0, 0])
(v2, v3) = v1.BuildOrthonormalFrame()
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
SetVec(v1, [1, 0, 0, 0])
(v2, v3) = v1.BuildOrthonormalFrame()
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
SetVec(v1, [1, 0, 0, 0])
(v2, v3) = v1.BuildOrthonormalFrame(2)
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v3, v1), 0, eps))
self.assertTrue(Gf.IsClose(Gf.Dot(v2, v3), 0, eps))
# test Slerp w/ orthogonal vectors
SetVec(v1, [1, 0, 0])
SetVec(v2, [0, 1, 0])
v3 = Gf.Slerp(0, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps))
v3 = Gf.Slerp(1, v1, v2)
self.assertTrue(Gf.IsClose(v3, v3, eps))
v3 = Gf.Slerp(0.5, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0.7071, 0.7071, 0), eps))
# test Slerp w/ nearly parallel vectors
SetVec(v1, [1, 0, 0])
SetVec(v2, [1.001, 0.0001, 0])
v2.Normalize()
v3 = Gf.Slerp(0, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps))
v3 = Gf.Slerp(1, v1, v2)
self.assertTrue(Gf.IsClose(v3, v3, eps))
v3 = Gf.Slerp(0.5, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps), [v3, v1, eps])
self.assertTrue(Gf.IsClose(v3, v2, eps))
# test Slerp w/ opposing vectors
SetVec(v1, [1, 0, 0])
SetVec(v2, [-1, 0, 0])
v3 = Gf.Slerp(0, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps))
v3 = Gf.Slerp(0.25, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0.70711, 0, -0.70711), eps))
v3 = Gf.Slerp(0.5, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0, 0, -1), eps))
v3 = Gf.Slerp(0.75, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(-0.70711, 0, -0.70711), eps))
v3 = Gf.Slerp(1, v1, v2)
self.assertTrue(Gf.IsClose(v3, v3, eps))
# test Slerp w/ opposing vectors
SetVec(v1, [0, 1, 0])
SetVec(v2, [0, -1, 0])
v3 = Gf.Slerp(0, v1, v2)
self.assertTrue(Gf.IsClose(v3, v1, eps))
v3 = Gf.Slerp(0.25, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0, 0.70711, 0.70711), eps))
v3 = Gf.Slerp(0.5, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0, 0, 1), eps))
v3 = Gf.Slerp(0.75, v1, v2)
self.assertTrue(Gf.IsClose(v3, Vec(0, -0.70711, 0.70711), eps))
v3 = Gf.Slerp(1, v1, v2)
self.assertTrue(Gf.IsClose(v3, v3, eps))
def test_Types(self):
from usdrt import Gf
vecTypes = [
Gf.Vec2d,
Gf.Vec2f,
Gf.Vec2h,
Gf.Vec2i,
Gf.Vec3d,
Gf.Vec3f,
Gf.Vec3h,
Gf.Vec3i,
Gf.Vec4d,
Gf.Vec4f,
Gf.Vec4h,
Gf.Vec4i,
]
for Vec in vecTypes:
self.ConstructorsTest(Vec)
self.OperatorsTest(Vec)
self.MethodsTest(Vec)
def test_TupleToVec(self):
from usdrt import Gf
""" nv edits - no implicit construction w/ pybind yet (TODO maybe?)
# Test passing tuples for vecs.
self.assertEqual(Gf.Dot((1,1), (1,1)), 2)
self.assertEqual(Gf.Dot((1,1,1), (1,1,1)), 3)
self.assertEqual(Gf.Dot((1,1,1,1), (1,1,1,1)), 4)
self.assertEqual(Gf.Dot((1.0,1.0), (1.0,1.0)), 2.0)
self.assertEqual(Gf.Dot((1.0,1.0,1.0), (1.0,1.0,1.0)), 3.0)
self.assertEqual(Gf.Dot((1.0,1.0,1.0,1.0), (1.0,1.0,1.0,1.0)), 4.0)
"""
self.assertEqual(Gf.Vec2f((1, 1)), Gf.Vec2f(1, 1))
self.assertEqual(Gf.Vec3f((1, 1, 1)), Gf.Vec3f(1, 1, 1))
self.assertEqual(Gf.Vec4f((1, 1, 1, 1)), Gf.Vec4f(1, 1, 1, 1))
# Test passing lists for vecs.
""" nv edits - no construction w/ lists yet (TODO maybe?)
#self.assertEqual(Gf.Dot([1,1], [1,1]), 2)
#self.assertEqual(Gf.Dot([1,1,1], [1,1,1]), 3)
#self.assertEqual(Gf.Dot([1,1,1,1], [1,1,1,1]), 4)
#self.assertEqual(Gf.Dot([1.0,1.0], [1.0,1.0]), 2.0)
#self.assertEqual(Gf.Dot([1.0,1.0,1.0], [1.0,1.0,1.0]), 3.0)
#self.assertEqual(Gf.Dot([1.0,1.0,1.0,1.0], [1.0,1.0,1.0,1.0]), 4.0)
#self.assertEqual(Gf.Vec2f([1,1]), Gf.Vec2f(1,1))
#self.assertEqual(Gf.Vec3f([1,1,1]), Gf.Vec3f(1,1,1))
#self.assertEqual(Gf.Vec4f([1,1,1,1]), Gf.Vec4f(1,1,1,1))
# Test passing both for vecs.
self.assertEqual(Gf.Dot((1,1), [1,1]), 2)
self.assertEqual(Gf.Dot((1,1,1), [1,1,1]), 3)
self.assertEqual(Gf.Dot((1,1,1,1), [1,1,1,1]), 4)
self.assertEqual(Gf.Dot((1.0,1.0), [1.0,1.0]), 2.0)
self.assertEqual(Gf.Dot((1.0,1.0,1.0), [1.0,1.0,1.0]), 3.0)
self.assertEqual(Gf.Dot((1.0,1.0,1.0,1.0), [1.0,1.0,1.0,1.0]), 4.0)
self.assertEqual(Gf.Vec2f([1,1]), Gf.Vec2f(1,1))
self.assertEqual(Gf.Vec3f([1,1,1]), Gf.Vec3f(1,1,1))
self.assertEqual(Gf.Vec4f([1,1,1,1]), Gf.Vec4f(1,1,1,1))
"""
""" nv edit - no implict construction
def test_Exceptions(self):
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1, 1))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1, 1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot('monkey', (1.0, 1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot((1, 1, 1, 1, 1, 1), (1, 1))
with self.assertRaises(TypeError):
Gf.Dot((1, 1, 1, 1, 1, 1), (1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot((1, 1, 1, 1, 1, 1), (1, 1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot((1.0, 1.0, 1.0, 1.0, 1.0, 1.0), (1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot((1.0, 1.0, 1.0, 1.0, 1.0, 1.0), (1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot((1.0, 1.0, 1.0, 1.0, 1.0, 1.0), (1.0, 1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b'), (1, 1))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b', 'c'), (1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b', 'c', 'd'), (1, 1, 1, 1))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b'), (1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b', 'c'), (1.0, 1.0, 1.0))
with self.assertRaises(TypeError):
Gf.Dot(('a', 'b', 'c', 'd'), (1.0, 1.0, 1.0, 1.0))
"""
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/test_gf_vec_extras.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 copy
import math
import os
import platform
import sys
import time
import unittest
from . import TestRtScenegraph, tc_logger, update_path_and_load_usd
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
update_path_and_load_usd()
def get_vec_info():
"""Return list of tuples of class, scalar size, item count, and format string"""
from usdrt import Gf
vec_info = [
(Gf.Vec2d, 8, 2, "d"),
(Gf.Vec2f, 4, 2, "f"),
(Gf.Vec2h, 2, 2, "e"),
(Gf.Vec2i, 4, 2, "i"),
(Gf.Vec3d, 8, 3, "d"),
(Gf.Vec3f, 4, 3, "f"),
(Gf.Vec3h, 2, 3, "e"),
(Gf.Vec3i, 4, 3, "i"),
(Gf.Vec4d, 8, 4, "d"),
(Gf.Vec4f, 4, 4, "f"),
(Gf.Vec4h, 2, 4, "e"),
(Gf.Vec4i, 4, 4, "i"),
]
return vec_info
def get_vec_numpy_types():
import numpy
import usdrt
equivalent_types = {
usdrt.Gf.Vec2d: numpy.double,
usdrt.Gf.Vec2f: numpy.single,
usdrt.Gf.Vec2h: numpy.half,
usdrt.Gf.Vec2i: numpy.int,
usdrt.Gf.Vec3d: numpy.double,
usdrt.Gf.Vec3f: numpy.single,
usdrt.Gf.Vec3h: numpy.half,
usdrt.Gf.Vec3i: numpy.int,
usdrt.Gf.Vec4d: numpy.double,
usdrt.Gf.Vec4f: numpy.single,
usdrt.Gf.Vec4h: numpy.half,
usdrt.Gf.Vec4i: numpy.int,
}
return equivalent_types
class TestGfVecBuffer(TestRtScenegraph):
"""Test buffer protocol for usdrt.Gf.Vec* classes"""
@tc_logger
def test_buffer_inspect(self):
"""Use memoryview to validate that buffer protocol is implemented"""
vec_info = get_vec_info()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
v = Vec(*test_values[:count])
view = memoryview(v)
self.assertEquals(view.itemsize, size)
self.assertEquals(view.ndim, 1)
self.assertEquals(view.shape, (count,))
self.assertEquals(view.format, fmt)
self.assertEquals(view.obj, Vec(*test_values[:count]))
@tc_logger
def test_buffer_init(self):
"""Validate initialization from an array using buffer protocol"""
import array
vec_info = get_vec_info()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
if fmt == "e":
# GfHalf not supported with array.array
continue
test_array = array.array(fmt, test_values[:count])
test_vec = Vec(test_array)
self.assertEquals(test_vec, Vec(*test_values[:count]))
@tc_logger
def test_buffer_init_from_pxr_type(self):
"""Validate initialization from equivalent Pixar types"""
import pxr
import usdrt
vec_info = get_vec_info()
equivalent_types = {
usdrt.Gf.Vec2d: pxr.Gf.Vec2d,
usdrt.Gf.Vec2f: pxr.Gf.Vec2f,
usdrt.Gf.Vec2h: pxr.Gf.Vec2h,
usdrt.Gf.Vec2i: pxr.Gf.Vec2i,
usdrt.Gf.Vec3d: pxr.Gf.Vec3d,
usdrt.Gf.Vec3f: pxr.Gf.Vec3f,
usdrt.Gf.Vec3h: pxr.Gf.Vec3h,
usdrt.Gf.Vec3i: pxr.Gf.Vec3i,
usdrt.Gf.Vec4d: pxr.Gf.Vec4d,
usdrt.Gf.Vec4f: pxr.Gf.Vec4f,
usdrt.Gf.Vec4h: pxr.Gf.Vec4h,
usdrt.Gf.Vec4i: pxr.Gf.Vec4i,
}
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
test_pxr_type = equivalent_types[Vec](test_values[:count])
# Note that in all cases pybind choses the tuple initializer and
# not the buffer initializer. Oh well.
test_vec = Vec(test_pxr_type)
self.assertEquals(test_vec, Vec(*test_values[:count]))
@tc_logger
def test_buffer_init_from_numpy_type(self):
"""Test initialization from numpy types"""
import numpy
vec_info = get_vec_info()
equivalent_types = get_vec_numpy_types()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
test_numpy_type = numpy.array(test_values[:count], dtype=equivalent_types[Vec])
# Note that in all cases except half pybind choses the tuple initializer and
# not the buffer initializer. Oh well.
test_vec = Vec(test_numpy_type)
self.assertEquals(test_vec, Vec(*test_values[:count]))
@tc_logger
def test_buffer_init_wrong_type(self):
"""Verify that an exception is raised with initializing via buffer with different data type"""
import array
vec_info = get_vec_info()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
if fmt in ["e"]:
# GfHalf is tricky because it will cast from any
# numeric type, which pybind too-helpfully interprets
# into a tuple of GfHalf
continue
# Here, pybind will convert arrays of similar types to tuples
# which is fine I guess but makes testing harder to validate
# type correctness with buffer support
test_array = array.array("d" if fmt == "i" else "h", test_values[:count])
with self.assertRaises(ValueError):
test_vec = Vec(test_array)
@tc_logger
def test_buffer_init_wrong_size(self):
"""Verify that an exception is raised with initializing via buffer with different data array length"""
import array
vec_info = get_vec_info()
test_values = [9, 8, 7, 6, 5]
for Vec, size, count, fmt in vec_info:
if fmt in ["e"]:
# GfHalf not supported with array.array
continue
# Here, pybind will convert arrays of similar types to tuples
# which is fine I guess but makes testing harder to validate
# type correctness with buffer support
test_array = array.array(fmt, test_values)
with self.assertRaises(ValueError):
test_vec = Vec(test_array)
@tc_logger
def test_buffer_init_wrong_dimension(self):
"""Verify that an exception is raised with initializing via buffer with different data dimensions"""
import numpy
vec_info = get_vec_info()
equivalent_types = get_vec_numpy_types()
test_values = [9, 8, 7, 6]
for Vec, size, count, fmt in vec_info:
test_array = numpy.array([test_values[:count], test_values[:count]], dtype=equivalent_types[Vec])
with self.assertRaises(ValueError):
test_vec = Vec(test_array)
class TestGfVecCopy(TestRtScenegraph):
"""Test copy and deepcopy support for Gf.Vec* classes"""
@tc_logger
def test_copy(self):
"""Test __copy__"""
vec_info = get_vec_info()
for Vec, size, count, fmt in vec_info:
x = Vec()
y = x
self.assertTrue(y is x)
y[0] = 10
self.assertEqual(x[0], 10)
z = copy.copy(y)
self.assertFalse(z is y)
y[0] = 100
self.assertEqual(z[0], 10)
@tc_logger
def test_deepcopy(self):
"""Test __deepcopy__"""
vec_info = get_vec_info()
for Vec, size, count, fmt in vec_info:
x = Vec()
y = x
self.assertTrue(y is x)
y[0] = 10
self.assertEqual(x[0], 10)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y[0] = 100
self.assertEqual(z[0], 10)
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/__init__.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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
# I wasted an hour finding this
scan_for_test_modules = True
TestRtScenegraph = omni.kit.test.AsyncTestCase
def tc_logger(func):
"""
Print TC macros about the test when running on TC
(unneeded in kit)
"""
return func
def update_path_and_load_usd():
"""
Stub to help load USD before USDRT
(unneeded in kit)
"""
pass
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfMath.py | #!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import division
# Note: This is just pulled directly from USD and lightly modified
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfMath.py
__copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 math
import sys
import unittest
# In python 3 there is no type called "long", but a regular int is backed by
# a long. Fake it here so we can keep test coverage working for the types
# available in python 2, where there are separate int and long types
if sys.version_info.major >= 3:
long = int
def err(msg):
return "ERROR: " + msg + " failed"
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
class TestGfMath(TestClass):
def _AssertListIsClose(self, first, second, delta=1e-6):
self.assertTrue(len(first) == len(second))
for (f, s) in zip(first, second):
self.assertAlmostEqual(f, s, delta=delta)
""" nv edit - no _HalfRoundTrip
def test_HalfRoundTrip(self):
from pxr.Gf import _HalfRoundTrip
self.assertEqual(1.0, _HalfRoundTrip(1.0))
self.assertEqual(1.0, _HalfRoundTrip(1))
self.assertEqual(2.0, _HalfRoundTrip(2))
self.assertEqual(3.0, _HalfRoundTrip(long(3)))
with self.assertRaises(TypeError):
_HalfRoundTrip([])
"""
def test_RadiansDegrees(self):
from usdrt.Gf import DegreesToRadians, RadiansToDegrees
self.assertEqual(0, RadiansToDegrees(0))
self.assertEqual(180, RadiansToDegrees(math.pi))
self.assertEqual(720, RadiansToDegrees(4 * math.pi))
self.assertEqual(0, DegreesToRadians(0))
self.assertEqual(math.pi, DegreesToRadians(180))
self.assertEqual(8 * math.pi, DegreesToRadians(4 * 360))
""" nv edit - not supporting some basic math stuff for now
def test_Sqr(self):
self.assertEqual(9, Sqr(3))
self.assertAlmostEqual(Sqr(math.sqrt(2)), 2, delta=1e-7)
self.assertEqual(5, Sqr(Vec2i(1,2)))
self.assertEqual(14, Sqr(Vec3i(1,2,3)))
self.assertEqual(5, Sqr(Vec2d(1,2)))
self.assertEqual(14, Sqr(Vec3d(1,2,3)))
self.assertEqual(30, Sqr(Vec4d(1,2,3,4)))
self.assertEqual(5, Sqr(Vec2f(1,2)))
self.assertEqual(14, Sqr(Vec3f(1,2,3)))
self.assertEqual(30, Sqr(Vec4f(1,2,3,4)))
def test_Sgn(self):
self.assertEqual(-1, Sgn(-3))
self.assertEqual(1, Sgn(3))
self.assertEqual(0, Sgn(0))
self.assertEqual(-1, Sgn(-3.3))
self.assertEqual(1, Sgn(3.3))
self.assertEqual(0, Sgn(0.0))
def test_Sqrt(self):
self.assertAlmostEqual( Sqrt(2), math.sqrt(2), delta=1e-5 )
self.assertAlmostEqual( Sqrtf(2), math.sqrt(2), delta=1e-5 )
def test_Exp(self):
self.assertAlmostEqual( Sqr(math.e), Exp(2), delta=1e-5 )
self.assertAlmostEqual( Sqr(math.e), Expf(2), delta=1e-5 )
def test_Log(self):
self.assertEqual(1, Log(math.e))
self.assertAlmostEqual(Log(Exp(math.e)), math.e, delta=1e-5)
self.assertAlmostEqual(Logf(math.e), 1, delta=1e-5)
self.assertAlmostEqual(Logf(Expf(math.e)), math.e, delta=1e-5)
def test_Floor(self):
self.assertEqual(3, Floor(3.141))
self.assertEqual(-4, Floor(-3.141))
self.assertEqual(3, Floorf(3.141))
self.assertEqual(-4, Floorf(-3.141))
def test_Ceil(self):
self.assertEqual(4, Ceil(3.141))
self.assertEqual(-3, Ceil(-3.141))
self.assertEqual(4, Ceilf(3.141))
self.assertEqual(-3, Ceilf(-3.141))
def test_Abs(self):
self.assertAlmostEqual(Abs(-3.141), 3.141, delta=1e-6)
self.assertAlmostEqual(Abs(3.141), 3.141, delta=1e-6)
self.assertAlmostEqual(Absf(-3.141), 3.141, delta=1e-6)
self.assertAlmostEqual(Absf(3.141), 3.141, delta=1e-6)
def test_Round(self):
self.assertEqual(3, Round(3.1))
self.assertEqual(4, Round(3.5))
self.assertEqual(-3, Round(-3.1))
self.assertEqual(-4, Round(-3.6))
self.assertEqual(3, Roundf(3.1))
self.assertEqual(4, Roundf(3.5))
self.assertEqual(-3, Roundf(-3.1))
self.assertEqual(-4, Roundf(-3.6))
def test_Pow(self):
self.assertEqual(16, Pow(2, 4))
self.assertEqual(16, Powf(2, 4))
def test_Clamp(self):
self.assertAlmostEqual(Clamp(3.141, 3.1, 3.2), 3.141, delta=1e-5)
self.assertAlmostEqual(Clamp(2.141, 3.1, 3.2), 3.1, delta=1e-5)
self.assertAlmostEqual(Clamp(4.141, 3.1, 3.2), 3.2, delta=1e-5)
self.assertAlmostEqual(Clampf(3.141, 3.1, 3.2), 3.141, delta=1e-5)
self.assertAlmostEqual(Clampf(2.141, 3.1, 3.2), 3.1, delta=1e-5)
self.assertAlmostEqual(Clampf(4.141, 3.1, 3.2), 3.2, delta=1e-5)
def test_Mod(self):
self.assertEqual(2, Mod(5, 3))
self.assertEqual(1, Mod(-5, 3))
self.assertEqual(2, Modf(5, 3))
self.assertEqual(1, Modf(-5, 3))
"""
""" nv edit - not supporting these for scalars
def test_Dot(self):
from usdrt.Gf import Dot
self.assertEqual(Dot(2.0, 3.0), 6.0)
self.assertEqual(Dot(-2.0, 3.0), -6.0)
def test_CompMult(self):
from usdrt.Gf import CompMult
self.assertEqual(CompMult(2.0, 3.0), 6.0)
self.assertEqual(CompMult(-2.0, 3.0), -6.0)
def test_CompDiv(self):
from usdrt.Gf import CompDiv
self.assertEqual(CompDiv(6.0, 3.0), 2.0)
self.assertEqual(CompDiv(-6.0, 3.0), -2.0)
"""
if __name__ == "__main__":
unittest.main()
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/test_gf_matrix_extras.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 copy
import math
import os
import platform
import sys
import time
import unittest
from . import TestRtScenegraph, tc_logger, update_path_and_load_usd
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
update_path_and_load_usd()
def get_mat_info():
"""Return list of tuples of class, scalar size, item count, and format string"""
from usdrt import Gf
mat_info = [
(Gf.Matrix3d, 8, 9, "d"),
(Gf.Matrix3f, 4, 9, "f"),
(Gf.Matrix4d, 8, 16, "d"),
(Gf.Matrix4f, 4, 16, "f"),
]
return mat_info
def get_mat_numpy_types():
import numpy
import usdrt
equivalent_types = {
usdrt.Gf.Matrix3d: numpy.double,
usdrt.Gf.Matrix3f: numpy.single,
usdrt.Gf.Matrix4d: numpy.double,
usdrt.Gf.Matrix4f: numpy.single,
}
return equivalent_types
class TestGfMatBuffer(TestRtScenegraph):
"""Test buffer protocol for usdrt.Gf.Matrix* classes"""
@tc_logger
def test_buffer_inspect(self):
"""Use memoryview to validate that buffer protocol is implemented"""
mat_info = get_mat_info()
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
v = Mat(*test_values[:count])
view = memoryview(v)
self.assertEquals(view.itemsize, size)
self.assertEquals(view.ndim, 2)
self.assertEquals(view.shape, (math.sqrt(count), math.sqrt(count)))
self.assertEquals(view.format, fmt)
self.assertEquals(view.obj, Mat(*test_values[:count]))
@tc_logger
def test_buffer_init_from_pxr_type(self):
"""Validate initialization from equivalent Pixar types"""
import pxr
import usdrt
mat_info = get_mat_info()
equivalent_types = {
usdrt.Gf.Matrix3d: pxr.Gf.Matrix3d,
usdrt.Gf.Matrix3f: pxr.Gf.Matrix3f,
usdrt.Gf.Matrix4d: pxr.Gf.Matrix4d,
usdrt.Gf.Matrix4f: pxr.Gf.Matrix4f,
}
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
test_pxr_type = equivalent_types[Mat](*test_values[:count])
test_mat = Mat(test_pxr_type)
self.assertEquals(test_mat, Mat(*test_values[:count]))
@tc_logger
def test_buffer_init_from_numpy_type(self):
"""Test initialization from numpy types"""
import numpy
mat_info = get_mat_info()
equivalent_types = get_mat_numpy_types()
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
py_mat = []
stride = int(math.sqrt(count))
for i in range(stride):
py_mat.append(test_values[i * stride : i * stride + stride])
test_numpy_type = numpy.array(py_mat, dtype=equivalent_types[Mat])
test_mat = Mat(test_numpy_type)
self.assertEquals(test_mat, Mat(*test_values[:count]))
@tc_logger
def test_buffer_init_wrong_type(self):
"""Verify that an exception is raised with initializing via buffer with different data type"""
import numpy
mat_info = get_mat_info()
equivalent_types = get_mat_numpy_types()
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
py_mat = []
stride = int(math.sqrt(count))
for i in range(stride):
py_mat.append(test_values[i * stride : i * stride + stride])
test_numpy_type = numpy.array(py_mat, dtype=numpy.int_)
with self.assertRaises(ValueError):
test_mat = Mat(test_numpy_type)
@tc_logger
def test_buffer_init_wrong_size(self):
"""Verify that an exception is raised with initializing via buffer with different data array length"""
import numpy
mat_info = get_mat_info()
equivalent_types = get_mat_numpy_types()
test_values = [[0, 1], [2, 3]]
for Mat, size, count, fmt in mat_info:
test_numpy_type = numpy.array(test_values, dtype=equivalent_types[Mat])
with self.assertRaises(ValueError):
test_mat = Mat(test_numpy_type)
@tc_logger
def test_buffer_init_wrong_dimension(self):
"""Verify that an exception is raised with initializing via buffer with different data dimensions"""
import numpy
mat_info = get_mat_info()
equivalent_types = get_mat_numpy_types()
test_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
for Mat, size, count, fmt in mat_info:
test_array = numpy.array(test_values[:count], dtype=equivalent_types[Mat])
with self.assertRaises(ValueError):
test_mat = Mat(test_array)
class TestGfMatrixGetSetItem(TestRtScenegraph):
"""Test single-item accessors for usdrt.Gf.Matrix* classes"""
@tc_logger
def test_get_item(self):
"""Validate GetArrayItem on GfMatrix"""
from usdrt import Gf
for Mat in [Gf.Matrix3d, Gf.Matrix3f, Gf.Matrix4d, Gf.Matrix4f]:
items = Mat.dimension[0] * Mat.dimension[1]
m = Mat(*[i for i in range(items)])
for i in range(items):
self.assertTrue(m.GetArrayItem(i) == i)
@tc_logger
def test_set_item(self):
"""Validate SetArrayItem on GfMatrix"""
from usdrt import Gf
for Mat in [Gf.Matrix3d, Gf.Matrix3f, Gf.Matrix4d, Gf.Matrix4f]:
m = Mat()
self.assertEqual(m, Mat(1))
items = Mat.dimension[0] * Mat.dimension[1]
expected = Mat(*[i for i in range(items)])
for i in range(items):
m.SetArrayItem(i, i)
self.assertNotEqual(m, Mat(1))
self.assertEqual(m, expected)
class TestGfMatCopy(TestRtScenegraph):
"""Test copy and deepcopy support for Gf.Mat* classes"""
@tc_logger
def test_copy(self):
"""Test __copy__"""
mat_info = get_mat_info()
for Mat, size, count, fmt in mat_info:
x = Mat()
y = x
self.assertTrue(y is x)
y[0, 0] = 10
self.assertEqual(x[0, 0], 10)
z = copy.copy(y)
self.assertFalse(z is y)
y[0, 0] = 100
self.assertEqual(z[0, 0], 10)
@tc_logger
def test_deepcopy(self):
"""Test __deepcopy__"""
mat_info = get_mat_info()
for Mat, size, count, fmt in mat_info:
x = Mat()
y = x
self.assertTrue(y is x)
y[0, 0] = 10
self.assertEqual(x[0, 0], 10)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y[0, 0] = 100
self.assertEqual(z[0, 0], 10)
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfMatrix.py | # Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and lightly modified
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfMatrix.py
from __future__ import division, print_function
__copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 math
import sys
import unittest
##### Uncomment for better assert messages
# if 'unittest.util' in __import__('sys').modules:
# # Show full diff in self.assertEqual.
# __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
try:
import numpy
hasNumpy = True
except ImportError:
print("numpy not available, skipping buffer protocol tests")
hasNumpy = False
def makeValue(Value, vals):
if Value == float:
return Value(vals[0])
else:
v = Value()
for i in range(v.dimension):
v[i] = vals[i]
return v
class TestGfMatrix(TestClass):
def test_Basic(self):
from usdrt import Gf
Matrices = [ # (Gf.Matrix2d, Gf.Vec2d),
# (Gf.Matrix2f, Gf.Vec2f),
(Gf.Matrix3d, Gf.Vec3d),
(Gf.Matrix3f, Gf.Vec3f),
(Gf.Matrix4d, Gf.Vec4d),
(Gf.Matrix4f, Gf.Vec4f),
]
for (Matrix, Vec) in Matrices:
# constructors
self.assertIsInstance(Matrix(), Matrix)
self.assertIsInstance(Matrix(1), Matrix)
self.assertIsInstance(Matrix(Vec()), Matrix)
# python default constructor produces identity.
self.assertEqual(Matrix(), Matrix(1))
if hasNumpy:
# Verify population of numpy arrays.
emptyNumpyArray = numpy.empty((1, Matrix.dimension[0], Matrix.dimension[1]), dtype="float32")
emptyNumpyArray[0] = Matrix(1)
if Matrix.dimension == (2, 2):
self.assertIsInstance(Matrix(1, 2, 3, 4), Matrix)
self.assertEqual(Matrix().Set(1, 2, 3, 4), Matrix(1, 2, 3, 4))
array = numpy.array(Matrix(1, 2, 3, 4))
self.assertEqual(array.shape, (2, 2))
# XXX: Currently cannot round-trip Gf.Matrix*f through
# numpy.array
if Matrix != Gf.Matrix2f:
self.assertEqual(Matrix(array), Matrix(1, 2, 3, 4))
elif Matrix.dimension == (3, 3):
self.assertIsInstance(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9), Matrix)
self.assertEqual(Matrix().Set(1, 2, 3, 4, 5, 6, 7, 8, 9), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9))
array = numpy.array(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9))
self.assertEqual(array.shape, (3, 3))
# XXX: Currently cannot round-trip Gf.Matrix*f through
# numpy.array
if Matrix != Gf.Matrix3f:
self.assertEqual(Matrix(array), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9))
elif Matrix.dimension == (4, 4):
self.assertIsInstance(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), Matrix)
self.assertEqual(
Matrix().Set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
)
array = numpy.array(Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
self.assertEqual(array.shape, (4, 4))
# XXX: Currently cannot round-trip Gf.Matrix*f through
# numpy.array
if Matrix != Gf.Matrix4f:
self.assertEqual(Matrix(array), Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
else:
self.fail()
self.assertEqual(Matrix().SetIdentity(), Matrix(1))
self.assertEqual(Matrix().SetZero(), Matrix(0))
self.assertEqual(Matrix().SetDiagonal(0), Matrix().SetZero())
self.assertEqual(Matrix().SetDiagonal(1), Matrix().SetIdentity())
def test_Comparisons(self):
from usdrt import Gf
Matrices = [(Gf.Matrix3d, Gf.Matrix3f), (Gf.Matrix4d, Gf.Matrix4f)] # (Gf.Matrix2d, Gf.Matrix2f),
for (Matrix, Matrixf) in Matrices:
# Test comparison of Matrix and Matrixf
#
size = Matrix.dimension[0] * Matrix.dimension[1]
contents = list(range(1, size + 1))
md = Matrix(*contents)
mf = Matrixf(*contents)
self.assertEqual(md, mf)
contents.reverse()
md.Set(*contents)
mf.Set(*contents)
self.assertEqual(md, mf)
# Convert to double precision floating point values
contents = [1.0 / x for x in contents]
mf.Set(*contents)
md.Set(*contents)
# These should *NOT* be equal due to roundoff errors in the floats.
self.assertNotEqual(md, mf)
def test_Other(self):
from usdrt import Gf
Matrices = [ # (Gf.Matrix2d, Gf.Vec2d),
# (Gf.Matrix2f, Gf.Vec2f),
(Gf.Matrix3d, Gf.Vec3d),
(Gf.Matrix3f, Gf.Vec3f),
(Gf.Matrix4d, Gf.Vec4d),
(Gf.Matrix4f, Gf.Vec4f),
]
for (Matrix, Vec) in Matrices:
v = Vec()
for i in range(v.dimension):
v[i] = i
m1 = Matrix().SetDiagonal(v)
m2 = Matrix(0)
for i in range(m2.dimension[0]):
m2[i, i] = i
self.assertEqual(m1, m2)
v = Vec()
for i in range(v.dimension):
v[i] = 10
self.assertEqual(Matrix().SetDiagonal(v), Matrix().SetDiagonal(10))
self.assertEqual(type(Matrix()[0]), Vec)
m = Matrix()
m[0] = makeValue(Vec, (3, 1, 4, 1))
self.assertEqual(m[0], makeValue(Vec, (3, 1, 4, 1)))
m = Matrix()
m[-1] = makeValue(Vec, (3, 1, 4, 1))
self.assertEqual(m[-1], makeValue(Vec, (3, 1, 4, 1)))
m = Matrix()
m[0, 0] = 1
m[1, 0] = 2
m[0, 1] = 3
m[1, 1] = 4
self.assertTrue(m[0, 0] == 1 and m[1, 0] == 2 and m[0, 1] == 3 and m[1, 1] == 4)
m = Matrix()
m[-1, -1] = 1
m[-2, -1] = 2
m[-1, -2] = 3
m[-2, -2] = 4
self.assertTrue(m[-1, -1] == 1 and m[-2, -1] == 2 and m[-1, -2] == 3 and m[-2, -2] == 4)
m = Matrix()
for i in range(m.dimension[0]):
for j in range(m.dimension[1]):
m[i, j] = i * m.dimension[1] + j
m = m.GetTranspose()
for i in range(m.dimension[0]):
for j in range(m.dimension[1]):
self.assertEqual(m[j, i], i * m.dimension[1] + j)
self.assertEqual(Matrix(1).GetInverse(), Matrix(1))
self.assertEqual(Matrix(4).GetInverse() * Matrix(4), Matrix(1))
# nv edit - intentionally diverge from pixar's implementation
# GetInverse for zero matrix returns zero matrix instead of max float scale matrix
# "so that multiplying by this is less likely to be catastrophic."
self.assertEqual(Matrix(0).GetInverse(), Matrix(0))
self.assertEqual(Matrix(3).GetDeterminant(), 3 ** Matrix.dimension[0])
self.assertEqual(len(Matrix()), Matrix.dimension[0])
# Test GetRow, GetRow3, GetColumn
m = Matrix(1)
for i in range(m.dimension[0]):
for j in range(m.dimension[1]):
m[i, j] = i * m.dimension[1] + j
for i in range(m.dimension[0]):
j0 = i * m.dimension[1]
self.assertEqual(m.GetRow(i), makeValue(Vec, tuple(range(j0, j0 + m.dimension[1]))))
if Matrix == Gf.Matrix4d:
self.assertEqual(m.GetRow3(i), Gf.Vec3d(j0, j0 + 1, j0 + 2))
for j in range(m.dimension[1]):
self.assertEqual(
m.GetColumn(j), makeValue(Vec, tuple(j + x * m.dimension[0] for x in range(m.dimension[0])))
)
# Test SetRow, SetRow3, SetColumn
m = Matrix(1)
for i in range(m.dimension[0]):
j0 = i * m.dimension[1]
v = makeValue(Vec, tuple(range(j0, j0 + m.dimension[1])))
m.SetRow(i, v)
self.assertEqual(v, m.GetRow(i))
m = Matrix(1)
if Matrix == Gf.Matrix4d:
for i in range(m.dimension[0]):
j0 = i * m.dimension[1]
v = Gf.Vec3d(j0, j0 + 1, j0 + 2)
m.SetRow3(i, v)
self.assertEqual(v, m.GetRow3(i))
m = Matrix(1)
for j in range(m.dimension[0]):
v = makeValue(Vec, tuple(j + x * m.dimension[0] for x in range(m.dimension[0])))
m.SetColumn(i, v)
self.assertEqual(v, m.GetColumn(i))
m = Matrix(4)
m *= Matrix(1.0 / 4)
self.assertEqual(m, Matrix(1))
m = Matrix(4)
self.assertEqual(m * Matrix(1.0 / 4), Matrix(1))
self.assertEqual(Matrix(4) * 2, Matrix(8))
self.assertEqual(2 * Matrix(4), Matrix(8))
m = Matrix(4)
m *= 2
self.assertEqual(m, Matrix(8))
m = Matrix(3)
m += Matrix(2)
self.assertEqual(m, Matrix(5))
m = Matrix(3)
m -= Matrix(2)
self.assertEqual(m, Matrix(1))
self.assertEqual(Matrix(2) + Matrix(3), Matrix(5))
self.assertEqual(Matrix(4) - Matrix(4), Matrix(0))
self.assertEqual(-Matrix(-1), Matrix(1))
self.assertEqual(Matrix(3) / Matrix(2), Matrix(3) * Matrix(2).GetInverse())
self.assertEqual(Matrix(2) * makeValue(Vec, (3, 1, 4, 1)), makeValue(Vec, (6, 2, 8, 2)))
self.assertEqual(makeValue(Vec, (3, 1, 4, 1)) * Matrix(2), makeValue(Vec, (6, 2, 8, 2)))
Vecf = {Gf.Vec2d: Gf.Vec2f, Gf.Vec3d: Gf.Vec3f, Gf.Vec4d: Gf.Vec4f}.get(Vec)
if Vecf is not None:
self.assertEqual(Matrix(2) * makeValue(Vecf, (3, 1, 4, 1)), makeValue(Vecf, (6, 2, 8, 2)))
self.assertEqual(makeValue(Vecf, (3, 1, 4, 1)) * Matrix(2), makeValue(Vecf, (6, 2, 8, 2)))
self.assertTrue(2 in Matrix(2) and not 4 in Matrix(2))
m = Matrix(1)
try:
m[m.dimension[0] + 1] = Vec()
except:
pass
else:
self.fail()
m = Matrix(1)
try:
m[m.dimension[0] + 1, m.dimension[1] + 1] = 10
except:
pass
else:
self.fail()
m = Matrix(1)
try:
m[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] = 3
self.fail()
except:
pass
try:
x = m[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
self.fail()
except:
pass
m = Matrix(1)
try:
m["foo"] = 3
except:
pass
else:
self.fail()
self.assertEqual(m, eval(repr(m)))
self.assertTrue(len(str(Matrix())))
def test_Matrix3Transforms(self):
from usdrt import Gf
# TODO - Gf.Rotation not supported,
# so this test is currently a noop
Matrices = [ # (Gf.Matrix3d, Gf.Vec3d, Gf.Quatd),
# (Gf.Matrix3f, Gf.Vec3f, Gf.Quatf)
]
for (Matrix, Vec, Quat) in Matrices:
def _VerifyOrthonormVecs(mat):
v0 = Vec(mat[0][0], mat[0][1], mat[0][2])
v1 = Vec(mat[1][0], mat[1][1], mat[1][2])
v2 = Vec(mat[2][0], mat[2][1], mat[2][2])
self.assertTrue(
Gf.IsClose(Gf.Dot(v0, v1), 0, 0.0001)
and Gf.IsClose(Gf.Dot(v0, v2), 0, 0.0001)
and Gf.IsClose(Gf.Dot(v1, v2), 0, 0.0001)
)
m = Matrix()
m.SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30))
m2 = Matrix(m)
m_o = m.GetOrthonormalized()
self.assertEqual(m_o, m2)
m.Orthonormalize()
self.assertEqual(m, m2)
m = Matrix(3)
m_o = m.GetOrthonormalized()
# GetOrthonormalized() should not mutate m
self.assertNotEqual(m, m_o)
self.assertEqual(m_o, Matrix(1))
m.Orthonormalize()
self.assertEqual(m, Matrix(1))
m = Matrix(1, 0, 0, 1, 0, 0, 1, 0, 0)
# should print a warning
print("expect a warning about failed convergence in OrthogonalizeBasis:")
m.Orthonormalize()
m = Matrix(1, 0, 0, 1, 0, 0.0001, 0, 1, 0)
m_o = m.GetOrthonormalized()
_VerifyOrthonormVecs(m_o)
m.Orthonormalize()
_VerifyOrthonormVecs(m)
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)).ExtractRotation()
r2 = Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 1, 1), 60)).ExtractRotation()
r2 = Gf.Rotation(Gf.Vec3d(1, 1, 1), 60)
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 1, 1), 90)).ExtractRotation()
r2 = Gf.Rotation(Gf.Vec3d(1, 1, 1), 90)
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 1, 1), 120)).ExtractRotation()
r2 = Gf.Rotation(Gf.Vec3d(1, 1, 1), 120)
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
# Setting rotation using a quaternion should give the same results
# as setting a GfRotation.
rot = Gf.Rotation(Gf.Vec3d(1, 1, 1), 120)
quat = Quat(rot.GetQuaternion().GetReal(), Vec(rot.GetQuaternion().GetImaginary()))
r = Matrix().SetRotate(rot).ExtractRotation()
r2 = Matrix().SetRotate(quat).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
self.assertEqual(Matrix().SetScale(10), Matrix(10))
m = Matrix().SetScale(Vec(1, 2, 3))
self.assertTrue(m[0, 0] == 1 and m[1, 1] == 2 and m[2, 2] == 3)
# Initializing with GfRotation should give same results as SetRotate.
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)).ExtractRotation()
r2 = Matrix(Gf.Rotation(Gf.Vec3d(1, 0, 0), 30)).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
# Initializing with a quaternion should give same results as SetRotate.
rot = Gf.Rotation(Gf.Vec3d(1, 1, 1), 120)
quat = Quat(rot.GetQuaternion().GetReal(), Vec(rot.GetQuaternion().GetImaginary()))
r = Matrix().SetRotate(quat).ExtractRotation()
r2 = Matrix(quat).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and Gf.IsClose(r.angle, r2.angle, 0.0001))
self.assertEqual(Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1).GetHandedness(), 1.0)
self.assertEqual(Matrix(-1, 0, 0, 0, 1, 0, 0, 0, 1).GetHandedness(), -1.0)
self.assertEqual(Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0).GetHandedness(), 0.0)
self.assertTrue(Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1).IsRightHanded())
self.assertTrue(Matrix(-1, 0, 0, 0, 1, 0, 0, 0, 1).IsLeftHanded())
# Test that this does not generate a nan in the angle (bug #12744)
mx = Gf.Matrix3d(
0.999999999982236,
-5.00662622471027e-06,
2.07636574601397e-06,
5.00666175191934e-06,
1.0000000000332,
-2.19113616402155e-07,
-2.07635686422463e-06,
2.19131379884019e-07,
1,
)
r = mx.ExtractRotation()
# math.isnan won't be available until python 2.6
if sys.version_info[0] >= 2 and sys.version_info[1] >= 6:
self.assertFalse(math.isnan(r.angle))
else:
# If this fails, then r.angle is Nan. Works on linux, may not be portable.
self.assertEqual(r.angle, r.angle)
def test_Matrix4Transforms(self):
from usdrt import Gf
# nv edit - TODO support Quatd and Quatf
Matrices = [
(Gf.Matrix4d, Gf.Vec4d, Gf.Matrix3d, Gf.Vec3d), # , Gf.Quatd),
(Gf.Matrix4f, Gf.Vec4f, Gf.Matrix3f, Gf.Vec3f),
] # , Gf.Quatf)]
# for (Matrix, Vec, Matrix3, Vec3, Quat) in Matrices:
for (Matrix, Vec, Matrix3, Vec3) in Matrices:
def _VerifyOrthonormVecs(mat):
v0 = Vec3(mat[0][0], mat[0][1], mat[0][2])
v1 = Vec3(mat[1][0], mat[1][1], mat[1][2])
v2 = Vec3(mat[2][0], mat[2][1], mat[2][2])
self.assertTrue(
Gf.IsClose(Gf.Dot(v0, v1), 0, 0.0001)
and Gf.IsClose(Gf.Dot(v0, v2), 0, 0.0001)
and Gf.IsClose(Gf.Dot(v1, v2), 0, 0.0001)
)
m = Matrix()
m.SetLookAt(Vec3(1, 0, 0), Vec3(0, 0, 1), Vec3(0, 1, 0))
# nv edit - break this across multiple statements
self.assertTrue(Gf.IsClose(m[0], Vec(-0.707107, 0, 0.707107, 0), 0.0001))
self.assertTrue(Gf.IsClose(m[1], Vec(0, 1, 0, 0), 0.0001))
self.assertTrue(Gf.IsClose(m[2], Vec(-0.707107, 0, -0.707107, 0), 0.0001))
self.assertTrue(Gf.IsClose(m[3], Vec(0.707107, 0, -0.707107, 1), 0.0001))
# Transform
v = Gf.Vec3f(1, 1, 1)
v2 = Matrix(3).Transform(v)
self.assertEqual(v2, Gf.Vec3f(1, 1, 1))
self.assertEqual(type(v2), Gf.Vec3f)
v = Gf.Vec3d(1, 1, 1)
v2 = Matrix(3).Transform(v)
self.assertEqual(v2, Gf.Vec3d(1, 1, 1))
self.assertEqual(type(v2), Gf.Vec3d)
# TransformDir
v = Gf.Vec3f(1, 1, 1)
v2 = Matrix(3).TransformDir(v)
self.assertEqual(v2, Gf.Vec3f(3, 3, 3))
self.assertEqual(type(v2), Gf.Vec3f)
v = Gf.Vec3d(1, 1, 1)
v2 = Matrix(3).TransformDir(v)
self.assertEqual(v2, Gf.Vec3d(3, 3, 3))
self.assertEqual(type(v2), Gf.Vec3d)
# TransformAffine
v = Gf.Vec3f(1, 1, 1)
# nv edit - no implict conversion from tuple yet
v2 = Matrix(3).SetTranslateOnly(Vec3(1, 2, 3)).TransformAffine(v)
self.assertEqual(v2, Gf.Vec3f(4, 5, 6))
self.assertEqual(type(v2), Gf.Vec3f)
v = Gf.Vec3d(1, 1, 1)
# nv edit - no implict conversion from tuple yet
v2 = Matrix(3).SetTranslateOnly(Vec3(1, 2, 3)).TransformAffine(v)
self.assertEqual(v2, Gf.Vec3d(4, 5, 6))
self.assertEqual(type(v2), Gf.Vec3d)
# Constructor, SetRotate, and SetRotateOnly w/GfQuaternion
""" nv edit Gf.Rotation not supported
m = Matrix()
r = Gf.Rotation(Gf.Vec3d(1,0,0), 30)
quat = r.GetQuaternion()
m.SetRotate(Quat(quat.GetReal(), Vec3(quat.GetImaginary())))
m2 = Matrix(r, Vec3(0,0,0))
m_o = m.GetOrthonormalized()
self.assertEqual(m_o, m2)
m.Orthonormalize()
self.assertEqual(m, m2)
m3 = Matrix(1)
m3.SetRotateOnly(Quat(quat.GetReal(), Vec3(quat.GetImaginary())))
self.assertEqual(m2, m3)
# Constructor, SetRotate, and SetRotateOnly w/GfRotation
m = Matrix()
r = Gf.Rotation(Gf.Vec3d(1,0,0), 30)
m.SetRotate(r)
m2 = Matrix(r, Vec3(0,0,0))
m_o = m.GetOrthonormalized()
self.assertEqual(m_o, m2)
m.Orthonormalize()
self.assertEqual(m, m2)
m3 = Matrix(1)
m3.SetRotateOnly(r)
self.assertEqual(m2, m3)
# Constructor, SetRotate, and SetRotateOnly w/mx
m3d = Matrix3()
m3d.SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), 30))
m = Matrix(m3d, Vec3(0,0,0))
m2 = Matrix()
m2 = m2.SetRotate(m3d)
m3 = Matrix()
m3 = m2.SetRotateOnly(m3d)
self.assertEqual(m, m2)
self.assertEqual(m2, m3)
"""
m = Matrix().SetTranslate(Vec3(12, 13, 14)) * Matrix(3)
m.Orthonormalize()
t = Matrix().SetTranslate(m.ExtractTranslation())
mnot = m * t.GetInverse()
self.assertEqual(mnot, Matrix(1))
m = Matrix()
m.SetTranslate(Vec3(1, 2, 3))
m2 = Matrix(m)
m3 = Matrix(1)
m3.SetTranslateOnly(Vec3(1, 2, 3))
m_o = m.GetOrthonormalized()
self.assertEqual(m_o, m2)
self.assertEqual(m_o, m3)
m.Orthonormalize()
self.assertEqual(m, m2)
self.assertEqual(m, m3)
v = Vec3(11, 22, 33)
m = Matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16).SetTranslateOnly(v)
self.assertEqual(m.ExtractTranslation(), v)
# Initializing with GfRotation should give same results as SetRotate
# and SetTransform
""" nv edit TODO
r = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0),30)).ExtractRotation()
r2 = Matrix(Gf.Rotation(Gf.Vec3d(1,0,0),30), Vec3(1,2,3)).ExtractRotation()
r3 = Matrix().SetTransform(Gf.Rotation(Gf.Vec3d(1,0,0),30), Vec3(1,2,3)).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and \
Gf.IsClose(r.angle, r2.angle, 0.0001))
self.assertTrue(Gf.IsClose(r3.axis, r2.axis, 0.0001) and \
Gf.IsClose(r3.angle, r2.angle, 0.0001))
# Initializing with GfRotation should give same results as
# SetRotate(quaternion) and SetTransform
rot = Gf.Rotation(Gf.Vec3d(1,0,0),30)
quat = Quat(rot.GetQuaternion().GetReal(),
Vec3(rot.GetQuaternion().GetImaginary()))
r = Matrix().SetRotate(quat).ExtractRotation()
r2 = Matrix(rot, Vec3(1,2,3)).ExtractRotation()
r3 = Matrix().SetTransform(rot, Vec3(1,2,3)).ExtractRotation()
self.assertTrue(Gf.IsClose(r.axis, r2.axis, 0.0001) and \
Gf.IsClose(r.angle, r2.angle, 0.0001))
self.assertTrue(Gf.IsClose(r3.axis, r2.axis, 0.0001) and \
Gf.IsClose(r3.angle, r2.angle, 0.0001))
# Same test w/mx instead of GfRotation
mx3d = Matrix3(Gf.Rotation(Gf.Vec3d(1,0,0),30))
r4 = Matrix().SetTransform(mx3d, Vec3(1,2,3)).ExtractRotation()
r5 = Matrix(mx3d, Vec3(1,2,3)).ExtractRotation()
self.assertTrue(Gf.IsClose(r4.axis, r2.axis, 0.0001) and \
Gf.IsClose(r4.angle, r2.angle, 0.0001))
self.assertTrue(Gf.IsClose(r4.axis, r5.axis, 0.0001) and \
Gf.IsClose(r4.angle, r5.angle, 0.0001))
# ExtractQuat() and ExtractRotation() should yield
# equivalent rotations.
m = Matrix(mx3d, Vec3(1,2,3))
r1 = m.ExtractRotation()
r2 = Gf.Rotation(m.ExtractRotationQuat())
self.assertTrue(Gf.IsClose(r1.axis, r2.axis, 0.0001) and \
Gf.IsClose(r2.angle, r2.angle, 0.0001))
m4 = Matrix(mx3d, Vec3(1,2,3)).ExtractRotationMatrix()
self.assertEqual(m4, mx3d)
"""
# Initializing with GfMatrix3d
# nv edit - dumb, not supported
# m = Matrix(1,2,3,0,4,5,6,0,7,8,9,0,10,11,12,1)
# m2 = Matrix(Matrix3(1,2,3,4,5,6,7,8,9), Vec3(10, 11, 12))
# assert(m == m2)
m = Matrix(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1)
# should print a warning - nv edit - our implementation doesn't
# print("expect a warning about failed convergence in OrthogonalizeBasis:")
m.Orthonormalize()
m = Matrix(1, 0, 0, 0, 1, 0, 0.0001, 0, 0, 1, 0, 0, 0, 0, 0, 1)
m_o = m.GetOrthonormalized()
_VerifyOrthonormVecs(m_o)
m.Orthonormalize()
_VerifyOrthonormVecs(m)
m = Matrix()
m[3, 0] = 4
m[3, 1] = 5
m[3, 2] = 6
self.assertEqual(m.ExtractTranslation(), Vec3(4, 5, 6))
self.assertEqual(Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).GetHandedness(), 1.0)
self.assertEqual(Matrix(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).GetHandedness(), -1.0)
self.assertEqual(Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).GetHandedness(), 0.0)
self.assertTrue(Matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).IsRightHanded())
self.assertTrue(Matrix(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).IsLeftHanded())
# RemoveScaleShear
""" nv edit Gf.Rotation not supported
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), 45))
m = Matrix().SetScale(Vec3(3,4,2)) * m
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), -30)) * m
r = m.RemoveScaleShear()
ro = r
ro.Orthonormalize()
self.assertEqual(ro, r)
shear = Matrix(1,0,1,0, 0,1,0,0, 0,0,1,0, 0,0,0,1)
r = shear.RemoveScaleShear()
ro = r
ro.Orthonormalize()
self.assertEqual(ro, r)
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), 45))
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), -30)) * m
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,1,0), 59)) * m
r = m.RemoveScaleShear()
maxEltErr = 0
for i in range(4):
for j in range(4):
maxEltErr = max(maxEltErr, abs(r[i][j] - m[i][j]))
self.assertTrue(Gf.IsClose(maxEltErr, 0.0, 1e-5))
# IsClose
self.assertFalse(Gf.IsClose(Matrix(1), Matrix(1.0001), 1e-5))
self.assertTrue(Gf.IsClose(Matrix(1), Matrix(1.000001), 1e-5))
"""
def test_Matrix4Factoring(self):
from usdrt import Gf
""" nv edit Gf.Rotation not supported
Matrices = [(Gf.Matrix4d, Gf.Vec3d),
(Gf.Matrix4f, Gf.Vec3f)]
for (Matrix, Vec3) in Matrices:
def testFactor(m, expectSuccess, eps=None):
factor = lambda m : m.Factor()
if eps is not None:
factor = lambda m : m.Factor(eps)
(success, scaleOrientation, scale, rotation, \
translation, projection) = factor(m)
self.assertEqual(success, expectSuccess)
factorProduct = scaleOrientation * \
Matrix().SetScale(scale) * \
scaleOrientation.GetInverse() * \
rotation * \
Matrix().SetTranslate(translation) * \
projection
maxEltErr = 0
for i in range(4):
for j in range(4):
maxEltErr = max(maxEltErr, abs(factorProduct[i][j] - m[i][j]))
self.assertTrue(Gf.IsClose(maxEltErr, 0.0, 1e-5), maxEltErr)
# A rotate
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), 45))
testFactor(m,True)
# A couple of rotates
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), -45))
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), 45)) * m
testFactor(m,True)
# A scale
m = Matrix().SetScale(Vec3(3,1,4))
testFactor(m,True)
# A scale in a rotated space
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), 45))
m = Matrix().SetScale(Vec3(3,4,2)) * m
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), -45)) * m
testFactor(m,True)
# A nearly degenerate scale
if Matrix == Gf.Matrix4d:
eps = 1e-10
elif Matrix == Gf.Matrix4f:
eps = 1e-5
m = Matrix().SetScale((eps*2, 1, 1))
testFactor(m,True)
# Test with epsilon.
m = Matrix().SetScale((eps*2, 1, 1))
testFactor(m,False,eps*3)
# A singular (1) scale in a rotated space
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,1,1), Gf.Vec3d(1,0,0) ))
m = m * Matrix().SetScale(Vec3(0,1,1))
m = m * Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), Gf.Vec3d(1,1,1) ))
testFactor(m,False)
# A singular (2) scale in a rotated space
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,1,1), Gf.Vec3d(1,0,0) ))
m = m * Matrix().SetScale(Vec3(0,0,1))
m = m * Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(1,0,0), Gf.Vec3d(1,1,1) ))
testFactor(m,False)
# A scale in a sheared space
shear = Matrix(1)
shear.SetRow3(0, Vec3(1, 1, 1).GetNormalized())
m = shear.GetInverse() * Matrix().SetScale(Vec3(2,3,4)) * shear
testFactor(m,True)
# A singular (1) scale in a sheared space
shear = Matrix(1)
shear.SetRow3(0, Vec3(1, 1, 1).GetNormalized())
m = shear.GetInverse() * Matrix().SetScale(Vec3(2,0,4)) * shear
testFactor(m,False)
# A singular (2) scale in a sheared space
shear = Matrix(1)
shear.SetRow3(0, Vec3(1, 1, 1).GetNormalized())
m = shear.GetInverse() * Matrix().SetScale(Vec3(0,3,0)) * shear
testFactor(m,False)
# A scale and a rotate
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) ))
m = Matrix().SetScale(Vec3(1,2,3)) * m
testFactor(m,True)
# A singular (1) scale and a rotate
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) ))
m = Matrix().SetScale(Vec3(0,2,3)) * m
testFactor(m,False)
# A singular (2) scale and a rotate
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) ))
m = Matrix().SetScale(Vec3(0,0,3)) * m
testFactor(m,False)
# A singular scale (1), rotate, translate
m = Matrix().SetTranslate(Vec3(3,1,4))
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) )) * m
m = Matrix().SetScale(Vec3(0,2,3)) * m
testFactor(m,False)
# A translate, rotate, singular scale (1), translate
m = Matrix().SetTranslate(Vec3(3,1,4))
m = Matrix().SetRotate(Gf.Rotation(Gf.Vec3d(0,0,1), Gf.Vec3d(1,1,-1) )) * m
m = Matrix().SetScale(Vec3(0,2,3)) * m
m = Matrix().SetTranslate(Vec3(-10,-20,-30)) * m
testFactor(m,False)
"""
def test_Matrix4Determinant(self):
from usdrt import Gf
Matrices = [Gf.Matrix4d, Gf.Matrix4f]
for Matrix in Matrices:
# Test GetDeterminant and GetInverse on Matrix4
def AssertDeterminant(m, det):
# Unfortunately, we don't have an override of Gf.IsClose
# for Gf.Matrix4*
for row1, row2 in zip(m * m.GetInverse(), Matrix()):
self.assertTrue(Gf.IsClose(row1, row2, 1e-5))
self.assertTrue(Gf.IsClose(m.GetDeterminant(), det, 1e-5))
m1 = Matrix(0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
det1 = -1.0
m2 = Matrix(0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)
det2 = -1.0
m3 = Matrix(0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0)
det3 = -1.0
m4 = Matrix(1.0, 2.0, -1.0, 3.0, 2.0, 1.0, 4.0, 5.1, 2.0, 3.0, 1.0, 6.0, 3.0, 2.0, 1.0, 1.0)
det4 = 16.8
AssertDeterminant(m1, det1)
AssertDeterminant(m2, det2)
AssertDeterminant(m3, det3)
AssertDeterminant(m4, det4)
AssertDeterminant(m1 * m1, det1 * det1)
AssertDeterminant(m1 * m4, det1 * det4)
AssertDeterminant(m1 * m3 * m4, det1 * det3 * det4)
AssertDeterminant(m1 * m3 * m4 * m2, det1 * det3 * det4 * det2)
AssertDeterminant(m2 * m3 * m4 * m2, det2 * det3 * det4 * det2)
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/test_gf_range_extras.py | __copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 copy
import math
import os
import platform
import sys
import time
import unittest
from . import TestRtScenegraph, tc_logger, update_path_and_load_usd
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
update_path_and_load_usd()
class TestGfRangeCopy(TestRtScenegraph):
"""Test copy and deepcopy support for Gf.Range* classes"""
@tc_logger
def test_copy(self):
"""Test __copy__"""
from usdrt import Gf
x = Gf.Range3d()
y = x
self.assertTrue(y is x)
y.min[0] = 10
self.assertEqual(x.min[0], 10)
z = copy.copy(y)
self.assertFalse(z is y)
y.min[0] = 100
self.assertEqual(z.min[0], 10)
x = Gf.Range2d()
y = x
self.assertTrue(y is x)
y.min[0] = 20
self.assertEqual(x.min[0], 20)
z = copy.copy(y)
self.assertFalse(z is y)
y.min[0] = 200
self.assertEqual(z.min[0], 20)
x = Gf.Range1d()
y = x
self.assertTrue(y is x)
y.min = 30
self.assertEqual(x.min, 30)
z = copy.copy(y)
self.assertFalse(z is y)
y.min = 300
self.assertEqual(z.min, 30)
@tc_logger
def test_deepcopy(self):
"""Test __deepcopy__"""
from usdrt import Gf
x = Gf.Range3d()
y = x
self.assertTrue(y is x)
y.min[0] = 10
self.assertEqual(x.min[0], 10)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y.min[0] = 100
self.assertEqual(z.min[0], 10)
x = Gf.Range2d()
y = x
self.assertTrue(y is x)
y.min[0] = 20
self.assertEqual(x.min[0], 20)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y.min[0] = 200
self.assertEqual(z.min[0], 20)
x = Gf.Range1d()
y = x
self.assertTrue(y is x)
y.min = 30
self.assertEqual(x.min, 30)
z = copy.deepcopy(y)
self.assertFalse(z is y)
y.min = 300
self.assertEqual(z.min, 30)
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfRange.py | #!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and modified
# (we only support Gf.Range3d classes, but not Gf.Range3f, so
# these tests are updated to reflect that)
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfRange.py
import math
import sys
import unittest
##### Uncomment for better assert messages
# if 'unittest.util' in __import__('sys').modules:
# # Show full diff in self.assertEqual.
# __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
from usdrt import Gf
def makeValue(Value, vals):
if Value == float:
return Value(vals[0])
else:
v = Value()
for i in range(v.dimension):
v[i] = vals[i]
return v
class TestGfRange(TestClass):
Ranges = [
(Gf.Range1d, float),
(Gf.Range2d, Gf.Vec2d),
(Gf.Range3d, Gf.Vec3d),
(Gf.Range1f, float),
(Gf.Range2f, Gf.Vec2f),
(Gf.Range3f, Gf.Vec3f),
]
def runTest(self):
for Range, Value in self.Ranges:
# constructors
self.assertIsInstance(Range(), Range)
self.assertIsInstance(Range(Value(), Value()), Range)
v = makeValue(Value, [1, 2, 3, 4])
r = Range()
r.min = v
self.assertEqual(r.min, v)
r.max = v
self.assertEqual(r.max, v)
r = Range()
self.assertTrue(r.IsEmpty())
r = Range(-1)
self.assertTrue(r.IsEmpty())
v1 = makeValue(Value, [-1, -2, -3, -4])
v2 = makeValue(Value, [1, 2, 3, 4])
r = Range(v2, v1)
self.assertTrue(r.IsEmpty())
r = Range(v1, v2)
self.assertFalse(r.IsEmpty())
r.SetEmpty()
self.assertTrue(r.IsEmpty())
r = Range(v1, v2)
self.assertEqual(r.GetSize(), v2 - v1)
v1 = makeValue(Value, [-1, 1, -11, 2])
v2 = makeValue(Value, [1, 3, -10, 2])
v3 = makeValue(Value, [0, 2, -10.5, 2])
v4 = makeValue(Value, [0, 0, 0, 0])
r1 = Range(v1, v2)
self.assertEqual(r1.GetMidpoint(), v3)
r1.SetEmpty()
r2 = Range()
self.assertEqual(r1.GetMidpoint(), v4)
self.assertEqual(r2.GetMidpoint(), v4)
v1 = makeValue(Value, [-1, -2, -3, -4])
v2 = makeValue(Value, [1, 2, 3, 4])
r = Range(v1, v2)
v1 = makeValue(Value, [0, 0, 0, 0])
v2 = makeValue(Value, [2, 3, 4, 5])
self.assertTrue(r.Contains(v1))
self.assertFalse(r.Contains(v2))
v1 = makeValue(Value, [-2, -4, -6, -8])
v2 = makeValue(Value, [2, 4, 6, 8])
r1 = Range(v1, v2)
v1 = makeValue(Value, [-1, -2, -3, -4])
v2 = makeValue(Value, [1, 2, 3, 4])
r2 = Range(v1, v2)
self.assertTrue(r1.Contains(r2))
self.assertFalse(r2.Contains(r1))
v1 = makeValue(Value, [-1, -2, -3, -4])
v2 = makeValue(Value, [2, 4, 6, 8])
v3 = makeValue(Value, [-2, -4, -6, -8])
v4 = makeValue(Value, [1, 2, 3, 4])
r1 = Range(v1, v2)
r2 = Range(v3, v4)
self.assertEqual(Range.GetUnion(r1, r2), Range(v3, v2))
self.assertEqual(Range.GetIntersection(r1, r2), Range(v1, v4))
r1 = Range(v1, v2)
self.assertEqual(r1.UnionWith(r2), Range(v3, v2))
r1 = Range(v1, v2)
self.assertEqual(r1.UnionWith(v3), Range(v3, v2))
r1 = Range(v1, v2)
self.assertEqual(r1.IntersectWith(r2), Range(v1, v4))
r1 = Range(v1, v2)
v5 = makeValue(Value, [100, 100, 100, 100])
dsqr = r1.GetDistanceSquared(v5)
if Value == float:
self.assertEqual(dsqr, 9604)
elif Value.dimension == 2:
self.assertEqual(dsqr, 18820)
elif Value.dimension == 3:
self.assertEqual(dsqr, 27656)
else:
self.fail()
r1 = Range(v1, v2)
v5 = makeValue(Value, [-100, -100, -100, -100])
dsqr = r1.GetDistanceSquared(v5)
if Value == float:
self.assertEqual(dsqr, 9801)
elif Value.dimension == 2:
self.assertEqual(dsqr, 19405)
elif Value.dimension == 3:
self.assertEqual(dsqr, 28814)
else:
self.fail()
v1 = makeValue(Value, [1, 2, 3, 4])
v2 = makeValue(Value, [2, 3, 4, 5])
v3 = makeValue(Value, [3, 4, 5, 6])
v4 = makeValue(Value, [4, 5, 6, 7])
r1 = Range(v1, v2)
r2 = Range(v2, v3)
r3 = Range(v3, v4)
r4 = Range(v4, v5)
self.assertEqual(r1 + r2, Range(makeValue(Value, [3, 5, 7, 9]), makeValue(Value, [5, 7, 9, 11])))
self.assertEqual(r1 - r2, Range(makeValue(Value, [-2, -2, -2, -2]), makeValue(Value, [0, 0, 0, 0])))
self.assertEqual(r1 * 10, Range(makeValue(Value, [10, 20, 30, 40]), makeValue(Value, [20, 30, 40, 50])))
self.assertEqual(10 * r1, Range(makeValue(Value, [10, 20, 30, 40]), makeValue(Value, [20, 30, 40, 50])))
tmp = r1 / 10
self.assertTrue(
Gf.IsClose(tmp.min, makeValue(Value, [0.1, 0.2, 0.3, 0.4]), 0.00001)
and Gf.IsClose(tmp.max, makeValue(Value, [0.2, 0.3, 0.4, 0.5]), 0.00001)
)
self.assertEqual(r1, Range(makeValue(Value, [1, 2, 3, 4]), makeValue(Value, [2, 3, 4, 5])))
self.assertFalse(r1 != Range(makeValue(Value, [1, 2, 3, 4]), makeValue(Value, [2, 3, 4, 5])))
r1 = Range(v1, v2)
r2 = Range(v2, v3)
r1 += r2
self.assertEqual(r1, Range(makeValue(Value, [3, 5, 7, 9]), makeValue(Value, [5, 7, 9, 11])))
r1 = Range(v1, v2)
r1 -= r2
self.assertEqual(r1, Range(makeValue(Value, [-2, -2, -2, -2]), makeValue(Value, [0, 0, 0, 0])))
r1 = Range(v1, v2)
r1 *= 10
self.assertEqual(r1, Range(makeValue(Value, [10, 20, 30, 40]), makeValue(Value, [20, 30, 40, 50])))
r1 = Range(v1, v2)
r1 *= -10
self.assertEqual(r1, Range(makeValue(Value, [-20, -30, -40, -50]), makeValue(Value, [-10, -20, -30, -40])))
r1 = Range(v1, v2)
r1 /= 10
self.assertTrue(
Gf.IsClose(r1.min, makeValue(Value, [0.1, 0.2, 0.3, 0.4]), 0.00001)
and Gf.IsClose(r1.max, makeValue(Value, [0.2, 0.3, 0.4, 0.5]), 0.00001)
)
self.assertEqual(r1, eval(repr(r1)))
self.assertTrue(len(str(Range())))
# now test GetCorner and GetOctant for Gf.Range2f and Gf.Range2d
Ranges = [(Gf.Range2d, Gf.Vec2d), (Gf.Range2f, Gf.Vec2f)]
for Range, Value in Ranges:
rf = Range.unitSquare()
self.assertTrue(
rf.GetCorner(0) == Value(0, 0)
and rf.GetCorner(1) == Value(1, 0)
and rf.GetCorner(2) == Value(0, 1)
and rf.GetCorner(3) == Value(1, 1)
)
self.assertTrue(
rf.GetQuadrant(0) == Range(Value(0, 0), Value(0.5, 0.5))
and rf.GetQuadrant(1) == Range(Value(0.5, 0), Value(1, 0.5))
and rf.GetQuadrant(2) == Range(Value(0, 0.5), Value(0.5, 1))
and rf.GetQuadrant(3) == Range(Value(0.5, 0.5), Value(1, 1))
)
# now test GetCorner and GetOctant for Gf.Range3f and Gf.Range3d
Ranges = [(Gf.Range3d, Gf.Vec3d), (Gf.Range3f, Gf.Vec3f)]
for Range, Value in Ranges:
rf = Range.unitCube()
self.assertTrue(
rf.GetCorner(0) == Value(0, 0, 0)
and rf.GetCorner(1) == Value(1, 0, 0)
and rf.GetCorner(2) == Value(0, 1, 0)
and rf.GetCorner(3) == Value(1, 1, 0)
and rf.GetCorner(4) == Value(0, 0, 1)
and rf.GetCorner(5) == Value(1, 0, 1)
and rf.GetCorner(6) == Value(0, 1, 1)
and rf.GetCorner(7) == Value(1, 1, 1)
and rf.GetCorner(8) == Value(0, 0, 0)
)
vals = [
[(0.0, 0.0, 0.0), (0.5, 0.5, 0.5)],
[(0.5, 0.0, 0.0), (1.0, 0.5, 0.5)],
[(0.0, 0.5, 0.0), (0.5, 1.0, 0.5)],
[(0.5, 0.5, 0.0), (1.0, 1.0, 0.5)],
[(0.0, 0.0, 0.5), (0.5, 0.5, 1.0)],
[(0.5, 0.0, 0.5), (1.0, 0.5, 1.0)],
[(0.0, 0.5, 0.5), (0.5, 1.0, 1.0)],
[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)],
]
ranges = [Range(Value(v[0]), Value(v[1])) for v in vals]
for i in range(8):
self.assertEqual(rf.GetOctant(i), ranges[i])
if __name__ == "__main__":
unittest.main()
|
omniverse-code/kit/exts/usdrt.gf.tests/usdrt/gf/tests/testGfQuat.py | # Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Note: This is just pulled directly from USD and modified
# (we only support Gf.Quat classes, but not Gf.Quaternion, so
# these tests are updated to reflect that)
# https://github.com/PixarAnimationStudios/USD/blob/release/pxr/base/gf/testenv/testGfQuaternion.py
from __future__ import division
__copyright__ = "Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved."
__license__ = """
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 math
import sys
import unittest
##### Uncomment for better assert messages
# if 'unittest.util' in __import__('sys').modules:
# # Show full diff in self.assertEqual.
# __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
def setUpModule():
# pre-load USD before anything else to prevent crash
# from weird carb conflict
# FIXME ^^^
try:
from . import update_path_and_load_usd
update_path_and_load_usd()
except ImportError:
# not needed in Kit
pass
try:
import omni.kit.test
TestClass = omni.kit.test.AsyncTestCase
except ImportError:
TestClass = unittest.TestCase
class TestGfQuaternion(TestClass):
def test_Constructors(self):
from usdrt import Gf
# self.assertIsInstance(Gf.Quaternion(), Gf.Quaternion)
# self.assertIsInstance(Gf.Quaternion(0), Gf.Quaternion)
# self.assertIsInstance(Gf.Quaternion(1, Gf.Vec3d(1,1,1)), Gf.Quaternion)
self.assertIsInstance(Gf.Quath(Gf.Quath()), Gf.Quath)
self.assertIsInstance(Gf.Quatf(Gf.Quatf()), Gf.Quatf)
self.assertIsInstance(Gf.Quatd(Gf.Quatd()), Gf.Quatd)
# Testing conversions between Quat[h,f,d]
self.assertIsInstance(Gf.Quath(Gf.Quatf()), Gf.Quath)
self.assertIsInstance(Gf.Quath(Gf.Quatd()), Gf.Quath)
self.assertIsInstance(Gf.Quatf(Gf.Quath()), Gf.Quatf)
self.assertIsInstance(Gf.Quatf(Gf.Quatd()), Gf.Quatf)
self.assertIsInstance(Gf.Quatd(Gf.Quath()), Gf.Quatd)
self.assertIsInstance(Gf.Quatd(Gf.Quatf()), Gf.Quatd)
def test_Properties(self):
from usdrt import Gf
# nv edit - use Quat classses instead of Quaternion
for Quat, Vec in ((Gf.Quatd, Gf.Vec3d), (Gf.Quatf, Gf.Vec3f), (Gf.Quath, Gf.Vec3h)):
q = Quat()
q.real = 10
self.assertEqual(q.real, 10)
q.imaginary = Vec(1, 2, 3)
self.assertEqual(q.imaginary, Vec(1, 2, 3))
def test_Methods(self):
from usdrt import Gf
# nv edit - use Quat classses instead of Quaternion
for Quat, Vec in ((Gf.Quatd, Gf.Vec3d), (Gf.Quatf, Gf.Vec3f), (Gf.Quath, Gf.Vec3h)):
q = Quat()
self.assertEqual(Quat.GetIdentity(), Quat(1, Vec()))
self.assertTrue(
Quat.GetIdentity().GetLength() == 1
and Gf.IsClose(Quat(1, Vec(2, 3, 4)).GetLength(), 5.4772255750516612, 0.00001)
)
q = Quat(1, Vec(2, 3, 4)).GetNormalized()
self.assertTrue(
Gf.IsClose(q.real, 0.182574, 0.0001)
and Gf.IsClose(q.imaginary, Vec(0.365148, 0.547723, 0.730297), 0.00001)
)
# nv edit - linalg does not support arbitrary epsilon here
# q = Quat(1,Vec(2,3,4)).GetNormalized(10)
# self.assertEqual(q, Quat.GetIdentity())
q = Quat(1, Vec(2, 3, 4))
q.Normalize()
self.assertTrue(
Gf.IsClose(q.real, 0.182574, 0.0001)
and Gf.IsClose(q.imaginary, Vec(0.365148, 0.547723, 0.730297), 0.00001)
)
# nv edit - linalg does not support arbitrary epsilon here
# q = Quat(1,Vec(2,3,4)).Normalize(10)
# self.assertEqual(q, Quat.GetIdentity())
if Quat == Gf.Quath:
# FIXME - below test does not pass for Quath:
# AssertionError: Gf.Quath(1.0, Gf.Vec3h(0.0, 0.0, 0.0)) != Gf.Quath(1.0, Gf.Vec3h(-0.0, -0.0, -0.0))
continue
q = Quat.GetIdentity()
self.assertEqual(q, q.GetInverse())
q = Quat(1, Vec(1, 2, 3))
q.Normalize()
(re, im) = (q.real, q.imaginary)
self.assertTrue(
Gf.IsClose(q.GetInverse().real, re, 0.00001) and Gf.IsClose(q.GetInverse().imaginary, -im, 0.00001)
)
def test_Operators(self):
from usdrt import Gf
# nv edit - use Quat classses instead of Quaternion
for Quat, Vec in ((Gf.Quatd, Gf.Vec3d), (Gf.Quatf, Gf.Vec3f), (Gf.Quath, Gf.Vec3h)):
q1 = Quat(1, Vec(2, 3, 4))
q2 = Quat(1, Vec(2, 3, 4))
self.assertEqual(q1, q2)
self.assertFalse(q1 != q2)
q2.real = 2
self.assertTrue(q1 != q2)
q = Quat(1, Vec(2, 3, 4)) * Quat.GetIdentity()
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q = Quat(1, Vec(2, 3, 4))
q *= Quat.GetIdentity()
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q *= 10
self.assertEqual(q, Quat(10, Vec(20, 30, 40)))
q = q * 10
self.assertEqual(q, Quat(100, Vec(200, 300, 400)))
q = 10 * q
self.assertEqual(q, Quat(1000, Vec(2000, 3000, 4000)))
q /= 100
self.assertEqual(q, Quat(10, Vec(20, 30, 40)))
q = q / 10
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q += q
self.assertEqual(q, Quat(2, Vec(4, 6, 8)))
q -= Quat(1, Vec(2, 3, 4))
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q = q + q
self.assertEqual(q, Quat(2, Vec(4, 6, 8)))
q = q - Quat(1, Vec(2, 3, 4))
self.assertEqual(q, Quat(1, Vec(2, 3, 4)))
q = q * q
self.assertEqual(q, Quat(-28, Vec(4, 6, 8)))
q1 = Quat(1, Vec(2, 3, 4)).GetNormalized()
q2 = Quat(4, Vec(3, 2, 1)).GetNormalized()
self.assertEqual(Gf.Slerp(0, q1, q2), q1)
# nv edit - these are close but not exact with our implementation
eps = 0.00001 if Quat in [Gf.Quatd, Gf.Quatf] else 0.001
# self.assertEqual(Gf.Slerp(1, q1, q2), q2)
self.assertTrue(Gf.IsClose(Gf.Slerp(1, q1, q2), q2, eps))
# self.assertEqual(Gf.Slerp(0.5, q1, q2), Quat(0.5, Vec(0.5, 0.5, 0.5)))
self.assertTrue(Gf.IsClose(Gf.Slerp(0.5, q1, q2), Quat(0.5, Vec(0.5, 0.5, 0.5)), eps))
# code coverage goodness
q1 = Quat(0, Vec(1, 1, 1))
q2 = Quat(0, Vec(-1, -1, -1))
q = Gf.Slerp(0.5, q1, q2)
self.assertTrue(Gf.IsClose(q.real, 0, 0.00001) and Gf.IsClose(q.imaginary, Vec(1, 1, 1), 0.00001))
q1 = Quat(0, Vec(1, 1, 1))
q2 = Quat(0, Vec(1, 1, 1))
q = Gf.Slerp(0.5, q1, q2)
self.assertTrue(Gf.IsClose(q.real, 0, 0.00001) and Gf.IsClose(q.imaginary, Vec(1, 1, 1), 0.00001))
self.assertEqual(q, eval(repr(q)))
self.assertTrue(len(str(Quat())))
for quatType in (Gf.Quatd, Gf.Quatf, Gf.Quath):
q1 = quatType(1, [2, 3, 4])
q2 = quatType(2, [3, 4, 5])
self.assertTrue(Gf.IsClose(Gf.Dot(q1, q2), 40, 0.00001))
if __name__ == "__main__":
unittest.main()
|
omniverse-code/kit/exts/usdrt.gf.tests/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "usdrt.Gf tests"
description="Tests for usdrt.Gf library"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Runtime"
# Keywords for the extension
keywords = ["usdrt", "runtime", "tests"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
# changelog="docs/CHANGELOG.md"
[dependencies]
"omni.usd.libs" = {}
# Main python module this extension provides, it will be publicly available as "import omni.example.hello".
[[python.module]]
name = "usdrt.gf.tests"
[[test]]
name="pxrGf"
dependencies = [
"omni.kit.test"
]
|
omniverse-code/kit/exts/omni.kit.property.audio/PACKAGE-LICENSES/omni.kit.property.audio-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. |
omniverse-code/kit/exts/omni.kit.property.audio/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.6"
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 = "Audio Property Widget"
description="View and Edit Audio Property Values"
# URL of the extension source repository.
repository = ""
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
# 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", "usd", "property", "audio", "sound"]
# 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.usd" = {}
"omni.ui" = {}
"omni.kit.window.property" = {}
"omni.kit.property.usd" = {}
"omni.kit.property.layer" = {}
[[python.module]]
name = "omni.kit.property.audio"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test"
]
|
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/__init__.py | from .scripts import *
|
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/scripts/audio_properties.py | import os
import carb
import omni.ext
from pathlib import Path
from .audio_settings_widget import AudioSettingsWidget
from pxr import Sdf, OmniAudioSchema, UsdMedia
TEST_DATA_PATH = ""
class AudioPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget, MultiSchemaPropertiesWidget
w = p.get_window()
if w:
w.register_widget("prim", "media", SchemaPropertiesWidget("Media", UsdMedia.SpatialAudio, False))
w.register_widget("prim", "audio_sound", SchemaPropertiesWidget("Sound", OmniAudioSchema.OmniSound, False))
w.register_widget("prim", "audio_listener", SchemaPropertiesWidget("Listener", OmniAudioSchema.OmniListener, False))
w.register_widget("layers", "audio_settings", AudioSettingsWidget())
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "media")
w.unregister_widget("prim", "audio_sound")
w.unregister_widget("prim", "audio_listener")
w.unregister_widget("layers", "audio_settings")
self._registered = False
|
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/scripts/__init__.py | from .audio_properties import *
|
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/scripts/audio_settings_widget.py | # Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.kit.app
import omni.kit.ui
import omni.ui as ui
from pxr import Usd
import omni.usd
import omni.usd.audio
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import SimplePropertyWidget
class AudioSettingsWidget(SimplePropertyWidget):
def __init__(self):
super().__init__(title="Audio Settings", collapsed=False)
self._stage = None
self._audio = omni.usd.audio.get_stage_audio_interface()
self._listener_setting_model = None
self._events = self._audio.get_metadata_change_stream()
if self._events is not None:
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_metadata_event, name="audio settings window"
)
self._doppler_setting = None
self._distance_delay_setting = None
self._interaural_delay_setting = None
self._concurrent_voices_setting = None
self._speed_of_sound_setting = None
self._doppler_scale_setting = None
self._doppler_limit_setting = None
self._spatial_timescale_setting = None
self._nonspatial_timescale_setting = None
def __del__(self):
self._stage_event_sub = None
self._events = None
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
# stage is not part of LayerItem payload
self.set_stage(omni.usd.get_context().get_stage())
return payload is not None
class ListenerComboBoxNotifier(omni.ui.AbstractItemModel):
class MinimalItem(omni.ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = omni.ui.SimpleStringModel(text)
def __init__(self, refresh_items_callback, set_callback):
super().__init__()
self._current_index = omni.ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._changed_model)
self._set_callback = set_callback
self._refresh_items_callback = refresh_items_callback
self._options = []
self.refresh_items()
self._path = ""
def get_value_as_string(self):
return self._path
def refresh_items(self):
self._options = ["Active Camera"]
self._options.extend(self._refresh_items_callback())
self._items = [
AudioSettingsWidget.ListenerComboBoxNotifier.MinimalItem(text) for text in self._options
]
return self._items
def _changed_model(self, model):
self._set_callback(model.as_int - 1)
self._item_changed(None)
def set_value(self, value):
# item 0 will always be "Active Camera" => handle 'None' or an empty string specially
# as if it were that value.
if value is None or value == "":
self._current_index.as_int = 0
self._path = ""
return
for i in range(0, len(self._options)):
if self._options[i] == value:
self._current_index.as_int = i
break
self._path = value
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
class DefaultsComboBoxNotifier(omni.ui.AbstractItemModel):
class MinimalItem(omni.ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = omni.ui.SimpleStringModel(text)
def __init__(self, set_callback):
super().__init__()
self._options = [
["on", omni.usd.audio.FeatureDefault.ON],
["off", omni.usd.audio.FeatureDefault.OFF],
["force on", omni.usd.audio.FeatureDefault.FORCE_ON],
["force off", omni.usd.audio.FeatureDefault.FORCE_OFF],
]
self._current_index = omni.ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._changed_model)
self._set_callback = set_callback
self._items = [
AudioSettingsWidget.DefaultsComboBoxNotifier.MinimalItem(text) for (text, value) in self._options
]
def _changed_model(self, model):
self._set_callback(self._options[model.as_int][1])
self._item_changed(None)
def set_value(self, value):
for i in range(0, len(self._options) - 1):
if self._options[i][1] == value:
self._current_index.as_int = i
break
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
class ChangeNotifier(omni.ui.AbstractValueModel):
def __init__(self, update_callback):
super(AudioSettingsWidget.ChangeNotifier, self).__init__()
self._update_callback = update_callback
self._value = 0
def get_value_as_string(self):
return str(self._value)
def get_value_as_int(self):
return int(self._value)
def get_value_as_float(self):
return float(self._value)
def begin_edit(self):
pass
class SlowChangeNotifier(ChangeNotifier):
def __init__(self, update_callback):
super(AudioSettingsWidget.SlowChangeNotifier, self).__init__(update_callback)
def set_value(self, value):
self._value = value
self._value_changed()
def end_edit(self):
self._update_callback(self._value)
pass
class FastChangeNotifier(ChangeNotifier):
def __init__(self, update_callback):
super(AudioSettingsWidget.FastChangeNotifier, self).__init__(update_callback)
def set_value(self, value):
self._value = value
self._value_changed()
self._update_callback(self._value)
def end_edit(self):
pass
def set_stage(self, stage: Usd.Stage):
self._stage = stage
def _caption(self, text, width=150):
"""Create a formated heading"""
with omni.ui.ZStack():
omni.ui.Rectangle(name="caption", width=width, style={"background_color": 0x454545})
omni.ui.Label(text, name="caption")
def _create_tooltip(self, text):
"""Create a tooltip in a fixed style"""
with omni.ui.VStack(width=400, style={"Label": {"color": 0xFF3B494B}}):
omni.ui.Label(text, word_wrap=True)
def _refresh_active_listener(self):
if not self._listener_setting_model:
return
active_listener = self._audio.get_active_listener()
if active_listener is None:
self._listener_setting_model.set_value(None)
else:
self._listener_setting_model.set_value(str(active_listener.GetPath()))
def _refresh(self):
self._refresh_active_listener()
if not self._listener_setting_model:
return
if self._doppler_setting:
self._doppler_setting.model.set_value(self._audio.get_doppler_default())
if self._distance_delay_setting:
self._distance_delay_setting.model.set_value(self._audio.get_distance_delay_default())
if self._interaural_delay_setting:
self._interaural_delay_setting.model.set_value(self._audio.get_interaural_delay_default())
if self._concurrent_voices_setting:
self._concurrent_voices_setting.model.set_value(self._audio.get_concurrent_voices())
if self._speed_of_sound_setting:
self._speed_of_sound_setting.model.set_value(self._audio.get_speed_of_sound())
if self._doppler_scale_setting:
self._doppler_scale_setting.model.set_value(self._audio.get_doppler_scale())
if self._doppler_limit_setting:
self._doppler_limit_setting.model.set_value(self._audio.get_doppler_limit())
if self._spatial_timescale_setting:
self._spatial_timescale_setting.model.set_value(self._audio.get_spatial_time_scale())
if self._nonspatial_timescale_setting:
self._nonspatial_timescale_setting.model.set_value(self._audio.get_nonspatial_time_scale())
def _on_metadata_event(self, event):
if event.type == int(omni.usd.audio.EventType.METADATA_CHANGE):
self._refresh()
elif event.type == int(omni.usd.audio.EventType.LISTENER_LIST_CHANGE):
if self._listener_setting_model is not None:
self._listener_setting_model.refresh_items()
elif event.type == int(omni.usd.audio.EventType.ACTIVE_LISTENER_CHANGE):
self._refresh_active_listener()
def _refresh_listeners(self):
list = []
count = self._audio.get_listener_count()
for i in range(0, count):
list.append(str(self._audio.get_listener_by_index(i).GetPath()))
return list
def _set_active_listener(self, index):
# a negative index means the active camera should be used as the listener.
if index < 0:
self._audio.set_active_listener(None)
# all other indices are assumed to be an index into the listener list.
else:
prim = self._audio.get_listener_by_index(index)
if prim is None:
return
self._audio.set_active_listener(prim)
def _add_label(self, label: str):
filter_text = self._filter.name
UsdPropertiesWidgetBuilder._create_label(label, {}, {"highlight": filter_text})
self._any_item_visible = True
def build_items(self):
def item_visible(label: str) -> bool:
return not self._filter or self._filter.matches(label)
with omni.ui.VStack(height=0, spacing=8):
if item_visible("Active Listener"):
with ui.HStack():
self._add_label("Active Listener")
self._listener_setting_model = AudioSettingsWidget.ListenerComboBoxNotifier(
self._refresh_listeners, self._set_active_listener
)
self._listener_setting = omni.ui.ComboBox(
self._listener_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"The path to the active Listener prim in the current USD scene. "
+ "Spatial audio calculations use the active listener as the position "
+ "(and optionally orientation) in 3D space, where the audio is heard "
+ "from. This value must be set to a valid Listener prim if 'Use "
+ "active camera as listener' is unchecked."
),
)
if item_visible("Doppler default"):
with ui.HStack():
self._add_label("Doppler default")
self._doppler_setting_model = AudioSettingsWidget.DefaultsComboBoxNotifier(
self._audio.set_doppler_default
)
self._doppler_setting = omni.ui.ComboBox(
self._doppler_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"This sets the value that Sound prims will use for enableDoppler "
+ "when that parameter is set to 'default'. This also allows the "
+ "setting to be forced on or off on all prims for testing purposes, "
+ "using the 'force on' and 'force off' values"
),
)
if item_visible("Distance delay default"):
with ui.HStack():
self._add_label("Distance delay default")
self._distance_delay_setting_model = AudioSettingsWidget.DefaultsComboBoxNotifier(
self._audio.set_distance_delay_default
)
self._distance_delay_setting = omni.ui.ComboBox(
self._distance_delay_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"The value that Sound prims will use for enableDistanceDelay when "
+ "that parameter is set to 'default'. This also allows the setting "
+ "to be forced on or off on all prims for testing purposes, using "
+ "the 'force on' and 'force off' values"
),
)
if item_visible("Interaural delay default"):
with ui.HStack():
self._add_label("Interaural delay default")
self._interaural_delay_setting_model = AudioSettingsWidget.DefaultsComboBoxNotifier(
self._audio.set_interaural_delay_default
)
self._interaural_delay_setting = omni.ui.ComboBox(
self._interaural_delay_setting_model,
tooltip_fn=lambda: self._create_tooltip(
"The value that Sound prims will use for enableInterauralDelay when "
+ "that parameter is set to 'default'. This also allows the setting "
+ "to be forced on or off on all prims for testing purposes, using "
+ "the 'force on' and 'force off' values"
),
)
if item_visible("Concurrent voices"):
with ui.HStack():
self._add_label("Concurrent voices")
self._concurrent_voices_setting_notifier = AudioSettingsWidget.SlowChangeNotifier(
self._audio.set_concurrent_voices
)
self._concurrent_voices_setting = omni.ui.IntDrag(
self._concurrent_voices_setting_notifier,
min=2,
max=4096,
tooltip_fn=lambda: self._create_tooltip(
"The number of sounds in a scene that can be played concurrently. "
+ "In a scene where there this is set to N and N + 1 sounds are "
+ "played concurrently, the N + 1th sound will be simulated instead "
+ "of playing on the audio device and instead simulate that voice. "
+ "The simulated voice will begin playing again when fewer than N "
+ "voices are playing"
),
)
if item_visible("Speed of sound"):
with ui.HStack():
self._add_label("Speed of sound")
self._speed_of_sound_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_speed_of_sound
)
self._speed_of_sound_setting = omni.ui.FloatDrag(
self._speed_of_sound_setting_notifier,
min=0.0001,
max=float("inf"),
step=1.0,
tooltip_fn=lambda: self._create_tooltip(
"Sets the speed of sound in the medium surrounding the listener "
+ "(typically air). This is measured in meters per second. This would "
+ "typically be adjusted when doing an underwater scene (as an "
+ "example). The speed of sound in dry air at sea level is "
+ "approximately 340.0m/s."
),
)
if item_visible("Doppler scale"):
with ui.HStack():
self._add_label("Doppler scale")
self._doppler_scale_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_doppler_scale
)
self._doppler_scale_setting = omni.ui.FloatDrag(
self._doppler_scale_setting_notifier,
min=0.0001,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"The scaler that can exaggerate or lessen the Doppler effect. Setting "
+ "this above 1.0 will exaggerate the Doppler effect. Setting this "
+ "below 1.0 will lessen the Doppler effect."
),
)
if item_visible("Doppler limit"):
with ui.HStack():
self._add_label("Doppler limit")
self._doppler_limit_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_doppler_limit
)
self._doppler_limit_setting = omni.ui.FloatDrag(
self._doppler_limit_setting_notifier,
min=1.0,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"A Limit on the maximum Doppler pitch shift that can be applied to "
+ "a playing voice. Since supersonic spatial audio is not handled, a "
+ "maximum frequency shift must be set for prims that move toward the "
+ "listener at or faster than the speed of sound."
),
)
if item_visible("Spatial time scale"):
with ui.HStack():
self._add_label("Spatial time scale")
self._spatial_timescale_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_spatial_time_scale
)
self._spatial_timescale_setting = omni.ui.FloatDrag(
self._spatial_timescale_setting_notifier,
min=0.0001,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"The timescale modifier for all spatial voices. Each spatial Sound "
+ "prim multiplies its timeScale attribute by this value. For "
+ "example, setting this to 0.5 will play all spatial sounds at half "
+ "speed and setting this to 2.0 will play all spatial sounds at "
+ "double speed. This affects delay times for the distance delay "
+ "effect. This feature is intended to allow time-dilation to be "
+ "performed with the sound effects in the scene without affecting "
+ "non-spatial elements like the background music."
),
)
if item_visible("Non-spatial time scale"):
with ui.HStack():
self._add_label("Non-spatial time scale")
self._nonspatial_timescale_setting_notifier = AudioSettingsWidget.FastChangeNotifier(
self._audio.set_nonspatial_time_scale
)
self._nonspatial_timescale_setting = omni.ui.FloatDrag(
self._nonspatial_timescale_setting_notifier,
min=0.0001,
max=float("inf"),
tooltip_fn=lambda: self._create_tooltip(
"The timescale modifier for all non-spatial voices. Each non-spatial "
+ "Sound prim multiplies its timeScale attribute by this value. For "
+ "example, setting this to 0.5 will play all non-spatial sounds at "
+ "half speed and setting this to 2.0 will play all non-spatial "
+ "sounds at double speed."
),
)
self._refresh()
|
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/tests/test_audio.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf
import pathlib
class TestAudioWidget(OmniUiTest): # pragma: no cover
# Before running each test
async def setUp(self):
await super().setUp()
from omni.kit.property.audio.scripts.audio_properties import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_sound_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=675,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("audio_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/Sound"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_sound_ui.png")
async def test_listener_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=295,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("audio_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/Listener"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_listener_ui.png")
|
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/tests/__init__.py | from .test_audio import *
from .test_layer_audio import *
|
omniverse-code/kit/exts/omni.kit.property.audio/omni/kit/property/audio/tests/test_layer_audio.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class TestLayerAudioWidget(OmniUiTest): # pragma: no cover
# Before running each test
async def setUp(self):
await super().setUp()
await arrange_windows("Layer")
from omni.kit.property.audio.scripts.audio_properties import TEST_DATA_PATH
self._usd_path = TEST_DATA_PATH.absolute()
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("audio_test.usda").absolute()
usd_context.open_stage(str(test_file_path))
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_layer_sound_ui(self):
await ui_test.find("Layer").focus()
await ui_test.find("Layer//Frame/**/TreeView[*]").find(f"**/Label[*].text=='Root Layer (Authoring Layer)'").click()
await ui_test.human_delay(50)
|
omniverse-code/kit/exts/omni.kit.property.audio/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.6] - 2022-08-17
### Changes
- Updated golden image due to SdfAssetPath widget change.
## [1.0.5] - 2021-07-16
### Changes
- Fixed audio active listener tooltip color
## [1.0.4] - 2021-02-16
### Changes
- Added UI image test
## [1.0.3] - 2020-12-09
### Changes
- Added extension icon
- Added readme
- Updated preview image
## [1.0.2] - 2020-11-10
### Changes
- Moved audio settings window onto layer property window
## [1.0.1] - 2020-11-03
### Changes
- Moved audio settings window into property window
## [1.0.0] - 2020-10-13
### Changes
- Created
|
omniverse-code/kit/exts/omni.kit.property.audio/docs/README.md | # omni.kit.property.audio
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension supports editing of these Usd Types;
- UsdMedia.SpatialAudio
- AudioSchema.Sound
- AudioSchema.Listener
|
omniverse-code/kit/exts/omni.kit.property.audio/docs/index.rst | omni.kit.property.audio
###########################
Property Audio Values
.. toctree::
:maxdepth: 1
CHANGELOG
|
omniverse-code/kit/exts/omni.kit.property.audio/data/tests/audio_test.usda | #usda 1.0
(
customLayerData = {
dictionary cameraSettings = {
dictionary Front = {
double radius = 500
double3 target = (0, 0, 0)
}
dictionary Perspective = {
double3 position = (500.0000000000001, 500.0000000000001, 499.9999999999998)
double3 target = (0, 0, 0)
}
dictionary Right = {
double radius = 500
double3 target = (0, 0, 0)
}
dictionary Top = {
double radius = 500
double3 target = (0, 0, 0)
}
string boundCamera = "/OmniverseKit_Persp"
}
dictionary renderSettings = {
float "rtx:post:lensDistortion:cameraFocalLength" = 18.147562
}
}
defaultPrim = "World"
endTimeCode = 100
metersPerUnit = 0.009999999776482582
startTimeCode = 0
timeCodesPerSecond = 24
upAxis = "Y"
)
def Xform "World"
{
def OmniSound "Sound"
{
uniform asset filePath = @test.wav@
}
def OmniListener "Listener"
{
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.