file_path
stringlengths 21
202
| content
stringlengths 12
1.02M
| size
int64 12
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 10
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportFullscreen.cpp | // Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include "OgnSetViewportFullscreenDatabase.h"
#include <omni/kit/IAppWindow.h>
#include <omni/kit/KitUtils.h>
namespace omni
{
namespace graph
{
namespace ui_nodes
{
class OgnSetViewportFullscreen
{
public:
static bool compute(OgnSetViewportFullscreenDatabase& db)
{
NameToken const mode = db.inputs.mode();
bool fullscreen = false;
bool hideUI = false;
if (mode == OgnSetViewportFullscreenDatabase::tokens.Default)
{
fullscreen = false;
hideUI = false;
}
else if (mode == OgnSetViewportFullscreenDatabase::tokens.Fullscreen)
{
fullscreen = true;
hideUI = true;
}
else if (mode == OgnSetViewportFullscreenDatabase::tokens.HideUI)
{
fullscreen = false;
hideUI = true;
}
else
{
CARB_ASSERT(false, "Invalid mode");
}
carb::settings::ISettings* settings = omni::kit::getSettings();
// Only toggle fullscreen on/off when displayModeLock is off.
if (!settings->get<bool>("/app/window/displayModeLock"))
{
setFullscreen(fullscreen);
}
settings->set("/app/window/hideUi", hideUI);
db.outputs.exec() = kExecutionAttributeStateEnabled;
return true;
}
private:
static void setFullscreen(bool fullscreen)
{
omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow();
CARB_ASSERT(appWindow);
if (appWindow)
{
appWindow->setFullscreen(fullscreen);
}
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
| 2,103 | C++ | 24.349397 | 77 | 0.630052 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnPrintText.py | """
This is the implementation of the OGN node defined in OgnPrintText.ogn
"""
import time
import carb
import omni.graph.core as og
from omni.kit.viewport.utility import get_viewport_from_window_name, post_viewport_message
class OgnOnCustomEventInternalState:
"""Convenience class for maintaining per-node state information"""
def __init__(self):
self.display_time: float = 0
class OgnPrintText:
"""
Prints text to the log and optionally the viewport
"""
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnOnCustomEventInternalState()
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
def ok():
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
return True
try:
toast_min_period_s = 5.0
to_screen = db.inputs.toScreen
log_level = db.inputs.logLevel.lower()
text = db.inputs.text
if not text:
return ok()
if log_level:
if log_level not in ("error", "warning", "warn", "info"):
db.log_error("Log Level must be one of error, warning or info")
return False
else:
log_level = "info"
if to_screen:
toast_time = db.internal_state.display_time
viewport_name = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport_name)
if viewport_api is None:
# Preserve legacy behavior of erroring when a name was provided
if viewport_name:
db.log_error(f"Could not get viewport window {viewport_name}")
return False
return ok()
now_s = time.time()
toast_age = now_s - toast_time
if toast_age > toast_min_period_s:
toast_time = 0
if toast_time == 0:
post_viewport_message(viewport_api, text)
db.state.displayTime = now_s
else:
# FIXME: Toast also prints to log so we only do one or the other
if log_level == "info":
carb.log_info(text)
elif log_level.startswith("warn"):
carb.log_warn(text)
else:
carb.log_error(text)
return ok()
except Exception as error: # pylint: disable=broad-except
db.log_error(str(error))
return False
| 2,717 | Python | 30.97647 | 90 | 0.536621 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/ViewportHoverNodeCommon.h | // 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.
//
#include "UINodeCommon.h"
namespace omni
{
namespace graph
{
namespace ui_nodes
{
constexpr carb::events::EventType kHoverBeganEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.hover.began");
constexpr carb::events::EventType kHoverChangedEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.hover.changed");
constexpr carb::events::EventType kHoverEndedEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.hover.ended");
class ViewportHoverEventPayloads
{
public:
struct Key
{
char const* viewportWindowName;
bool operator<(Key const& other) const
{
return std::strcmp(viewportWindowName, other.viewportWindowName) < 0;
}
};
struct HoverBeganValue
{
pxr::GfVec2d positionNorm;
pxr::GfVec2d positionPixel;
bool isValid;
};
struct HoverChangedValue
{
pxr::GfVec2d positionNorm;
pxr::GfVec2d positionPixel;
pxr::GfVec2d velocityNorm;
pxr::GfVec2d velocityPixel;
bool isValid;
};
struct HoverEndedValue
{
bool isValid;
};
// Store a hover began event payload
void setHoverBeganPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {stringMemo.lookup(idict->get<char const*>(payload, "viewport"))};
hoverBeganPayloadMap[key] = HoverBeganValue {
pxr::GfVec2d {
idict->get<double>(payload, "pos_norm_x"),
idict->get<double>(payload, "pos_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "pos_pixel_x"),
idict->get<double>(payload, "pos_pixel_y")
},
true
};
}
// Store a hover changed event payload
void setHoverChangedPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {stringMemo.lookup(idict->get<char const*>(payload, "viewport"))};
hoverChangedPayloadMap[key] = HoverChangedValue {
pxr::GfVec2d {
idict->get<double>(payload, "pos_norm_x"),
idict->get<double>(payload, "pos_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "pos_pixel_x"),
idict->get<double>(payload, "pos_pixel_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "vel_norm_x"),
idict->get<double>(payload, "vel_norm_y")
},
pxr::GfVec2d {
idict->get<double>(payload, "vel_pixel_x"),
idict->get<double>(payload, "vel_pixel_y")
},
true
};
}
// Store a hover ended event payload
void setHoverEndedPayload(carb::dictionary::Item* payload)
{
auto idict = carb::dictionary::getCachedDictionaryInterface();
Key key {stringMemo.lookup(idict->get<char const*>(payload, "viewport"))};
hoverEndedPayloadMap[key] = HoverEndedValue {true};
}
// Invalidate all stored payloads
void clear()
{
for (auto& p : hoverBeganPayloadMap)
{
p.second.isValid = false;
}
for (auto& p : hoverChangedPayloadMap)
{
p.second.isValid = false;
}
for (auto& p : hoverEndedPayloadMap)
{
p.second.isValid = false;
}
}
bool empty()
{
if (std::any_of(hoverBeganPayloadMap.begin(), hoverBeganPayloadMap.end(),
[](auto const& p) {
return p.second.isValid;
}))
{
return false;
}
if (std::any_of(hoverChangedPayloadMap.begin(), hoverChangedPayloadMap.end(),
[](auto const& p) {
return p.second.isValid;
}))
{
return false;
}
if (std::any_of(hoverEndedPayloadMap.begin(), hoverEndedPayloadMap.end(),
[](auto const& p) {
return p.second.isValid;
}))
{
return false;
}
return true;
}
std::map<Key, HoverBeganValue> const& hoverBeganPayloads()
{
return hoverBeganPayloadMap;
}
std::map<Key, HoverChangedValue> const& hoverChangedPayloads()
{
return hoverChangedPayloadMap;
}
std::map<Key, HoverEndedValue> const& hoverEndedPayloads()
{
return hoverEndedPayloadMap;
}
private:
std::map<Key, HoverBeganValue> hoverBeganPayloadMap;
std::map<Key, HoverChangedValue> hoverChangedPayloadMap;
std::map<Key, HoverEndedValue> hoverEndedPayloadMap;
StringMemo stringMemo;
};
using ViewportHoverEventStateKey = ViewportHoverEventPayloads::Key;
struct ViewportHoverEventStateValue
{
bool isHovered = false;
pxr::GfVec2d positionNorm = {0.0, 0.0};
pxr::GfVec2d positionPixel = {0.0, 0.0};
pxr::GfVec2d velocityNorm = {0.0, 0.0};
pxr::GfVec2d velocityPixel = {0.0, 0.0};
};
using ViewportHoverEventStates = std::map<ViewportHoverEventStateKey, ViewportHoverEventStateValue>;
}
}
}
| 5,631 | C | 28.030928 | 122 | 0.600604 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnReadViewportHoverState.cpp | // 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.
//
#include <OgnReadViewportHoverStateDatabase.h>
#include "ViewportHoverNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
namespace omni
{
namespace graph
{
namespace ui_nodes
{
class OgnReadViewportHoverState
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr hoverBeganSub;
carb::events::ISubscriptionPtr hoverChangedSub;
carb::events::ISubscriptionPtr hoverEndedSub;
carb::events::ISubscriptionPtr updateSub;
ViewportHoverEventPayloads eventPayloads;
ViewportHoverEventStates eventStates;
} m_internalState;
exec::unstable::Stamp m_setStamp; // stamp set when the event occurs
exec::unstable::SyncStamp m_syncStamp; // stamp set by each instance
// Process event payloads and update event states every frame
static void updateEventStates(ViewportHoverEventStates& eventStates, ViewportHoverEventPayloads& eventPayloads)
{
for (auto& eventState : eventStates)
{
eventState.second.velocityNorm = {0.0, 0.0};
eventState.second.velocityPixel = {0.0, 0.0};
}
for (auto const& hoverBeganPayload : eventPayloads.hoverBeganPayloads())
{
if (!hoverBeganPayload.second.isValid)
continue;
auto& eventStateValue = eventStates[hoverBeganPayload.first];
eventStateValue.isHovered = true;
eventStateValue.positionNorm = hoverBeganPayload.second.positionNorm;
eventStateValue.positionPixel = hoverBeganPayload.second.positionPixel;
eventStateValue.velocityNorm = {0.0, 0.0};
eventStateValue.velocityPixel = {0.0, 0.0};
}
for (auto const& hoverChangedPayload : eventPayloads.hoverChangedPayloads())
{
if (!hoverChangedPayload.second.isValid)
continue;
auto& eventStateValue = eventStates[hoverChangedPayload.first];
if (eventStateValue.isHovered)
{
eventStateValue.positionNorm = hoverChangedPayload.second.positionNorm;
eventStateValue.positionPixel = hoverChangedPayload.second.positionPixel;
eventStateValue.velocityNorm = hoverChangedPayload.second.velocityNorm;
eventStateValue.velocityPixel = hoverChangedPayload.second.velocityPixel;
}
}
for (auto const& hoverEndedPayload : eventPayloads.hoverEndedPayloads())
{
if (!hoverEndedPayload.second.isValid)
continue;
auto& eventStateValue = eventStates[hoverEndedPayload.first];
if (eventStateValue.isHovered)
{
eventStateValue.isHovered = false;
eventStateValue.positionNorm = {0.0, 0.0};
eventStateValue.positionPixel = {0.0, 0.0};
eventStateValue.velocityNorm = {0.0, 0.0};
eventStateValue.velocityPixel = {0.0, 0.0};
}
}
eventPayloads.clear();
}
static void initialize(GraphContextObj const&, NodeObj const& nodeObj)
{
OgnReadViewportHoverState& state =
OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj);
// Subscribe to hover events and update tick
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.hoverBeganSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kHoverBeganEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportHoverState& state =
OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj);
state.m_internalState.eventPayloads.setHoverBeganPayload(e->payload);
state.m_setStamp.next();
}
}
);
state.m_internalState.hoverChangedSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kHoverChangedEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportHoverState& state =
OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj);
state.m_internalState.eventPayloads.setHoverChangedPayload(e->payload);
state.m_setStamp.next();
}
}
);
state.m_internalState.hoverEndedSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kHoverEndedEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportHoverState& state =
OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj);
state.m_internalState.eventPayloads.setHoverEndedPayload(e->payload);
state.m_setStamp.next();
}
}
);
state.m_internalState.updateSub = carb::events::createSubscriptionToPush(
app->getUpdateEventStream(),
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnReadViewportHoverState& state =
OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj);
updateEventStates(state.m_internalState.eventStates, state.m_internalState.eventPayloads);
state.m_setStamp.next();
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnReadViewportHoverState& state =
OgnReadViewportHoverStateDatabase::sSharedState<OgnReadViewportHoverState>(nodeObj);
// Unsubscribe from hover events and update tick
if (state.m_internalState.hoverBeganSub.get())
state.m_internalState.hoverBeganSub.detach()->unsubscribe();
if (state.m_internalState.hoverChangedSub.get())
state.m_internalState.hoverChangedSub.detach()->unsubscribe();
if (state.m_internalState.hoverEndedSub.get())
state.m_internalState.hoverEndedSub.detach()->unsubscribe();
if (state.m_internalState.updateSub.get())
state.m_internalState.updateSub.detach()->unsubscribe();
}
static bool compute(OgnReadViewportHoverStateDatabase& db)
{
OgnReadViewportHoverState& sharedState = db.sharedState<OgnReadViewportHoverState>();
OgnReadViewportHoverState& perInstanceState = db.perInstanceState<OgnReadViewportHoverState>();
if(perInstanceState.m_syncStamp.makeSync(sharedState.m_setStamp))
{
// Get the targeted viewport
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
// Output hover state
auto it = sharedState.m_internalState.eventStates.find({viewportWindowName});
if (it != sharedState.m_internalState.eventStates.end())
{
if (db.inputs.useNormalizedCoords())
{
db.outputs.position() = it->second.positionNorm;
db.outputs.velocity() = it->second.velocityNorm;
}
else
{
db.outputs.position() = it->second.positionPixel;
db.outputs.velocity() = it->second.velocityPixel;
}
db.outputs.isHovered() = it->second.isHovered;
db.outputs.isValid() = true;
}
else
{
db.outputs.position() = {0.0, 0.0};
db.outputs.velocity() = {0.0, 0.0};
db.outputs.isHovered() = false;
db.outputs.isValid() = false;
}
}
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
| 9,050 | C++ | 38.697368 | 115 | 0.589724 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnOnPicked.cpp | // 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.
//
#include <OgnOnPickedDatabase.h>
#include "PickingNodeCommon.h"
#include <omni/kit/IApp.h>
#include <omni/ui/Workspace.h>
#include <omni/graph/core/PreUsdInclude.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/relationship.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <omni/graph/core/PostUsdInclude.h>
namespace omni
{
namespace graph
{
namespace ui_nodes
{
class OgnOnPicked
{
public:
struct InternalState
{
carb::events::ISubscriptionPtr pickingSub;
PickingEventPayloads eventPayloads;
} m_internalState;
exec::unstable::Stamp m_setStamp; // stamp set when the event occurs
exec::unstable::SyncStamp m_syncStamp; // stamp set by each instance
static void initialize(GraphContextObj const&, NodeObj const& nodeObj)
{
OgnOnPicked& state = OgnOnPickedDatabase::sSharedState<OgnOnPicked>(nodeObj);
// Subscribe to picking events
if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>())
{
state.m_internalState.pickingSub = carb::events::createSubscriptionToPushByType(
app->getMessageBusEventStream(),
kPickingEventType,
[nodeObj](carb::events::IEvent* e)
{
if (e)
{
OgnOnPicked& state = OgnOnPickedDatabase::sSharedState<OgnOnPicked>(nodeObj);
state.m_internalState.eventPayloads.clear(); // invalidate previous payloads
state.m_internalState.eventPayloads.setPayload(e->payload);
state.m_setStamp.next();
if (nodeObj.iNode->isValid(nodeObj))
nodeObj.iNode->requestCompute(nodeObj);
}
}
);
}
}
static void release(const NodeObj& nodeObj)
{
OgnOnPicked& state = OgnOnPickedDatabase::sSharedState<OgnOnPicked>(nodeObj);
// Unsubscribe from picking events
if (state.m_internalState.pickingSub.get())
state.m_internalState.pickingSub.detach()->unsubscribe();
}
static bool compute(OgnOnPickedDatabase& db)
{
if (checkNodeDisabledForOnlyPlay(db))
return true;
auto pathInterface = carb::getCachedInterface<omni::fabric::IPath>();
auto tokenInterface = carb::getCachedInterface<omni::fabric::IToken>();
if (!pathInterface || !tokenInterface)
{
CARB_LOG_ERROR("Failed to initialize path or token interface");
return 0;
}
OgnOnPicked& sharedState = db.sharedState<OgnOnPicked>();
OgnOnPicked& perInstanceState = db.perInstanceState<OgnOnPicked>();
if(perInstanceState.m_syncStamp.makeSync(sharedState.m_setStamp))
{
if (sharedState.m_internalState.eventPayloads.empty())
return true;
// Get the targeted viewport and gesture
char const* const viewportWindowName = db.tokenToString(db.inputs.viewport());
char const* const gestureName = db.tokenToString(db.inputs.gesture());
if (!omni::ui::Workspace::getWindow(viewportWindowName))
{
db.logWarning("Viewport window '%s' not found", viewportWindowName);
}
auto const* eventPayloadValuePtr = sharedState.m_internalState.eventPayloads.getPayloadValue(viewportWindowName, gestureName);
if (eventPayloadValuePtr)
{
// Get the picked path and pos for the targeted viewport and gesture
char const* const pickedPrimPath = eventPayloadValuePtr->pickedPrimPath;
pxr::GfVec3d const& pickedWorldPos = eventPayloadValuePtr->pickedWorldPos;
// Determine if a tracked prim is picked
bool isTrackedPrimPicked;
const auto& trackedPrims = db.inputs.trackedPrims();
// First determine if any prim is picked
bool const isAnyPrimPicked = pickedPrimPath && pickedPrimPath[0] != '\0';
if (isAnyPrimPicked)
{
TargetPath pickedPrim = db.stringToPath(pickedPrimPath);
// If no tracked prims are specified then we consider all prims to be tracked
// Else search the list of tracked prims for the picked prim
if (trackedPrims.empty())
isTrackedPrimPicked = true;
else
isTrackedPrimPicked = std::any_of(trackedPrims.begin(), trackedPrims.end(),
[pickedPrim](TargetPath const& trackedPrim) {
return (trackedPrim == pickedPrim);
});
db.outputs.pickedPrim().resize(1);
db.outputs.pickedPrim()[0] = pickedPrim;
db.outputs.pickedPrimPath() = db.stringToToken(pickedPrimPath);
}
else
{
// No prim is picked at all, so a tracked prim certainly isn't picked
isTrackedPrimPicked = false;
db.outputs.pickedPrim().resize(0);
db.outputs.pickedPrimPath() = Token();
}
// Set outputs
db.outputs.pickedWorldPos() = pickedWorldPos;
db.outputs.isTrackedPrimPicked() = isTrackedPrimPicked;
auto& trackedPrimPaths = db.outputs.trackedPrimPaths();
trackedPrimPaths.resize(trackedPrims.size());
std::transform(trackedPrims.begin(), trackedPrims.end(), trackedPrimPaths.begin(),
[tokenInterface, pathInterface](TargetPath const& trackedPrim) {
return tokenInterface->getHandle(pathInterface->getText(trackedPrim));
});
if (isTrackedPrimPicked)
{
db.outputs.picked() = kExecutionAttributeStateEnabled;
db.outputs.missed() = kExecutionAttributeStateDisabled;
}
else
{
db.outputs.picked() = kExecutionAttributeStateDisabled;
db.outputs.missed() = kExecutionAttributeStateEnabled;
}
}
}
return true;
}
};
REGISTER_OGN_NODE()
} // ui
} // graph
} // omni
| 6,992 | C++ | 38.96 | 138 | 0.589674 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnButton.post.rst | Further information on the button operation can be found in the documentation of :py:class:`omni.ui.Button`.
| 109 | reStructuredText | 53.999973 | 108 | 0.798165 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportRenderer.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
from omni.kit.viewport.utility import get_viewport_from_window_name
class OgnSetViewportRenderer:
"""
Sets renderer for the target viewport.
"""
# renderer: (hd_engine, render_mode)
RENDERER_CONFIGS = {
"RTX: Realtime": ("rtx", "RaytracedLighting"),
"RTX: Path Tracing": ("rtx", "PathTracing"),
"RTX: Iray": ("iray", "iray"),
}
@staticmethod
def initialize(context, node):
"""Assign default value and allowed tokens for the inputs:renderer attribute"""
renderers = []
# Query which engines are enabled.
setting = carb.settings.get_settings().get("/renderer/enabled")
engines = setting.split(",") if setting else ["rtx", "iray"]
# Third-party Hydra render delegates are ignored as requested by OM-75851, but they can be included if needed.
for renderer, (engine, _) in OgnSetViewportRenderer.RENDERER_CONFIGS.items():
if engine in engines:
renderers.append(renderer)
allowed_tokens = ",".join(renderers)
attr = node.get_attribute("inputs:renderer")
attr.set_metadata(ogn.MetadataKeys.ALLOWED_TOKENS, allowed_tokens)
# If the attr is not authored, its default value will be the first enabled renderer.
if attr.get() == "" and len(renderers) > 0:
attr.set(renderers[0])
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
renderer = db.inputs.renderer
if renderer != "":
viewport = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport)
if viewport_api is not None:
allowed_tokens = db.attributes.inputs.renderer.get_metadata(ogn.MetadataKeys.ALLOWED_TOKENS)
renderers = allowed_tokens.split(",")
if renderer in renderers and renderer in OgnSetViewportRenderer.RENDERER_CONFIGS:
hd_engine, render_mode = OgnSetViewportRenderer.RENDERER_CONFIGS[renderer]
# Update the legacy "/renderer/active" setting for anyone that may be watching for it
carb.settings.get_settings().set("/renderer/active", hd_engine)
viewport_api.set_hd_engine(hd_engine, render_mode)
else:
db.log_error(f"Unknown renderer '{renderer}'")
else:
db.log_error(f"Unknown viewport window '{viewport}'")
db.outputs.exec = og.ExecutionAttributeState.ENABLED
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
return True
| 3,271 | Python | 37.952381 | 118 | 0.62886 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSpacer.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.graph.core as og
import omni.ui as ui
from . import UINodeCommon
class OgnSpacer(UINodeCommon.OgWidgetNode):
@staticmethod
def compute(db) -> bool:
if db.inputs.create != og.ExecutionAttributeState.DISABLED:
parent_widget_path = db.inputs.parentWidgetPath
if not parent_widget_path:
db.log_error("No parentWidgetPath supplied.")
return False
parent_widget = UINodeCommon.find_widget_among_all_windows(parent_widget_path)
if parent_widget is None:
db.log_error("Could not find parent widget.")
return False
style = {}
try:
style = UINodeCommon.to_ui_style(db.inputs.style)
except SyntaxError as err:
db.log_error(f"'inputs:style': {err.msg}")
return False
widget_identifier = UINodeCommon.get_unique_widget_identifier(db)
# Now create the spacer widget and register it.
with parent_widget:
spacer = ui.Spacer(identifier=widget_identifier, width=db.inputs.width, height=db.inputs.height)
if style:
spacer.set_style(style)
OgnSpacer.register_widget(db.abi_context, widget_identifier, spacer)
db.outputs.created = og.ExecutionAttributeState.ENABLED
db.outputs.widgetPath = UINodeCommon.find_widget_path(spacer)
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
# The spacer has no properties or styles of its own: height and width are base Widget properties.
| 2,116 | Python | 37.490908 | 112 | 0.657845 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnButton.pre.rst | Here is an example of a button that was created using the text ``Press Me``:
.. image:: ../../../../../source/extensions/omni.graph.ui_nodes/docs/PressMe.png
:alt: "Press Me" Button
| 187 | reStructuredText | 36.599993 | 80 | 0.663102 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnReadMouseState.cpp | // 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.
//
#include <OgnReadMouseStateDatabase.h>
#include <carb/input/IInput.h>
#include <carb/input/InputTypes.h>
#include <omni/kit/IAppWindow.h>
#include <omni/ui/Workspace.h>
using namespace carb::input;
namespace omni {
namespace graph {
namespace ui_nodes
{
// We do not read the specific input for scrolls and movements for four directions
// We only read the coordinates instead, normalized one or absolute one.
constexpr size_t s_numNames = size_t(carb::input::MouseInput::eCount) - 8 + 2;
static std::array<NameToken, s_numNames> s_mouseInputTokens;
class OgnReadMouseState
{
public:
static bool compute(OgnReadMouseStateDatabase& db)
{
NameToken const& mouseIn = db.inputs.mouseElement();
// First time look up all the token string values
static bool callOnce = ([&db] {
s_mouseInputTokens = {
db.tokens.LeftButton,
db.tokens.RightButton,
db.tokens.MiddleButton,
db.tokens.ForwardButton,
db.tokens.BackButton,
db.tokens.MouseCoordsNormalized,
db.tokens.MouseCoordsPixel
};
} (), true);
omni::kit::IAppWindow* appWindow = omni::kit::getDefaultAppWindow();
if (!appWindow)
{
return false;
}
Mouse* mouse = appWindow->getMouse();
if (!mouse)
{
CARB_LOG_ERROR_ONCE("No Mouse!");
return false;
}
IInput* input = carb::getCachedInterface<IInput>();
if (!input)
{
CARB_LOG_ERROR_ONCE("No Input!");
return false;
}
bool isPressed = false;
// Get the index of the token of the mouse input of interest
auto iter = std::find(s_mouseInputTokens.begin(), s_mouseInputTokens.end(), mouseIn);
if (iter == s_mouseInputTokens.end())
return true;
size_t token_index = iter - s_mouseInputTokens.begin();
if (token_index < 5) // Mouse Input is related to a button
{
MouseInput button = MouseInput(token_index);
isPressed = (carb::input::kButtonFlagStateDown & input->getMouseButtonFlags(mouse, button));
db.outputs.isPressed() = isPressed;
}
else // Mouse Input is position
{
carb::Float2 coords = input->getMouseCoordsPixel(mouse);
bool foundWindow{ false };
NameToken windowToken = omni::fabric::kUninitializedToken;
float windowWidth = static_cast<float>(appWindow->getWidth());
float windowHeight = static_cast<float>(appWindow->getHeight());
if (db.inputs.useRelativeCoords())
{
// Find the workspace window the mouse pointer is over, and convert the coords to window-relative
for (auto const& window : omni::ui::Workspace::getWindows())
{
if ((window->isDocked() && !window->isSelectedInDock()) || !window->isVisible())
continue;
std::string const& windowTitle = window->getTitle();
if (windowTitle == "DockSpace")
continue;
float dpiScale = omni::ui::Workspace::getDpiScale();
float left = window->getPositionX() * dpiScale;
float top = window->getPositionY() * dpiScale;
float curWindowWidth = window->getWidth() * dpiScale;
float curWindowHeight = window->getHeight() * dpiScale;
if (coords.x >= left && coords.y >= top && coords.x <= left + curWindowWidth && coords.y <= top + curWindowHeight)
{
foundWindow = true;
coords.x -= left;
coords.y -= top;
windowToken = db.stringToToken(windowTitle.c_str());
windowWidth = curWindowWidth;
windowHeight = curWindowHeight;
break;
}
}
}
else
{
foundWindow = true;
}
float* data = db.outputs.coords().data();
if (foundWindow)
{
if (*iter == db.tokens.MouseCoordsNormalized)
{
coords.x /= windowWidth;
coords.y /= windowHeight;
}
data[0] = coords.x;
data[1] = coords.y;
}
else
{
data[0] = 0.f;
data[1] = 0.f;
}
if (windowToken == omni::fabric::kUninitializedToken)
windowToken = db.stringToToken("");
db.outputs.window() = windowToken;
}
return true;
}
};
REGISTER_OGN_NODE()
} // namespace ui_nodes
} // namespace graph
} // namespace omni
| 5,438 | C++ | 32.574074 | 134 | 0.545053 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetViewportResolution.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.graph.core as og
from omni.kit.viewport.utility import get_viewport_from_window_name
class OgnSetViewportResolution:
"""
Sets the resolution of the target viewport.
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
viewport = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport)
if viewport_api is not None:
resolution = db.inputs.resolution
if resolution[0] > 0 and resolution[1] > 0:
viewport_api.resolution = resolution
else:
db.log_error(f"Invalid resolution {resolution[0]}x{resolution[1]}.")
else:
db.log_error(f"Unknown viewport window '{viewport}'")
db.outputs.exec = og.ExecutionAttributeState.ENABLED
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
return True
| 1,461 | Python | 33.809523 | 88 | 0.651608 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnReadWidgetProperty.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.graph.core as og
from . import UINodeCommon
class OgnReadWidgetProperty:
@staticmethod
def compute(db) -> bool:
widget_path = db.inputs.widgetPath
if not widget_path:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
db.log_warning("No widgetIdentifier or widgetPath provided.")
return False
widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier)
if not widget:
db.log_warning(f"No widget with identifier '{widget_identifier}' found in this graph.")
return False
else:
widget = UINodeCommon.find_widget_among_all_windows(widget_path)
if not widget:
db.log_warning(f"No widget found at path '{widget_path}'.")
return False
# For error messages only.
widget_identifier = widget_path
property_name = db.inputs.propertyName
if not property_name:
db.log_warning("No property provided.")
return False
if not hasattr(widget, property_name):
db.log_error(f"Widget '{widget_identifier}' has no property '{property_name}'.")
return False
widget_summary = f"widget '{widget_identifier}' ({type(widget)})"
callbacks = UINodeCommon.get_widget_callbacks(widget)
if not callbacks:
db.log_error(f"{widget_summary} is not supported by the ReadWidgetProperty node.")
return False
if not hasattr(callbacks, "get_property_names") or not callable(callbacks.get_property_names):
db.log_error(f"No 'get_property_names' callback found for {widget_summary}")
return False
readable_props = callbacks.get_property_names(widget, False)
if not readable_props or property_name not in readable_props:
db.log_error(f"'{property_name}' is not a readable property of {widget_summary}")
return False
if not hasattr(callbacks, "resolve_output_property") or not callable(callbacks.resolve_output_property):
db.log_error(f"No 'resolve_output_property' callback found for {widget_summary}")
return False
try:
callbacks.resolve_output_property(widget, property_name, db.node.get_attribute("outputs:value"))
except og.OmniGraphError as og_error:
db.log_error(
f"Could resolve outputs from '{property_name}' for {widget_summary}\n{og_error}", add_context=False
)
return False
if not hasattr(callbacks, "get_property_value") or not callable(callbacks.get_property_value):
db.log_error(f"No 'get_property_value' callback found for {widget_summary}")
return False
try:
callbacks.get_property_value(widget, property_name, db.outputs.value)
except og.OmniGraphError as og_error:
db.log_error(f"Could not get value of '{property_name}' on {widget_summary}\n{og_error}", add_context=False)
return False
return True
| 3,584 | Python | 43.259259 | 120 | 0.646484 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnGetViewportResolution.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.kit.viewport.utility import get_viewport_from_window_name
class OgnGetViewportResolution:
"""
Gets the resolution of the target viewport.
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
try:
viewport = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport)
if viewport_api is not None:
db.outputs.resolution = viewport_api.resolution
else:
db.outputs.resolution = (0, 0)
db.log_error(f"Unknown viewport window '{viewport}'")
except Exception as error: # noqa: PLW0703
db.log_error(str(error))
return False
return True
| 1,199 | Python | 32.333332 | 76 | 0.668891 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnSetActiveViewportCamera.py | """
This is the implementation of the OGN node defined in OgnSetActiveViewportCamera.ogn
"""
import omni.graph.core as og
from omni.kit.viewport.utility import get_viewport_from_window_name
from pxr import Sdf, UsdGeom
class OgnSetActiveViewportCamera:
"""
Sets a viewport's actively bound camera to a free camera
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
db.outputs.execOut = og.ExecutionAttributeState.DISABLED
try:
new_camera_path = db.inputs.primPath
if not Sdf.Path.IsValidPathString(new_camera_path):
return True
viewport_name = db.inputs.viewport
viewport_api = get_viewport_from_window_name(viewport_name)
if not viewport_api:
return True
stage = viewport_api.stage
new_camera_prim = stage.GetPrimAtPath(new_camera_path) if stage else False
if not new_camera_prim:
return True
if not new_camera_prim.IsA(UsdGeom.Camera):
return True
new_camera_path = Sdf.Path(new_camera_path)
if viewport_api.camera_path != new_camera_path:
viewport_api.camera_path = new_camera_path
except Exception as error: # pylint: disable=broad-except
db.log_error(str(error))
return False
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
return True
| 1,503 | Python | 32.422222 | 86 | 0.626081 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/ogn/nodes/OgnWriteWidgetProperty.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.graph.core as og
from . import UINodeCommon
class OgnWriteWidgetProperty:
@staticmethod
def compute(db) -> bool:
if db.inputs.write != og.ExecutionAttributeState.DISABLED:
widget_path = db.inputs.widgetPath
if not widget_path:
widget_identifier = db.inputs.widgetIdentifier
if not widget_identifier:
db.log_warning("No widgetIdentifier or widgetPath provided.")
return False
widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier)
if not widget:
db.log_warning(f"No widget with identifier '{widget_identifier}' found in this graph.")
return False
else:
widget = UINodeCommon.find_widget_among_all_windows(widget_path)
if not widget:
db.log_warning(f"No widget found at path '{widget_path}'.")
return False
# For error messages only.
widget_identifier = widget_path
property_name = db.inputs.propertyName
if not property_name:
db.log_error("No property provided.")
return False
if not hasattr(widget, property_name):
db.log_error(f"Widget '{widget_identifier}' has no property '{property_name}'.")
return False
widget_summary = f"widget '{widget_identifier}' ({type(widget)})"
callbacks = UINodeCommon.get_widget_callbacks(widget)
if not callbacks:
db.log_error(f"{widget_summary} is not supported by the WriteWidgetProperty node.")
return False
if not hasattr(callbacks, "get_property_names") or not callable(callbacks.get_property_names):
db.log_error(f"No 'get_property_names' callback found for {widget_summary}")
return False
writeable_props = callbacks.get_property_names(widget, True)
if not writeable_props or property_name not in writeable_props:
db.log_error(f"'{property_name}' is not a writeable property of {widget_summary}")
return False
if not hasattr(callbacks, "set_property_value") or not callable(callbacks.set_property_value):
db.log_error(f"No 'set_property_value' callback found for {widget_summary}")
return False
try:
callbacks.set_property_value(widget, property_name, db.inputs.value)
except og.OmniGraphError as og_error:
db.log_error(
f"Could not set value of '{property_name}' on {widget_summary}\n{og_error}", add_context=False
)
return False
db.outputs.written = og.ExecutionAttributeState.ENABLED
return True
db.log_warning("Unexpected execution with no execution input enabled")
return False
| 3,457 | Python | 44.499999 | 114 | 0.612381 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/scripts/variant_utils.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# 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 re
from typing import Any, Optional
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry
from usdrt import Sdf, Usd
def print_widget_tree(widget: ui.Widget, level: int = 0):
# Prints the widget tree to the console
for child in ui.Inspector.get_children(widget):
print_widget_tree(child, level + 1)
def get_descendants(widget: ui.Widget):
# Returns a list of all descendants of the given widget
kids = []
local_kids = ui.Inspector.get_children(widget)
kids.extend(local_kids)
for k in local_kids:
child_kids = get_descendants(k)
kids.extend(child_kids)
return kids
def get_attr_value(prim: Usd.Prim, attr_name: str) -> Any:
# Returns the value of the given attribute from usdrt
if prim:
attr = prim.GetAttribute(attr_name)
if attr:
return og.Controller().get(attribute=prim.GetAttribute(attr_name))
return False
def get_use_path(stage: Usd.Stage, node_prim_path: Sdf.Path) -> bool:
# Returns the value of the usePath input attribute
prim = stage.GetPrimAtPath(node_prim_path)
if prim:
return get_attr_value(prim, "inputs:usePath")
return False
def get_attr_has_connections(prim: Usd.Prim, attr_name: str) -> bool:
# Returns True if the attribute has authored connections
if prim:
attr = prim.GetAttribute(attr_name)
if attr:
return attr.HasAuthoredConnections()
return False
def get_target_prim(stage: Usd.Stage, node_prim_path: Sdf.Path) -> Optional[Usd.Prim]:
# Return the target prim if it exists depending on the value of the usePath input attribute.
# If usePath is True, the target prim is the prim at the path specified by the primPath input attribute.
# If usePath is False, the target prim is the first target of the prim relationship.
prim = stage.GetPrimAtPath(node_prim_path)
if prim:
if get_attr_value(prim, "inputs:usePath"):
prim_path = get_attr_value(prim, "inputs:primPath")
if prim_path is not None:
return stage.GetPrimAtPath(prim_path)
else:
rel = prim.GetRelationship("inputs:prim")
if rel.IsValid():
targets = rel.GetTargets()
if targets:
return stage.GetPrimAtPath(targets[0])
return None
def pretty_name(name: str) -> str:
# Returns a pretty name for the given property
name = name.split(":")[-1]
name = name[0].upper() + name[1:]
name = re.sub(r"([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", r"\1 ", name)
return name
def override_display_name(prop: UsdPropertyUiEntry):
# Overrides the display name of the given property with a consistent format
prop_name = pretty_name(prop.prop_name)
prop.override_display_name(prop_name)
| 3,240 | Python | 34.615384 | 108 | 0.675617 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/scripts/variants.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# 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 functools import partial
from typing import List, Optional
import omni.graph.core as og
import omni.ui as ui
from omni.graph.ui import OmniGraphAttributeModel, OmniGraphPropertiesWidgetBuilder
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel
from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_WIDTH
from usdrt import Sdf, Usd
from .variant_utils import ( # noqa PLE0402
get_attr_has_connections,
get_attr_value,
get_descendants,
get_target_prim,
get_use_path,
override_display_name,
pretty_name,
)
ATTRIB_LABEL_STYLE = {"alignment": ui.Alignment.RIGHT_TOP}
class VariantTokenModel(TfTokenAttributeModel):
"""Model for selecting the variant set name. We modify the list to show variant sets which are available
on the target prim."""
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, item, label):
"""
Args:
item: the variant set name token to be shown
label: the label to show in the drop-down
"""
super().__init__()
self.token = item
self.model = ui.SimpleStringModel(label)
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
node_prim_path: Sdf.Path,
):
"""
Args:
stage: The current stage
attribute_paths: The list of full attribute paths
self_refresh: ignored
metadata: pass-through metadata for model
node_prim_path: The path of the compute node
"""
self._stage = stage
self._node_prim_path = node_prim_path
self._target_prim = None
super().__init__(stage, attribute_paths, self_refresh, metadata)
def _get_allowed_tokens(self, _):
# Override of TfTokenAttributeModel to specialize what tokens are to be shown
# Returns the attributes we want to let the user select from
prim = self._stage.GetPrimAtPath(self._node_prim_path)
if not prim:
return []
self._target_prim = get_target_prim(self._stage, self._node_prim_path)
tokens = self._get_tokens(self._target_prim)
current_value = og.Controller().get(attribute=self._get_attributes()[0])
if current_value and current_value not in tokens:
tokens.append(current_value)
tokens.insert(0, "")
return tokens
@staticmethod
def _item_factory(item):
# Construct the item for the model
label = item
return VariantTokenModel.AllowedTokenItem(item, label)
def _update_allowed_token(self, **kwargs):
# Override of TfTokenAttributeModel to specialize the model items
super()._update_allowed_token(token_item=self._item_factory)
def _get_tokens(self, prim: Usd.Prim) -> List[str]:
return []
class VariantSetNamesTokenModel(VariantTokenModel):
def _get_variant_set_names(self, prim: Usd.Prim) -> List[str]:
if prim:
variant_sets = prim.GetVariantSets()
variant_sets_names = list(variant_sets.GetNames())
return variant_sets_names
return []
def _get_tokens(self, prim: Usd.Prim) -> List[str]:
return self._get_variant_set_names(prim)
class VariantNamesTokenModel(VariantTokenModel):
def _get_variant_names(self, prim: Usd.Prim) -> List[str]:
node_prim = self._stage.GetPrimAtPath(self._node_prim_path)
if node_prim and prim:
variant_sets = prim.GetVariantSets()
variant_set_name = get_attr_value(node_prim, "inputs:variantSetName")
variant_set = variant_sets.GetVariantSet(variant_set_name)
variant_sets_names = list(variant_set.GetVariantNames())
return variant_sets_names
return []
def _get_tokens(self, prim: Usd.Prim) -> List[str]:
return self._get_variant_names(prim)
# noinspection PyProtectedMember
class CustomVariantLayout:
"""Custom layout for the variant set and variant name attributes"""
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.prim_path_layout = None
self.prim_path_model = None
self.use_path_model = False
self.prim_rel_layout = None
self.prim_rel_model = None
self.variant_set_name_token_model = None
self.variant_set_name_string_model = None
self.variant_name_token_model = None
self.variant_name_string_model = None
self.variant_set_name_string_layout = None
self.variant_set_name_token_layout = None
self.variant_name_string_layout = None
self.variant_name_token_layout = None
def get_node_prim_path(self):
node_prim_path = self.compute_node_widget.payload[-1]
return node_prim_path
def get_use_path(self):
stage = self.compute_node_widget.stage
node_prim_path = self.get_node_prim_path()
use_path = get_use_path(stage, node_prim_path)
return use_path
@staticmethod
def _set_child_string_field_enabled(widget: ui.Widget, enabled: bool):
for child in get_descendants(widget):
if isinstance(child, ui.StringField):
child.enabled = enabled
def _get_target_prim(self) -> Usd.Prim:
return get_target_prim(self.compute_node_widget.stage, self.get_node_prim_path())
def _get_attr_has_connections(self, attr_name: str) -> bool:
stage = self.compute_node_widget.stage
node_prim_path = self.get_node_prim_path()
prim = stage.GetPrimAtPath(node_prim_path)
return get_attr_has_connections(prim, attr_name)
def _token_builder(self, ui_prop: UsdPropertyUiEntry):
return OmniGraphPropertiesWidgetBuilder._tftoken_builder( # noqa: PLW0212
stage=self.compute_node_widget.stage,
attr_name=ui_prop.prop_name,
type_name=ui_prop.property_type,
metadata=ui_prop.metadata,
prim_paths=[self.get_node_prim_path()],
additional_label_kwargs={"style": ATTRIB_LABEL_STYLE},
additional_widget_kwargs={"no_allowed_tokens_model_cls": OmniGraphAttributeModel},
)
def _relationship_builder(self, ui_prop: UsdPropertyUiEntry, changed_fn):
return OmniGraphPropertiesWidgetBuilder._relationship_builder( # noqa: PLW0212
stage=self.compute_node_widget.stage,
attr_name=ui_prop.prop_name,
metadata=ui_prop.metadata,
prim_paths=[self.get_node_prim_path()],
additional_label_kwargs={"style": ATTRIB_LABEL_STYLE},
additional_widget_kwargs={
"on_remove_target": changed_fn,
"target_picker_on_add_targets": changed_fn,
"targets_limit": 1,
},
)
def _bool_builder(self, ui_prop: UsdPropertyUiEntry):
return OmniGraphPropertiesWidgetBuilder._bool_builder( # noqa: PLW0212
stage=self.compute_node_widget.stage,
attr_name=ui_prop.prop_name,
type_name=ui_prop.property_type,
metadata=ui_prop.metadata,
prim_paths=[self.get_node_prim_path()],
additional_label_kwargs={"style": ATTRIB_LABEL_STYLE},
)
def _combo_box_builder(self, ui_prop: UsdPropertyUiEntry, model_cls, changed_fn=None):
stage = self.compute_node_widget.stage
node_prim_path = self.get_node_prim_path()
with ui.HStack(spacing=HORIZONTAL_SPACING):
prop_name = pretty_name(ui_prop.prop_name)
ui.Label(prop_name, name="label", style=ATTRIB_LABEL_STYLE, width=LABEL_WIDTH)
ui.Spacer(width=HORIZONTAL_SPACING)
with ui.ZStack():
attr_path = node_prim_path.AppendProperty(ui_prop.prop_name)
# Build the token-selection widget when prim is known
model = model_cls(stage, [attr_path], False, {}, node_prim_path)
ui.ComboBox(model)
if changed_fn:
model._current_index.add_value_changed_fn(changed_fn) # noqa PLW0212
return model
def _prim_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the token input prim path widget
self.prim_path_layout = ui.HStack(spacing=0)
with self.prim_path_layout:
self.prim_path_model = self._token_builder(ui_prop)
self._update_prim_path()
self.prim_path_model.add_value_changed_fn(self._on_target_prim_path_changed)
def _update_prim_path(self):
use_path = self.get_use_path()
attr_has_connections = self._get_attr_has_connections("inputs:primPath")
self.prim_path_layout.enabled = use_path
enabled = use_path and not attr_has_connections
self._set_child_string_field_enabled(self.prim_path_layout, enabled)
def _prim_rel_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the relationship input prim widget
self.prim_rel_layout = ui.HStack(spacing=0)
with self.prim_rel_layout:
self.prim_rel_model = self._relationship_builder(ui_prop, self._on_target_prim_rel_changed)
self._update_prim_rel()
def _update_prim_rel(self):
self.prim_rel_layout.enabled = not self.get_use_path()
def _use_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the boolean toggle for inputs:usePath
self.use_path_model = self._bool_builder(ui_prop)
self.use_path_model.add_value_changed_fn(self._on_use_path_changed)
def _variant_set_name_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the VariantSetName widget
# Build the simple string input for data-driven variant set name and a ComboBox for when there are
# variants and no data-driven variant set name
self.variant_set_name_string_layout = ui.HStack(spacing=0)
with self.variant_set_name_string_layout:
self.variant_set_name_string_model = self._token_builder(ui_prop)
self.variant_set_name_token_layout = ui.HStack(spacing=0)
with self.variant_set_name_token_layout:
self.variant_set_name_token_model = self._combo_box_builder(
ui_prop, VariantSetNamesTokenModel, self._on_variant_set_changed
)
self._update_variant_set_visibility()
def _update_variant_set_visibility(self):
# Show the string input if the prim is unknown or if the attribute has connections
# otherwise show the token input
if self.variant_set_name_string_layout and self.variant_set_name_token_layout:
attr_has_connections = self._get_attr_has_connections("inputs:variantSetName")
target_prim = self._get_target_prim()
use_string = not target_prim or attr_has_connections
self.variant_set_name_string_layout.visible = use_string
self.variant_set_name_token_layout.visible = not use_string
def _update_variant_set_name(self):
# Update the variant set name widget visibility when the target prim changes
self._update_variant_set_visibility()
if self.variant_set_name_token_model:
self.variant_set_name_token_model._set_dirty() # noqa: PLW0212
if self.variant_set_name_string_model:
self.variant_set_name_string_model._set_dirty() # noqa: PLW0212
def _variant_name_build_fn(self, ui_prop: UsdPropertyUiEntry, *_):
# Build the VariantName widget
# Build the simple string input for data-driven variant name and a ComboBox for when there are
# variants and no data-driven variant name
self.variant_name_string_layout = ui.HStack(spacing=0)
with self.variant_name_string_layout:
self.variant_name_string_model = self._token_builder(ui_prop)
self.variant_name_token_layout = ui.HStack(spacing=0)
with self.variant_name_token_layout:
self.variant_name_token_model = self._combo_box_builder(ui_prop, VariantNamesTokenModel)
self._update_variant_name_visibility()
def _update_variant_name_visibility(self):
# Show the string input if the prim is unknown or if the attribute has connections
# otherwise show the token input
attr_has_connections = self._get_attr_has_connections("inputs:variantName")
target_prim = self._get_target_prim()
if self.variant_name_string_layout and self.variant_name_token_layout:
use_string = not target_prim or attr_has_connections
self.variant_name_string_layout.visible = use_string
self.variant_name_token_layout.visible = not use_string
def _update_variant_name(self):
# Update the variant name widget visibility when the target prim changes
self._update_variant_name_visibility()
if self.variant_name_token_model:
self.variant_name_token_model._set_dirty() # noqa: PLW0212
if self.variant_name_string_model:
self.variant_name_string_model._set_dirty() # noqa: PLW0212
def _on_target_prim_rel_changed(self, *_):
# When the inputs:primRel token changes update the relevant widgets
self.prim_rel_model._set_dirty() # noqa: PLW0212
self._update_prim_rel()
self._update_variant_set_name()
self._update_variant_name()
def _on_target_prim_path_changed(self, *_):
# When the inputs:primPath token changes update the relevant widgets
self._update_variant_set_name()
self._update_variant_name()
def _on_use_path_changed(self, _):
# When the usePath toggle changes update the relevant widgets
self._update_prim_rel()
self._update_prim_path()
self._update_variant_set_name()
self._update_variant_name()
def _on_variant_set_changed(self, _):
# When the variantSet changes update the relevant widgets
self._update_variant_name()
def apply(self, props):
# Apply the property values to the compute node
def find_prop(name) -> Optional[UsdPropertyUiEntry]:
try:
return next((p for p in props if p.prop_name == name))
except StopIteration:
return None
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
prop_fuctions = [
("prim", self._prim_rel_build_fn),
("usePath", self._use_path_build_fn),
("primPath", self._prim_path_build_fn),
("variantSetName", self._variant_set_name_build_fn),
("variantName", self._variant_name_build_fn),
]
for prop_name, build_fn in prop_fuctions:
prop = find_prop(f"inputs:{prop_name}")
if prop:
override_display_name(prop)
CustomLayoutProperty(prop.prop_name, None, build_fn=partial(build_fn, prop))
with CustomLayoutGroup("Outputs"):
for attr in ["exists", "success", "variantSetNames", "variantName"]:
prop = find_prop(f"outputs:{attr}")
if prop:
CustomLayoutProperty(prop.prop_name, pretty_name(prop.prop_name))
return frame.apply(props)
| 16,097 | Python | 41.251968 | 113 | 0.63751 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/tests/test_ui_nodes.py | # noqa: PLC0302
import unittest
from pathlib import Path
from typing import Any, Dict, List
import carb
import carb.settings
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from omni.kit import ui_test
from omni.kit.ui_test.input import (
emulate_mouse_drag_and_drop,
emulate_mouse_move,
emulate_mouse_move_and_click,
emulate_mouse_scroll,
)
from omni.kit.ui_test.vec2 import Vec2
from omni.ui.tests.test_base import OmniUiTest
EXT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.graph.ui_nodes}"))
class TestUINodes(OmniUiTest):
def __init__(self, tests=()):
super().__init__(tests)
self.settings = carb.settings.get_settings()
# The first value for each setting is what we want to set it to, the second is where we will store
# its original value.
self.viewport_settings: Dict[str, List[Any, Any]] = {
"/persistent/app/viewport/displayOptions": [0, None],
"/app/viewport/grid/enabled": [False, None],
"/persistent/app/viewport/{vp_id}/guide/grid/visible": [False, None],
"/persistent/app/viewport/{vp_id}/guide/axis/visible": [False, None],
# This doesn't currently work while the test is running so we set it in the test args instead.
# "/persistent/app/viewport/{vp_id}/hud/visible": [False, None],
}
self.TEST_GRAPH_PATH = "/World/TestGraph"
self.wait_frames_for_visual_update = 5
# It takes 6 frames for the nodes and connections to all draw in their proper positions.
self.wait_frames_for_graph_draw = 6
# Wait 10 frames for commands to execute and the graph to update
self.wait_frames_for_commands = 10
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
self.viewport_name, self.viewport_id = self.get_viewport_name_and_id()
self._golden_img_dir = EXT_PATH.absolute().resolve().joinpath("data/golden_images")
# Make sure the viewport looks the same as when we generated the golden images.
for setting, values in self.viewport_settings.items():
key = setting.format(vp_id=self.viewport_id)
values[1] = self.settings.get(key)
self.settings.set(key, values[0])
await omni.usd.get_context().new_stage_async()
self.stage = omni.usd.get_context().get_stage()
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
# Restore viewport settings.
for setting, (values) in self.viewport_settings.items():
key = setting.format(vp_id=self.viewport_id)
if values[1] is None:
self.settings.destroy_item(key)
else:
self.settings.set(key, values[1])
values[1] = None
omni.usd.get_context().close_stage() # Activate OnClosing node
def get_viewport_name_and_id(self):
try:
import omni.kit.viewport.window as vp
viewport = next(vp.get_viewport_window_instances())
return (viewport.name, viewport.viewport_api.id)
except StopIteration as exc:
raise og.OmniGraphError("Legacy viewport not supported for UI nodes.") from exc
def create_graph(self) -> og.Graph:
"""Create an execution graph."""
return og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
async def edit_ui_execution_graph(self, graph_path: str, graph_node_data: dict, error_thrown=False):
"""Edit graph with nodes, connections and values common to all tests."""
keys = og.Controller.Keys
data = og.Controller.edit(
graph_path,
{
keys.CREATE_NODES: [
("onLoaded", "omni.graph.action.OnLoaded"),
("viewport", "omni.graph.ui_nodes.SetViewportMode"),
("viewportClose", "omni.graph.ui_nodes.SetViewportMode"),
("onClosing", "omni.graph.action.OnClosing"),
]
+ graph_node_data.get(keys.CREATE_NODES, []),
keys.CONNECT: [
("onLoaded.outputs:execOut", "viewport.inputs:execIn"),
("onClosing.outputs:execOut", "viewportClose.inputs:execIn"),
]
+ graph_node_data.get(keys.CONNECT, []),
keys.SET_VALUES: [
("viewport.inputs:viewport", self.viewport_name),
("viewportClose.inputs:viewport", self.viewport_name),
("viewport.inputs:mode", 1),
("viewport.inputs:enablePicking", True),
]
+ graph_node_data.get(keys.SET_VALUES, []),
},
)
# There's no graph window so we're not actually waiting for it to draw, but we still need
# to give some time for all the connections to resolve.
if error_thrown:
with ogts.ExpectedError():
await ui_test.wait_n_updates(self.wait_frames_for_graph_draw)
else:
await ui_test.wait_n_updates(self.wait_frames_for_graph_draw)
return data
def get_attribute(self, attribute, node):
return og.Controller.get(og.Controller.attribute(attribute, node))
def get_attribute_and_assert_equals(self, attribute, node, expected):
attr = self.get_attribute(attribute, node)
self.assertEquals(attr, expected)
def get_attribute_and_assert_list_equals(self, attribute, node, expected):
attr = self.get_attribute(attribute, node).tolist()
self.assertListEqual(attr, expected)
def get_attribute_and_assert_list_almost_equals(self, attribute, node, expected):
attr = self.get_attribute(attribute, node).tolist()
for a, e in zip(attr, expected):
self.assertAlmostEquals(a, e)
def assert_compute_message(self, node, error_message, severity=og.Severity.ERROR):
error = node.get_compute_messages(severity)[0].split("\n")[0]
self.assertEquals(error, error_message)
async def test_button_ui(self):
"""Test UI button"""
graph = self.create_graph()
widget_identifier = "testbutton"
keys = og.Controller.Keys
(_, (_, viewport, _, _, button, click, counter), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("click", "omni.graph.ui_nodes.OnWidgetClicked"),
("counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("click.outputs:clicked", "counter.inputs:execIn"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("click.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "THIS IS A TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
],
},
)
# Click the button
await emulate_mouse_move_and_click(Vec2(50, 55))
self.get_attribute_and_assert_equals(
"inputs:parentWidgetPath", button, self.get_attribute("outputs:widgetPath", viewport)
)
self.get_attribute_and_assert_equals(
"inputs:create", button, self.get_attribute("outputs:scriptedMode", viewport)
)
self.get_attribute_and_assert_equals("inputs:widgetIdentifier", button, widget_identifier)
self.get_attribute_and_assert_equals("inputs:widgetIdentifier", click, widget_identifier)
# Test button click event
self.get_attribute_and_assert_equals("outputs:count", counter, 1)
await self.finalize_test_no_image()
async def test_set_viewport_mode(self):
"""Test SetViewportMode UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, viewport, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.SET_VALUES: [("viewport.inputs:mode", 0)],
},
)
self.get_attribute_and_assert_equals("outputs:scriptedMode", viewport, 0)
self.get_attribute_and_assert_equals("outputs:defaultMode", viewport, 1)
await self.finalize_test_no_image()
async def test_on_viewport_clicked(self):
"""Test OnViewportClicked and ReadViewportClickState UI nodes"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_clicked, viewport_click_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_clicked", "omni.graph.ui_nodes.OnViewportClicked"),
("viewport_click_state", "omni.graph.ui_nodes.ReadViewportClickState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_click_state.outputs:position", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_clicked.outputs:clicked", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_clicked.inputs:viewport", self.viewport_name),
("viewport_click_state.inputs:viewport", self.viewport_name),
("on_viewport_clicked.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_move_and_click(Vec2(85, 255))
position = [72.40223463687151, 158.88268156424587] # Translated (x, y) position fo the mouse click
self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_clicked, "Left Mouse Click")
self.get_attribute_and_assert_equals("inputs:gesture", viewport_click_state, "Left Mouse Click")
self.get_attribute_and_assert_list_almost_equals("outputs:position", on_viewport_clicked, position)
self.get_attribute_and_assert_list_almost_equals("outputs:position", viewport_click_state, position)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_click_state, True)
await self.finalize_test_no_image()
async def test_on_viewport_pressed(self):
"""Test OnViewportPressed UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
(
_,
(_, _, _, _, on_viewport_pressed, viewport_press_state, _, _, _, _),
_,
_,
) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_pressed", "omni.graph.ui_nodes.OnViewportPressed"),
("viewport_press_state", "omni.graph.ui_nodes.ReadViewportPressState"),
("to_string", "omni.graph.nodes.ToString"),
("to_string2", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
("print2", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_press_state.outputs:pressPosition", "to_string.inputs:value"),
("viewport_press_state.outputs:releasePosition", "to_string2.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("to_string2.outputs:converted", "print2.inputs:text"),
("on_viewport_pressed.outputs:pressed", "print.inputs:execIn"),
("on_viewport_pressed.outputs:released", "print2.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_pressed.inputs:viewport", self.viewport_name),
("viewport_press_state.inputs:viewport", self.viewport_name),
("on_viewport_pressed.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_move_and_click(Vec2(85, 255))
position = [72.40223463687151, 158.88268156424587] # Translated (x, y) position fo the mouse click
self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_pressed, "Left Mouse Press")
self.get_attribute_and_assert_equals("inputs:gesture", viewport_press_state, "Left Mouse Press")
self.get_attribute_and_assert_list_equals("outputs:pressPosition", on_viewport_pressed, position)
self.get_attribute_and_assert_list_equals("outputs:releasePosition", on_viewport_pressed, position)
self.get_attribute_and_assert_list_equals("outputs:pressPosition", viewport_press_state, position)
self.get_attribute_and_assert_list_equals("outputs:releasePosition", viewport_press_state, position)
self.get_attribute_and_assert_equals("outputs:isReleasePositionValid", viewport_press_state, True)
self.get_attribute_and_assert_equals("outputs:isPressed", viewport_press_state, False)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_press_state, True)
await self.finalize_test_no_image()
async def test_on_viewport_scrolled(self):
"""Test OnViewportScrolled UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_scrolled, viewport_scroll_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_scrolled", "omni.graph.ui_nodes.OnViewportScrolled"),
("viewport_scroll_state", "omni.graph.ui_nodes.ReadViewportScrollState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_scroll_state.outputs:position", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_scrolled.outputs:scrolled", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_scrolled.inputs:viewport", self.viewport_name),
("viewport_scroll_state.inputs:viewport", self.viewport_name),
("on_viewport_scrolled.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_move(Vec2(85, 255))
await emulate_mouse_scroll(Vec2(0, 900)) # (x, y) make a variable
position = [72.40223463687151, 158.88268156424587]
self.get_attribute_and_assert_equals("outputs:scrolled", on_viewport_scrolled, 1)
self.get_attribute_and_assert_list_equals("outputs:position", on_viewport_scrolled, position)
self.get_attribute_and_assert_list_equals("outputs:position", viewport_scroll_state, position)
self.get_attribute_and_assert_equals("outputs:scrollValue", on_viewport_scrolled, 1)
self.get_attribute_and_assert_equals("outputs:scrollValue", viewport_scroll_state, 1)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_scroll_state, True)
await self.finalize_test_no_image()
async def test_on_viewport_hovered(self):
"""Test OnViewportHovered UI node"""
graph = self.create_graph()
await emulate_mouse_move(Vec2(0, 0)) # Move the cursor away from final position
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_hover, viewport_hover_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_hover", "omni.graph.ui_nodes.OnViewportHovered"),
("viewport_hover_state", "omni.graph.ui_nodes.ReadViewportHoverState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_hover_state.outputs:position", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_hover.outputs:began", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_hover.inputs:viewport", self.viewport_name),
("viewport_hover_state.inputs:viewport", self.viewport_name),
("on_viewport_hover.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_move(Vec2(85, 255))
position = [72.40223463687151, 158.88268156424587]
self.get_attribute_and_assert_equals("outputs:began", on_viewport_hover, 1)
self.get_attribute_and_assert_equals("outputs:isHovered", viewport_hover_state, True)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_hover_state, True)
self.get_attribute_and_assert_list_equals("outputs:position", viewport_hover_state, position)
await self.finalize_test_no_image()
async def test_on_viewport_dragged(self):
"""Test OnViewportDrag UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_dragged, viewport_drag_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_dragged", "omni.graph.ui_nodes.OnViewportDragged"),
("viewport_drag_state", "omni.graph.ui_nodes.ReadViewportDragState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_drag_state.outputs:currentPosition", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_dragged.outputs:ended", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_dragged.inputs:viewport", self.viewport_name),
("viewport_drag_state.inputs:viewport", self.viewport_name),
("on_viewport_dragged.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_drag_and_drop(Vec2(85, 255), Vec2(100, 455))
start_position = [72.40223463687151, 158.88268156424587]
end_position = [85.81005586592177, 337.6536312849162]
self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_dragged, "Left Mouse Drag")
self.get_attribute_and_assert_list_equals("outputs:initialPosition", on_viewport_dragged, start_position)
self.get_attribute_and_assert_list_equals("outputs:finalPosition", on_viewport_dragged, end_position)
self.get_attribute_and_assert_list_equals("outputs:currentPosition", viewport_drag_state, end_position)
self.get_attribute_and_assert_list_equals("outputs:initialPosition", viewport_drag_state, start_position)
self.get_attribute_and_assert_list_equals("outputs:velocity", viewport_drag_state, [0, 0])
self.get_attribute_and_assert_equals("outputs:isValid", viewport_drag_state, True)
self.get_attribute_and_assert_equals("outputs:isDragInProgress", viewport_drag_state, False)
await self.finalize_test_no_image()
async def test_on_viewport_dragged_began(self):
"""Test OnViewportDrag UI node where we begin the drag but don't complete it."""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, on_viewport_dragged, viewport_drag_state, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_viewport_dragged", "omni.graph.ui_nodes.OnViewportDragged"),
("viewport_drag_state", "omni.graph.ui_nodes.ReadViewportDragState"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport_drag_state.outputs:currentPosition", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
("on_viewport_dragged.outputs:began", "print.inputs:execIn"),
],
keys.SET_VALUES: [
("viewport.inputs:enableViewportMouseEvents", True),
("on_viewport_dragged.inputs:viewport", self.viewport_name),
("viewport_drag_state.inputs:viewport", self.viewport_name),
("on_viewport_dragged.inputs:onlyPlayback", False),
],
},
)
# Click inside viewport
await emulate_mouse_drag_and_drop(Vec2(85, 255), Vec2(100, 455))
start_position = [72.40223463687151, 158.88268156424587]
velocity = [0.8938547486033599, 22.346368715083777]
self.get_attribute_and_assert_equals("inputs:gesture", on_viewport_dragged, "Left Mouse Drag")
self.get_attribute_and_assert_list_equals("outputs:initialPosition", on_viewport_dragged, start_position)
self.get_attribute_and_assert_list_equals("outputs:initialPosition", viewport_drag_state, start_position)
self.get_attribute_and_assert_list_equals("outputs:velocity", viewport_drag_state, velocity)
self.get_attribute_and_assert_equals("outputs:isValid", viewport_drag_state, True)
self.get_attribute_and_assert_equals("outputs:isDragInProgress", viewport_drag_state, True)
await self.finalize_test_no_image()
async def test_read_window_size_viewport_connection(self):
"""Test ReadWindowSize UI node with the viewport/window widget path connection"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "print.inputs:execIn"),
("viewport.outputs:widgetPath", "read_window_size.inputs:widgetPath"),
("read_window_size.outputs:height", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("read_window_size.inputs:isViewport", True),
],
},
)
self.get_attribute_and_assert_equals("outputs:width", read_window_size, 1440)
self.get_attribute_and_assert_equals("outputs:height", read_window_size, 900)
await self.finalize_test_no_image()
async def test_read_window_size(self):
"""Test ReadWindowSize UI node with the viewport/window name"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "print.inputs:execIn"),
("read_window_size.outputs:height", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("read_window_size.inputs:isViewport", True),
("read_window_size.inputs:name", self.viewport_name),
],
},
)
self.get_attribute_and_assert_equals("outputs:width", read_window_size, 1440)
self.get_attribute_and_assert_equals("outputs:height", read_window_size, 900)
await self.finalize_test_no_image()
async def test_read_window_size_no_window(self):
"""Test ReadWindowSize UI node without window (error flow)"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "print.inputs:execIn"),
("read_window_size.outputs:height", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("read_window_size.inputs:isViewport", True),
],
},
error_thrown=True,
)
warning = "OmniGraph Warning: No window name or widgetPath provided."
self.assert_compute_message(read_window_size, warning, og.Severity.WARNING)
await self.finalize_test_no_image()
async def test_read_window_size_invalid_window(self):
"""Test ReadWindowSize UI node with invalid window name (error flow)"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, read_window_size, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("read_window_size", "omni.graph.ui_nodes.ReadWindowSize"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "print.inputs:execIn"),
("read_window_size.outputs:height", "to_string.inputs:value"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("read_window_size.inputs:isViewport", True),
("read_window_size.inputs:name", "invalid-viewport"),
],
},
error_thrown=True,
)
error = "OmniGraph Error: No viewport named 'invalid-viewport' found."
self.assert_compute_message(read_window_size, error, og.Severity.ERROR)
await self.finalize_test_no_image()
async def test_write_widget_property(self):
"""Test WriteWidgetProperty UI node"""
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
(_, (_, viewport, _, _, button, click, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("click", "omni.graph.ui_nodes.OnWidgetClicked"),
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("click.outputs:clicked", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("click.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "THIS IS A TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("string.inputs:value", "NEW BUTTON"),
("write.inputs:widgetIdentifier", widget_identifier),
("write.inputs:propertyName", "text"),
],
},
)
# Click the button to trigger property write
await emulate_mouse_move_and_click(Vec2(50, 55))
self.get_attribute_and_assert_equals(
"inputs:parentWidgetPath", button, self.get_attribute("outputs:widgetPath", viewport)
)
self.get_attribute_and_assert_equals(
"inputs:create", button, self.get_attribute("outputs:scriptedMode", viewport)
)
self.get_attribute_and_assert_equals("inputs:widgetIdentifier", button, widget_identifier)
self.get_attribute_and_assert_equals("inputs:widgetIdentifier", click, widget_identifier)
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
golden_img_name="omni.graph.ui_nodes.test_write_widget_property.png",
)
async def test_read_widget_property(self):
"""Test ReadWidgetProperty UI node"""
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
(_, (_, _, _, _, button, read, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("read", "omni.graph.ui_nodes.ReadWidgetProperty"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "print.inputs:execIn"),
("read.outputs:value", "print.inputs:text"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "THIS IS A TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("read.inputs:widgetIdentifier", widget_identifier),
("read.inputs:propertyName", "text"),
],
},
)
self.get_attribute_and_assert_equals("inputs:text", button, self.get_attribute("outputs:value", read))
await self.finalize_test_no_image()
async def test_write_widget_property_with_widget_path(self):
"""Test WriteWidgetProperty UI node"""
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("click", "omni.graph.ui_nodes.OnWidgetClicked"),
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("click.outputs:clicked", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
("button.outputs:widgetPath", "write.inputs:widgetPath"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("click.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "THIS IS A TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("string.inputs:value", "NEW BUTTON"),
("write.inputs:propertyName", "text"),
],
},
)
# Click the button to trigger property write
await emulate_mouse_move_and_click(Vec2(50, 55))
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
golden_img_name="omni.graph.ui_nodes.test_write_widget_property_with_widget_path.png",
)
async def test_write_widget_style(self):
"""Test WriteWidgetProperty UI node"""
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("write", "omni.graph.ui_nodes.WriteWidgetStyle"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "write.inputs:write"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "A BUTTON"),
("write.inputs:widgetIdentifier", widget_identifier),
("write.inputs:style", '{"background_color": "blue"}'),
],
},
)
# Click the viewport to see it
await emulate_mouse_move_and_click(Vec2(80, 255))
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
golden_img_name="omni.graph.ui_nodes.test_write_widget_style.png",
)
async def test_write_widget_style_with_widget_path(self):
"""Test WriteWidgetProperty UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("write", "omni.graph.ui_nodes.WriteWidgetStyle"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "write.inputs:write"),
("button.outputs:widgetPath", "write.inputs:widgetPath"),
],
keys.SET_VALUES: [
("button.inputs:text", "A BUTTON"),
("write.inputs:style", '{"background_color": "blue"}'),
],
},
)
# Click the viewport to see it
await emulate_mouse_move_and_click(Vec2(80, 255))
await self.finalize_test(
golden_img_dir=self._golden_img_dir,
golden_img_name="omni.graph.ui_nodes.test_write_widget_style_with_widget_path.png",
)
async def test_placer(self):
"""Test Placer UI node"""
graph = self.create_graph()
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("placer", "omni.graph.ui_nodes.Placer"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "placer.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "placer.inputs:create"),
("placer.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("placer.outputs:created", "button.inputs:create"),
],
keys.SET_VALUES: [
("button.inputs:text", "THIS IS A PLACED BUTTON"),
("button.inputs:style", '{"background_color": "blue"}'),
("placer.inputs:position", (20.0, 250.0)),
],
},
)
# Click the viewport
await emulate_mouse_move_and_click(Vec2(50, 55))
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_placer.png"
)
async def test_vstack_and_spacer(self):
"""Test VStack and Spacer UI nodes"""
buttons = 3
colors = ["green", "blue", "orange"]
stack = [f"button{b}" for b in range(buttons)]
stack.insert(1, "spacer")
# To ensure a consistent ordering of the children within the stack, the creation of the stack triggers the
# creation of its first child widget and each child then triggers the creation of the next one.
widget_creation_connections = [("stack.outputs:created", f"{stack[0]}.inputs:create")]
for i in range(len(stack) - 1):
widget_creation_connections += [(f"{stack[i]}.outputs:created", f"{stack[i+1]}.inputs:create")]
graph = self.create_graph()
keys = og.Controller.Keys
await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("stack", "omni.graph.ui_nodes.VStack"),
("spacer", "omni.graph.ui_nodes.Spacer"),
]
+ [(f"button{b}", "omni.graph.ui_nodes.Button") for b in range(buttons)],
keys.CONNECT: [
("viewport.outputs:widgetPath", "stack.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "stack.inputs:create"),
]
+ widget_creation_connections
+ [("stack.outputs:widgetPath", f"{widget}.inputs:parentWidgetPath") for widget in stack],
keys.SET_VALUES: [("spacer.inputs:height", 100)]
+ [(f"button{b}.inputs:text", f"Button {b+1}") for b in range(buttons)]
+ [(f"button{b}.inputs:style", '{"background_color": "' + colors[b] + '"}') for b in range(buttons)],
},
)
# Click the viewport
await emulate_mouse_move_and_click(Vec2(50, 55))
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="omni.graph.ui_nodes.test_vstack_and_spacer.png"
)
async def test_button_negative_size(self):
"""Test UI button error flow - negative size"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, button), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [("button", "omni.graph.ui_nodes.Button")],
keys.CONNECT: [("viewport.outputs:scriptedMode", "button.inputs:create")],
keys.SET_VALUES: [("button.inputs:size", (-1, -1))], # Negative size
},
error_thrown=True,
)
self.assert_compute_message(button, "OmniGraph Error: The size of the widget cannot be negative!")
await self.finalize_test_no_image()
async def test_button_negative_no_parent_widget(self):
"""Test UI button error flow - no parent widget"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, button), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [("button", "omni.graph.ui_nodes.Button")],
keys.CONNECT: [("viewport.outputs:scriptedMode", "button.inputs:create")],
},
error_thrown=True,
)
self.assert_compute_message(button, "OmniGraph Error: No parentWidgetPath supplied.")
await self.finalize_test_no_image()
async def test_button_negative_invalid_style(self):
"""Test UI button error flow - style not valid"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, button), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [("button", "omni.graph.ui_nodes.Button")],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "button.inputs:create"),
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
],
keys.SET_VALUES: [("button.inputs:style", "bad style")],
},
error_thrown=True,
)
# The expected error message contains the text of a Python SyntaxError exception, which is
# different depending on the Python version. So rather than do an exact match on the entire message
# we'll just check for some identifying text that is under our control.
msg = button.get_compute_messages(og.Severity.ERROR)[0].split("\n")[0]
self.assertTrue("OmniGraph Error: 'inputs:style': Invalid style syntax" in msg, "expected syntax error")
await self.finalize_test_no_image()
async def test_write_widget_property_invalid_widget_identifier(self):
"""Test WriteWidgetProperty UI node error flow - invalid widget identifier"""
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, write, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
("impulse", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("impulse.outputs:execOut", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("write.inputs:widgetIdentifier", "invalid-id"),
("string.inputs:value", "new style"),
("impulse.state:enableImpulse", True),
("impulse.inputs:onlyPlayback", False),
],
},
)
warning = "OmniGraph Warning: No widget with identifier 'invalid-id' found in this graph."
self.assert_compute_message(write, warning, og.Severity.WARNING)
await self.finalize_test_no_image()
async def test_write_widget_property_invalid_widget_path(self):
graph = self.create_graph()
widget_path = "Viewport//Frame/ZStack[0]/Frame[3]/OG_overlay/Placer[2]/testbutton11"
keys = og.Controller.Keys
(_, (_, _, _, _, write, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
("impulse", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("impulse.outputs:execOut", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("write.inputs:widgetPath", widget_path),
("string.inputs:value", "new style"),
("impulse.state:enableImpulse", True),
("impulse.inputs:onlyPlayback", False),
],
},
)
warning = f"OmniGraph Warning: No widget found at path '{widget_path}'."
self.assert_compute_message(write, warning, og.Severity.WARNING)
await self.finalize_test_no_image()
async def test_write_widget_property_invalid_widget(self):
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, write, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
("impulse", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("impulse.outputs:execOut", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("string.inputs:value", "new style"),
("impulse.state:enableImpulse", True),
("impulse.inputs:onlyPlayback", False),
],
},
)
warning = "OmniGraph Warning: No widgetIdentifier or widgetPath provided."
self.assert_compute_message(write, warning, og.Severity.WARNING)
await self.finalize_test_no_image()
async def test_write_widget_property_no_property(self):
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
(_, (_, _, _, _, _, write, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "write.inputs:write"),
("button.outputs:widgetPath", "write.inputs:widgetPath"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("string.inputs:value", "NEW BUTTON"),
],
},
error_thrown=True,
)
error = "OmniGraph Error: No property provided."
self.assert_compute_message(write, error)
await self.finalize_test_no_image()
async def test_write_widget_property_invalid_property(self):
graph = self.create_graph()
widget_identifier = "testbutton1"
keys = og.Controller.Keys
(_, (_, _, _, _, _, write, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("button", "omni.graph.ui_nodes.Button"),
("write", "omni.graph.ui_nodes.WriteWidgetProperty"),
("string", "omni.graph.nodes.ConstantString"),
],
keys.CONNECT: [
("viewport.outputs:widgetPath", "button.inputs:parentWidgetPath"),
("viewport.outputs:scriptedMode", "button.inputs:create"),
("button.outputs:created", "write.inputs:write"),
("string.inputs:value", "write.inputs:value"),
],
keys.SET_VALUES: [
("button.inputs:widgetIdentifier", widget_identifier),
("write.inputs:widgetIdentifier", widget_identifier),
("button.inputs:text", "TEST BUTTON"),
("button.inputs:style", '{"background_color": "green"}'),
("string.inputs:value", "NEW BUTTON"),
("write.inputs:propertyName", "invalid-property"),
],
},
error_thrown=True,
)
error = f"OmniGraph Error: Widget '{widget_identifier}' has no property 'invalid-property'."
self.assert_compute_message(write, error)
await self.finalize_test_no_image()
async def test_get_set_active_viewport_camera(self):
graph = self.create_graph()
prim_path = "/OmniverseKit_Front"
keys = og.Controller.Keys
(_, (_, _, _, _, _, get_camera, _, _), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("set_camera", "omni.graph.ui_nodes.SetActiveViewportCamera"),
("get_camera", "omni.graph.ui_nodes.GetActiveViewportCamera"),
("to_string", "omni.graph.nodes.ToString"),
("print", "omni.graph.ui_nodes.PrintText"),
],
keys.CONNECT: [
("viewport.outputs:scriptedMode", "set_camera.inputs:execIn"),
("get_camera.outputs:camera", "to_string.inputs:value"),
("set_camera.outputs:execOut", "print.inputs:execIn"),
("to_string.outputs:converted", "print.inputs:text"),
],
keys.SET_VALUES: [
("set_camera.inputs:viewport", self.viewport_name),
("set_camera.inputs:primPath", prim_path),
],
},
)
self.get_attribute_and_assert_equals("outputs:camera", get_camera, prim_path)
await self.finalize_test_no_image()
# Using emulate_mouse_move_and_click() doesn't trigger the OnPicked node, even when done through the
# Script Editor in an interactive session.
@unittest.skip("OM-77263: Not working.")
async def test_on_picked(self):
graph = self.create_graph()
keys = og.Controller.Keys
(_, (_, _, _, _, _, counter), _, _) = await self.edit_ui_execution_graph(
graph,
{
keys.CREATE_NODES: [
("on_picked", "omni.graph.ui_nodes.OnPicked"),
("counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("on_picked.outputs:picked", "counter.inputs:execIn"),
],
keys.SET_VALUES: [
("on_picked.inputs:viewport", self.viewport_name),
("on_picked.inputs:onlyPlayback", False),
],
},
)
await emulate_mouse_move_and_click(Vec2(85, 255))
cube = ogts.create_cube(self.stage, "my_cube", (1, 1, 1))
attr = cube.GetAttribute("size")
attr.Set(10.0)
await ui_test.wait_n_updates(20)
self.get_attribute_and_assert_equals("outputs:count", counter, 1)
await self.finalize_test()
async def test_pass_clicks_thru(self):
await self.create_test_area(width=1200, height=800, block_devices=False)
selection: omni.usd.Selection = omni.usd.get_context().get_selection()
# Load some geometry so that we have something which can be selected with a mouse click.
# The pxr renderer (aka "Storm") has problems selecting implicit geometry such as that generated by
# the Cube prim, so we need to use a mesh.
(result, error) = await ogts.load_test_file("mesh-cube.usd", use_caller_subdirectory=True)
self.assertTrue(result, error)
cube_path = "/World/Cube"
cube_pos = Vec2(700, 400)
# Create an execution graph with a SetViewportMode node and a variable to control its passClicksThru.
# An OnVariableChange node triggers the SetViewportMode node whenever the variable's value changes.
graph = self.create_graph()
keys = og.Controller.Keys
controller = og.Controller()
controller.edit(
graph,
{
keys.CREATE_VARIABLES: [("passThruMode", "bool", False)],
keys.CREATE_NODES: [
("readVariable", "omni.graph.core.ReadVariable"),
("viewportMode", "omni.graph.ui_nodes.SetViewportMode"),
("variableChanged", "omni.graph.action.OnVariableChange"),
# These are needed to ensure that the viewport is set back to default mode when the test is done.
("viewportClose", "omni.graph.ui_nodes.SetViewportMode"),
("onClosing", "omni.graph.action.OnClosing"),
],
keys.SET_VALUES: [
("readVariable.inputs:variableName", "passThruMode"),
("viewportMode.inputs:viewport", self.viewport_name),
("viewportMode.inputs:mode", 1),
("variableChanged.inputs:variableName", "passThruMode"),
("variableChanged.inputs:onlyPlayback", False),
("viewportClose.inputs:viewport", self.viewport_name),
],
keys.CONNECT: [
("readVariable.outputs:value", "viewportMode.inputs:passClicksThru"),
("variableChanged.outputs:changed", "viewportMode.inputs:execIn"),
("onClosing.outputs:execOut", "viewportClose.inputs:execIn"),
],
},
)
variable = graph.find_variable("passThruMode")
# Make sure nothing is selected and give the viewport some time to settle down.
selection.clear_selected_prim_paths()
await ui_test.wait_n_updates(2)
# Enable passClicksThru and click on the cube. It should be selected.
variable.set(graph.get_context(), True)
await ui_test.wait_n_updates(2)
await emulate_mouse_move_and_click(cube_pos)
await ui_test.wait_n_updates(8)
self.assertTrue(cube_path in selection.get_selected_prim_paths(), "Selection with passClicksThru True.")
# Disable passClicksThru and click on the cube. It should not be selected.
selection.clear_selected_prim_paths()
variable.set(graph.get_context(), False)
await ui_test.wait_n_updates(2)
await emulate_mouse_move_and_click(cube_pos)
await ui_test.wait_n_updates(8)
self.assertFalse(cube_path in selection.get_selected_prim_paths(), "Selection with passClicksThru False.")
await self.finalize_test_no_image()
| 55,826 | Python | 43.307143 | 120 | 0.553846 |
omniverse-code/kit/exts/omni.graph.ui_nodes/omni/graph/ui_nodes/tests/test_omnigraph_action.py | """
Tests that verify action UI-dependent nodes
"""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from omni.kit.viewport.utility import get_active_viewport
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from pxr import Gf
# ======================================================================
class TestOmniGraphAction(ogts.OmniGraphTestCase):
"""Encapsulate simple sanity tests"""
# ----------------------------------------------------------------------
async def setUp(self):
await super().setUp()
viewport_api = get_active_viewport()
viewport_api.camera_path = "/OmniverseKit_Persp"
# ----------------------------------------------------------------------
async def _test_camera_nodes(self, use_prim_connections):
"""Test camera-related node basic functionality"""
keys = og.Controller.Keys
controller = og.Controller()
viewport_api = get_active_viewport()
active_cam = viewport_api.camera_path
persp_cam = "/OmniverseKit_Persp"
self.assertEqual(active_cam.pathString, persp_cam)
(graph, _, _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("SetCam", "omni.graph.ui_nodes.SetActiveViewportCamera"),
],
keys.SET_VALUES: [
("SetCam.inputs:primPath", "/OmniverseKit_Top"),
],
keys.CONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")],
},
)
await controller.evaluate()
active_cam = viewport_api.camera_path
self.assertEqual(active_cam.pathString, "/OmniverseKit_Top")
# be nice - set it back
viewport_api.camera_path = persp_cam
# Tests moving the camera and camera target
controller.edit(
graph,
{
keys.DISCONNECT: [("OnTick.outputs:tick", "SetCam.inputs:execIn")],
},
)
await controller.evaluate()
(graph, (_, _, get_pos, get_target), _, _) = controller.edit(
graph,
{
keys.CREATE_NODES: [
("SetPos", "omni.graph.ui_nodes.SetCameraPosition"),
("SetTarget", "omni.graph.ui_nodes.SetCameraTarget"),
("GetPos", "omni.graph.ui_nodes.GetCameraPosition"),
("GetTarget", "omni.graph.ui_nodes.GetCameraTarget"),
],
keys.SET_VALUES: [
("SetPos.inputs:position", Gf.Vec3d(1.0, 2.0, 3.0)),
# Target should be different than position
("SetTarget.inputs:target", Gf.Vec3d(-1.0, -2.0, -3.0)),
],
keys.CONNECT: [
("OnTick.outputs:tick", "SetPos.inputs:execIn"),
("SetPos.outputs:execOut", "SetTarget.inputs:execIn"),
],
},
)
if use_prim_connections:
controller.edit(
graph,
{
keys.CREATE_NODES: [
("GetPrimAtPath", "omni.graph.nodes.GetPrimsAtPath"),
("ConstToken", "omni.graph.nodes.ConstantToken"),
],
keys.CONNECT: [
("ConstToken.inputs:value", "GetPrimAtPath.inputs:path"),
("GetPrimAtPath.outputs:prims", "SetPos.inputs:prim"),
("GetPrimAtPath.outputs:prims", "SetTarget.inputs:prim"),
("GetPrimAtPath.outputs:prims", "GetPos.inputs:prim"),
("GetPrimAtPath.outputs:prims", "GetTarget.inputs:prim"),
],
keys.SET_VALUES: [
("SetPos.inputs:usePath", False),
("SetTarget.inputs:usePath", False),
("GetPos.inputs:usePath", False),
("GetTarget.inputs:usePath", False),
("ConstToken.inputs:value", persp_cam),
],
},
)
else:
controller.edit(
graph,
{
keys.SET_VALUES: [
("SetPos.inputs:primPath", persp_cam),
("SetTarget.inputs:primPath", persp_cam),
("GetPos.inputs:primPath", persp_cam),
("GetTarget.inputs:primPath", persp_cam),
],
},
)
await controller.evaluate()
# XXX: May need to force these calls through legacy_viewport as C++ nodes call through to that interface.
camera_state = ViewportCameraState(persp_cam) # , viewport=viewport_api, force_legacy_api=True)
x, y, z = camera_state.position_world
for a, b in zip([x, y, z], [1.0, 2.0, 3.0]):
self.assertAlmostEqual(a, b, places=5)
x, y, z = camera_state.target_world
for a, b in zip([x, y, z], [-1.0, -2.0, -3.0]):
self.assertAlmostEqual(a, b, places=5)
# evaluate again, because push-evaluator may not have scheduled the getters after the setters
await controller.evaluate()
get_pos = og.Controller.get(controller.attribute(("outputs:position", get_pos)))
for a, b in zip(get_pos, [1.0, 2.0, 3.0]):
self.assertAlmostEqual(a, b, places=5)
get_target = og.Controller.get(controller.attribute(("outputs:target", get_target)))
for a, b in zip(get_target, [-1.0, -2.0, -3.0]):
self.assertAlmostEqual(a, b, places=5)
# ----------------------------------------------------------------------
async def test_camera_nodes(self):
await self._test_camera_nodes(use_prim_connections=False)
# ----------------------------------------------------------------------
async def test_camera_nodes_with_prim_connection(self):
await self._test_camera_nodes(use_prim_connections=True)
# ----------------------------------------------------------------------
async def test_on_new_frame(self):
"""Test OnNewFrame node"""
keys = og.Controller.Keys
controller = og.Controller()
# Check that the NewFrame node is getting updated when frames are being generated
(_, (new_frame_node,), _, _) = controller.edit(
"/TestGraph", {keys.CREATE_NODES: [("NewFrame", "omni.graph.ui_nodes.OnNewFrame")]}
)
attr = controller.attribute(("outputs:frameNumber", new_frame_node))
await og.Controller.evaluate()
frame_num = og.Controller.get(attr)
# Need to tick Kit before evaluation in order to update
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await og.Controller.evaluate()
self.assertLess(frame_num, og.Controller.get(attr))
# -------------------------------------------------------------------------
async def test_get_active_camera_viewport_prim_output(self):
"""Tests the prim output on GetActiveCameraView node returns the correct value"""
keys = og.Controller.Keys
controller = og.Controller()
(graph, (_cam_node, path_node), _, _) = controller.edit(
"/TestGraph",
{
keys.CREATE_NODES: [
("GetCamera", "omni.graph.ui_nodes.GetActiveViewportCamera"),
("GetPrimPath", "omni.graph.nodes.GetPrimPath"),
],
keys.CONNECT: [("GetCamera.outputs:cameraPrim", "GetPrimPath.inputs:prim")],
},
)
await og.Controller.evaluate(graph)
self.assertEqual(og.Controller.get(("outputs:primPath", path_node)), "/OmniverseKit_Persp")
# -------------------------------------------------------------------------
async def test_get_active_camera_viewport_from_file(self):
"""
Test the prim output on GetActiveCameraView node exists and returns the correct value
when an older version of the node is loaded from a file.
"""
(result, error) = await ogts.load_test_file("GetActiveViewportCamera.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
# validate the node and attribute exist after loading. The attribute does not exist in the file
cam_node = og.Controller.node("/World/Graph/get_active_camera")
self.assertTrue(cam_node.is_valid())
prim_output = og.Controller.attribute("/World/Graph/get_active_camera.outputs:cameraPrim")
self.assertTrue(prim_output.is_valid())
# modify the graph and evaluate it, to verify it gets the expected results
keys = og.Controller.Keys
controller = og.Controller()
(graph, nodes, _, _) = controller.edit(
"/World/Graph",
{
keys.CREATE_NODES: [
("GetPrimPath", "omni.graph.nodes.GetPrimPath"),
],
},
)
prim_inputs = nodes[0].get_attribute("inputs:prim")
controller.connect(prim_output, prim_inputs)
await og.Controller.evaluate(graph)
self.assertEqual(og.Controller.get(("outputs:primPath", nodes[0])), "/OmniverseKit_Persp")
| 9,466 | Python | 42.828704 | 113 | 0.516586 |
omniverse-code/kit/exts/omni.uiaudio/config/extension.toml | [package]
title = "Kit UI Audio"
category = "Audio"
feature = true
version = "1.0.0"
description = "An audio API for playing sounds for UI interactions."
authors = ["NVIDIA"]
keywords = ["audio", "ui"]
[dependencies]
"carb.audio" = {}
[[native.plugin]]
path = "bin/*.plugin"
[[python.module]]
name = "omni.kit.uiaudio"
| 323 | TOML | 16.052631 | 68 | 0.662539 |
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/_uiaudio.pyi | """
This module contains bindings to the C++ omni::audio::IUiAudio interface.
This provides functionality for playing sounds through the editor UI.
Sound files may be in RIFF/WAV, Ogg, or FLAC format.
Data in the sound files may use 8, 16, 24, or 32 bit integer samples,
or 32 bit floating point samples. Channel counts may be from 1 to 64
If more channels of data are provided than the audio device can play,
some channels will be blended together automatically.
"""
from __future__ import annotations
import omni.kit.uiaudio._uiaudio
import typing
__all__ = [
"IUiAudio",
"UiSound",
"acquire_ui_audio_interface"
]
class IUiAudio():
"""
This interface contains functions for playing audio in editor UI. This is intended to be used
to provide auditory feedback to the user for events such as errors or long processing steps
completing.
The sounds loaded by this interface will persist until destroyed and can be played any number of
times as needed. Any particular sound file will only be loaded into memory once and will be shared
by all callers that try to load it. Each call to create a new sound object must be paired with a
call to destroy it once it is no longer needed.
Up to 64 sounds may be playing at any given time for the editor UI. Playing a sound will only
schedule it to be played then return immediately. The sound will continue to play. Callers can
block until a sound has finished playing or query whether it has finished playing by using The
IUiAudio::isSoundPlaying() call. It is best practice to use monaural or stereo sounds for
this interface since they use less memory, are processed more easily, and will typically play
as expected through all devices.
Note that if a single long sound object is played multiple times simultaneously, attempting to
stop or query the playing sound will only affect the most recently played instance of it. In
this case, all other instances will continue playing until they finish naturally.
All the function in this interface are in omni.kit.audio.IUiAudio class. To retrieve
this object, use get_ui_audio_interface() method:
>>> import omni.kit.audio
>>> a = omni.kit.audio.get_ui_audio_interface()
>>> sound = a.create_sound("${sounds}/test.wav")
>>> a.play_sound(sound)
"""
def create_sound(self, filename: str) -> UiSound:
"""
Loads a UI sound from local disk.
This loads a sound that can be played with play_sound() at a later time. This
sound only needs to be loaded once but can be played as many times as needed.
When no longer needed, the sound will be destroyed when it is cleared out or
is garbage collected.
File names passed in here may contain special path markers. The guaranteed
set of markers are as follows (note that other special paths may also exist
but are not included here):
* "*${executable}*": resolves to the directory containing the main executable
file.
* "*${resources}*": resolves to the 'resources/' folder in the same directory
as the main executable file.
* "*${sounds}*": resolves to the 'resources/sounds/' folder in the same directory
as the main executable.
* "*${icons}*": resolves to the 'resources/icons/' folder in the same directory
as the main executable.
Args:
filename: the path to the sound file to load. This should be an absolute
path, but can be a relative path that will be resolved using the current
working directory for the process. Parts of this path may include some
special path specifiers that will be resolved when trying to open the
file. See above for more info on special paths. This may not be *None*
or an empty string.
Returns:
If successful, this return the sound object representing the new loaded sound.
This sound can be passed to play_sound() later. Each sound object returned
here will be destroyed when it is cleared out or garbage collected. Note that
destroying the sound object will stop all playing instances of it. However, if
more than one reference to the same sound object still exists, destroying one of
the sound objects (ie: assigning it to *None* or letting it get garbage collected)
will not stop any of the instances from playing. It is best practice to always
explicitly stop a sound before destroying it.
If the requested sound file could not be found or loaded, None will be returned.
"""
def get_sound_length(self, sound: UiSound) -> float:
"""
Retrieves length of a sound in seconds (if known).
This calculates the length of a UI sound in seconds. This is just the length
of the sound asset in seconds.
Args:
sound: the sound to retrieve the length for. This may not be *None*.
Returns:
The play length of the sound in seconds if the asset is loaded and the length
can be calculated, or 0.0 otherwise.
"""
def is_sound_playing(self, sound: UiSound) -> bool:
"""
Queries whether a sound object is currently playing.
This queries whether a sound is currently playing. If this fails, that may mean the
sound ended naturally on its own or it was explicitly stopped. Note that this may
continue to return true for a short period after a sound has been stopped with
stop_sound(). This period may be up to 20 milliseconds in extreme cases but will
usually not exceed 10 milliseconds.
Args:
sound: the sound to query the playing state for. This may not be *None*.
Returns:
true if the sound object is currently playing, or false if the sound has either
finished playing or has not been played yet.
"""
def play_sound(self, sound: UiSound) -> None:
"""
Immediately plays the requested UI sound if it is loaded.
This plays a single non-looping instance of a UI sound immediately. The UI sound
must have already been loaded with create_sound(). If the sound resource was missing
or couldn't be loaded, this call will simply be ignored. This will return immediately
after scheduling the sound to play. It will never block for the duration of the sound's
playback. This sound may be prematurely stopped with stop_sound().
Args:
sound: the sound to be played. This may not be *None*.
Returns:
No return value.
"""
def stop_sound(self, sound: UiSound) -> None:
"""
Immediately stops the playback of a sound.
This stops the playback of an active sound. If the sound was not playing or had
already naturally stopped on its own, this call is ignored.
Args:
sound: the sound object to stop playback for. This may not be *None*.
Returns:
No return value.
"""
pass
class UiSound():
"""
An opaque object representing a loaded UI sound. This object is used for the
IUiAudio interface. These objects may be passed to many of the other methods in
the IUiAudio interface to operate on. These objects are acquired from the create_sound()
method. The sound object will be destroyed when it is either cleared out (ie: assigned
*None*) or gets garbage collected.
"""
pass
def acquire_ui_audio_interface(plugin_name: str = None, library_path: str = None) -> IUiAudio:
pass
| 7,848 | unknown | 46.283132 | 103 | 0.66998 |
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/__init__.py | """
This module contains bindings for the omni::kit::uiaudio module.
This provides functionality for playing and managing sound prims in
USD scenes.
Sound files may be in RIFF/WAV, Ogg, or FLAC format.
Data in the sound files may use 8, 16, 24, or 32 bit integer samples,
or 32 bit floating point samples. Channel counts may be from 1 to 64
If more channels of data are provided than the audio device can play,
some channels will be blended together automatically.
"""
from ._uiaudio import *
# Cached UI audio instance pointer
def get_ui_audio_interface() -> IUiAudio:
"""
helper method to retrieve a cached version of the IUiAudio interface.
Returns:
The cached :class:`omni.kit.uiaudio.IUiAudio` interface. This will only be
retrieved on the first call. All subsequent calls will return the cached interface
object.
"""
if not hasattr(get_ui_audio_interface, "ui_audio"):
get_ui_audio_interface.ui_audio = acquire_ui_audio_interface()
return get_ui_audio_interface.ui_audio
| 1,107 | Python | 34.741934 | 91 | 0.684734 |
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/tests/test_audio.py |
import omni.kit.test
import omni.kit.uiaudio
class TestAudio(omni.kit.test.AsyncTestCase): # pragma: no cover
async def test_ui_audio(self):
audio = omni.kit.uiaudio.get_ui_audio_interface()
self.assertIsNotNone(audio)
# try to load a sound to test with.
sound = audio.create_sound("${sounds}/stop.wav")
if sound == None:
# still try to play the null sound.
audio.play_sound(sound)
# verify the sound's length is zero.
length = audio.get_sound_length(sound)
self.assertEqual(length, 0.0)
# make sure querying whether the null sound is playing fails.
playing = audio.is_sound_playing(sound)
self.assertFalse(playing)
else:
# play the sound.
audio.play_sound(sound)
# verify that it is playing.
playing = audio.is_sound_playing(sound)
self.assertTrue(playing)
# verify the sound's length is non-zero.
length = audio.get_sound_length(sound)
self.assertGreater(length, 0.0)
# wait so that a user can hear that sound is playing.
time.sleep(min(length, 5.0))
# clean up the local reference to the sound.
sound = None
| 1,316 | Python | 29.627906 | 73 | 0.582067 |
omniverse-code/kit/exts/omni.uiaudio/omni/kit/uiaudio/tests/__init__.py | from .test_audio import * # pragma: no cover
| 47 | Python | 14.999995 | 45 | 0.680851 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/hd_renderer_plugins.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["HdRendererPlugins"]
from pxr import Tf, Plug
class HdRendererPlugins:
def __init__(self, callback_fn: callable = None):
self.__callback_fn = callback_fn
self.__renderers = {}
self.__listener = Tf.Notice.RegisterGlobally(
"PlugNotice::DidRegisterPlugins", lambda notice, _: self.__add_renderers(notice.GetNewPlugins())
)
self.__add_renderers(Plug.Registry().GetAllPlugins())
def __add_renderers(self, plugins):
added = False
for renderer in [d for d in Tf.Type("HdRendererPlugin").GetAllDerivedTypes() if d not in self.__renderers]:
for plugin in plugins:
declared = plugin.GetMetadataForType(renderer)
if declared:
displayName = declared.get("displayName")
self.__renderers[renderer] = {"plugin": plugin, "displayName": displayName}
added = True
if added:
self.__callback_fn(self)
@property
def renderers(self):
for k, v in self.__renderers.items():
yield k, v
def destroy(self):
if self.__listener:
self.__listener.Revoke()
self.__listener = None
def __del__(self):
self.destroy()
| 1,711 | Python | 34.666666 | 115 | 0.630625 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/style.py | import carb.tokens
from pathlib import Path
ICON_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.render}")).joinpath("data").joinpath("icons").absolute()
ICON_CORE_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.core}")).joinpath("data").joinpath("icons").absolute()
UI_STYLE = {
"Menu.Item.Icon::Renderer": {
"image_url": f"{ICON_PATH}/viewport_renderer.svg"
},
"Menu.Item.Button": {
"background_color": 0,
"margin": 0,
"padding": 0,
},
"Menu.Item.Button.Image::OptionBox": {
"image_url": f"{ICON_CORE_PATH}/settings_submenu.svg"
},
}
| 674 | Python | 32.749998 | 148 | 0.637982 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/extension.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportRenderMenuBarExtension", "get_instance", "SingleRenderMenuItemBase", "SingleRenderMenuItem"]
from .menu_item.single_render_menu_item import SingleRenderMenuItem, SingleRenderMenuItemBase
from .renderer_menu_container import RendererMenuContainer
import omni.ext
from typing import Callable
_extension_instance = None
def get_instance():
global _extension_instance
return _extension_instance
class ViewportRenderMenuBarExtension(omni.ext.IExt):
"""The Entry Point for the Render Settings in Viewport Menu Bar"""
def on_startup(self, ext_id):
self._render_menu = RendererMenuContainer()
global _extension_instance
_extension_instance = self
def register_menu_item_type(self, menu_item_type: Callable[..., "SingleRenderMenuItemBase"]):
"""
Register a custom menu type for the default created renderer
Args:
menu_item_type: callable that will create the menu item
"""
if self._render_menu:
self._render_menu.set_menu_item_type(menu_item_type)
def on_shutdown(self):
if self._render_menu:
self._render_menu.destroy()
self._render_menu = None
global _extension_instance
_extension_instance = None
| 1,713 | Python | 32.607842 | 112 | 0.718039 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/hd_renderer_list.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["HdEngineRendererMenuFactory"]
from .hd_renderer_plugins import HdRendererPlugins
import carb
_log_issue = carb.log_warn
class HdRenderer:
def __init__(self, *args):
self.pluginID, self.displayName, self.usdPlugin = args
def __repr__(self):
return f'HdRenderer("{self.pluginID}", "{self.displayName}")'
class HdEngineRenderer:
def __init__(self, *args):
self.engineName, self.renderModePath = args
self.renderers = []
def __repr__(self):
return f'HdEngineRenderer("{self.engineName}", "{self.renderModePath}", {[r for r in self.renderers]})'
class HdRendererList:
RTX_RENDER_MODE_PATH = "/rtx/rendermode"
IRY_RENDER_MODE_PATH = "/rtx/iray/rendermode"
PXR_RENDER_MODE_PATH = "/pxr/rendermode"
@classmethod
def enabled_engines(cls):
engines = carb.settings.get_settings().get("/renderer/enabled")
if engines:
# Return as an ordered list based on how renderers should display
engines = engines.split(",")
for engine in ("rtx", "iray", "index", "pxr"):
if engine in engines:
engines.remove(engine)
yield engine
else:
engines = ("rtx", "iray", "pxr")
for engine in engines:
yield engine
def __init__(self, update_fn: callable = None, engines=None):
# Use an OrderedDict to preserve incoming or app-default order when added
from collections import OrderedDict
self.__renderers = OrderedDict()
self.__hd_plugins = None
self.__updated_fn = update_fn
if not engines:
engines = self.enabled_engines()
for hdEngine in engines:
if hdEngine == "rtx":
self.__add_renderer(hdEngine, self.RTX_RENDER_MODE_PATH, "RaytracedLighting", "RTX - Real-Time")
self.__add_renderer(hdEngine, self.RTX_RENDER_MODE_PATH, "PathTracing", "RTX - Interactive (Path Tracing)")
if carb.settings.get_settings().get("/rtx-transient/aperture/enabled"):
self.__add_renderer(
hdEngine, self.RTX_RENDER_MODE_PATH, "LightspeedAperture", "RTX - Aperture (Game Path Tracer)"
)
elif hdEngine == "iray":
self.__add_renderer(hdEngine, self.IRY_RENDER_MODE_PATH, "iray", "RTX - Accurate (Iray)")
# No known setting to enable this.
if False:
self.__add_renderer(hdEngine, self.IRY_RENDER_MODE_PATH, "irt", "RTX - Accurate (Iray Interactive)")
elif hdEngine == "index":
self.__add_renderer(hdEngine, None, "index", "RTX - Scientific (IndeX)")
elif hdEngine == "pxr":
self.__hd_plugins = HdRendererPlugins(self.__add_pxr_renderers)
self.__add_pxr_renderers(self.__hd_plugins)
else:
_log_issue(f"Unknown Hydra engine'{hdEngine}'.")
def destroy(self):
if self.__hd_plugins:
self.__hd_plugins.destroy()
self.__hd_plugins = None
self.__renderers = {}
self.__updated_fn = None
def __del__(self):
self.destroy()
def __add_pxr_renderers(self, plugins):
for renderer, desc in plugins.renderers:
pluginID = renderer.typeName
displayName = desc.get("displayName")
# Special case Storm's displayName which is still 'GL'
if pluginID == "HdStormRendererPlugin":
displayName = "Pixar Storm"
self.__add_renderer("pxr", self.PXR_RENDER_MODE_PATH, pluginID, displayName, desc.get("plugin"))
def __add_renderer(self, engineName: str, renderModePath: str, pluginID: str, displayName=None, usdPlugin=None):
if not displayName:
displayName = pluginID
engineRenderers = self.__renderers.get(engineName)
if not engineRenderers:
engineRenderers = HdEngineRenderer(engineName, renderModePath)
self.__renderers[engineName] = engineRenderers
elif any([True for r in engineRenderers.renderers if r.pluginID == pluginID]):
return
engineRenderers.renderers.append(HdRenderer(pluginID, displayName, usdPlugin))
if self.__updated_fn:
self.__updated_fn(self)
@property
def renderers(self):
for k, v in self.__renderers.items():
yield k, v
| 4,912 | Python | 38.943089 | 123 | 0.608917 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/renderer_menu_container.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["RendererMenuContainer"]
from .menu_item.single_render_menu_item import SingleRenderMenuItem
from .hd_renderer_list import HdRendererList
from .style import UI_STYLE
from omni.kit.viewport.menubar.core import (
IconMenuDelegate,
ViewportMenuDelegate,
SettingComboBoxModel,
ViewportMenuContainer,
RadioMenuCollection,
SelectableMenuItem,
MenuDisplayStatus,
)
from omni.kit.app import SettingChangeSubscription
import omni.ui as ui
import omni.usd
import carb
import os
import sys
import asyncio
from functools import partial
from typing import Callable, Dict, List, Sequence, TYPE_CHECKING
if TYPE_CHECKING:
from .menu_item.single_render_menu_item import SingleRenderMenuItemBase
SHADING_MODE = "/exts/omni.kit.viewport.menubar.render/shadingMode"
LIGHTING_MODE = "/exts/omni.kit.viewport.menubar.render/lightingMode"
MATERIAL_MODE = "/exts/omni.kit.viewport.menubar.render/materialMode"
class BoolStringModel(ui.SimpleBoolModel):
def __init__(self, setting_path: str, value_map: Sequence[str] = ("default", "disabled"), *args, **kwargs):
super().__init__(*args, **kwargs)
self.__setting_path = setting_path
self.__value_map = value_map
self.__settings = carb.settings.get_settings()
self.__setting_sub = SettingChangeSubscription(setting_path, self.__setting_changed)
self.__in_set = False
def __del__(self):
self.destroy()
def destroy(self):
self.__setting_sub = None
def __setting_changed(self, item: carb.dictionary._dictionary.Item, event_type: carb.settings.ChangeEventType):
if event_type == carb.settings.ChangeEventType.CHANGED:
self._value_changed()
def get_value_as_string(self) -> bool:
return self.__settings.get(self.__setting_path)
def get_value_as_bool(self) -> bool:
return self.__settings.get(self.__setting_path) == self.__value_map[1]
def get_value(self) -> bool:
return self.get_value_as_bool()
def set_value(self, value: bool) -> bool:
cur_value = self.__settings.get(self.__setting_path)
str_value = self.__value_map[bool(value)]
changed = cur_value != str_value
if changed:
self.__settings.set(self.__setting_path, str_value)
return True
return changed
class FlashLightModel(BoolStringModel):
def set_value(self, value: bool) -> bool:
changed = super().set_value(value)
if changed:
settings = carb.settings.get_settings()
settings.set("/rtx/useViewLightingMode", value)
# settings.set("/rtx/shadows/enabled", not value)
return changed
class DisableMaterialModel(BoolStringModel):
def set_value(self, value: bool) -> bool:
changed = super().set_value(value)
if changed:
dbg_type = 0 if value else -1
settings = carb.settings.get_settings()
settings.set("/rtx/debugMaterialType", dbg_type)
wire_mode = settings.get("/rtx/wireframe/mode")
if wire_mode:
wire_mode = 2 if dbg_type == 0 else 1
settings.set("/rtx/wireframe/mode", wire_mode)
return changed
class ShadingModeModel(BoolStringModel):
def set_value(self, value: bool) -> bool:
changed = super().set_value(value)
if changed:
wire_mode = 0
settings = carb.settings.get_settings()
if value:
settings.set("/rtx/debugView/target", "")
if self.get_value_as_string() == "wireframe":
flat_shade = settings.get("/rtx/debugMaterialType") == 0
wire_mode = 2 if flat_shade else 1
settings.set("/rtx/wireframe/mode", wire_mode)
return changed
class DebugShadingModel(SettingComboBoxModel):
def __init__(self, viewport_api):
debug_view_items = {}
hd_engine = viewport_api.hydra_engine
if hd_engine == "rtx":
debug_view_items.update({
"Off": "",
"3D Motion Vectors [WARNING: Flashing Colors]": "targetMotion",
"Barycentrics": "barycentrics",
"Beauty After Tonemap": "beautyPostTonemap",
"Beauty Before Tonemap": "beautyPreTonemap",
"Depth": "depth",
"Instance ID": "instanceId",
"Interpolated Normal": "normal",
"Heat Map: Any Hit": "anyHitCountHeatMap",
"Heat Map: Intersection": "intersectionCountHeatMap",
"Heat Map: Timing": "timingHeatMap",
"SDG: Cross Correspondence": "sdgCrossCorrespondence",
"SDG: Motion": "sdgMotion",
"Semantic ID": "semanticId",
"Tangent U": "tangentu",
"Tangent V": "tangentv",
"Texture Coordinates 0": "texcoord0",
"Texture Coordinates 1": "texcoord1",
"Triangle Normal": "triangleNormal",
"Triangle Normal (OctEnc)": "triangleNormalOctEnc", # ReLAX Only
"Wireframe": "wire",
})
render_mode = viewport_api.render_mode
if render_mode == "RaytracedLighting":
debug_view_items.update({
"RT Ambient Occlusion": "ao",
"RT Caustics": "caustics",
"RT Denoised Dome Light": "denoisedDomeLightingTex",
"RT Denoised Sampled Lighting": "rtDenoisedSampledLighting",
"RT Denoised Sampled Lighting Diffuse": "rtDenoiseSampledLightingDiffuse", # ReLAX Only
"RT Denoised Sampled Lighting Specular": "rtDenoiseSampledLightingSpecular", # ReLAX Only
"RT Developer Debug Texture": "developerDebug",
"RT Diffuse GI": "indirectDiffuse",
"RT Diffuse GI (Not Accumulated)": "indirectDiffuseNonAccum",
"RT Diffuse Reflectance": "diffuseReflectance",
"RT Material Normal": "materialGeometryNormal",
"RT Material Normal (OctEnc)": "materialGeometryNormalOctEnc", # ReLAX Only
"RT Matte Object Compositing Alpha": "matteObjectAlpha",
"RT Matte Object Mask": "matteObjectMask",
"RT Matte Object View Before Postprocessing": "matteBeforePostprocessing",
"RT Noisy Dome Light": "noisyDomeLightingTex",
"RT Noisy Sampled Lighting": "rtNoisySampledLighting",
"RT Noisy Sampled Lighting (Not Accumulated)": "rtNoisySampledLightingNonAccum",
"RT Noisy Sampled Lighting Diffuse": "rtNoisySampledLightingDiffuse", # ReLAX Only
"RT Noisy Sampled Lighting Diffuse (Not Accumulated)": "sampledLightingDiffuseNonAccum",
"RT Noisy Sampled Lighting Specular": "rtNoisySampledLightingSpecular", # ReLAX Only
"RT Noisy Sampled Lighting Specular (Not Accumulated)": "sampledLightingSpecularNonAccum",
"RT Radiance": "radiance",
"RT Reflections": "reflections",
"RT Reflections (Not Accumulated)": "reflectionsNonAccum",
"RT Reflections 3D Motion Vectors [WARNING: Flashing Colors]": "reflectionsMotion",
"RT Roughness": "roughness",
"RT Shadow (last light)": "shadow",
"RT Specular Reflectance": "reflectance",
"RT Translucency": "translucency",
"RT World Position": "worldPosition",
})
elif render_mode == "PathTracing":
debug_view_items.update({
"PT Adaptive Sampling Error [WARNING: Flashing Colors]": "PTAdaptiveSamplingError",
"PT Denoised Result": "pathTracerDenoised",
"PT Noisy Result": "pathTracerNoisy",
"PT AOV Background": "PTAOVBackground",
"PT AOV Diffuse Filter": "PTAOVDiffuseFilter",
"PT AOV Direct Illumation": "PTAOVDI",
"PT AOV Global Illumination": "PTAOVGI",
"PT AOV Reflections": "PTAOVReflections",
"PT AOV Reflection Filter": "PTAOVReflectionFilter",
"PT AOV Refractions": "PTAOVRefractions",
"PT AOV Refraction Filter": "PTAOVRefractionFilter",
"PT AOV Self-Illumination": "PTAOVSelfIllum",
"PT AOV Volumes": "PTAOVVolumes",
"PT AOV World Normal": "PTAOVWorldNormals",
"PT AOV World Position": "PTAOVWorldPos",
"PT AOV Z-Depth": "PTAOVZDepth",
"PT AOV Multimatte0": "PTAOVMultimatte0",
"PT AOV Multimatte1": "PTAOVMultimatte1",
"PT AOV Multimatte2": "PTAOVMultimatte2",
"PT AOV Multimatte3": "PTAOVMultimatte3",
"PT AOV Multimatte4": "PTAOVMultimatte4",
"PT AOV Multimatte5": "PTAOVMultimatte5",
"PT AOV Multimatte6": "PTAOVMultimatte6",
"PT AOV Multimatte7": "PTAOVMultimatte7",
})
# Sort the above alphabetically
names, values = [], []
if debug_view_items:
for k, v in (debug_view_items.items()):
names.append(k)
values.append(v)
else:
names = []
values = []
super().__init__("/rtx/debugView/target", names, values=values)
def _on_change(self, *args, **kwargs) -> None:
super()._on_change(*args, **kwargs)
current_value = self._settings.get(self._path)
if current_value == '':
if self._settings.get(SHADING_MODE).startswith("custom:"):
self._settings.set(SHADING_MODE, "default")
else:
self._settings.set(SHADING_MODE, f"custom:{current_value}")
self._settings.set("/rtx/wireframe/mode", 0)
def empty(self):
children = self.get_item_children(None)
return len(children) == 0 if children else True
def __del__(self):
self.destroy()
def destroy(self):
super().destroy()
class MenuContext():
def __init__(self, root_menu: ui.Menu, viewport_api, renderer_changed_fn: Callable):
super().__init__()
self.__root_menu = root_menu
self.__viewport_api = viewport_api
self.__destroyable = {}
self.__usd_context_sub = viewport_api.usd_context.get_stage_event_stream().create_subscription_to_pop(
self.__on_usd_context_event, name=f"omni.kit.viewport.menubar.render.menu_context.{id(self)}"
)
self.__renderer_changed_fn = renderer_changed_fn
self.__rs_changed_sub = viewport_api.subscribe_to_render_settings_change(self.__render_settings_changed)
def __on_usd_context_event(self, event: omni.usd.StageEventType):
if event.type == int(omni.usd.StageEventType.SETTINGS_LOADED):
self.set_default_state()
def __render_settings_changed(self, *args, **kwargs):
self.__renderer_changed_fn(self, self.__viewport_api)
def set_default_state(self):
stage = self.__viewport_api.stage
if stage:
render_settings = stage.GetMetadata('customLayerData').get('renderSettings', {})
dbg_mat_type = render_settings.get('rtx:debugMaterialType')
view_lighting = render_settings.get('rtx:useViewLightingMode')
wire_mode = render_settings.get('rtx:wireframe:mode')
dbg_target = render_settings.get('rtx:debugView:target')
settings = carb.settings.get_settings()
settings.set(MATERIAL_MODE, "disabled" if dbg_mat_type == 0 else "default")
settings.set(LIGHTING_MODE, "disabled" if view_lighting else "default")
if wire_mode:
shade_mode = "wireframe"
elif dbg_target:
shade_mode = f"custom:{dbg_target}"
else:
shade_mode = "default"
settings.set(SHADING_MODE, shade_mode)
@property
def root_menu(self) -> ui.Menu:
return self.__root_menu
@property
def delegate(self) -> ui.MenuDelegate:
return self.root_menu.delegate
@property
def viewport_api(self):
return self.__viewport_api
def add_destroyables(self, key: str, destroyables: Sequence):
self.destroy(key)
self.__destroyable[key] = destroyables
def destroy(self, key: str = None):
if key is not None:
items = self.__destroyable.get(key)
if items:
for item in items:
item.destroy()
del self.__destroyable[key]
return
if self.__usd_context_sub:
self.__usd_context_sub = None
if self.__rs_changed_sub:
self.__rs_changed_sub = None
if self.__destroyable:
for items in self.__destroyable.values():
for item in items:
item.destroy()
self.__destroyable = {}
if self.__root_menu:
self.__root_menu.destroy()
self.__root_menu = None
class RendererMenuContainer(ViewportMenuContainer):
"""The menu with the list of renderers"""
PXR_IN_USE = "/app/viewport/omni_hydra_pxr_in_use"
__enabled_engines = None
def __init__(self):
super().__init__(
name="Renderer",
delegate=None,
visible_setting_path="/exts/omni.kit.viewport.menubar.render/visible",
order_setting_path="/exts/omni.kit.viewport.menubar.render/order",
style=UI_STYLE
)
self.__render_list = None
self.__render_state_subs = None
self._folder_exist_popup = None
self.__menu_item_type = SingleRenderMenuItem
self.__pending_render_change = False
self.__menu_context: Dict[int, MenuContext] = {}
# FIXME: Grab this now (on startup) as OmniHydraEngineFactoryBase can mutate it on first activation
if not RendererMenuContainer.__enabled_engines:
RendererMenuContainer.__enabled_engines = HdRendererList.enabled_engines()
# We can possibly drop these subscriptions when Viewport-1 is retired; but for now we have to watch for some
# common events if both VP-1 and VP-2 are sharing a hydra engine instance.
settings = carb.settings.get_settings()
self.__render_state_subs = (
settings.subscribe_to_node_change_events(self.PXR_IN_USE, self.__dirty_menu),
settings.subscribe_to_node_change_events("/pxr/renderers", self.__dirty_menu),
settings.subscribe_to_node_change_events(HdRendererList.PXR_RENDER_MODE_PATH, self.__dirty_menu),
settings.subscribe_to_node_change_events(HdRendererList.RTX_RENDER_MODE_PATH, self.__dirty_menu),
settings.subscribe_to_node_change_events(HdRendererList.IRY_RENDER_MODE_PATH, self.__dirty_menu),
settings.subscribe_to_node_change_events("/renderer/enabled", self.__dirty_renderers),
)
# Watch for extension enable/disable to support backgorund renderer loading
self.__setup_extenion_watching()
def __setup_extenion_watching(self):
import omni.kit.app
app = omni.kit.app.get_app()
if not app:
return
def setup_ext_hooks(*args, **kwargs):
import omni.ext
ext_manager = omni.kit.app.get_app().get_extension_manager()
if ext_manager:
self.__ext_manager_hooks = ext_manager.subscribe_to_extension_enable(
self.__ext_enabled, self.__ext_disabled,
# ext_name="omni.hydra.*",
hook_name="omni.kit.viewport.menubar.render.extension_change",
)
if not app.is_app_ready():
self.__app_ready_sub = app.get_startup_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, setup_ext_hooks, name="omni.kit.viewport.menubar.render.app_ready"
)
else:
setup_ext_hooks()
def set_menu_item_type(self, menu_item_type: Callable[..., "SingleRenderMenuItemBase"]):
"""
Set the menu type for the default created renderer
Args:
menu_item_type: callable that will create the menu item
"""
if menu_item_type is None:
menu_item_type = SingleRenderMenuItem
if self.__menu_item_type != menu_item_type:
self.__menu_item_type = menu_item_type
self.__dirty_menu()
def __hide_on_click(self, viewport_context: Dict = None):
return viewport_context.get("hide_on_click", False) if viewport_context else False
def destroy(self):
self.__app_ready_sub = None
self.__ext_manager_hooks = None
if self.__render_list:
self.__render_list.destroy()
self.__render_list = None
if self.__render_state_subs:
settings = carb.settings.get_settings()
for sub in self.__render_state_subs:
settings.unsubscribe_to_change_events(sub)
self.__render_state_subs = None
for context in self.__menu_context.values():
context.destroy()
self.__menu_context = {}
super().destroy()
@property
def render_list(self):
"""Returns the list of available renderers"""
if not self.__render_list:
def set_dirty(*args):
self.__dirty_menu()
self.__render_list = HdRendererList(set_dirty, self.__enabled_engines)
return self.__render_list
def build_fn(self, viewport_context: Dict):
"""Entry point for the menu bar"""
viewport_api = viewport_context.get('viewport_api')
viewport_api_id = viewport_api.id
menu_context = self.__menu_context.get(viewport_api_id)
if menu_context:
menu_context.destroy()
root_menu = ui.Menu(self.name,
delegate=IconMenuDelegate("Renderer", text=True),
on_build_fn=partial(self._build_menu, viewport_context),
style=self._style,
hide_on_click=self.__hide_on_click(viewport_context)
)
self.__menu_context[viewport_api_id] = MenuContext(root_menu, viewport_api, self.__set_menu_label)
# It will set the renderer name
self.__dirty_menu()
def get_display_status(self, factory_args: dict) -> MenuDisplayStatus:
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
if context.delegate.text_visible:
return MenuDisplayStatus.LABEL
else:
return MenuDisplayStatus.MIN
def get_require_size(self, factory_args: dict, expand: bool = False) -> float:
display_status = self.get_display_status(factory_args)
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
if expand:
if display_status == MenuDisplayStatus.LABEL:
return 0
else:
return context.delegate.text_size
else:
return 0
def expand(self, factory_args: dict) -> None:
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
if context.delegate.text_visible:
return
else:
context.delegate.text_visible = True
if context.root_menu:
context.root_menu.invalidate()
def can_contract(self, factory_args: dict) -> bool:
display_status = self.get_display_status(factory_args)
return display_status == MenuDisplayStatus.LABEL
def contract(self, factory_args: dict) -> bool:
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
display_status = self.get_display_status(factory_args)
if display_status == MenuDisplayStatus.LABEL:
context.delegate.text_visible = False
if context.root_menu:
context.root_menu.invalidate()
return True
return False
def __add_destroyables(self, viewport_api, key: str, destroyables: Sequence):
menu_context = self.__menu_context.get(viewport_api.id)
assert menu_context, f"No MenuContext for {viewport_api} (id: {viewport_api.id})"
menu_context.add_destroyables(key, destroyables)
def __build_renderers(self, viewport_context):
"""Build the menu with the list of the renderers"""
viewport_api = viewport_context["viewport_api"]
viewport_api_id = viewport_api.id
hide_on_click = self.__hide_on_click(viewport_context)
settings = carb.settings.get_settings()
# See if the omni.hydra.pxr engine is available for use in this Viewport
pxr_eng_available = self.__pxr_available(settings, viewport_api)
# Example: HdStormRendererPlugin:Storm
pxr_rnd_available = settings.get("/pxr/renderers")
# Example: rtx
current_engine_name = viewport_api.hydra_engine
for engine_name, hd_engine_renderer in self.render_list.renderers:
is_pxr = engine_name == "pxr"
is_engine_current = engine_name == current_engine_name
# Only sort renderers of the engine alphabetically for pxr renderers
if is_pxr:
renderers = sorted(
hd_engine_renderer.renderers, key=lambda hd_renderer: hd_renderer.displayName.lower()
)
else:
renderers = hd_engine_renderer.renderers
# Example: /rtx/rendermode
render_mode_path = hd_engine_renderer.renderModePath
# Get current from settings
if is_engine_current:
# Example: RaytracedLighting
current_render_mode = settings.get(render_mode_path) if render_mode_path else None
else:
current_render_mode = None
for hd_renderer in renderers:
# Example: RaytracedLighting
render_mode = hd_renderer.pluginID
enabled = True
if is_pxr:
# Check the renderer hasn't actually de-registered itself
# And only enable these menu items if omni.hydra.pxr engine is available for this Viewport instance
if not pxr_eng_available or (pxr_rnd_available and pxr_rnd_available.find(render_mode) == -1):
enabled = False
checked = is_engine_current and (render_mode == current_render_mode if render_mode_path else True)
def apply(viewport_api, engine_name, render_mode_path, render_mode):
"""Switch the current renderer"""
if True:
settings = carb.settings.get_settings()
# Set the legacy /renderer/active change for anyone that may be watching for it
settings.set('/renderer/active', engine_name)
# Now set the render-mode on that engine too
if render_mode_path:
settings.set(render_mode_path, render_mode)
# Finally apply it to the backing texture
viewport_api.set_hd_engine(engine_name, render_mode)
self.__menu_item_type(
hd_renderer.displayName,
engine_name,
hd_engine_renderer,
hd_renderer,
viewport_api,
enabled=enabled,
checked=checked,
hide_on_click=hide_on_click,
triggered_fn=partial(apply, viewport_api, engine_name, render_mode_path, render_mode),
)
def __build_shading_modes(self, viewport_context):
"""Build the shading modes"""
hide_on_click = self.__hide_on_click(viewport_context)
viewport_api = viewport_context.get("viewport_api")
engine_name = viewport_api.hydra_engine
is_rtx_or_pxr = engine_name == "rtx" or engine_name == "pxr"
default_shade_mode = SelectableMenuItem(
"Default",
model=ShadingModeModel(SHADING_MODE, ("wireframe", "default")),
delegate=ViewportMenuDelegate(force_checked=True),
hide_on_click=hide_on_click,
toggle=False,
enabled=is_rtx_or_pxr,
)
wireframe_mode = SelectableMenuItem(
"Wireframe",
model=ShadingModeModel(SHADING_MODE, ("default", "wireframe")),
delegate=ViewportMenuDelegate(force_checked=True),
hide_on_click=hide_on_click,
toggle=False,
enabled=is_rtx_or_pxr,
)
debug_mode = RadioMenuCollection(
"Debug View",
DebugShadingModel(viewport_api),
hide_on_click=hide_on_click,
)
debug_mode.enabled = not debug_mode._model.empty()
self.__add_destroyables(viewport_api, 'omni.kit.viewport.menubar.render.shading_modes', [default_shade_mode, wireframe_mode, debug_mode])
if not debug_mode.enabled:
carb.settings.get_settings().set("/rtx/debugView/target", "")
async def toggle_states():
import omni.kit.app
await omni.kit.app.get_app().next_update_async()
if default_shade_mode.model:
default_shade_mode.delegate.checked = default_shade_mode.model.as_bool
if wireframe_mode.model:
wireframe_mode.delegate.checked = wireframe_mode.model.as_bool
import asyncio
asyncio.ensure_future(toggle_states())
def __build_preset_modes(self, viewport_context):
"""Build the first level menu"""
hide_on_click = self.__hide_on_click(viewport_context)
ui.MenuItem("Load from Preset", triggered_fn=None, hide_on_click=hide_on_click)
def __build_render_options(self, viewport_context):
# Get the useViewLightingMode and turn on/off shadows based on it
viewport_api = viewport_context["viewport_api"]
engine_name = viewport_api.hydra_engine
is_iray = engine_name == "iray"
is_rtx_or_pxr = engine_name == "rtx" or engine_name == "pxr"
flash_light = SelectableMenuItem("Camera Light",
model=FlashLightModel(LIGHTING_MODE),
enabled=is_rtx_or_pxr)
disable_mat = SelectableMenuItem("Disable Materials (White Mode)",
model=DisableMaterialModel(MATERIAL_MODE),
enabled=is_rtx_or_pxr or is_iray)
self.__add_destroyables(viewport_api, 'omni.kit.viewport.menubar.render.render_options', [flash_light, disable_mat])
def __build_rendering_settings(self, viewport_context):
"""Build the rendering settings presets"""
# loading settings with menu open results in weird refresh problems, so disabled
hide_on_click = True
# get presets
preset_dict = carb.settings.get_settings().get_settings_dictionary("exts/omni.kit.viewport.menubar.render/presets").get_dict()
# remove any unused presets
for preset in preset_dict.copy():
if not preset_dict[preset]:
del preset_dict[preset]
if preset_dict:
def get_title(name):
return name.replace("_", " ").title()
ui.Separator(text="Rendering Settings")
with ui.Menu("Load from Preset", hide_on_click=hide_on_click):
for preset in preset_dict:
ui.MenuItem(f"{get_title(preset)}", triggered_fn=lambda p=preset_dict[preset]: asyncio.ensure_future(self.__load_setting_file(carb.tokens.get_tokens_interface().resolve(p))), hide_on_click=hide_on_click)
ui.Separator()
ui.MenuItem("Load Preset From File", triggered_fn=lambda v=viewport_context: self.__load_settings(v), hide_on_click=hide_on_click)
ui.MenuItem("Save Current as Preset", triggered_fn=lambda v=viewport_context: self.__save_settings(v), hide_on_click=hide_on_click)
ui.MenuItem("Reset to Defaults", triggered_fn=self.__reset_settings, hide_on_click=hide_on_click)
def __reset_settings(self):
omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx")
def __save_settings(self, viewport_context):
try:
from omni.kit.window.file_exporter import get_file_exporter
def show_file_exist_popup(usd_path, save_file):
try:
from omni.kit.widget.prompt import Prompt
def on_confirm(usd_path):
on_cancel()
save_file(usd_path)
def on_cancel():
self._folder_exist_popup.hide()
self._folder_exist_popup = None
if not self._folder_exist_popup:
self._folder_exist_popup = Prompt(
title="Overwrite",
text="The file already exists, are you sure you want to overwrite it?",
ok_button_text="Overwrite",
cancel_button_text="Cancel",
ok_button_fn=lambda: on_confirm(usd_path),
cancel_button_fn=on_cancel,
)
self._folder_exist_popup.show()
except ModuleNotFoundError:
carb.log_error("omni.kit.widget.prompt not enabled!")
except Exception as exc:
carb.log_error(f"__save_settings.show_file_exist_popup errror {exc}")
def save_handler(filename: str, dirname: str, extension: str = "", selections: List[str] = []):
try:
from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser
def save_file(usd_path):
serialiser = USDSettingsSerialiser()
serialiser.save_to_usd(usd_path)
final_path = f"{dirname}/{filename}{extension}"
if os.path.exists(final_path):
show_file_exist_popup(final_path, save_file)
else:
save_file(final_path)
except ModuleNotFoundError:
carb.log_error("omni.rtx.window.settings not enabled!")
except Exception as exc:
carb.log_error(f"__save_settings.save_handler errror {exc}")
file_exporter = get_file_exporter()
if file_exporter:
file_exporter.show_window(
title="Save Settings File",
export_button_label="Save",
export_handler=save_handler,
filename_url=carb.tokens.get_tokens_interface().resolve("${cache}/"),
file_postfix_options=["settings"])
except ModuleNotFoundError:
carb.log_error("omni.kit.window.file_exporter not enabled!")
except Exception as exc:
carb.log_error(f"__save_settings errror {exc}")
def __load_settings(self, viewport_context):
try:
from omni.kit.window.file_importer import get_file_importer
def load_handler(filename: str, dirname: str, selections: List[str]):
from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser
final_path = f"{dirname}/{filename}"
try:
serialiser = USDSettingsSerialiser()
serialiser.load_from_usd(final_path)
except ModuleNotFoundError:
carb.log_error("omni.rtx.window.settings not enabled!")
except Exception as exc:
carb.log_error(f"__save_settings.save_handler errror {exc}")
file_importer = get_file_importer()
if file_importer:
file_importer.show_window(
title="Load Settings File",
import_button_label="Load",
import_handler=load_handler,
filename_url=carb.tokens.get_tokens_interface().resolve("${cache}/"),
file_postfix_options=["settings"])
except ModuleNotFoundError:
carb.log_error("omni.kit.window.file_importer not enabled!")
except Exception as exc:
carb.log_error(f"__load_settings errror {exc}")
async def __load_setting_file(self, preset_name):
await omni.kit.app.get_app().next_update_async()
try:
from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser
serialiser = USDSettingsSerialiser()
serialiser.load_from_usd(preset_name)
except ModuleNotFoundError:
carb.log_error("omni.rtx.window.settings not enabled!")
except Exception as exc:
carb.log_error(f"__load_setting_file errror {exc}")
def _build_menu(self, viewport_context):
"""Build the first level menu"""
hide_on_click = self.__hide_on_click(viewport_context)
viewport_api = viewport_context.get("viewport_api")
if not viewport_api:
return
menu_context = self.__menu_context.get(viewport_api.id)
self.__menu_context[viewport_api.id].root_menu.clear()
ui.MenuItemCollection(on_build_fn=lambda *args: self.__build_renderers(viewport_context))
# Rendering Settings
self.__build_rendering_settings(viewport_context)
# Rendering Mode
ui.Separator(text="Rendering Mode")
ui.Menu(checkable=True, on_build_fn=lambda *args: self.__build_shading_modes(viewport_context))
ui.Separator()
ui.Menu(checkable=True, on_build_fn=lambda *args: self.__build_render_options(viewport_context))
ui.Separator()
# This opens a new Window or goes to an existing preference-pane, so close the Menu
ui.MenuItem("Preferences", triggered_fn=self.__show_render_preferences, hide_on_click=hide_on_click)
# The rest of the menu on the case someone wants to put custom stuff
children = self._children
if children:
ui.Separator()
for child in children:
child.build_fn(viewport_context)
if not menu_context:
return
self.__set_menu_label(menu_context, viewport_api)
def __dirty_menu(self, *args, **kwargs):
"""Rebuild everything"""
for context in self.__menu_context.values():
if context.root_menu:
context.root_menu.invalidate()
self.dirty = True
def __dirty_renderers(self, *args, **kwargs):
# On 105.0, changes to /renderer/enabled can/will be recursive
if self.__pending_render_change:
return
self.__pending_render_change = True
async def update_render_list():
self.__pending_render_change = False
RendererMenuContainer.__enabled_engines = HdRendererList.enabled_engines()
self.__render_list = None
self.__dirty_menu()
from omni.kit.async_engine import run_coroutine
run_coroutine(update_render_list())
def __ext_changed(self, ext_name: str, enabled: bool):
if not ext_name.startswith("omni.hydra"):
return
settings = carb.settings.get_settings()
managed_hd_exts = settings.get("/exts/omni.kit.viewport.menubar.render/autoManageEnabledList")
if not managed_hd_exts:
return
managed_hd_exts = [ext.lstrip().rstrip() for ext in managed_hd_exts.split(",")]
engine_split = ext_name.split(".")
if len(engine_split) >= 3:
engine_split = engine_split[2].split("-")[0]
# Test is this extension is "managed"
if engine_split in managed_hd_exts:
rnd_enabled = settings.get("/renderer/enabled") or ""
rnd_loc = rnd_enabled.find(engine_split)
if enabled:
if rnd_loc == -1:
settings.set("/renderer/enabled", ",".join([rnd_enabled, engine_split]))
elif rnd_loc != -1:
rnd_enabled = rnd_enabled.split(",")
rnd_enabled.remove(engine_split)
settings.set("/renderer/enabled", ",".join(rnd_enabled))
self.__dirty_renderers()
def __ext_enabled(self, ext_name: str, *args, **kwargs):
self.__ext_changed(ext_name, True)
def __ext_disabled(self, ext_name: str, *args, **kwargs):
self.__ext_changed(ext_name, False)
def __pxr_available(self, settings, viewport_api):
# See if the omni.hydra.pxr engine is available for use in this Viewport
try:
usd_context_key = f"'{viewport_api.usd_context_name}':"
setting_path = viewport_api._settings_path
pxr_eng_in_use = settings.get(self.PXR_IN_USE)
if not pxr_eng_in_use:
return True
# Iterate the list of UsdContext.name => ViewportKey
usd_context_key_len = len(usd_context_key)
for in_use in pxr_eng_in_use:
# Is a omni.hydra.pxr engine instance running for this UsdContext?
if in_use.startswith(usd_context_key):
# Yes, so the menu must can only be in the Viewport that claims the context
if in_use.find(setting_path) == usd_context_key_len:
return True
# Otherwise this Viewport cannot use omni.hydra.pxr
return False
# omni.hydra.pxr is not in use for this UsdContext, so it is available
return True
except Exception:
pass
return False
def __get_current_name(self, viewport_api):
"""Returns display name of the current renderer"""
engine_name = viewport_api.hydra_engine
engine_name, hd_engine_renderer = next(
(i for i in self.render_list.renderers if i[0] == engine_name), (None, None)
)
if not hd_engine_renderer or not hd_engine_renderer.renderers:
return self.name
# Example: /rtx/rendermode
render_mode_path = hd_engine_renderer.renderModePath
if not render_mode_path:
return hd_engine_renderer.renderers[0].displayName
# Example: RaytracedLighting
current_render_mode = carb.settings.get_settings().get(render_mode_path)
return next((i.displayName for i in hd_engine_renderer.renderers if i.pluginID == current_render_mode), None)
def __set_menu_label(self, menu_context: MenuContext, viewport_api):
if menu_context is None:
menu_context = self.__menu_context.get(viewport_api.id)
if menu_context is None:
carb.log_error("No MenuContext for this menubar-item")
return
current_renderer_name = self.__get_current_name(viewport_api)
menu_context.root_menu.text = {
"RTX - Interactive (Path Tracing)": "RTX - Interactive",
"RTX - Accurate (Iray)": "RTX - Accurate",
"RTX - Scientific (IndeX)": "RTX - Scientific",
}.get(current_renderer_name, str(current_renderer_name)) if current_renderer_name else self.name
def __show_render_preferences(self, *args, **kwargs) -> None:
try:
import omni.kit.window.preferences as preferences
async def focus_async():
pref_window = ui.Workspace.get_window("Preferences")
if pref_window:
pref_window.focus()
PAGE_TITLE = "Rendering"
inst = preferences.get_instance()
if not inst:
carb.log_error("Preferences extension is not loaded yet")
return
pages = preferences.get_page_list()
for page in pages:
if page.get_title() == PAGE_TITLE:
inst.select_page(page)
# Show the Window
inst.show_preferences_window()
# Force the tab to be the active/focused tab (this currently needs to be done in async)
asyncio.ensure_future(focus_async())
return page
else:
carb.log_error("Render Preferences page not found!")
except ImportError:
carb.log_error("omni.kit.window.preferences not enabled!")
| 41,744 | Python | 41.771516 | 223 | 0.581952 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/menu_item/single_render_menu_item.py | import abc
from typing import Callable
import omni.ui as ui
from omni.kit.viewport.menubar.core import ViewportMenuDelegate
class SingleRenderMenuItemBase(ui.MenuItem):
"""
A single menu item represent a single camera in the camera list
"""
def __init__(
self,
display_name: str,
engine_name,
hd_engine_renderer,
hd_renderer,
viewport_api,
enabled: bool,
checked: bool,
hide_on_click: bool,
triggered_fn: Callable,
):
self.__viewport_api = viewport_api
self.__engine_name = engine_name
self.__hd_engine_renderer = hd_engine_renderer
self.__hd_renderer = hd_renderer
self.__options_button = None
super().__init__(
display_name,
enabled=enabled,
checkable=True,
checked=checked,
delegate=ViewportMenuDelegate(
force_checked=False,
build_custom_widgets=lambda delegate, item: self._build_menuitem_widgets(),
),
hide_on_click=hide_on_click,
triggered_fn=triggered_fn
)
def destroy(self):
self.__options_button = None
super().destroy()
@property
def hd_renderer(self):
return self.__hd_renderer
@property
def hd_engine_renderer(self):
return self.__hd_engine_renderer
@property
def engine_name(self):
return self.__engine_name
@property
def viewport_api(self):
return self.__viewport_api
def _build_menuitem_widgets(self):
ui.Spacer(width=10)
with ui.VStack(content_clipping=1, width=0):
# Button to show renderer settings
self.__options_button = ui.Button(
style_type_name_override="Menu.Item.Button",
name="OptionBox",
width=16,
height=16,
image_width=16,
image_height=16,
visible=self.checked,
clicked_fn=self._option_clicked,
)
@abc.abstractmethod
def _option_clicked(self):
"""Function to implement when the option is clicked. Used by RTX Remix"""
pass
def set_checked(self, checked: bool) -> None:
self.checked = checked
self.delegate.checked = checked
# Only show options button when it is current camera
self.__options_button.visible = checked
class SingleRenderMenuItem(SingleRenderMenuItemBase):
"""
A single menu item represent a single camera in the camera list
"""
def _option_clicked(self):
try:
from omni.rtx.window.settings import RendererSettingsFactory
rs_instance = RendererSettingsFactory.render_settings_extension_instance
if rs_instance:
rs_instance.show_render_settings(self.engine_name, self.hd_renderer.pluginID, True)
except ImportError:
pass
| 2,988 | Python | 27.740384 | 99 | 0.587349 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/tests/test_api.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestAPI']
import omni.kit.test
import functools
from omni.kit.test import AsyncTestCase
from unittest.mock import patch, call
from omni.kit.viewport.menubar.render import get_instance as _get_menubar_extension
from omni.kit.viewport.menubar.render import SingleRenderMenuItem as _SingleRenderMenuItem
from omni.kit.viewport.menubar.render import SingleRenderMenuItemBase as _SingleRenderMenuItemBase
from omni.kit.viewport.menubar.render.renderer_menu_container import RendererMenuContainer as _RendererMenuContainer
class TestAPI(AsyncTestCase):
async def test_get_instance(self):
extension = _get_menubar_extension()
self.assertIsNotNone(extension)
async def test_register_custom_menu_item_type(self):
def _single_render_menu_item(*args, **kwargs):
class SingleRenderMenuItem(_SingleRenderMenuItemBase):
pass
return SingleRenderMenuItem(*args, **kwargs)
extension = _get_menubar_extension()
try:
with patch.object(_RendererMenuContainer, "set_menu_item_type") as set_menu_item_type_mock:
fn = functools.partial(_single_render_menu_item)
extension.register_menu_item_type(
fn
)
self.assertEqual(1, set_menu_item_type_mock.call_count)
self.assertEqual(call(fn), set_menu_item_type_mock.call_args)
finally:
extension.register_menu_item_type(None)
async def test_register_regular_menu_item_type(self):
def _single_render_menu_item(*args, **kwargs):
return _SingleRenderMenuItem(*args, **kwargs)
extension = _get_menubar_extension()
try:
with patch.object(_RendererMenuContainer, "set_menu_item_type") as set_menu_item_type_mock:
fn = functools.partial(_single_render_menu_item)
extension.register_menu_item_type(
fn
)
self.assertEqual(1, set_menu_item_type_mock.call_count)
self.assertEqual(call(fn), set_menu_item_type_mock.call_args)
finally:
extension.register_menu_item_type(None)
| 2,635 | Python | 40.187499 | 116 | 0.677799 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/tests/__init__.py | from .test_api import *
from .test_ui import *
| 47 | Python | 14.999995 | 23 | 0.702128 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.render/omni/kit/viewport/menubar/render/tests/test_ui.py | import omni.kit.test
from re import I
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.viewport.window import ViewportWindow
import omni.kit.ui_test as ui_test
from omni.kit.ui_test import Vec2
import omni.usd
import omni.kit.app
from pathlib import Path
import carb.input
import functools
from omni.kit.viewport.menubar.render import get_instance as _get_menubar_extension
from omni.kit.viewport.menubar.render import SingleRenderMenuItemBase as _SingleRenderMenuItemBase
CURRENT_PATH = Path(__file__).parent
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests")
TEST_WIDTH, TEST_HEIGHT = 600, 400
class TestSettingMenuWindow(OmniUiTest):
async def setUp(self):
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
self._vw = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT)
self._viewport_api = self._vw.viewport_api
await omni.kit.app.get_app().next_update_async()
# After running each test
async def tearDown(self):
self._vw.destroy()
del self._vw
await super().tearDown()
async def __show_render_menu(self, mouse_pos: Vec2 = None):
# Enable mouse input
app_window = omni.appwindow.get_default_app_window()
for device in [carb.input.DeviceType.MOUSE]:
app_window.set_input_blocking_state(device, None)
await ui_test.emulate_mouse_move(mouse_pos if mouse_pos else Vec2(40, 40))
await ui_test.emulate_mouse_click()
await omni.kit.app.get_app().next_update_async()
async def __close_render_menu(self):
await ui_test.emulate_mouse_move(Vec2(TEST_WIDTH, TEST_HEIGHT))
await ui_test.emulate_mouse_click()
await self.wait_n_updates()
async def test_render_menu_with_custom_type(self):
"""Test custom options area item. (This likely breaks order independent testing)"""
menu_option_clicked = 0
def _single_render_menu_item(*args, **kwargs):
class SingleRenderMenuItem(_SingleRenderMenuItemBase):
def _option_clicked(self):
nonlocal menu_option_clicked
menu_option_clicked += 1
return SingleRenderMenuItem(*args, **kwargs)
extension = _get_menubar_extension()
self.assertIsNotNone(extension)
try:
await self.__show_render_menu()
self.assertEqual(0, menu_option_clicked)
# Simluate a click in options-area, but do it on Storm; not RTX
await self.__show_render_menu(Vec2(205, 135))
self.assertEqual(0, menu_option_clicked)
extension.register_menu_item_type(
functools.partial(_single_render_menu_item)
)
await self.wait_n_updates()
await ui_test.emulate_mouse_click()
await self.wait_n_updates()
self.assertEqual(1, menu_option_clicked)
finally:
extension.register_menu_item_type(None)
await self.__close_render_menu()
await self.finalize_test_no_image()
async def test_auto_manage_renderer_list(self):
"""Test auto management of the renderer menu based on extension load. (This likely breaks order independent testing)"""
settings = carb.settings.get_settings()
restore_value = settings.get("/renderer/enabled")
try:
async def change_available_renderers(golden_img_name: str, renderers: str = None):
# Close the menu to avoid issues with golden images as menu shrink is animated over time
if renderers:
settings.set("/renderer/enabled", renderers)
await self.__show_render_menu()
await self.capture_and_compare(
golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name
)
await self.__close_render_menu()
await change_available_renderers("menubar_default_list_0.png")
# Disable everything but RTX
await change_available_renderers("menubar_rtx_only.png", "rtx")
# Disable everything but Iray and Storm
await change_available_renderers("menubar_pxr_iray_only.png", "pxr,iray")
# Enable omni.hydra.index extension (Note it will enable RTX as well due to dependencies)
omni.kit.app.get_app().get_extension_manager().set_extension_enabled_immediate("omni.hydra.index", True)
await change_available_renderers("menubar_all_shipping.png")
# Disbale omni.hydra.index extension, and list should be back to menubar_default_list
omni.kit.app.get_app().get_extension_manager().set_extension_enabled_immediate("omni.hydra.index", False)
await change_available_renderers("menubar_default_list_1.png")
finally:
settings.set("/renderer/enabled", restore_value if restore_value else "")
await self.__close_render_menu()
await self.finalize_test_no_image()
| 5,203 | Python | 39.976378 | 127 | 0.647703 |
omniverse-code/kit/exts/omni.kit.widget.stage/config/extension.toml | [package]
title = "Stage Widget"
description = "Stage Widget"
version = "2.7.24"
category = "Internal"
authors = ["NVIDIA"]
repository = ""
keywords = ["stage", "outliner", "scene"]
changelog = "docs/CHANGELOG.md"
[dependencies]
"omni.activity.core" = {}
"omni.kit.context_menu" = {}
"omni.ui" = {}
"omni.usd" = {}
"omni.kit.usd.layers" = {}
"omni.usd.schema.physics" = {}
"omni.usd.schema.anim" = {}
"omni.kit.window.file_exporter" = {}
"omni.client" = {}
[[python.module]]
name = "omni.kit.widget.stage"
# Settings. They are applied on the root of global settings. In case of conflict original settings are kept.
[settings]
persistent.exts."omni.kit.widget.stage".showColumnVisibility = true
persistent.exts."omni.kit.widget.stage".showColumnType = true
[[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",
"--/persistent/app/stage/dragDropImport='reference'",
"--/persistent/material/stage/dragDropMaterialPath='absolute'",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.widget.stage",
"omni.kit.window.content_browser",
"omni.kit.property.material",
"omni.kit.window.stage",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers",
"omni.hydra.pxr",
"omni.kit.window.viewport",
]
stdoutFailPatterns.exclude = [
"*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop
"*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available
]
# RTX regression OM-51983
timeout = 600
| 1,992 | TOML | 28.746268 | 122 | 0.684739 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageWidgetExtension"]
import omni.ext
from .stage_column_delegate_registry import StageColumnDelegateRegistry
from .visibility_column_delegate import VisibilityColumnDelegate
from .type_column_delegate import TypeColumnDelegate
from .delegates import NameColumnDelegate
from .stage_actions import register_actions, deregister_actions
from .export_utils import _get_stage_open_sub
from .stage_style import Styles as StageStyles
class StageWidgetExtension(omni.ext.IExt):
"""The entry point for Stage Window"""
def on_startup(self, ext_id):
# Register column delegates
self._name_column_sub = StageColumnDelegateRegistry().register_column_delegate("Name", NameColumnDelegate)
self._type_column_sub = StageColumnDelegateRegistry().register_column_delegate("Type", TypeColumnDelegate)
self._visibility_column_sub = StageColumnDelegateRegistry().register_column_delegate("Visibility", VisibilityColumnDelegate)
self._ext_name = omni.ext.get_extension_name(ext_id)
StageStyles.on_startup()
self._registered_hotkeys = []
register_actions(self._ext_name, self)
self._stage_open_sub = _get_stage_open_sub()
def on_shutdown(self):
self._name_column_sub = None
self._visibility_column_sub = None
self._type_column_sub = None
deregister_actions(self._ext_name, self)
self._stage_open_sub = None
| 1,860 | Python | 42.279069 | 132 | 0.746237 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/column_menu.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .event import Event
from .event import EventSubscription
from .stage_column_delegate_registry import StageColumnDelegateRegistry
from typing import Callable
from typing import List
from typing import Optional
from typing import Tuple
from .stage_icons import StageIcons as Icons
import omni.ui as ui
import weakref
class ColumnMenuDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
MENU_STYLES = {
"Menu.CheckBox": {"background_color": 0x0, "margin": 0},
"Menu.CheckBox::drag": {
"image_url": Icons().get("drag"),
"color": 0xFF505050,
"alignment": ui.Alignment.CENTER,
},
"Menu.CheckBox.Image": {"image_url": Icons().get("check_off"), "color": 0xFF8A8777},
"Menu.CheckBox.Image:checked": {"image_url": Icons().get("check_on"), "color": 0x34C7FFFF},
}
def __init__(self):
super().__init__()
def destroy(self):
pass
def build_header(self, column_id):
pass
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
with ui.HStack(height=0, style=ColumnMenuDelegate.MENU_STYLES):
ui.ToolButton(
item.checked_model,
style_type_name_override="Menu.CheckBox",
width=18,
height=18,
image_width=18,
image_height=18,
)
ui.Label(item.name_model.as_string)
ui.Image(style_type_name_override="Menu.CheckBox", name="drag", width=10)
class ColumnMenuItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, model, text, checked):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.checked_model = ui.SimpleBoolModel(checked)
self.checked_model.add_value_changed_fn(self._on_checked_changed)
self.__weak_model = weakref.ref(model)
def _on_checked_changed(self, model):
model = self.__weak_model()
if model:
model._item_changed(self)
model._on_column_checked_changed([i[0] for i in model.get_columns()])
def __repr__(self):
return f'"{self.name_model.as_string}"'
class ColumnMenuModel(ui.AbstractItemModel):
"""
Represents the model for available columns.
"""
def __init__(self, enabled: Optional[List[str]] = None, accepted: Optional[List[str]] = None):
super().__init__()
self._column_delegate_sub = StageColumnDelegateRegistry().subscribe_delegate_changed(
self._on_column_delegate_changed
)
self._accepted = accepted
if enabled is None:
self._children = []
else:
self._children = [
ColumnMenuItem(self, name, True) for name in enabled if not self._accepted or name in self._accepted
]
self._on_column_delegate_changed(enabled is None)
self._on_column_checked_changed = Event()
def destroy(self):
self._column_delegate_sub = None
self._children = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
# As we don't do Drag and Drop to the operating system, we return the string.
return item.name_model.as_string
def drop_accepted(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called to highlight target when drag and drop."""
# If target_item is None, it's the drop to root. Since it's
# list model, we support reorganizetion of root only and we
# don't want to create tree.
return not target_item and drop_location >= 0
def drop(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called when dropping something to the item."""
try:
source_id = self._children.index(source)
except ValueError:
try:
current_names = [c.name_model.as_string for c in self._children]
source_id = current_names.index(source)
source = self._children[source_id]
except ValueError:
# Not in the list. This is the source from another model.
return
if source_id == drop_location:
# Nothing to do
return
self._children.pop(source_id)
if drop_location > len(self._children):
# Drop it to the end
self._children.append(source)
else:
if source_id < drop_location:
# Becase when we removed source, the array became shorter
drop_location = drop_location - 1
self._children.insert(drop_location, source)
self._item_changed(None)
def get_columns(self) -> List[Tuple[str, bool]]:
"""
Return all the columns in the format
`[("Visibility", True), ("Type", False)]`
The first item is the column name, and the second item is a flag that
is True if the column is enabled.
"""
current_names = [c.name_model.as_string for c in self._children]
current_checked = [c.checked_model.as_bool for c in self._children]
return list(zip(current_names, current_checked))
def subscribe_delegate_changed(self, fn: Callable[[List[str]], None]) -> EventSubscription:
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return EventSubscription(self._on_column_checked_changed, fn)
def _on_column_delegate_changed(self, enabled=False):
"""Called by StageColumnDelegateRegistry"""
current_names = [c.name_model.as_string for c in self._children]
column_delegate_names = StageColumnDelegateRegistry().get_column_delegate_names()
# Exclude "Name" as it's enabled always.
if "Name" in column_delegate_names:
column_delegate_names.remove("Name")
# Filter columns. We only need the columns that is in self._accepted list.
if self._accepted:
column_delegate_names = [name for name in column_delegate_names if name in self._accepted]
# Form the new list keeping the order of the old columns
new_names = []
for name in current_names:
if name in column_delegate_names:
new_names.append(name)
# Put the new columns to the end of the list
unused_names = [name for name in column_delegate_names if name not in new_names]
new_names += unused_names
if current_names == new_names:
# Nothing changed
return
# Create item for new columns and reuse the items for old columns
new_children = []
for name in new_names:
if name in current_names:
i = current_names.index(name)
new_children.append(self._children[i])
else:
new_children.append(ColumnMenuItem(self, name, enabled))
# Replace children
self._children = new_children
self._item_changed(None)
| 8,582 | Python | 34.912134 | 116 | 0.61629 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/abstract_stage_column_delegate.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["AbstractStageColumnDelegate", "StageColumnItem"]
from pxr import Sdf, Usd
from typing import List
from .stage_item import StageItem
import abc
import omni.ui as ui
class StageColumnItem: # pragma: no cover
"""
It's not clear which data we need to pass to build_widget. It's path, but
there are potentially other information the column has. To keep API
unchanged over the time, we pass data in a struct. It also allow to pass
custom data with deriving from this class.
"""
def __init__(self, path: Sdf.Path, stage: Usd.Stage, enabled: bool, expanded: bool = True):
"""
## Arguments
`path`: Full path to the item
`stage`: USD Stage
`enabled`: When false, the widget should be grayed out
"""
self._path = path
self._stage = stage
self._enabled = enabled
self._expanded = expanded
@property
def path(self):
return self._path
@property
def stage(self):
return self._stage
@property
def enabled(self):
return self._enabled
@property
def expanded(self):
return self._expanded
class AbstractStageColumnDelegate(metaclass=abc.ABCMeta): # pragma: no cover
"""
An abstract object that is used to put the widget to the file browser
asynchronously.
"""
def destroy(self):
"""Place to release resources."""
pass
@property
def initial_width(self):
"""The initial width of the column."""
return ui.Fraction(1)
@property
def minimum_width(self):
return ui.Pixel(10)
def build_header(self, **kwargs):
"""
Build the header widget. If the column is sortable,
stage widget will help to build a background rectangle
that has hover state to tell user if the column is sortable so
all columns don't need to build that by themself. You can override
this function to build customized widgets as column header.
"""
pass
@abc.abstractmethod
async def build_widget(self, item: StageColumnItem, **kwargs):
"""
Build the widget for the given path. Works inside Frame in async
mode. Once the widget is created, it will replace the content of the
frame. It allow to await something for a while and create the widget
when the result is available.
Args:
item (StageColumnItem): DEPRECATED. It includes the non-cached simple prim
information. It's better to use keyword argument `stage_item` instead, which
provides cached rich information about the prim influened by this column.
Keyword Arguments:
stage_model (StageModel): The instance of current StageModel.
stage_item (StageItem): The current StageItem to build. It's possible that
stage_item is None when TreeView enabled display of root node.
"""
pass
def on_header_hovered(self, hovered: bool):
"""Callback when header area is hovered."""
pass
def on_stage_items_destroyed(self, items: List[StageItem]):
"""
Called when stage items are destroyed to give opportunity to delegate to release
corresponding resources.
"""
pass
@property
def sortable(self):
"""
Whether this column is sortable or not. When it's True, stage widget will build header
widget with hover and selection state to tell user it's sortable. This is only used
to instruct user that this column is sortable from UX.
"""
return False
@property
def order(self):
"""
The order to sort columns. The columns are sorted in ascending order from left to right of the stage widget.
So the smaller the order is, the closer the column is to the left of the stage widget.
"""
return 0
| 4,398 | Python | 30.647482 | 116 | 0.649613 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_delegate.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageDelegate"]
from .abstract_stage_column_delegate import AbstractStageColumnDelegate
from .abstract_stage_column_delegate import StageColumnItem
from .delegates import NameColumnDelegate
from .context_menu import ContextMenu
from .stage_icons import StageIcons
from .stage_model import StageItem
from typing import List
from functools import partial
import asyncio
import inspect
import weakref
import omni.ui as ui
class AwaitWithFrame:
"""
A future-like object that runs the given future and makes sure it's
always in the given frame's scope. It allows creating widgets
asynchronously.
"""
def __init__(self, frame: ui.Frame, future: asyncio.Future):
self._frame = frame
self._future = future
def __await__(self):
# create an iterator object from that iterable
iter_obj = iter(self._future.__await__())
# infinite loop
while True:
try:
with self._frame:
yield next(iter_obj)
except StopIteration:
break
self._frame = None
self._future = None
class ContextMenuEvent:
"""The object comatible with ContextMenu"""
def __init__(self, stage: "pxr.Usd.Stage", path_string, expanded=None):
self.type = 0
self.payload = {"stage": stage, "prim_path": path_string, "node_open": expanded}
class ContextMenuHandler:
"""The object that the ContextMenu calls to expand the item"""
def __init__(self):
self._expand_fn = None
self._collapse_fn = None
@property
def expand_fn(self):
return self._expand_fn
@expand_fn.setter
def expand_fn(self, value):
self._expand_fn = value
@property
def collapse_fn(self):
return self._collapse_fn
@collapse_fn.setter
def collapse_fn(self, value):
self._collapse_fn = value
def _expand(self, path):
if self._expand_fn:
self._expand_fn(path)
def _collapse(self, path):
if self._collapse_fn:
self._collapse_fn(path)
def context_menu_handler(self, cmd, prim_path):
if cmd == "opentree":
self._expand(prim_path)
elif cmd == "closetree":
self._collapse(prim_path)
class StageDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
self._context_menu = ContextMenu()
self._context_menu._stage_win = ContextMenuHandler()
self._column_delegates: List[AbstractStageColumnDelegate] = []
self._header_layout = None
self._header_layout_is_hovered = False
self._mouse_pressed_task = None
self._on_stage_items_destroyed_sub = None
self._name_column_delegate = None
@property
def model(self):
return self._stage_model
@model.setter
def model(self, value):
if self._on_stage_items_destroyed_sub:
self._on_stage_items_destroyed_sub.destroy()
self._on_stage_items_destroyed_sub = None
self._stage_model = value
if self._stage_model:
self._on_stage_items_destroyed_sub = self._stage_model.subscribe_stage_items_destroyed(
self.__on_stage_items_destroyed
)
def __on_stage_items_destroyed(self, items: List[StageItem]):
for delegate in self._column_delegates:
delegate.on_stage_items_destroyed(items)
@property
def expand_fn(self):
return self._context_menu._stage_win.expand_fn
@expand_fn.setter
def expand_fn(self, value):
self._context_menu._stage_win.expand_fn = value
@property
def collapse_fn(self):
return self._context_menu._stage_win.collapse_fn
@collapse_fn.setter
def collapse_fn(self, value):
self._context_menu._stage_win.collapse_fn = value
def destroy(self):
if self._on_stage_items_destroyed_sub:
self._on_stage_items_destroyed_sub.destroy()
self._on_stage_items_destroyed_sub = None
self._stage_model = None
self._context_menu.function_list.pop("rename_item", None)
self._context_menu.destroy()
self._context_menu = None
self._name_column_delegate = None
for d in self._column_delegates:
d.destroy()
self._column_delegates = []
if self._header_layout:
self._header_layout.set_mouse_hovered_fn(None)
self._header_layout = None
if self._mouse_pressed_task:
self._mouse_pressed_task.cancel()
self._mouse_pressed_task = None
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=20 * (level + 1), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.Image(
StageIcons().get(image_name), width=10, height=10, style_type_name_override="TreeView.Item"
)
ui.Spacer(width=5)
def on_mouse_pressed(self, button, stage: "pxr.Usd.Stage", item, expanded):
"""Called when the user press the mouse button on the item"""
if button != 1:
return
async def show_context_menu(stage: "pxr.Usd.Stage", item, expanded):
import omni.kit.app
await omni.kit.app.get_app().next_update_async()
# menu is for context menu only but don't check in on_mouse_pressed func as it can be out of date
# check layout_is_hovered here to make sure its updated for current mouse position
if self._header_layout_is_hovered:
return
# Form the event
path = item.path if item else None
event = ContextMenuEvent(stage, path, expanded)
# Show the menu
self._context_menu.on_mouse_event(event)
self._mouse_pressed_task = None
# this function can get called multiple times sometimes with different item values
if self._mouse_pressed_task:
self._mouse_pressed_task.cancel()
self._mouse_pressed_task = None
self._mouse_pressed_task = asyncio.ensure_future(show_context_menu(stage, item, expanded))
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per item"""
if column_id >= len(self._column_delegates):
return
if item:
column_item = StageColumnItem(item.path, model.stage, not item.instance_proxy, expanded)
else:
column_item = None
stage = model.stage
frame = ui.Frame(mouse_pressed_fn=lambda x, y, b, _: self.on_mouse_pressed(b, stage, item, expanded))
# Name column needs special treatment to build frame synchronously so all items will not be built
# in the same line.
if self._name_column_delegate and self._name_column_delegate == self._column_delegates[column_id]:
with frame:
self._name_column_delegate.build_widget_sync(column_item, stage_item=item, stage_model=model)
else:
# This is for back compatibility of old interface.
build_widget_func = self._column_delegates[column_id].build_widget
argspec = inspect.getfullargspec(build_widget_func)
if not argspec.varkw:
future = build_widget_func(column_item)
else:
future = build_widget_func(column_item, stage_item=item, stage_model=model)
asyncio.ensure_future(AwaitWithFrame(frame, future))
def __on_header_hovered(self, hovered):
self._header_layout_is_hovered = hovered
def build_header(self, column_id):
if column_id >= len(self._column_delegates):
return
self._header_layout = ui.ZStack()
self._header_layout.set_mouse_hovered_fn(self.__on_header_hovered)
with self._header_layout:
column_delegate = self._column_delegates[column_id]
if column_delegate.sortable:
def on_drop_down_hovered(weakref_delegate, hovered):
if not weakref_delegate():
return
weakref_delegate().on_header_hovered(hovered)
hovered_area = ui.Rectangle(name="hovering", style_type_name_override="TreeView.Header")
weakref_delegate = weakref.ref(column_delegate)
hovered_area.set_mouse_hovered_fn(partial(on_drop_down_hovered, weakref_delegate))
build_header_func = column_delegate.build_header
argspec = inspect.getfullargspec(build_header_func)
# This is for back compatibility of old interface.
if not argspec.varkw:
build_header_func()
else:
build_header_func(stage_model=self.model)
def set_highlighting(self, enable: bool = None, text: str = None):
"""
Specify if the widgets should consider highlighting. Also set the text that should be highlighted in flat mode.
"""
if self._name_column_delegate:
self._name_column_delegate.set_highlighting(enable, text)
def set_column_delegates(self, delegates):
"""Add custom columns"""
self._name_column_delegate = None
for d in self._column_delegates:
d.destroy()
self._column_delegates = delegates
self._context_menu.function_list.pop("rename_item", None)
def rename_item(prim_path):
if not self.model:
return
item = self.model.find(prim_path)
if not item:
return
self._name_column_delegate.rename_item(item)
for delegate in delegates:
if isinstance(delegate, NameColumnDelegate):
self._name_column_delegate = delegate
self._context_menu.function_list["rename_item"] = rename_item
break
def get_name_column_delegate(self):
return self._name_column_delegate
| 10,721 | Python | 34.269737 | 119 | 0.611603 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/event.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.
#
class Event(list):
"""
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
"""
def __call__(self, *args, **kwargs):
"""Called when the instance is “called” as a function"""
# Call all the saved functions
for f in self:
f(*args, **kwargs)
def __repr__(self):
"""
Called by the repr() built-in function to compute the “official”
string representation of an object.
"""
return f"Event({list.__repr__(self)})"
class EventSubscription:
"""
Event subscription.
Event has callback while this object exists.
"""
def __init__(self, event, fn):
"""
Save the function, the event, and add the function to the event.
"""
self._fn = fn
self._event = event
event.append(self._fn)
def destroy(self):
if self._fn in self._event:
self._event.remove(self._fn)
def __del__(self):
"""Called by GC."""
self.destroy()
| 1,526 | Python | 27.81132 | 76 | 0.625164 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_style.py | import omni.ui as ui
class Styles:
ITEM_DARK = None
ITEM_GRAY = None
ITEM_HOVER = None
ITEM_SEL = None
ITEM_BG_SEL = None
ICON_DARK = None
STAGE_WIDGET = None
@staticmethod
def on_startup():
from .stage_icons import StageIcons as Icons
# List Items
Styles.ITEM_DARK = 0x7723211F
Styles.ITEM_GRAY = 0xFF8A8777
Styles.ITEM_HOVER = 0xFFBBBAAA
Styles.ITEM_SEL = 0xFFDDDCCC
Styles.ITEM_BG_SEL = 0x66888777
Styles.LIVE_GREEN = 0xFF00B86B
Styles.LIVE_SEL = 0xFF00F86E
Styles.RELOAD_ORANGE = 0xFF0088CC
Styles.RELOAD_SEL = 0xFF00AAFF
Styles.STAGE_WIDGET = {
"Button.Image::filter": {"image_url": Icons().get("filter"), "color": 0xFF8A8777},
"Button.Image::options": {"image_url": Icons().get("options"), "color": 0xFF8A8777},
"Button.Image::visibility": {"image_url": Icons().get("eye_on"), "color": 0xFF8A8777},
"Button.Image::visibility:checked": {"image_url": Icons().get("eye_off"), "color": 0x88DDDCCC},
"Button.Image::visibility:disabled": {"color": 0x608A8777},
"Button.Image::visibility:selected": {"color": 0xFFCCCCCC},
"Button::filter": {"background_color": 0x0, "margin": 0},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button::visibility": {"background_color": 0x0, "margin": 0, "margin_width": 1},
"Button::visibility:checked": {"background_color": 0x0},
"Button::visibility:hovered": {"background_color": 0x0},
"Button::visibility:pressed": {"background_color": 0x0},
"Label::search": {"color": 0xFF808080, "margin_width": 4},
"Menu.CheckBox": {"background_color": 0x0, "margin": 0},
"Menu.CheckBox::drag": {
"image_url": Icons().get("drag"),
"color": 0xFF505050,
"alignment": ui.Alignment.CENTER,
},
"Menu.CheckBox.Image": {"image_url": Icons().get("check_off"), "color": 0xFF8A8777},
"Menu.CheckBox.Image:checked": {"image_url": Icons().get("check_on"), "color": 0x34C7FFFF},
"TreeView": {
"background_color": 0xFF23211F,
"background_selected_color": 0x664F4D43,
"secondary_color": 0xFF403B3B,
"border_width": 1.5,
},
"TreeView.ScrollingFrame": {"background_color": 0xFF23211F},
"TreeView.Image::object_icon_grey": {"color": 0x80FFFFFF},
"TreeView.Image:disabled": {"color": 0x60FFFFFF},
"TreeView.Item": {"color": Styles.ITEM_GRAY},
"TreeView.Item:disabled": {"color": 0x608A8777},
"TreeView.Item::object_name_grey": {"color": 0xFF4D4B42},
"TreeView.Item::object_name_missing": {"color": 0xFF6F72FF},
"TreeView.Item::object_name_missing:hovered": {"color": 0xFF6F72FF},
"TreeView.Item::object_name_missing:selected": {"color": 0xFF6F72FF},
"TreeView.Item:hovered": {"color": Styles.ITEM_HOVER},
"TreeView.Item:selected": {"color": Styles.ITEM_SEL},
"TreeView.Item.Outdated": {"color": Styles.RELOAD_ORANGE},
"TreeView.Item.Outdated:hovered": {"color": Styles.RELOAD_SEL},
"TreeView.Item.Outdated:selected": {"color": Styles.RELOAD_SEL},
"TreeView.Item.Live": {"color": Styles.LIVE_GREEN},
"TreeView.Item.Live:hovered": {"color": Styles.LIVE_SEL},
"TreeView.Item.Live:selected": {"color": Styles.LIVE_SEL},
"TreeView:selected": {"background_color": Styles.ITEM_BG_SEL},
"TreeView:drop": {
"background_color": ui.color.shade(ui.color("#34C7FF3B")),
"background_selected_color": ui.color.shade(ui.color("#34C7FF3B")),
"border_color": ui.color.shade(ui.color("#2B87AA")),
},
# Top of the column section (that has sorting options)
"TreeView.Header": {"background_color": 0xFF343432, "color": 0xFFCCCCCC, "font_size": 12},
"TreeView.Header::visibility_header": {"image_url": Icons().get("eye_header"), "color": 0xFF888888},
"TreeView.Header::drop_down_background": {"background_color": 0xE0808080},
"TreeView.Header::drop_down_button": {"background_color": ui.color.white},
"TreeView.Header::drop_down_hovered_area": {"background_color": ui.color.transparent},
"TreeView.Header::hovering": {"background_color": 0x0, "border_radius": 1.5},
"TreeView.Header::hovering:hovered": {
"background_color": ui.color.shade(ui.color("#34C7FF3B")),
"border_width": 1.5,
"border_color": ui.color.shade(ui.color("#2B87AA"))
}
}
| 4,877 | Python | 50.347368 | 112 | 0.573098 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/selection_watch.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DefaultSelectionWatch"]
from pxr import Sdf, Trace
import omni.usd
from typing import Optional
class DefaultSelectionWatch(object):
"""
The object that update selection in TreeView when the scene selection is
changed and updated scene selection when TreeView selection is changed.
"""
def __init__(self, tree_view=None, usd_context=None):
self._usd_context = usd_context or omni.usd.get_context()
self._selection = None
self._in_selection = False
self._tree_view = None
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="Stage Window Selection Update"
)
self.set_tree_view(tree_view)
self.__filter_string: Optional[str] = None
# When True, SelectionWatch should consider filtering
self.__filter_checking: bool = False
def destroy(self):
self._usd_context = None
self._selection = None
self._stage_event_sub = None
self._events = None
if self._tree_view:
self._tree_view.set_selection_changed_fn(None)
self._tree_view = None
def set_tree_view(self, tree_view):
"""Replace TreeView that should show the selection"""
if self._tree_view != tree_view:
if self._tree_view:
self._tree_view.set_selection_changed_fn(None)
self._tree_view = tree_view
self._tree_view.set_selection_changed_fn(self._on_widget_selection_changed)
self._last_selected_prim_paths = None
self._on_kit_selection_changed()
def set_filtering(self, filter_string: Optional[str]):
if filter_string:
self.__filter_string = filter_string.lower()
else:
self.__filter_string = filter_string
def enable_filtering_checking(self, enable: bool):
"""
When `enable` is True, SelectionWatch should consider filtering when
changing Kit's selection.
"""
self.__filter_checking = enable
def _on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_kit_selection_changed()
@Trace.TraceFunction
def _on_kit_selection_changed(self):
"""Send the selection from Kit to TreeView"""
if not self._tree_view or self._in_selection:
return
# Make sure it's a new selection. It happens that omni.usd sends the same selection twice. No sorting because
# the order of selection is important.
prim_paths = self._selection.get_selected_prim_paths()
if prim_paths == self._last_selected_prim_paths:
return
self._last_selected_prim_paths = [Sdf.Path(prim_path) for prim_path in prim_paths]
# Pump the changes to the model because to select something, TreeView should be updated.
self._tree_view.model.update_dirty()
selection = []
for path in prim_paths:
# Get the selected item and its parents. Expand all the parents of the new selection.
full_chain = self._tree_view.model.find_full_chain(path)
# When the new object is created, omni.usd sends the selection is changed before the object appears in the
# stage and it means we can't select it. In this way it's better to return because we don't have the item
# in the model yet.
# TODO: Use UsdNotice to track if the object is created.
if not full_chain or full_chain[-1].path != path:
continue
if full_chain:
for item in full_chain[:-1]:
self._tree_view.set_expanded(item, True, False)
# Save the last item in the chain. It's the selected item
selection.append(full_chain[-1])
# Send all of this to TreeView.
self._in_selection = True
self._tree_view.selection = selection
self._in_selection = False
@Trace.TraceFunction
def _on_widget_selection_changed(self, selection):
"""Send the selection from TreeView to Kit"""
if self._in_selection:
return
prim_paths = [item.path for item in selection if item]
# Filter selection
if self.__filter_string or self.__filter_checking:
# Check if the selected prims are filtered and re-select filtered items only if necessary.
filtered_paths = [item.path for item in selection if item and item.filtered]
if filtered_paths != prim_paths:
filtered_selection = [item for item in selection if item and item.path in filtered_paths]
self._tree_view.selection = filtered_selection
return
if prim_paths == self._last_selected_prim_paths:
return
# Send the selection to Kit
self._in_selection = True
old_paths = [sdf_path.pathString for sdf_path in self._last_selected_prim_paths]
new_paths = [sdf_path.pathString for sdf_path in prim_paths]
omni.kit.commands.execute("SelectPrims", old_selected_paths=old_paths, new_selected_paths=new_paths, expand_in_stage=True)
self._in_selection = False
self._last_selected_prim_paths = prim_paths
| 5,914 | Python | 40.654929 | 130 | 0.636287 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/commands.py | __all__ = ["ReorderPrimCommand"]
import carb
import omni.kit.commands
import omni.usd
from pxr import Usd, Sdf
class ReorderPrimCommand(omni.kit.commands.Command):
"""
Command to reorder prim in its parent. This command uses the support from USD to
override the reorder property, and it will always be authored into the root layer
without considering the edit target.
"""
def __init__(self, stage: Usd.Stage, prim_path: Sdf.Path, move_to_location: int):
"""
Constructor.
Args:
stage (Usd.Stage): USD stage.
prim_path (Sdf.Path): Prim to reorder.
move_to_location (int): Move to the location in its parent. If it's -1, it means to move
the prim to the bottom.
"""
self.__stage = stage
self.__prim_path = Sdf.Path(prim_path)
self.__move_to_location = move_to_location
self.__old_location = -1
self.__success = False
def __move_to(self, location):
if self.__prim_path == Sdf.Path.emptyPath or self.__prim_path == Sdf.Path.absoluteRootPath:
carb.log_warn("Failed to reorder prim as empty path or absolute root path is not supported.")
return False
prim = self.__stage.GetPrimAtPath(self.__prim_path)
if not prim:
carb.log_error(f"Failed to reorder prim {self.__prim_path} as prim is not found in the stage.")
return False
parent_path = self.__prim_path.GetParentPath()
parent_prim = self.__stage.GetPrimAtPath(parent_path)
if not parent_prim:
return
all_children = parent_prim.GetAllChildrenNames()
total_children = len(all_children)
name = self.__prim_path.name
if name in all_children:
index = all_children.index(name)
self.__old_location = index
all_children.remove(name)
else:
index = -1
if index == location:
return
if location < 0 or location > total_children:
location = -1
elif location > index and index != -1:
# If it's to move from up to down.
location -= 1
all_children.insert(location, name)
# Use Sdf API so it can be batched.
parent_prim_spec = Sdf.CreatePrimInLayer(self.__stage.GetRootLayer(), parent_path)
parent_prim_spec.nameChildrenOrder = all_children
self.__success = True
return True
def do(self):
with Usd.EditContext(self.__stage, self.__stage.GetRootLayer()):
return self.__move_to(self.__move_to_location)
def undo(self):
if self.__success:
with Usd.EditContext(self.__stage, self.__stage.GetRootLayer()):
self.__move_to(self.__old_location)
self.__success = False
| 2,855 | Python | 32.209302 | 107 | 0.592294 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_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.
#
__all__ = ["StageIcons"]
import omni.kit.app
from .singleton import Singleton
from pathlib import Path
from typing import Union
ICON_FOLDER_PATH = Path(
f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/icons"
)
@Singleton
class StageIcons:
"""A singleton that scans the icon folder and returns the icon depending on the type"""
class _Event(list):
"""
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
"""
def __call__(self, *args, **kwargs):
"""Called when the instance is “called” as a function"""
# Call all the saved functions
for f in self:
f(*args, **kwargs)
def __repr__(self):
"""
Called by the repr() built-in function to compute the “official”
string representation of an object.
"""
return f"Event({list.__repr__(self)})"
class _EventSubscription:
"""
Event subscription.
_Event has callback while this object exists.
"""
def __init__(self, event, fn):
"""
Save the function, the event, and add the function to the event.
"""
self._fn = fn
self._event = event
event.append(self._fn)
def __del__(self):
"""Called by GC."""
self._event.remove(self._fn)
def __init__(self):
self._on_icons_changed = self._Event()
# Read all the svg files in the directory
self._icons = {icon.stem: str(icon) for icon in ICON_FOLDER_PATH.glob("*.svg")}
def set(self, prim_type: str, icon_path: Union[str, Path]):
"""Set the new icon path for a specific prim type"""
if icon_path is None:
# Remove the icon
if prim_type in self._icons:
del self._icons[prim_type]
else:
self._icons[prim_type] = str(icon_path)
self._on_icons_changed()
def get(self, prim_type: str, default: Union[str, Path] = None) -> str:
"""Checks the icon cache and returns the icon if exists"""
found = self._icons.get(prim_type)
if not found and default:
found = self._icons.get(default)
if found:
return found
return ""
def subscribe_icons_changed(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self._on_icons_changed, fn)
| 3,070 | Python | 30.336734 | 100 | 0.595765 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/__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 .context_menu import ContextMenu
from .stage_extension import *
from .stage_icons import *
from .stage_widget import *
from .selection_watch import *
from .stage_model import *
from .stage_item import *
from .export_utils import ExportPrimUSD
from .commands import *
from .abstract_stage_column_delegate import *
from .stage_column_delegate_registry import *
| 797 | Python | 38.899998 | 76 | 0.797992 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_column_delegate_registry.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageColumnDelegateRegistry"]
from .abstract_stage_column_delegate import AbstractStageColumnDelegate
from .event import Event
from .event import EventSubscription
from .singleton import Singleton
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
import carb
@Singleton
class StageColumnDelegateRegistry:
"""
Singleton that keeps all the column delegated. It's used to put custom
columns to the content browser.
"""
class _ColumnDelegateSubscription:
"""
Event subscription.
Event has callback while this object exists.
"""
def __init__(self, name, delegate):
"""
Save name and type to the list.
"""
self._name = name
StageColumnDelegateRegistry()._delegates[self._name] = delegate
StageColumnDelegateRegistry()._on_delegates_changed()
def __del__(self):
"""Called by GC."""
del StageColumnDelegateRegistry()._delegates[self._name]
StageColumnDelegateRegistry()._on_delegates_changed()
def __init__(self):
self._delegates: Dict[str, Callable[[], AbstractStageColumnDelegate]] = {}
self._names: List[str] = []
self._on_delegates_changed = Event()
self.__delegate_changed_sub = self.subscribe_delegate_changed(self.__delegate_changed)
def register_column_delegate(self, name: str, delegate: Callable[[], AbstractStageColumnDelegate]):
"""
Add a new engine to the registry.
## Arguments
`name`: the name of the engine as it appears in the menu.
`delegate`: the type derived from AbstractColumnDelegate. Content
browser will create an object of this type to build
widgets for the custom column.
"""
if name in self._delegates:
carb.log_warn(f"Column delegate with name {name} is registered already.")
return
return self._ColumnDelegateSubscription(name, delegate)
def get_column_delegate_names(self) -> List[str]:
"""Returns all the column delegate names"""
return self._names
def get_column_delegate(self, name: str) -> Optional[Callable[[], AbstractStageColumnDelegate]]:
"""Returns the type of derived from AbstractColumnDelegate for the given name"""
return self._delegates.get(name, None)
def subscribe_delegate_changed(self, fn: Callable[[], None]) -> EventSubscription:
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return EventSubscription(self._on_delegates_changed, fn)
def __delegate_changed(self):
self._names = list(sorted(self._delegates.keys()))
| 3,251 | Python | 36.37931 | 103 | 0.665949 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/context_menu.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.
#
import os, sys
import asyncio
import carb
import omni.usd
import omni.kit.ui
import omni.kit.usd.layers as layers
from omni import ui
from functools import partial
from pxr import Usd, Sdf, UsdShade, UsdGeom, UsdLux, Kind
class ContextMenu:
def __init__(self):
self.function_list = {}
def destroy(self):
self.function_list = {}
def on_mouse_event(self, event):
# check its expected event
if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE):
return
# get context menu core functionality & check its enabled
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None:
carb.log_error("context_menu is disabled!")
return
# get stage
stage = event.payload.get("stage", None)
if stage is None:
carb.log_error("stage not avaliable")
return None
# get parameters passed by event
prim_path = event.payload["prim_path"]
# setup objects, this is passed to all functions
objects = {}
objects["use_hovered"] = True if prim_path else False
objects["stage_win"] = self._stage_win
objects["node_open"] = event.payload["node_open"]
objects["stage"] = stage
objects["function_list"] = self.function_list
prim_list = []
hovered_prim = event.payload["prim_path"]
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
if len(paths) > 0:
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim:
prim_list.append(prim)
if prim == hovered_prim:
hovered_prim = None
elif prim_path is not None:
prim = stage.GetPrimAtPath(prim_path)
if prim:
prim_list.append(prim)
if prim_list:
objects["prim_list"] = prim_list
if hovered_prim:
objects["hovered_prim"] = stage.GetPrimAtPath(hovered_prim)
# setup menu
menu_dict = [
{"populate_fn": context_menu.show_selected_prims_names},
{"populate_fn": ContextMenu.show_create_menu},
{"name": ""},
{
"name": "Clear Default Prim",
"glyph": "menu_rename.svg",
"show_fn": [context_menu.is_prim_selected, ContextMenu.is_prim_sudo_root, ContextMenu.has_default_prim],
"onclick_fn": ContextMenu.clear_default_prim,
},
{
"name": "Set as Default Prim",
"glyph": "menu_rename.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_one_prim_selected,
ContextMenu.is_prim_sudo_root,
ContextMenu.no_default_prim,
],
"onclick_fn": ContextMenu.set_default_prim,
},
{"name": ""},
{
"name": "Find in Content Browser",
"glyph": "menu_search.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_one_prim_selected,
context_menu.can_show_find_in_browser,
],
"onclick_fn": context_menu.find_in_browser,
},
{"name": ""},
{
"name": "Group Selected",
"glyph": "group_selected.svg",
"show_fn": context_menu.is_prim_selected,
"onclick_fn": context_menu.group_selected_prims,
},
{
"name": "Ungroup Selected",
"glyph": "group_selected.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_prim_in_group,
],
"onclick_fn": context_menu.ungroup_selected_prims,
},
{
"name": "Duplicate",
"glyph": "menu_duplicate.svg",
"show_fn": [context_menu.is_prim_selected, context_menu.can_be_copied],
"onclick_fn": context_menu.duplicate_prim,
},
{
"name": "Rename",
"glyph": "menu_rename.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_one_prim_selected,
context_menu.can_delete,
ContextMenu.has_rename_function
],
"onclick_fn": ContextMenu.rename_prim,
},
{
"name": "Delete",
"glyph": "menu_delete.svg",
"show_fn": [context_menu.is_prim_selected, context_menu.can_delete],
"onclick_fn": context_menu.delete_prim,
},
{
"name": "Save Selected",
"glyph": "menu_save.svg",
"show_fn": [context_menu.is_prim_selected],
"onclick_action": ("omni.kit.widget.stage", "save_prim"),
},
{"name": ""},
{
"name": "Refresh Reference",
"glyph": "sync.svg",
"name_fn": context_menu.refresh_reference_payload_name,
"show_fn": [context_menu.is_prim_selected, context_menu.has_payload_or_reference],
"onclick_fn": context_menu.refresh_payload_or_reference,
},
{
"name": "Convert Payloads to References",
"glyph": "menu_duplicate.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.has_payload,
context_menu.can_convert_references_or_payloads
],
"onclick_fn": context_menu.convert_payload_to_reference,
},
{
"name": "Convert References to Payloads",
"glyph": "menu_duplicate.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.has_reference,
context_menu.can_convert_references_or_payloads
],
"onclick_fn": context_menu.convert_reference_to_payload,
},
{
"name": "Select Bound Objects",
"glyph": "menu_search.svg",
"show_fn": [context_menu.is_prim_selected, context_menu.is_material],
"onclick_fn": context_menu.select_prims_using_material,
},
{
"name": "Bind Material To Selected Objects",
"glyph": "menu_material.svg",
"show_fn": [
context_menu.is_prim_selected,
ContextMenu.is_hovered_prim_material,
context_menu.is_material_bindable,
context_menu.is_one_prim_selected,
],
"onclick_fn": ContextMenu.bind_material_to_selected_prims,
},
{
"name":
{
'Expand':
[
{
"name": "Expand To:",
},
{
"name": "All",
"onclick_fn": ContextMenu.expand_all,
},
{
"name": "Component",
"onclick_fn": lambda o, k="component": ContextMenu.expand_to(o, k),
},
{
"name": "Group",
"onclick_fn": lambda o, k="group": ContextMenu.expand_to(o, k),
},
{
"name": "Assembly",
"onclick_fn": lambda o, k="assembly": ContextMenu.expand_to(o, k),
},
{
"name": "SubComponent",
"onclick_fn": lambda o, k="subcomponent": ContextMenu.expand_to(o, k),
},
]
},
"glyph": "menu_plus.svg",
"show_fn": [ContextMenu.show_open_tree],
},
{
"name":
{
'Collapse':
[
{
"name": "Collapse To:",
},
{
"name": "All",
"onclick_fn": ContextMenu.collapse_all,
},
{
"name": "Component",
"onclick_fn": lambda o, k="component": ContextMenu.collapse_to(o, k),
},
{
"name": "Group",
"onclick_fn": lambda o, k="group": ContextMenu.collapse_to(o, k),
},
{
"name": "Assembly",
"onclick_fn": lambda o, k="assembly": ContextMenu.collapse_to(o, k),
},
{
"name": "SubComponent",
"onclick_fn": lambda o, k="subcomponent": ContextMenu.collapse_to(o, k),
},
]
},
"glyph": "menu_minus.svg",
"show_fn": [ContextMenu.show_open_tree],
},
{"name": ""},
{
"name": "Assign Material",
"glyph": "menu_material.svg",
"show_fn_async": context_menu.can_assign_material_async,
"onclick_fn": ContextMenu.bind_material_to_prim_dialog,
},
{"name": "", "show_fn_async": context_menu.can_assign_material_async},
{
"name": "Copy URL Link",
"glyph": "menu_link.svg",
"show_fn": [
context_menu.is_prim_selected,
context_menu.is_one_prim_selected,
context_menu.can_show_find_in_browser,
context_menu.can_use_find_in_browser,
],
"onclick_fn": context_menu.copy_prim_url,
},
{
"name": "Copy Prim Path",
"glyph": "menu_link.svg",
"show_fn": context_menu.is_prim_selected,
"onclick_fn": context_menu.copy_prim_path,
},
]
if stage:
layers_interface = layers.get_layers(omni.usd.get_context())
auto_authoring = layers_interface.get_auto_authoring()
layers_state = layers_interface.get_layers_state()
edit_mode = layers_interface.get_edit_mode()
if edit_mode == layers.LayerEditMode.SPECS_LINKING:
per_layer_link_menu = []
for layer in stage.GetLayerStack():
if auto_authoring.is_auto_authoring_layer(layer.identifier):
continue
layer_name = layers_state.get_layer_name(layer.identifier)
per_layer_link_menu.append(
{
"name":
{
f"{layer_name}":
[
{
"name": "Link Selected",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.link_selected, True,
layer.identifier, False
),
},
{
"name": "Link Selected Hierarchy",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.link_selected, True,
layer.identifier, True
),
},
{
"name": "Unlink Selected",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.link_selected, False,
layer.identifier, False
),
},
{
"name": "Unlink Selected Hierarchy",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.link_selected, False,
layer.identifier, True
),
},
{
"name": "Select Linked Prims",
"show_fn": [
],
"onclick_fn": ContextMenu.select_linked_prims,
},
]
}
}
)
menu_dict.extend([{"name": ""}])
menu_dict.append(
{
"name":
{
"Layers": per_layer_link_menu
},
"glyph": "menu_link.svg",
}
)
menu_dict.extend([{"name": ""}])
menu_dict.append(
{
"name":
{
"Locks": [
{
"name": "Lock Selected",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.lock_selected, True,
False
),
},
{
"name": "Lock Selected Hierarchy",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.lock_selected, True,
True
),
},
{
"name": "Unlock Selected",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.lock_selected, False,
False
),
},
{
"name": "Unlock Selected Hierarchy",
"show_fn": [
context_menu.is_prim_selected,
],
"onclick_fn": partial(
ContextMenu.lock_selected, False,
True
),
},
{
"name": "Select Locked Prims",
"show_fn": [
],
"onclick_fn": ContextMenu.select_locked_prims,
},
]
},
"glyph": "menu_lock.svg",
}
)
menu_dict += omni.kit.context_menu.get_menu_dict("MENU", "")
menu_dict += omni.kit.context_menu.get_menu_dict("MENU", "omni.kit.widget.stage")
omni.kit.context_menu.reorder_menu_dict(menu_dict)
def _get_kinds():
builtin_kinds = ["model", "assembly", "group", "component", "subcomponent"]
display_builtin_kinds = builtin_kinds[1:]
plugin_kinds = list(set(Kind.Registry.GetAllKinds()) - set(builtin_kinds))
display_builtin_kinds.extend(plugin_kinds)
return display_builtin_kinds
def _set_kind(kind_string):
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
stage = omni.usd.get_context().get_stage()
for p in paths:
model = Usd.ModelAPI(stage.GetPrimAtPath(p))
model.SetKind(kind_string)
kind_list = _get_kinds()
sub_menu = []
menu = {}
menu["name"] = "None"
menu["onclick_fn"] = lambda i, kind_string="": _set_kind(kind_string)
sub_menu.append(menu)
for k in kind_list:
menu = {}
menu["name"] = str(k).capitalize()
menu["onclick_fn"] = lambda i, kind_string=str(k): _set_kind(kind_string)
sub_menu.append(menu)
menu_dict.append(
{
"name": {
"Set Kind": sub_menu
},
"glyph": "none.svg"
}
)
# show menu
context_menu.show_context_menu("stagewindow", objects, menu_dict)
# ---------------------------------------------- menu show functions ----------------------------------------------
def is_prim_sudo_root(objects):
if not "prim_list" in objects:
return False
prim_list = objects["prim_list"]
if len(prim_list) != 1:
return False
prim = prim_list[0]
return prim.GetParent() == prim.GetStage().GetPseudoRoot()
def has_default_prim(objects):
if not "prim_list" in objects:
return False
prim_list = objects["prim_list"]
if len(prim_list) != 1:
return False
stage = objects["stage"]
return stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim_list[0]
def no_default_prim(objects):
return not ContextMenu.has_default_prim(objects)
def is_hovered_prim_material(objects):
hovered_prim = objects.get("hovered_prim", None)
if not hovered_prim:
return False
return hovered_prim.IsA(UsdShade.Material)
def show_open_tree(objects): # pragma: no cover
"""Unused"""
if not "prim_list" in objects:
return False
prim = objects["prim_list"][0]
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
if prim.IsA(UsdGeom.Camera) or ((prim.HasAPI(UsdLux.LightAPI)) if hasattr(UsdLux, 'LightAPI') else prim.IsA(UsdLux.Light)):
if len(prim.GetChildren()) <= 1:
return False
else:
if len(prim.GetChildren()) == 0:
return False
if objects["node_open"]:
return False
else:
return True
def show_close_tree(objects): # pragma: no cover
"""Unused"""
if not "prim_list" in objects:
return False
prim = objects["prim_list"][0]
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
if prim.IsA(UsdGeom.Camera) or ((prim.HasAPI(UsdLux.LightAPI)) if hasattr(UsdLux, 'LightAPI') else prim.IsA(UsdLux.Light)):
if len(prim.GetChildren()) <= 1:
return False
else:
if len(prim.GetChildren()) == 0:
return False
if objects["node_open"]:
return True
else:
return False
# ---------------------------------------------- menu onClick functions ----------------------------------------------
def expand_all(objects):
prim = None
if "hovered_prim" in objects and objects["hovered_prim"]:
prim = objects["hovered_prim"]
elif "prim_list" in objects and objects["prim_list"]:
prim = objects["prim_list"]
if not prim:
return
if isinstance(prim, list):
prim_list = prim
else:
prim_list = [prim]
def recurse_expand(prim):
objects["stage_win"].context_menu_handler(
cmd="opentree", prim_path=prim.GetPath().pathString
)
for p in prim.GetChildren():
recurse_expand(p)
for p in prim_list:
if isinstance(p, Usd.Prim):
recurse_expand(p)
def expand_to(objects, kind):
prim = None
if "hovered_prim" in objects and objects["hovered_prim"]:
prim = objects["hovered_prim"]
elif "prim_list" in objects and objects["prim_list"]:
prim = objects["prim_list"]
if not prim:
return
if isinstance(prim, list):
prim_list = prim
else:
prim_list = [prim]
def recurse_expand(prim, kind):
expand = False
model = Usd.ModelAPI(prim)
if model.GetKind() != kind:
for p in prim.GetChildren():
expand = recurse_expand(p, kind) or expand
else:
# do not expand the target kind
return True
if expand:
objects["stage_win"].context_menu_handler(
cmd="opentree", prim_path=prim.GetPath().pathString
)
return expand
for p in prim_list:
if isinstance(p, Usd.Prim):
recurse_expand(p, kind)
def collapse_all(objects):
prim = None
if "hovered_prim" in objects and objects["hovered_prim"]:
prim = objects["hovered_prim"]
elif "prim_list" in objects and objects["prim_list"]:
prim = objects["prim_list"]
if not prim:
return
if isinstance(prim, list):
prim_list = prim
else:
prim_list = [prim]
for p in prim_list:
if isinstance(p, Usd.Prim):
objects["stage_win"].context_menu_handler(
cmd="closetree", prim_path=p.GetPath().pathString
)
def collapse_to(objects, kind):
prim = None
if "hovered_prim" in objects and objects["hovered_prim"]:
prim = objects["hovered_prim"]
elif "prim_list" in objects and objects["prim_list"]:
prim = objects["prim_list"]
if not prim:
return
if isinstance(prim, list):
prim_list = prim
else:
prim_list = [prim]
def recurse_collapse(prim, kind):
collapse = False
model = Usd.ModelAPI(prim)
if model.GetKind() != kind:
for p in prim.GetChildren():
collapse = recurse_collapse(p, kind) or collapse
else:
collapse = True
if collapse:
objects["stage_win"].context_menu_handler(
cmd="closetree", prim_path=prim.GetPath().pathString
)
for p in prim_list:
if isinstance(p, Usd.Prim):
recurse_collapse(p, kind)
def link_selected(link_or_unlink, layer_identifier, hierarchy, objects): # pragma: no cover
prim_list = objects.get("prim_list", None)
if not prim_list:
return
prim_paths = []
for prim in prim_list:
prim_paths.append(prim.GetPath())
if link_or_unlink:
command = "LinkSpecs"
else:
command = "UnlinkSpecs"
omni.kit.commands.execute(
command,
spec_paths=prim_paths,
layer_identifiers=layer_identifier,
hierarchy=hierarchy
)
def lock_selected(lock_or_unlock, hierarchy, objects):
prim_list = objects.get("prim_list", None)
if not prim_list:
return
prim_paths = []
for prim in prim_list:
prim_paths.append(prim.GetPath())
if lock_or_unlock:
command = "LockSpecs"
else:
command = "UnlockSpecs"
omni.kit.commands.execute(
command,
spec_paths=prim_paths,
hierarchy=hierarchy
)
def select_linked_prims(objects): # pragma: no cover
usd_context = omni.usd.get_context()
links = omni.kit.usd.layers.get_all_spec_links(usd_context)
prim_paths = [spec_path for spec_path in links.keys() if Sdf.Path(spec_path).IsPrimPath()]
if prim_paths:
old_prim_paths = usd_context.get_selection().get_selected_prim_paths()
omni.kit.commands.execute(
"SelectPrims", old_selected_paths=old_prim_paths,
new_selected_paths=prim_paths, expand_in_stage=True
)
def select_locked_prims(objects):
usd_context = omni.usd.get_context()
locked_specs = omni.kit.usd.layers.get_all_locked_specs(usd_context)
prim_paths = [spec_path for spec_path in locked_specs if Sdf.Path(spec_path).IsPrimPath()]
if prim_paths:
old_prim_paths = usd_context.get_selection().get_selected_prim_paths()
omni.kit.commands.execute(
"SelectPrims", old_selected_paths=old_prim_paths,
new_selected_paths=prim_paths, expand_in_stage=True
)
def clear_default_prim(objects):
objects["stage"].ClearDefaultPrim()
def set_default_prim(objects):
objects["stage"].SetDefaultPrim(objects["prim_list"][0])
def show_create_menu(objects):
prim_list = objects["prim_list"] if "prim_list" in objects else None
omni.kit.context_menu.get_instance().build_create_menu(
objects, prim_list, omni.kit.context_menu.get_menu_dict("CREATE", "omni.kit.widget.stage")
)
omni.kit.context_menu.get_instance().build_add_menu(
objects, prim_list, omni.kit.context_menu.get_menu_dict("ADD", "omni.kit.widget.stage")
)
def bind_material_to_prim_dialog(objects):
if not "prim_list" in objects:
return
omni.kit.material.library.bind_material_to_prims_dialog(objects["stage"], objects["prim_list"])
def bind_material_to_selected_prims(objects):
if not all(item in objects for item in ["hovered_prim", "prim_list"]):
return
material_prim = objects["hovered_prim"]
prim_paths = [i.GetPath() for i in objects["prim_list"]]
omni.kit.commands.execute(
"BindMaterial", prim_path=prim_paths, material_path=material_prim.GetPath().pathString, strength=None
)
def has_rename_function(objects):
return "rename_item" in objects["function_list"]
def rename_prim(objects):
if not "prim_list" in objects:
return False
prim_list = objects["prim_list"]
if len(prim_list) != 1:
return False
prim = prim_list[0]
if "rename_item" in objects["function_list"]:
objects["function_list"]["rename_item"](prim.GetPath().pathString)
@staticmethod
def add_menu(menu_dict):
"""
Add the menu to the end of the context menu. Return the object that
should be alive all the time. Once the returned object is destroyed,
the added menu is destroyed as well.
"""
return omni.kit.context_menu.add_menu(menu_dict, "MENU", "omni.kit.widget.stage")
@staticmethod
def add_create_menu(menu_dict):
"""
Add the menu to the end of the stage context create menu. Return the object that
should be alive all the time. Once the returned object is destroyed,
the added menu is destroyed as well.
"""
return omni.kit.context_menu.add_menu(menu_dict, "CREATE", "omni.kit.widget.stage")
| 29,955 | Python | 37.306905 | 131 | 0.441362 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_actions.py | import carb
import omni.usd
import omni.kit.actions.core
import omni.kit.hotkeys.core
from omni.kit.hotkeys.core import KeyCombination, get_hotkey_registry
from .export_utils import ExportPrimUSD
def post_notification(message: str, info: bool = False, duration: int = 3):
try:
import omni.kit.notification_manager as nm
if info:
type = nm.NotificationStatus.INFO
else:
type = nm.NotificationStatus.WARNING
nm.post_notification(message, status=type, duration=duration)
except ModuleNotFoundError:
carb.log_warn(message)
def save_prim(objects):
if not objects:
prim_list = []
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
stage = omni.usd.get_context().get_stage()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim:
prim_list.append(prim)
objects = {"prim_list": prim_list}
elif isinstance(objects, tuple):
objects = objects[0]
if not "prim_list" in objects:
return False
prim_list = objects["prim_list"]
if len(prim_list) == 0:
post_notification("Cannot save prims as no prims are selected")
elif len(prim_list) == 1:
ExportPrimUSD(select_msg=f"Save \"{prim_list[0].GetName()}\" As...").export(prim_list)
else:
ExportPrimUSD(select_msg=f"Save Prims As...").export(prim_list)
def register_actions(extension_id, owner):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Stage Actions"
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"save_prim",
lambda *o: save_prim(o),
display_name="Stage->Save Prim",
description="Save Prim",
tag=actions_tag,
)
def deregister_actions(extension_id, owner):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
hotkey_registry = get_hotkey_registry()
for key_reg in owner._registered_hotkeys:
hotkey_registry.deregister_hotkey(key_reg)
owner._registered_hotkeys = []
| 2,191 | Python | 31.235294 | 94 | 0.651301 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/utils.py | import carb
import traceback
import functools
def handle_exception(func):
"""
Decorator to print exception in async functions
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
| 475 | Python | 21.666666 | 60 | 0.6 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_widget.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageWidget"]
from .column_menu import ColumnMenuDelegate
from .column_menu import ColumnMenuItem
from .column_menu import ColumnMenuModel
from .event import Event, EventSubscription
from .stage_column_delegate_registry import StageColumnDelegateRegistry
from .stage_delegate import StageDelegate
from .stage_icons import StageIcons
from .stage_model import StageModel
from .stage_settings import StageSettings
from .stage_style import Styles as StageStyles
from .stage_filter import StageFilterButton
from pxr import Sdf
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from pxr import UsdSkel
from typing import Callable
from typing import List
from typing import Tuple
import asyncio
import carb.settings
import omni.kit.app
import omni.ui as ui
import omni.kit.notification_manager as nm
import omni.kit.usd.layers as layers
import weakref
class StageWidget:
"""The Stage widget"""
def __init__(
self, stage: Usd.Stage,
columns_accepted: List[str] = None,
columns_enabled: List[str] = None,
lazy_payloads: bool = False,
**kwargs
):
"""
Constructor.
Args:
stage (Usd.Stage): The instance of USD stage to be managed by this widget.
columns_accepted (List[str]): The list of columns that are supported. By default, it's all registered
columns if this arg is not provided.
columns_enabled (List[str]): The list of columns that are enabled when the widget is shown by default.
lazy_payloads (bool): Whether it should load all payloads when stage items are shown or not.
False by default.
Kwargs:
children_reorder_supported (bool): Whether it should enable children reorder support or not. By default,
children reorder support is disabled, which means you cannot reorder children in the widget, and
renaming name of prim will put the prim at the end of the children list. REMINDER: Enabling this
option has performance penalty as it will trigger re-composition to the parent of the reordered/renamed
prims.
show_prim_display_name (bool): Whether it's to show displayName from prim's metadata or the name of the prim.
By default, it's False, which means it shows name of the prim.
auto_reload_prims (bool): Whether it will auto-reload prims if there are any new changes from disk. By
default, it's disabled.
Other:
All other arguments inside kwargs except the above 3 will be passed as params to the ui.Frame for the
stage widget.
"""
# create_stage_update_node` calls `_on_attach`, and the models will be created there.
self._model = None
self._tree_view = None
self._tree_view_flat = None
self._delegate = StageDelegate()
self._delegate.expand_fn = self.expand
self._delegate.collapse_fn = self.collapse
self._selection = None
self._stage_settings = StageSettings()
self._stage_settings.children_reorder_supported = kwargs.pop("children_reorder_supported", False)
self._stage_settings.show_prim_displayname = kwargs.pop("show_prim_display_name", False)
self._stage_settings.auto_reload_prims = kwargs.pop("auto_reload_prims", False)
# Initialize columns
self._columns_accepted = columns_accepted
self._columns_enabled = columns_enabled
self._lazy_payloads = lazy_payloads
self._column_widths = []
self._min_column_widths = []
self._column_model = ColumnMenuModel(self._columns_enabled, self._columns_accepted)
self._column_delegate = ColumnMenuDelegate()
self._column_changed_sub = self._column_model.subscribe_item_changed_fn(self._on_column_changed)
# We need it to be able to add callback to StageWidget
self._column_changed_event = Event()
self.open_stage(stage)
self._root_frame = ui.Frame(**kwargs)
self.build_layout()
# The filtering logic
self._begin_filter_subscription = self._search.subscribe_begin_edit_fn(
lambda _: StageWidget._set_widget_visible(self._search_label, False)
)
self._end_filter_subscription = self._search.subscribe_end_edit_fn(
lambda m: self._filter_by_text(m.as_string)
or StageWidget._set_widget_visible(self._search_label, not m.as_string)
)
# Update icons when they changed
self._icons_subscription = StageIcons().subscribe_icons_changed(self.update_icons)
self._expand_task = None
def build_layout(self):
"""Creates all the widgets in the window"""
style = StageStyles.STAGE_WIDGET
use_default_style = (
carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False
)
if not use_default_style:
self._root_frame.set_style(style)
with self._root_frame:
# Options menu
self._options_menu = ui.Menu("Options")
with self._options_menu:
ui.MenuItem("Options", enabled=False)
ui.Separator()
def _set_auto_reload_prims(value):
self.auto_reload_prims = value
stage_model = self.get_model()
all_stage_items = stage_model._get_all_stage_items_from_cache()
if not all_stage_items:
return
for stage_item in all_stage_items:
stage_item.update_flags()
stage_model._item_changed(stage_item)
property_window = omni.kit.window.property.get_window()
if property_window:
property_window.request_rebuild()
ui.MenuItem(
"Auto Reload Primitives",
checkable=True,
checked=self.auto_reload_prims,
checked_changed_fn=_set_auto_reload_prims
)
ui.MenuItem("Reload Outdated Primitives", triggered_fn=self._on_reload_all_prims)
ui.Separator()
self._options_menu_reset = ui.MenuItem("Reset", triggered_fn=self._on_reset)
ui.Separator()
ui.MenuItem(
"Flat List Search",
checkable=True,
checked=self._stage_settings.flat_search,
checked_changed_fn=self._on_flat_changed,
)
ui.MenuItem("Show Root", checkable=True, checked_changed_fn=self._on_show_root_changed)
def _set_display_name(value):
self.show_prim_display_name = value
ui.MenuItem(
"Show Display Names",
checkable=True,
checked=self.show_prim_display_name,
checked_changed_fn=_set_display_name
)
def _children_reorder_supported(value):
self.children_reorder_supported = value
ui.MenuItem(
"Enable Children Reorder",
checkable=True,
checked=self.children_reorder_supported,
checked_changed_fn=_children_reorder_supported
)
with ui.Menu("Columns"):
# Sub-menu with list view, so it's possible to reorder it.
with ui.Frame():
self._column_list = ui.TreeView(
self._column_model,
delegate=self._column_delegate,
root_visible=False,
drop_between_items=True,
width=150,
)
self._column_list.set_selection_changed_fn(self._on_column_selection_changed)
with ui.VStack(style=style):
ui.Spacer(height=4)
with ui.ZStack(height=0):
with ui.HStack(spacing=4):
# Search filed
self._search = ui.StringField(name="search").model
# Filter button
self._filter_button = StageFilterButton(self)
# Options button
ui.Button(name="options", width=20, height=20, clicked_fn=lambda: self._options_menu.show())
# The label on the top of the search field
self._search_label = ui.Label("Search", name="search")
ui.Spacer(height=7)
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style_type_name_override="TreeView.ScrollingFrame",
mouse_pressed_fn=lambda x, y, b, _: self._delegate.on_mouse_pressed(
b, self._model and self._model.stage, None, False
),
):
with ui.ZStack():
# Sometimes we need to switch between regular tree and flat list. To do it fast we keep
# both widgets.
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
drop_between_items=True,
header_visible=True,
root_visible=False,
columns_resizable=True,
)
self._tree_view_flat = ui.TreeView(
self._model,
delegate=self._delegate,
header_visible=True,
root_visible=False,
columns_resizable=True,
visible=False,
)
self.set_columns_widths()
def update_filter_menu_state(self, filter_type_list: list):
"""
Enable filters.
Args:
filter_type_list (list): List of usd types to be enabled. If not all usd types are pre-defined, hide filter button and Reset in options button
"""
unknown_types = self._filter_button.enable_filters(filter_type_list)
if unknown_types:
self._options_menu_reset.visible = False
def set_selection_watch(self, selection):
self._selection = selection
if self._selection:
if self._tree_view.visible:
self._selection.set_tree_view(self._tree_view)
if self._tree_view_flat.visible:
self._selection.set_tree_view(self._tree_view_flat)
def get_model(self) -> StageModel:
if self._tree_view.visible:
return self._tree_view.model
elif self._tree_view_flat.visible:
return self._tree_view_flat.model
return None
def expand(self, path: Sdf.Path):
"""Set the given path expanded"""
if isinstance(path, str):
path = Sdf.Path(path)
if self._tree_view.visible:
widget = self._tree_view
elif self._tree_view_flat.visible:
widget = self._tree_view_flat
else:
return
# Get the selected item and its parents. Expand all the parents of the new selection.
full_chain = widget.model.find_full_chain(path.pathString)
if full_chain:
for item in full_chain:
widget.set_expanded(item, True, False)
def collapse(self, path: Sdf.Path):
"""Set the given path collapsed"""
if isinstance(path, str):
path = Sdf.Path(path)
if self._tree_view.visible:
widget = self._tree_view
elif self._tree_view_flat.visible:
widget = self._tree_view_flat
else:
return
widget.set_expanded(widget.model.find(path), False, True)
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
self._cancel_expand_task()
self._begin_filter_subscription = None
self._end_filter_subscription = None
self._icons_subscription = None
self._tree_view = None
self._tree_view_flat = None
self._search_label = None
if self._model:
self._model.destroy()
self._model = None
if self._delegate:
self._delegate.destroy()
self._delegate = None
self._stage_subscription = None
self._selection = None
self._options_menu = None
self._filter_button.destroy()
self._filter_button = None
self._root_frame = None
self._column_list = None
self._column_model.destroy()
self._column_model = None
self._column_delegate.destroy()
self._column_delegate = None
self._column_changed_sub = None
def _clear_filter_types(self):
self._filter_button.model.reset()
def _on_flat_changed(self, flat):
"""Toggle flat/not flat search"""
# Disable search. It makes the layout resetting to the original state
self._filter_by_text("")
self._clear_filter_types()
# Change flag and clear the model
self._stage_settings.flat_search = flat
self._search.set_value("")
self._search_label.visible = True
def _on_reset(self):
"""Toggle "Reset" menu"""
self._model.reset()
def _on_show_root_changed(self, show):
"""Called to trigger "Show Root" menu item"""
self._tree_view.root_visible = show
@property
def show_prim_display_name(self):
return self._stage_settings.show_prim_displayname
@show_prim_display_name.setter
def show_prim_display_name(self, show):
if self._stage_settings.show_prim_displayname != show:
self._stage_settings.show_prim_displayname = show
self._model.show_prim_displayname = show
@property
def children_reorder_supported(self):
return self._stage_settings.children_reorder_supported
@children_reorder_supported.setter
def children_reorder_supported(self, enabled):
self._stage_settings.children_reorder_supported = enabled
self._model.children_reorder_supported = enabled
@property
def auto_reload_prims(self):
return self._stage_settings.auto_reload_prims
def _on_reload_all_prims(self):
self._on_reload_prims(not_in_session=False)
def _on_reload_prims(self, not_in_session=True):
if not self._model:
return
stage = self._model.stage
if not stage:
return
usd_context = omni.usd.get_context_from_stage(stage)
if not usd_context:
return
layers_state_interface = layers.get_layers_state(usd_context)
if not_in_session:
# this will auto reload all layers that are not currently in a live session ( silently )
layers_state_interface.reload_outdated_non_sublayers()
else:
# this will reload all layers but will confirm with user if it is in a live session
all_outdated_layers = layers_state_interface.get_all_outdated_layer_identifiers(not_in_session)
try:
from omni.kit.widget.live_session_management.utils import reload_outdated_layers
reload_outdated_layers(all_outdated_layers, usd_context)
except ImportError:
# If live session management is not enabled. Skipps UI prompt to reload it directly.
layers.LayerUtils.reload_all_layers(all_outdated_layers)
@auto_reload_prims.setter
def auto_reload_prims(self, enabled):
if self._stage_settings.auto_reload_prims != enabled:
self._stage_settings.auto_reload_prims = enabled
if enabled:
self._on_reload_prims()
@staticmethod
def _set_widget_visible(widget: ui.Widget, visible):
"""Utility for using in lambdas"""
widget.visible = visible
def _get_geom_primvar(self, prim, primvar_name):
primvars_api = UsdGeom.PrimvarsAPI(prim)
return primvars_api.GetPrimvar(primvar_name)
def _filter_by_flattener_basemesh(self, enabled):
self._filter_by_lambda({"_is_prim_basemesh": lambda prim: self._get_geom_primvar(prim, "materialFlattening_isBaseMesh")}, enabled)
def _filter_by_flattener_decal(self, enabled):
self._filter_by_lambda({"_is_prim_decal": lambda prim: self._get_geom_primvar(prim, "materialFlattening_isDecal")}, enabled)
def _filter_by_visibility(self, enabled):
"""Filter Hidden On/Off"""
def _is_prim_hidden(prim):
imageable = UsdGeom.Imageable(prim)
return imageable.ComputeVisibility() == UsdGeom.Tokens.invisible
self._filter_by_lambda({"_is_prim_hidden": _is_prim_hidden}, enabled)
def _filter_by_type(self, usd_types, enabled):
"""
Set filtering by USD type.
Args:
usd_types: The type or the list of types it's necessary to add or remove from filters.
enabled: True to add to filters, False to remove them from the filter list.
"""
if not isinstance(usd_types, list):
usd_types = [usd_types]
for usd_type in usd_types:
# Create a lambda filter
fn = lambda p, t=usd_type: p.IsA(t)
name_to_fn_dict = {Tf.Type(usd_type).typeName: fn}
self._filter_by_lambda(name_to_fn_dict, enabled)
def _filter_by_api_type(self, api_types, enabled):
"""
Set filtering by USD api type.
Args:
api_types: The api type or the list of types it's necessary to add or remove from filters.
enabled: True to add to filters, False to remove them from the filter list.
"""
if not isinstance(api_types, list):
api_types = [api_types]
for api_type in api_types:
# Create a lambda filter
fn = lambda p, t=api_type: p.HasAPI(t)
name_to_fn_dict = {Tf.Type(api_type).typeName: fn}
self._filter_by_lambda(name_to_fn_dict, enabled)
def _filter_by_lambda(self, filters: dict, enabled):
"""
Set filtering by lambda.
Args:
filters: The dictionary of this form: {"type_name_string", lambda prim: True}. When lambda is True,
the prim will be shown.
enabled: True to add to filters, False to remove them from the filter list.
"""
if self._tree_view.visible:
tree_view = self._tree_view
else:
tree_view = self._tree_view_flat
if enabled:
tree_view.model.filter(add=filters)
# Filtering mode always expanded.
tree_view.keep_alive = True
tree_view.keep_expanded = True
self._delegate.set_highlighting(enable=True)
if self._selection:
self._selection.enable_filtering_checking(True)
else:
for lambda_name in filters:
keep_filtering = tree_view.model.filter(remove=lambda_name)
if not keep_filtering:
# Filtering is finished. Return it back to normal.
tree_view.keep_alive = False
tree_view.keep_expanded = False
self._delegate.set_highlighting(enable=False)
if self._selection:
self._selection.enable_filtering_checking(False)
def _filter_by_text(self, filter_text: str):
"""Set the search filter string to the models and widgets"""
tree_view = self._tree_view_flat if self._stage_settings.flat_search else self._tree_view
if self._selection:
self._selection.set_filtering(filter_text)
# It's only set when the visibility is changed. We need it to move the filtering data from the flat model to
# the tree model.
was_visible_before = None
is_visible_now = None
if filter_text and self._stage_settings.flat_search:
# Check if _tree_view_flat is just became visible
self._model.flat = True
if self._tree_view.visible:
was_visible_before = self._tree_view
is_visible_now = self._tree_view_flat
self._tree_view.visible = False
self._tree_view_flat.visible = True
else:
# Check if _tree_view is just became visible
self._model.flat = False
if self._tree_view_flat.visible:
was_visible_before = self._tree_view_flat
is_visible_now = self._tree_view
self._tree_view_flat.visible = False
self._tree_view.visible = True
tree_view.keep_alive = not not filter_text
tree_view.keep_expanded = not not filter_text
tree_view.model.filter_by_text(filter_text)
if was_visible_before and is_visible_now:
# Replace treeview in the selection model will allow to use only one selection watch for two treeviews
if self._selection:
self._selection.set_tree_view(is_visible_now)
self._delegate.set_highlighting(text=filter_text)
def _on_column_changed(self, column_model: ColumnMenuModel, item: ColumnMenuItem = None):
"""Called by Column Model when columns are changed or toggled"""
all_columns = column_model.get_columns()
column_delegate_names = [i[0] for i in all_columns if i[1]]
# Name column should always be shown
if "Name" not in column_delegate_names:
column_delegate_names.append("Name")
column_delegate_types = [
StageColumnDelegateRegistry().get_column_delegate(name) for name in column_delegate_names
]
# Create the column delegates
column_delegates = [delegate_type() for delegate_type in column_delegate_types if delegate_type]
column_delegates.sort(key=lambda item: item.order)
# Set the model
self._delegate.set_column_delegates(column_delegates)
if self._model:
self._model.set_item_value_model_count(len(column_delegates))
# Set the column widths
self._column_widths = [d.initial_width for d in column_delegates]
self._min_column_widths = [d.minimum_width for d in column_delegates]
self.set_columns_widths()
# Callback if someone subscribed to the StageWidget events
self._column_changed_event(all_columns)
def _on_column_selection_changed(self, selection):
self._column_list.selection = []
def set_columns_widths(self):
for w in [self._tree_view, self._tree_view_flat]:
if not w:
continue
w.column_widths = self._column_widths
w.min_column_widths = self._min_column_widths
w.dirty_widgets()
def subscribe_columns_changed(self, fn: Callable[[List[Tuple[str, bool]]], None]) -> EventSubscription:
return EventSubscription(self._column_changed_event, fn)
def _cancel_expand_task(self):
if self._expand_task and not self._expand_task.done():
self._expand_task.cancel()
self._expand_task = None
def open_stage(self, stage: Usd.Stage):
"""Called when opening a new stage"""
if self._model:
self._clear_filter_types()
self._model.destroy()
# Sometimes we need to switch between regular tree and flat list. To do it fast we keep both models.
self._model = StageModel(
stage, load_payloads=self._lazy_payloads,
children_reorder_supported=self._stage_settings.children_reorder_supported,
show_prim_displayname=self._stage_settings.show_prim_displayname
)
# Don't regenerate delegate as it's constructed already and treeview references to it.
self._delegate.model = self._model
self._on_column_changed(self._column_model)
# Widgets are not created if `_on_attach` is called from the constructor.
if self._tree_view:
self._tree_view.model = self._model
if self._tree_view_flat:
self._tree_view_flat.model = self._model
async def expand(tree_view, path_str: str):
await omni.kit.app.get_app().next_update_async()
# It's possible that weakly referenced tree view is not existed anymore.
if not tree_view:
return
chain_to_world = tree_view.model.find_full_chain(path_str)
if chain_to_world:
for item in chain_to_world:
tree_view.set_expanded(item, True, False)
self._expand_task = None
# Expand default or the only prim or World
if self._tree_view and stage:
default: Usd.Prim = stage.GetDefaultPrim()
if default:
# We have default prim
path_str = default.GetPath().pathString
else:
root: Usd.Prim = stage.GetPseudoRoot()
children: List[Usd.Prim] = root.GetChildren()
if children and len(children) == 1:
# Root has the only child
path_str = children[0].GetPath().pathString
else:
# OK, try to open /World
path_str = "/World"
self._cancel_expand_task()
self._expand_task = asyncio.ensure_future(expand(weakref.proxy(self._tree_view), path_str))
def update_icons(self):
"""Called to update icons in the TreeView"""
self._tree_view.dirty_widgets()
self._tree_view_flat.dirty_widgets()
def get_context_menu(self):
return self._delegate._context_menu
| 26,733 | Python | 38.430678 | 154 | 0.588299 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_item.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageItem"]
import carb
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.usd
from .models import PrimNameModel, TypeModel, VisibilityModel
from pxr import Sdf, UsdGeom, Usd
from typing import List
class StageItem(ui.AbstractItem):
"""
A single AbstractItemModel item that represents a single prim.
StageItem is a cached view of the prim.
"""
def __init__(
self,
path: Sdf.Path,
stage,
stage_model,
# Deprecated
flat=False,
root_identifier=None,
load_payloads=False,
check_missing_references=False,
):
super().__init__()
self.__stage_model = stage_model
# Internal access
self._path = path
# Prim handle
self.__prim = None
# Filtering
self.filtered = None
# True if it has any descendant that is filtered
self.child_filtered = None
# defaultPrim
self.__is_default = False
# True if it has missing references
self.__missing_references = None
# True if it has references authored
self.__has_references = False
# All references/payloads for this prim
self.__payrefs = set()
# If this prim includes references/payloads that are out of sync.
self.__is_outdated = False
# True if it has payloads authored
self.__has_payloads = False
# True if it's visible
self.__visible = True
# True if is in session
self.__in_session = False
# True if it's instanceable
self.__instanceable = False
# True if this item should be auto-loaded when its
# references or payloads are outdated.
self.__auto_reload = False
# True if it's children of instance.
self.__instance_proxy = False
self.__display_name = None
# Lazy load
self.__flags_updated = True
# Models for builtin columns. Those models
# will only be accessed internally.
self.__name_model = None
self.__type_model = None
self.__visibility_model = None
def destroy(self):
self.__stage = None
self.__stage_model = None
self.__payrefs.clear()
@property
def path(self):
"""Prim path."""
return self._path
@property
def stage_model(self):
"""StageModel this StageItem belongs to."""
return self.__stage_model
@property
def usd_context(self) -> omni.usd.UsdContext:
return self.__stage_model.usd_context if self.__stage_model else None
@property
def stage(self) -> Usd.Stage:
"""USD stage the prim belongs to."""
return self.__stage_model.stage if self.__stage_model else None
@property
def payrefs(self) -> List[str]:
"""All external references and payloads that influence this prim."""
self.__update_flags_internal()
return list(self.__payrefs)
@property
def is_default(self) -> bool:
"""Whether this prim is the default prim or not."""
self.__update_flags_internal()
return self.__is_default
@property
def is_outdated(self) -> bool:
"""Whether this prim includes references or payloads that has new changes to fetch or not."""
self.__update_flags_internal()
return self.__is_outdated
@property
def in_session(self) -> bool:
"""Whether this prim includes references or payloads that are in session or not."""
self.__update_flags_internal()
return self.__in_session
@property
def auto_reload(self):
"""Whether this prim is configured as auto-reload when its references or payloads are outdated."""
self.__update_flags_internal()
return self.__auto_reload
@property
def root_identifier(self) -> str:
"""Returns the root layer's identifier of the stage this prim belongs to."""
stage = self.stage
return stage.GetRootLayer().identifier if stage else None
@property
def instance_proxy(self) -> bool:
"""Whether the prim is an instance proxy or not."""
self.__update_flags_internal()
return self.__instance_proxy
@property
def instanceable(self) -> bool:
"""True when it has `instanceable` flag enabled"""
self.__update_flags_internal()
return self.__instanceable
@property
def visible(self) -> bool:
self.__update_flags_internal()
return self.__visible
@property
def payloads(self):
"""True when the prim has authored payloads"""
self.__update_flags_internal()
return self.__has_payloads
@property
def references(self) -> bool:
"""True when the prim has authored references"""
self.__update_flags_internal()
return self.__has_references
@property
def name(self) -> str:
"""The path name."""
return self._path.name
@property
def display_name(self) -> str:
"""The display name of prim inside the metadata."""
self.__update_flags_internal()
return self.__display_name or self.name
@property
def prim(self):
"""The prim handle."""
self.__update_flags_internal()
return self.__prim
@property
def active(self):
"""True if the prim is active."""
self.__update_flags_internal()
if not self.__prim:
return False
return self.__prim.IsActive()
@property
def type_name(self):
"""Type name of the prim."""
self.__update_flags_internal()
prim = self.__prim
if not prim:
return ""
return prim.GetTypeName()
@property
def has_missing_references(self):
"""
Whether the prim includes any missing references or payloads or not.
It checkes the references/payloads recursively.
"""
self.__update_flags_internal()
return self.__missing_references
@property
def children(self):
"""Returns children items. If children are not populated yet, they will be populated."""
return self.__stage_model.get_item_children(self)
def update_flags(self, prim=None):
"""Refreshes item states from USD."""
# Lazy load.
self.__flags_updated = True
def __update_prim(self):
stage = self.stage
self.__prim = stage.GetPrimAtPath(self._path) if stage else None
def __update_visibility(self):
prim = self.prim
if prim and prim.IsA(UsdGeom.Imageable):
visibility = UsdGeom.Imageable(prim).ComputeVisibility()
self.__visible = visibility != UsdGeom.Tokens.invisible
else:
self.__visible = False
def __get_payrefs(self):
if not self.__has_references and not self.__has_payloads:
return set()
result = set()
references = omni.usd.get_composed_references_from_prim(self.__prim)
payloads = omni.usd.get_composed_payloads_from_prim(self.__prim)
for reference, layer in payloads + references:
if not reference.assetPath:
continue
absolute_path = layer.ComputeAbsolutePath(reference.assetPath)
result.add(absolute_path)
return result
def __get_live_status(self):
if not self.__stage_model.usd_context:
return
if self.__payrefs:
live_syncing = layers.get_live_syncing(self.__stage_model.usd_context)
for absolute_path in self.__payrefs:
if live_syncing.is_prim_in_live_session(self.prim.GetPath(), absolute_path):
return True
return False
def __get_outdated_status(self):
if not self.__stage_model.usd_context:
return
if self.__payrefs:
layers_state_interface = layers.get_layers_state(self.__stage_model.usd_context)
for absolute_path in self.__payrefs:
if layers_state_interface.is_layer_outdated(absolute_path):
return True
return False
def __get_auto_reload_status(self):
if not self.__stage_model.usd_context:
return
if carb.settings.get_settings().get_as_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS):
if not self.is_outdated:
return True
if self.__payrefs:
layers_state_interface = layers.get_layers_state(self.__stage_model.usd_context)
for absolute_path in self.__payrefs:
if layers_state_interface.is_auto_reload_layer(absolute_path):
return True
return False
def __has_missing_payrefs(self):
prim = self.prim
# If prim is not loaded.
if prim and not prim.IsLoaded():
return False
for identifier in self.payrefs:
layer = Sdf.Find(identifier)
if not layer:
return True
return False
def __update_flags_internal(self):
# Param is for back compitability.
if not self.__flags_updated:
return
self.__flags_updated = False
self.__update_prim()
prim = self.prim
if not prim:
return
self.__is_default = prim == self.stage.GetDefaultPrim()
self.__display_name = omni.usd.editor.get_display_name(prim) or ""
# Refresh model to decide which name to display.
if self.__name_model:
self.__name_model.rebuild()
self.__update_visibility()
self.__has_references = prim.HasAuthoredReferences()
self.__has_payloads = prim.HasAuthoredPayloads()
self.__payrefs = self.__get_payrefs()
self.__instanceable = prim.IsInstanceable()
self.__instance_proxy = prim.IsInstanceProxy()
self.__missing_references = self.__has_missing_payrefs()
self.__is_outdated = self.__get_outdated_status()
self.__in_session = self.__get_live_status()
self.__auto_reload = self.__get_auto_reload_status()
def __repr__(self):
return f"<Omni::UI Stage Item '{self._path}'>"
def __str__(self):
return f"{self._path}"
# Internal properties
@property
def name_model(self):
self.__update_flags_internal()
if not self.__name_model:
self.__name_model = PrimNameModel(self)
return self.__name_model
@property
def type_model(self):
self.__update_flags_internal()
if not self.__type_model:
self.__type_model = TypeModel(self)
return self.__type_model
@property
def visibility_model(self):
self.__update_flags_internal()
if not self.__visibility_model:
self.__visibility_model = VisibilityModel(self)
return self.__visibility_model
@property
def is_flat(self):
return self.__stage_model.flat if self.__stage_model else False
@is_flat.setter
def is_flat(self, flat: bool):
# Rebuild it only when it's populated
if self.__name_model:
self.__name_model.rebuild()
@property
def load_payloads(self):
return self.stage_model.load_payloads if self.stage_model else None
# Deprecated functions
@property
def check_missing_references(self):
"""Deprecated: It will always check missing references now."""
return True
@check_missing_references.setter
def check_missing_references(self, value):
"""Deprecated."""
pass
def set_default_prim(self, is_default):
"""Deprecated."""
pass
| 12,211 | Python | 26.198218 | 106 | 0.598641 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/export_utils.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["export", "Export"]
import os
from pathlib import Path
from typing import List
from functools import partial
from pxr import Sdf, Gf, Usd, UsdGeom, UsdUI
from omni.kit.window.file_exporter import get_file_exporter
from omni.kit.helper.file_utils import FileEventModel, FILE_SAVED_EVENT
import carb
import carb.tokens
import omni.kit.app
import omni.client
import omni.usd
last_dir = None
# OM-48055: Add subscription to stage open to update default save directory
_default_save_dir = None
def __on_stage_open(event: carb.events.IEvent):
"""Update default save directory on stage open."""
if event.type == int(omni.usd.StageEventType.OPENED):
stage = omni.usd.get_context().get_stage()
global _default_save_dir
_default_save_dir = os.path.dirname(stage.GetRootLayer().realPath)
def _get_stage_open_sub():
stage_open_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(__on_stage_open,
name="Export Selected Prim Stage Open")
return stage_open_sub
def __set_xform_prim_transform(prim: UsdGeom.Xformable, transform: Gf.Matrix4d):
prim = UsdGeom.Xformable(prim)
_, _, scale, rot_mat, translation, _ = transform.Factor()
angles = rot_mat.ExtractRotation().Decompose(Gf.Vec3d.ZAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis())
rotation = Gf.Vec3f(angles[2], angles[1], angles[0])
for xform_op in prim.GetOrderedXformOps():
attr = xform_op.GetAttr()
prim.GetPrim().RemoveProperty(attr.GetName())
prim.ClearXformOpOrder()
UsdGeom.XformCommonAPI(prim).SetTranslate(translation)
UsdGeom.XformCommonAPI(prim).SetRotate(rotation)
UsdGeom.XformCommonAPI(prim).SetScale(Gf.Vec3f(scale[0], scale[1], scale[2]))
def export(path: str, prims: List[Usd.Prim]):
"""Export prim to external USD file"""
filename = Path(path).stem
# TODO: stage.Flatten() is extreamly slow
stage = omni.usd.get_context().get_stage()
source_layer = stage.Flatten()
target_layer = Sdf.Layer.CreateNew(path)
target_stage = Usd.Stage.Open(target_layer)
axis = UsdGeom.GetStageUpAxis(stage)
UsdGeom.SetStageUpAxis(target_stage, axis)
# All prims will be put under /Root
root_path = Sdf.Path.absoluteRootPath.AppendChild("Root")
UsdGeom.Xform.Define(target_stage, root_path)
keep_transforms = len(prims) > 1
center_point = Gf.Vec3d(0.0)
transforms = []
if keep_transforms:
bound_box = Gf.BBox3d()
bbox_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
for prim in prims:
xformable = UsdGeom.Xformable(prim)
if xformable:
local_bound_box = bbox_cache.ComputeWorldBound(prim)
transforms.append(xformable.ComputeLocalToWorldTransform(Usd.TimeCode.Default()))
bound_box = Gf.BBox3d.Combine(bound_box, local_bound_box)
else:
transforms.append(None)
center_point = bound_box.ComputeCentroid()
else:
transforms.append(Gf.Matrix4d(1.0))
for i in range(len(transforms)):
if transforms[i]:
transforms[i] = transforms[i].SetTranslateOnly(transforms[i].ExtractTranslation() - center_point)
# Set default prim name
target_layer.defaultPrim = root_path.name
for i in range(len(prims)):
source_path = prims[i].GetPath()
if len(prims) > 1 and transforms[i]:
target_xform_path = root_path.AppendChild(source_path.name)
target_xform_path = Sdf.Path(omni.usd.get_stage_next_free_path(target_stage, target_xform_path, False))
target_xform = UsdGeom.Xform.Define(target_stage, target_xform_path)
__set_xform_prim_transform(target_xform, transforms[i])
target_path = target_xform_path.AppendChild(source_path.name)
else:
target_path = root_path.AppendChild(source_path.name)
target_path = Sdf.Path(omni.usd.get_stage_next_free_path(target_stage, target_path, False))
all_external_references = set([])
def on_prim_spec_path(root_path, prim_spec_path):
if prim_spec_path.IsPropertyPath():
return
if prim_spec_path == Sdf.Path.absoluteRootPath:
return
prim_spec = source_layer.GetPrimAtPath(prim_spec_path)
if not prim_spec or not prim_spec.HasInfo(Sdf.PrimSpec.ReferencesKey):
return
op = prim_spec.GetInfo(Sdf.PrimSpec.ReferencesKey)
items = []
items = op.ApplyOperations(items)
for item in items:
if not item.primPath.HasPrefix(root_path):
all_external_references.add(item.primPath)
# Traverse the source prim tree to find all references that are outside of the source tree.
source_layer.Traverse(source_path, partial(on_prim_spec_path, source_path))
# Copy dependencies
for path in all_external_references:
Sdf.CreatePrimInLayer(target_layer, path)
Sdf.CopySpec(source_layer, path, target_layer, path)
Sdf.CreatePrimInLayer(target_layer, target_path)
Sdf.CopySpec(source_layer, source_path, target_layer, target_path)
prim = target_stage.GetPrimAtPath(target_path)
if transforms[i]:
__set_xform_prim_transform(prim, Gf.Matrix4d(1.0))
# Edit UI info of compound
spec = target_layer.GetPrimAtPath(target_path)
attributes = spec.attributes
if UsdUI.Tokens.uiDisplayGroup not in attributes:
attr = Sdf.AttributeSpec(spec, UsdUI.Tokens.uiDisplayGroup, Sdf.ValueTypeNames.Token)
attr.default = "Material Graphs"
if UsdUI.Tokens.uiDisplayName not in attributes:
attr = Sdf.AttributeSpec(spec, UsdUI.Tokens.uiDisplayName, Sdf.ValueTypeNames.Token)
attr.default = target_path.name
if "ui:order" not in attributes:
attr = Sdf.AttributeSpec(spec, "ui:order", Sdf.ValueTypeNames.Int)
attr.default = 1024
# Save
target_layer.Save()
# OM-61553: Add exported USD file to recent files
# since the layer save will not trigger stage save event, it can't be caught automatically
# by omni.kit.menu.file.scripts stage event sub, thus we have to manually put it in the
# carb settings to trigger the update
_add_to_recent_files(path)
def _add_to_recent_files(filename: str):
"""Utility to add the filename to recent file list."""
if not filename:
return
# OM-87021: The "recentFiles" setting is deprecated. However, the welcome extension still
# reads from it so we leave this code here for the time being.
import carb.settings
recent_files = carb.settings.get_settings().get("/persistent/app/file/recentFiles") or []
recent_files.insert(0, filename)
carb.settings.get_settings().set("/persistent/app/file/recentFiles", recent_files)
# Emit a file saved event to the event stream
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(FILE_SAVED_EVENT, payload=FileEventModel(url=filename).dict())
class ExportPrimUSDLegacy:
"""
It's still used in Material Graph
"""
EXPORT_USD_EXTS = ("usd", "usda", "usdc")
def __init__(self, select_msg="Save As", save_msg="Save", save_dir=None, postfix_name=None):
self._prim = None
self._dialog = None
self._select_msg = select_msg
self._save_msg = save_msg
self._save_dir = save_dir
self._postfix_name = postfix_name
self._last_dir = None
def destroy(self):
self._prim = None
if self._dialog:
self._dialog.destroy()
self._dialog = None
def export(self, prim):
self.destroy()
if isinstance(prim, list):
self._prim = prim
else:
self._prim = [prim]
write_dir = self._save_dir
if not write_dir:
write_dir = last_dir if last_dir else ""
try:
from omni.kit.window.filepicker import FilePickerDialog
usd_filter_descriptions = [f"{ext.upper()} (*.{ext})" for ext in self.EXPORT_USD_EXTS]
usd_filter_descriptions.append("All Files (*)")
self._dialog = FilePickerDialog(
self._select_msg,
apply_button_label=self._save_msg,
current_directory=write_dir,
click_apply_handler=self.__on_apply_save,
item_filter_options=usd_filter_descriptions,
item_filter_fn=self.__on_filter_item,
)
except:
carb.log_info(f"Failed to import omni.kit.window.filepicker")
def __on_filter_item(self, item: "FileBrowserItem") -> bool:
if not item or item.is_folder:
return True
if self._dialog.current_filter_option < len(self.EXPORT_USD_EXTS):
# Show only files with listed extensions
return item.path.endswith("." + self.EXPORT_USD_EXTS[self._dialog.current_filter_option])
else:
# Show All Files (*)
return True
def __on_apply_save(self, filename: str, dir: str):
"""Called when the user presses the Save button in the dialog"""
# Get the file extension from the filter
if not filename.lower().endswith(self.EXPORT_USD_EXTS):
if self._dialog.current_filter_option < len(self.EXPORT_USD_EXTS):
filename += "." + self.EXPORT_USD_EXTS[self._dialog.current_filter_option]
# Add postfix name
if self._postfix_name:
filename = filename.replace(".usd", f".{self._postfix_name}.usd")
# TODO: Nucleus
path = omni.client.combine_urls(dir + "/", filename)
self._dialog.hide()
export(f"{path}", self._prim)
self._prim = None
global last_dir
last_dir = dir
class ExportPrimUSD:
def __init__(self, select_msg="Save As", save_msg="Save", save_dir=None, postfix_name=None):
self._select_msg = select_msg
if save_msg != "Save" or save_dir or postfix_name:
self._legacy = ExportPrimUSDLegacy(select_msg, save_msg, save_dir, postfix_name)
else:
self._legacy = None
def destroy(self):
if self._legacy:
self._legacy.destroy()
def export(self, prims: List[Usd.Prim]):
if self._legacy:
return self._legacy.export(prims)
file_exporter = get_file_exporter()
if file_exporter:
# OM-48055: Use the current stage directory as default save directory if export selected happened for the
# first time after opened the current stage; Otherwise use the last saved directory that user specifed.
global _default_save_dir
filename = prims[0].GetName() if prims else ""
dirname = _default_save_dir if _default_save_dir else ""
filename_url = ""
if dirname:
filename_url = dirname.rstrip('/') + '/'
if filename:
filename_url += filename
file_exporter.show_window(
title=self._select_msg,
export_button_label="Save Selected",
export_handler=partial(self.__on_apply_save, prims),
# OM-61553: Add default filename for export using the selected prim name
filename_url=filename_url or None,
)
def __on_apply_save(
self, prims: List[Usd.Prim], filename: str, dirname: str, extension: str, selections: List[str] = []
):
"""Called when the user presses the Save button in the dialog"""
if prims:
path = omni.client.combine_urls(dirname, f"{filename}{extension}")
export(path, prims)
# update default save dir after successful export
global _default_save_dir
_default_save_dir = dirname
| 12,466 | Python | 37.597523 | 117 | 0.634285 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_drag_and_drop_handler.py | __all__ = ["StageDragAndDropHandler", "AssetType"]
import carb
import re
import omni.kit.commands
import omni.kit.notification_manager as nm
from .stage_item import StageItem
from .stage_settings import StageSettings
from .utils import handle_exception
from pxr import Sdf, Tf, UsdGeom
from pathlib import Path
from omni.kit.async_engine import run_coroutine
KEEP_TRANSFORM_FOR_REPARENTING = "/persistent/app/stage/movePrimInPlace"
STAGE_DRAGDROP_IMPORT = "/persistent/app/stage/dragDropImport"
class AssetType:
"""A singleton that determines the type of asset using regex"""
def __init__(self):
self._re_mdl = re.compile(r"^.*\.mdl(\?.*)?(@.*)?$", re.IGNORECASE)
self._re_audio = re.compile(r"^.*\.(wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus)(\?.*)?$", re.IGNORECASE)
self._re_material_in_mdl = re.compile(r"export\s+material\s+([^\s]+)\s*\(")
self._read_material_tasks_or_futures = []
def destroy(self):
for task in self._read_material_tasks_or_futures:
if not task.done():
task.cancel()
self._read_material_tasks_or_futures.clear()
def is_usd(self, asset):
return omni.usd.is_usd_readable_filetype(asset)
def is_mdl(self, asset):
return self._re_mdl.match(asset)
def is_audio(self, asset):
return self._re_audio.match(asset)
def add_future(self, obj):
"""Add a future-like object to the global list, so it's not destroyed"""
# Destroy the objects that are done or canceled
self._read_material_tasks_or_futures = [
task_or_future for task_or_future in self._read_material_tasks_or_futures if not task_or_future.done() and not task_or_future.cancelled()
]
self._read_material_tasks_or_futures.append(run_coroutine(obj))
async def get_first_material_name(self, mdl_file):
"""Parse the MDL asset and return the name of the first shader"""
subid_list = await omni.kit.material.library.get_subidentifier_from_mdl(mdl_file, show_alert=True)
if subid_list:
return str(subid_list[0])
return None
class StageDragAndDropHandler:
def __init__(self, stage_model):
self.__stage_model = stage_model
self.__asset_type = AssetType()
self.__reordering_prim = False
self.__children_reorder_supported = False
@property
def children_reorder_supported(self):
return self.__children_reorder_supported
@children_reorder_supported.setter
def children_reorder_supported(self, enabled):
self.__children_reorder_supported = enabled
@property
def is_reordering_prim(self):
return self.__reordering_prim
@handle_exception
async def __apply_mdl(self, mdl_name, target_path):
"""Import and apply MDL asset to the specified prim"""
if mdl_name.startswith("material::"):
mdl_name = mdl_name[10:]
mtl_name = None
encoded_subid = False
# does the mdl name have the sub identifier encoded in it?
if "@" in mdl_name:
split = mdl_name.rfind("@")
if split > 0 and mdl_name[split+1:].isidentifier():
mtl_name = mdl_name[split+1:]
mdl_name = mdl_name[:split]
encoded_subid = True
if not mtl_name:
mtl_name = await self.__asset_type.get_first_material_name(mdl_name)
if not mtl_name:
carb.log_warn(f"[Stage Widget] the MDL Asset '{mdl_name}' doesn't have any material")
return
try:
import omni.usd
import omni.kit.material.library
stage = self.__stage_model.stage
subids = await omni.kit.material.library.get_subidentifier_from_mdl(mdl_name)
if not encoded_subid and len(subids) > 1:
# empty drops have target_path as /World - Fix
root_path = Sdf.Path.absoluteRootPath.pathString
if stage.HasDefaultPrim():
root_path = stage.GetDefaultPrim().GetPath().pathString
omni.kit.material.library.custom_material_dialog(
mdl_path=mdl_name, bind_prim_paths=[target_path] if target_path != root_path else None
)
return
except Exception as exc:
carb.log_error(f"error {exc}")
import traceback, sys
traceback.print_exc(file=sys.stdout)
except Exception:
carb.log_warn(f"Failed to use omni.kit.material.library custom_material_dialog")
# Create material with one sub-id
with omni.kit.undo.group():
# Create material. Despite the name, it only can bind to selection.
mtl_created_list = []
omni.kit.commands.execute(
"CreateAndBindMdlMaterialFromLibrary",
mdl_name=mdl_name,
mtl_name=mtl_name,
mtl_created_list=mtl_created_list,
select_new_prim=False,
)
# Bind created material to the target prim
# Special case: don't bind it to /World and to /World/Looks
if target_path and target_path not in ["/World", "/World/Looks"]:
omni.kit.commands.execute(
"BindMaterial", prim_path=target_path, material_path=mtl_created_list[0], strength=None
)
def drop_accepted(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called to highlight target when drag and drop."""
# Don't support drag and drop if the stage is not attached to any usd context.
stage_model = self.__stage_model
if not stage_model.usd_context:
return False
if source == target_item:
return False
# Skips it if reordering prims are not supported.
if not self.__children_reorder_supported and drop_location != -1:
return False
if isinstance(source, StageItem):
# Drag and drop from inside the StageView
if not target_item:
target_item = stage_model.root
if source.stage and source.stage == target_item.stage:
# It cannot move from parent into child.
# It stops if target_item already includes the source item.
target_parent = target_item.path.GetParentPath() or target_item.path
source_parent = source.path.GetParentPath() or source.path
if (
target_item.path.HasPrefix(source.path) or
(source in target_item.children and drop_location == -1) or
(target_parent != source_parent and drop_location != -1)
):
return False
else:
return True
else:
return not Sdf.Layer.IsAnonymousLayerIdentifier(source.root_identifier)
if isinstance(source, str):
# Drag and drop from the content browser
return True
try:
from omni.kit.widget.filebrowser import FileSystemItem
from omni.kit.widget.filebrowser import NucleusItem
if isinstance(source, FileSystemItem) or isinstance(source, NucleusItem):
# Drag and drop from the TreeView of Content Browser
return True
except Exception:
pass
try:
from omni.kit.widget.versioning.checkpoints_model import CheckpointItem
if isinstance(source, CheckpointItem):
return True
except Exception:
pass
return False
def __drop_location_to_prim_index(self, prim_path, drop_location, new_item=False):
"""
Gets the real prim index inside the children list of parent as drop location
only shows the UI location while some of the children are possibly
hidden in the stage window.
"""
parent = prim_path.GetParentPath() or Sdf.Path.absoluteRootPath
parent_item = self.__stage_model.find(parent)
total_children = len(parent_item.children)
# For new item, it needs to exclude current new item as the drop location is
# got before this item is created.
if new_item:
total_children -= 1
if drop_location >= total_children:
drop_item_name = parent_item.children[-1].path.name
else:
drop_item_name = parent_item.children[drop_location].path.name
parent_prim = parent_item.prim
children_names = parent_prim.GetAllChildrenNames()
if drop_item_name not in children_names:
return None
index = children_names.index(drop_item_name)
if drop_location >= total_children:
index += 1
return index
def __reorder_prim_to_drop_location(self, prim_path, drop_location, new_item):
if not self.__children_reorder_supported:
return
stage_model = self.__stage_model
stage = stage_model.stage
if prim_path and stage.GetPrimAtPath(prim_path) and drop_location != -1:
index = self.__drop_location_to_prim_index(prim_path, drop_location, new_item)
if index is None:
carb.log_error(f"Failed to re-order prim {prim_path} as it cannot be found in its parent.")
return
try:
self.__reordering_prim = True
success, _ = omni.kit.commands.execute(
"ReorderPrim", stage=stage, prim_path=prim_path, move_to_location=index
)
finally:
self.__reordering_prim = False
if success:
parent_item = stage_model.find(prim_path.GetParentPath())
if parent_item == stage_model.root:
parent_item = None
stage_model._item_changed(parent_item)
def drop(self, target_item, source, drop_location=-1):
"""
Reimplemented from AbstractItemModel. Called when dropping something to the item.
When drop_location is -1, it means to drop the source item on top of the target item.
When drop_location is not -1, it means to drop the source item between items.
"""
stage_model = self.__stage_model
stage = stage_model.stage
if not stage_model.root or not stage:
return
if isinstance(source, str) and source.startswith("env::"):
# Drop from environment window
action_registry = omni.kit.actions.core.get_action_registry()
action = action_registry.get_action("omni.kit.window.environment", "drop")
if action:
action.execute(source)
return
if isinstance(source, str) and source.startswith("SimReady::"):
# Drop from SimReady explorer
action_registry = omni.kit.actions.core.get_action_registry()
action = action_registry.get_action("omni.simready.explorer", "add_asset_from_drag")
if action:
if isinstance(target_item, StageItem):
if not target_item:
target_item = stage_model.root
path_to = target_item.path
else:
path_to = None
action.execute(source, path_to=path_to)
return
# Check type without importing if we have NucleusItem or FileSystemItem, we imported them in drop_accepted.
if type(source).__name__ in ["NucleusItem", "FileSystemItem"]:
# Drag and drop from the TreeView of Content Browser
source = source._path
# Check type without importing if we have CheckpointItem, we imported them in drop_accepted.
if type(source).__name__ == "CheckpointItem":
# Drag and drop from the TreeView of Content Browser
source = source.get_full_url()
with omni.kit.undo.group():
import_method = carb.settings.get_settings().get(STAGE_DRAGDROP_IMPORT) or "payload"
new_prim_path = None
new_item_added = False
if isinstance(source, StageItem):
if not target_item:
target_item = stage_model.root
if source.root_identifier == target_item.root_identifier:
# Drop the source item as a child item of target.
if drop_location == -1:
new_path = target_item.path.AppendChild(source.path.name)
settings = carb.settings.get_settings()
keep_transform = settings.get(KEEP_TRANSFORM_FOR_REPARENTING)
if keep_transform is None:
keep_transform = True
omni.kit.commands.execute(
"MovePrim",
path_from=str(source.path),
path_to=str(new_path),
keep_world_transform=keep_transform,
destructive=False
)
else:
# It's to drag and drop to re-order the children.
new_prim_path = source.path
else:
# Drag and drop from external stage
new_item_added = True
if import_method.lower() == "reference":
_, new_prim_path = omni.kit.commands.execute(
"CreateReference",
path_to=target_item.path.AppendChild(source.path.name),
asset_path=source.root_identifier,
prim_path=source.path,
usd_context=stage_model.usd_context
)
else:
_, new_prim_path = omni.kit.commands.execute(
"CreatePayload",
path_to=target_item.path.AppendChild(source.path.name),
asset_path=source.root_identifier,
prim_path=source.path,
usd_context=stage_model.usd_context
)
elif isinstance(source, str):
defaultedToDefaultPrim = False
# Don't drop it to default prim when it's to drop with location.
if not target_item and stage.HasDefaultPrim() and drop_location == -1:
default_prim = stage.GetDefaultPrim()
default_prim_path = default_prim.GetPath()
if (
not default_prim.IsA(UsdGeom.Gprim)
and not omni.usd.is_ancestor_prim_type(stage, default_prim_path, UsdGeom.Gprim)
):
target_item = stage_model.find(default_prim_path)
defaultedToDefaultPrim = True
if not target_item:
target_item = stage_model.root
defaultedToDefaultPrim = True
# Drag and drop from the content browser
for source_url in source.splitlines():
if source_url.endswith(".sbsar"):
new_item_added = True
if "AddSbsarReferenceAndBind" in omni.kit.commands.get_commands():
# mimic viewport drag & drop behaviour and not assign material to
# /World if we defaulted to it in the code above
targetPrimPath = target_item.path if not defaultedToDefaultPrim else None
success, sbar_mat_prim = omni.kit.commands.execute(
"AddSbsarReferenceAndBind", sbsar_path=source_url, target_prim_path=targetPrimPath
)
if success and sbar_mat_prim:
omni.usd.get_context().get_selection().set_selected_prim_paths([sbar_mat_prim], True)
new_prim_path = sbar_mat_prim.GetPath()
else:
nm.post_notification(
"To drag&drop sbsar files please enable the omni.kit.property.sbsar extension first.",
status=nm.NotificationStatus.WARNING
)
elif source_url.startswith("flow::"):
# mimic viewport drag & drop behaviour
(name, preset_url) = source_url[len("flow::"):].split("::")
omni.kit.commands.execute(
"FlowCreatePresetsCommand",
preset_name=name,
url=preset_url,
paths=[str(target_item.path)],
layer=-1)
elif omni.usd.is_usd_readable_filetype(source_url):
new_item_added = True
stem = Path(source_url).stem
# It drops as child.
if drop_location == -1:
path = target_item.path.AppendChild(Tf.MakeValidIdentifier(stem))
else:
# It drops between items.
path = target_item.path.GetParentPath()
if not path:
path = Sdf.Path.absoluteRootPath
path = path.AppendChild(Tf.MakeValidIdentifier(stem))
if import_method == "reference":
success, new_prim_path = omni.kit.commands.execute(
"CreateReference", path_to=path, asset_path=source_url, usd_context=stage_model.usd_context
)
else:
success, new_prim_path = omni.kit.commands.execute(
"CreatePayload", path_to=path, asset_path=source_url, usd_context=stage_model.usd_context
)
elif self.__asset_type.is_mdl(source_url):
self.__asset_type.add_future(self.__apply_mdl(source_url, target_item.path))
elif self.__asset_type.is_audio(source_url):
new_item_added = True
stem = Path(source_url).stem
path = target_item.path.AppendChild(Tf.MakeValidIdentifier(stem))
_, new_prim_path = omni.kit.commands.execute(
"CreateAudioPrimFromAssetPath",
path_to=path,
asset_path=source_url,
usd_context=stage_model.usd_context
)
if new_prim_path:
self.__reorder_prim_to_drop_location(new_prim_path, drop_location, new_item_added)
| 19,221 | Python | 43.49537 | 149 | 0.544821 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_settings.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.
#
# Selection Watch implementation has been moved omni.kit.widget.stage.
# Import it here for keeping back compatibility.
__all__ = ["StageSettings"]
class StageSettings:
def __init__(self):
super().__init__()
self.show_prim_displayname = False
self.auto_reload_prims = False
self.children_reorder_supported = False
self.flat_search = True
| 818 | Python | 36.227271 | 76 | 0.738386 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageModel", "StageItemSortPolicy"]
from pxr import Sdf, Tf, Trace, Usd, UsdGeom
from typing import List, Optional, Dict, Callable
from omni.kit.async_engine import run_coroutine
from .event import Event, EventSubscription
from .stage_item import StageItem
from .utils import handle_exception
from .stage_drag_and_drop_handler import StageDragAndDropHandler, AssetType
from enum import Enum
import carb
import carb.dictionary
import carb.settings
import omni.activity.core
import omni.client
import omni.ui as ui
import omni.usd
import omni.kit.usd.layers as layers
EXCLUSION_TYPES_SETTING = "ext/omni.kit.widget.stage/exclusion/types"
def should_prim_be_excluded_from_tree_view(prim, exclusion_types):
if (
not prim or not prim.IsActive()
or prim.GetMetadata("hide_in_stage_window")
or (exclusion_types and prim.GetTypeName() in exclusion_types)
):
return True
return False
class StageItemSortPolicy(Enum):
DEFAULT = 0
NAME_COLUMN_NEW_TO_OLD = 1
NAME_COLUMN_OLD_TO_NEW = 2
NAME_COLUMN_A_TO_Z = 3
NAME_COLUMN_Z_TO_A = 4
TYPE_COLUMN_A_TO_Z = 5
TYPE_COLUMN_Z_TO_A = 6
VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE = 7
VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE = 8
class StageModel(ui.AbstractItemModel):
"""The item model that watches the stage"""
def __init__(self, stage: Usd.Stage, flat=False, load_payloads=False, check_missing_references=False, **kwargs):
"""
StageModel provides the model for TreeView of Stage Widget, which also manages all StageItems.
Args:
stage (Usd.Stage): USD stage handle.
Flat (bool): If it's True, all the StageItems will be children of root node. This option only applies to
filtering mode.
load_payloads (bool): Whether it should load payloads during stage traversal automatically or not.
check_missing_references (bool): Deprecated.
Kwargs:
children_reorder_supported (bool): Whether to enable children reorder for drag and drop or not. False by default.
show_prim_displayname (bool): Whether to show prim's displayName from metadata or path name. False by default.
"""
super().__init__()
self.__flat_search = flat
self.load_payloads = load_payloads
# Stage item cache for quick access
self.__stage_item_cache: Dict[Sdf.Path, StageItem] = {}
self.__stage = stage
if self.__stage:
# Internal access that can be overrided.
self._root = StageItem(Sdf.Path.absoluteRootPath, self.stage, self)
self.__default_prim_name = self.__stage.GetRootLayer().defaultPrim
else:
self.__default_prim_name = None
self._root = None
# Stage watching
if self.__stage:
self.__stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.__on_objects_changed, self.__stage)
self.__layer_listener = Tf.Notice.Register(
Sdf.Notice.LayerInfoDidChange, self.__on_layer_info_change, self.__stage.GetRootLayer()
)
else:
self.__stage_listener = None
self.__layer_listener = None
# Delayed paths to be refreshed.
self.__dirty_prim_paths = set()
self.__prim_changed_task_or_future = None
# The string that the shown objects should have.
self.__filter_name_text = None
# The dict of form {"type_name_string", lambda prim: True}. When lambda is True, the prim will be shown.
self.__filters = {}
self.__stage_item_value_model_count = 1
# Exclusion list allows to hide prims of specific types silently
settings = carb.settings.get_settings()
self.__exclusion_types: Optional[List[str]] = settings.get(EXCLUSION_TYPES_SETTING)
self.__setting_sub = omni.kit.app.SettingChangeSubscription(
EXCLUSION_TYPES_SETTING, self.__on_exclusion_types_changed
)
# It's possible that stage is not attached to any context.
if self.__stage:
self.__usd_context = omni.usd.get_context_from_stage(self.__stage)
if self.__usd_context:
layers_interface = layers.get_layers(self.__usd_context)
self.layers_state_interface = layers_interface.get_layers_state()
self.__layers_event_subs = []
for event in [
layers.LayerEventType.OUTDATE_STATE_CHANGED, layers.LayerEventType.AUTO_RELOAD_LAYERS_CHANGED
]:
layers_event_sub = layers_interface.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layer_event, name=f"omni.kit.widget.stage {str(event)}"
)
self.__layers_event_subs.append(layers_event_sub)
else:
self.layers_state_interface = None
self.__layers_event_subs = None
else:
self.__usd_context = None
# Notifies when stage items are destroyed.
self.__on_stage_items_destroyed = Event()
self.__drag_and_drop_handler = StageDragAndDropHandler(self)
self.__drag_and_drop_handler.children_reorder_supported = kwargs.get("children_reorder_supported", False)
# If it's in progress of renaming prim.
self.__renaming_prim = False
self.__show_prim_displayname = kwargs.get("show_prim_displayname", False)
# The sorting strategy to use. Only builtin columns (name, type, and visibility) support to
# change the sorting policy directly through StageModel.
self.__items_builtin_sort_policy = StageItemSortPolicy.DEFAULT
self.__settings_builtin_sort_policy = False
self.__items_sort_func = None
self.__items_sort_reversed = False
def __on_layer_event(self, event):
payload = layers.get_layer_event_payload(event)
if (
payload.event_type != layers.LayerEventType.OUTDATE_STATE_CHANGED and
payload.event_type != layers.LayerEventType.AUTO_RELOAD_LAYERS_CHANGED
):
return
all_stage_items = self._get_all_stage_items_from_cache()
to_refresh_items = [item for item in all_stage_items if item.payrefs]
# Notify all items to refresh its live and outdate status
self.__refresh_stage_items(to_refresh_items, [])
def __clear_stage_item_cache(self):
if self.__stage_item_cache:
all_items = list(self.__stage_item_cache.items())
if all_items:
self.__refresh_stage_items([], destroyed_items=all_items)
for _, item in self.__stage_item_cache.items():
item.destroy()
self.__stage_item_cache = {}
def _cache_stage_item(self, item: StageItem):
if item == self._root:
return
if item.path not in self.__stage_item_cache:
self.__stage_item_cache[item.path] = item
def _get_stage_item_from_cache(self, path: Sdf.Path, create_if_not_existed=False):
"""Gets or creates stage item."""
if path == Sdf.Path.absoluteRootPath:
return self._root
stage_item = self.__stage_item_cache.get(path, None)
if not stage_item and create_if_not_existed:
prim = self.__stage.GetPrimAtPath(path)
if should_prim_be_excluded_from_tree_view(prim, self.__exclusion_types):
return None
stage_item = StageItem(path, self.stage, self)
self._cache_stage_item(stage_item)
return stage_item
def _get_all_stage_items_from_cache(self):
return list(self.__stage_item_cache.values())
@Trace.TraceFunction
def __get_stage_item_children(self, path: Sdf.Path):
"""
Gets all children stage items of path. If those stage items are not
created, they will be created. This optimization is used to implement
lazy loading that only paths that are accessed will create corresponding
stage items.
"""
if path == Sdf.Path.absoluteRootPath:
stage_item = self._root
else:
stage_item = self.__stage_item_cache.get(path, None)
if not stage_item or not stage_item.prim:
return []
prim = stage_item.prim
if self.load_payloads and not prim.IsLoaded():
# Lazy load payloads
prim.Load(Usd.LoadWithoutDescendants)
# This appears to be working fastly after testing with 10k nodes under a single parent.
# It does not need to cache all the prent-children relationship to save memory.
children = []
display_predicate = Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)
children_iterator = prim.GetFilteredChildren(display_predicate)
for child_prim in children_iterator:
child_path = child_prim.GetPath()
child = self._get_stage_item_from_cache(child_path, True)
if child:
children.append(child)
return children
def _remove_stage_item_from_cache(self, prim_path: Sdf.Path):
item = self.__stage_item_cache.pop(prim_path, None)
if item:
item.destroy()
return True
return False
@property
def usd_context(self) -> omni.usd.UsdContext:
return self.__usd_context
@property
def stage(self):
return self.__stage
@property
def root(self):
"""Item that represents the absolute root."""
return self._root
@property
def flat(self):
"""
Whether the model is in flat search mode or not. When it's in flat search mode,
all items will be the children of the root item, and empty children
for other items.
"""
return self.__flat_search and self.__has_filters()
@flat.setter
def flat(self, value):
self.__flat_search = value
for item in self.__stage_item_cache.values():
item.is_flat = value
def find(self, path: Sdf.Path):
"""Return item with the given path if it's populated already."""
path = Sdf.Path(path)
if path == Sdf.Path.absoluteRootPath:
return self._root
return self._get_stage_item_from_cache(path)
@Trace.TraceFunction
def find_full_chain(self, path):
"""Return the list of all the parent nodes and the node representing the given path"""
if not self._root:
return None
if not path:
return None
if isinstance(path, str) and path[-1] == "/":
path = path[:-1]
path = Sdf.Path(path)
if path == Sdf.Path.absoluteRootPath:
return None
result = [self._root]
# Finds the full chain and creates stage item on demand to avoid expanding whole tree.
prefixes = path.GetPrefixes()
for child_path in prefixes:
child_item = self._get_stage_item_from_cache(child_path, True)
if child_item:
result.append(child_item)
else:
break
return result
@Trace.TraceFunction
def update_dirty(self):
"""
Create/remove dirty items that was collected from TfNotice. Can be
called any time to pump changes.
"""
if not self.__dirty_prim_paths:
return
stage_update_activity = "Stage|Update|Stage Widget Model"
omni.activity.core.began(stage_update_activity)
dirty_prim_paths = list(self.__dirty_prim_paths)
self.__dirty_prim_paths = set()
# Updates the common root as refreshing subtree will filter
# all cache items to find the old stage items. So iterating each
# single prim path is not efficient as it needs to traverse
# whole cache each time. Even it's possible that dirty prim paths
# are not close to each other that results more stage traverse,
# the time is still acceptable after testing stage over 100k prims.
common_prefix = dirty_prim_paths[0]
for path in dirty_prim_paths[1:]:
common_prefix = Sdf.Path.GetCommonPrefix(common_prefix, path)
(
info_changed_stage_items,
children_refreshed_items,
destroyed_items
) = self.__refresh_prim_subtree(common_prefix)
self.__refresh_stage_items(
info_changed_stage_items, children_refreshed_items, destroyed_items
)
omni.activity.core.ended(stage_update_activity)
def __refresh_stage_items(
self, info_changed_items, children_refreshed_items=[], destroyed_items=[]
):
"""
`info_changed_items` includes only items that have flags/attributes updated.
`children_refreshed_items` includes only items that have children updated.
`destroyed_items` includes only items that are removed from stage.
"""
if info_changed_items:
for item in info_changed_items:
item.update_flags()
# Refresh whole item for now to maintain back-compatibility
if self._root == item:
self._item_changed(None)
else:
self._item_changed(item)
if children_refreshed_items:
if self.flat:
self._item_changed(None)
else:
for stage_item in children_refreshed_items:
if self._root == stage_item:
self._item_changed(None)
else:
self._item_changed(stage_item)
if destroyed_items:
self.__on_stage_items_destroyed(destroyed_items)
@Trace.TraceFunction
def __refresh_prim_subtree(self, prim_path):
"""
Refresh prim subtree in lazy way. It will only refresh those
stage items that are populated already to not load them beforehand
to improve perf, except the absolute root node.
"""
carb.log_verbose(f"Refresh prim tree rooted from {prim_path}")
old_stage_items = []
refreshed_stage_items = set([])
children_updated_stage_items = set([])
item = self._get_stage_item_from_cache(prim_path)
# This is new item, returning and refreshing it immediately if its parent is existed.
if not item:
if self.__has_filters():
self.__prefilter(prim_path)
parent = self._get_stage_item_from_cache(prim_path.GetParentPath())
if parent:
children_updated_stage_items.add(parent)
return refreshed_stage_items, children_updated_stage_items, []
# If it's to refresh whole stage, it should always refresh absolute root
# as new root prim should always be populated.
if prim_path == Sdf.Path.absoluteRootPath:
children_updated_stage_items.add(self._root)
if self.__has_filters():
# OM-84576: Filtering all as it's possible that new sublayers are inserted.
should_update_items = self.__prefilter(prim_path)
children_updated_stage_items.update(should_update_items)
old_stage_items = list(self.__stage_item_cache.values())
else:
for path, item in self.__stage_item_cache.items():
if path.HasPrefix(prim_path):
old_stage_items.append(item)
# If no cached items, and it's the root prims refresh, it should
# alwasy populate root prims if they are not populated yet.
if not old_stage_items:
children_updated_stage_items.add(self._root)
all_removed_items = []
for stage_item in old_stage_items:
if stage_item.path == Sdf.Path.absoluteRootPath:
continue
prim = self.__stage.GetPrimAtPath(stage_item.path)
if prim and prim.IsActive():
refreshed_stage_items.add(stage_item)
else:
parent = self._get_stage_item_from_cache(stage_item.path.GetParentPath())
if parent:
children_updated_stage_items.add(parent)
# Removes it from filter list.
if self.flat and (stage_item.filtered or stage_item.child_filtered):
children_updated_stage_items.add(self._root)
if self._remove_stage_item_from_cache(stage_item.path):
all_removed_items.append(stage_item)
return refreshed_stage_items, children_updated_stage_items, all_removed_items
@Trace.TraceFunction
def __on_objects_changed(self, notice, stage):
"""Called by Usd.Notice.ObjectsChanged"""
if not stage or stage != self.__stage or self.__drag_and_drop_handler.is_reordering_prim:
return
if self.__renaming_prim:
return
dirty_prims_paths = []
for p in notice.GetResyncedPaths():
if p.IsAbsoluteRootOrPrimPath():
dirty_prims_paths.append(p)
for p in notice.GetChangedInfoOnlyPaths():
if not p.IsAbsoluteRootOrPrimPath():
if p.name == UsdGeom.Tokens.visibility:
dirty_prims_paths.append(p.GetPrimPath())
continue
for field in notice.GetChangedFields(p):
if field == omni.usd.editor.HIDE_IN_STAGE_WINDOW or field == omni.usd.editor.DISPLAY_NAME:
dirty_prims_paths.append(p)
break
if not dirty_prims_paths:
return
self.__dirty_prim_paths.update(dirty_prims_paths)
# Update in the next frame. We need it because we want to accumulate the affected prims
if self.__prim_changed_task_or_future is None or self.__prim_changed_task_or_future.done():
self.__prim_changed_task_or_future = run_coroutine(self.__delayed_prim_changed())
@Trace.TraceFunction
def __on_layer_info_change(self, notice, sender):
"""Called by Sdf.Notice.LayerInfoDidChange when the metadata of the root layer is changed"""
if not sender or notice.key() != "defaultPrim":
return
new_default_prim = sender.defaultPrim
if new_default_prim == self.__default_prim_name:
return
# Unmark the old default
items_refreshed = []
if self.__default_prim_name:
found = self.find(Sdf.Path.absoluteRootPath.AppendChild(self.__default_prim_name))
if found:
items_refreshed.append(found)
# Mark the old default
if new_default_prim:
found = self.find(Sdf.Path.absoluteRootPath.AppendChild(new_default_prim))
if found:
items_refreshed.append(found)
self.__refresh_stage_items(items_refreshed)
self.__default_prim_name = new_default_prim
@handle_exception
@Trace.TraceFunction
async def __delayed_prim_changed(self):
await omni.kit.app.get_app().next_update_async()
# It's possible that stage is closed before coroutine
# is handled.
if not self.__stage:
return
# Pump the changes to the model.
self.update_dirty()
self.__prim_changed_task_or_future = None
@carb.profiler.profile
@Trace.TraceFunction
def get_item_children(self, item):
"""Reimplemented from AbstractItemModel"""
if item is None:
item = self._root
if not item:
return []
if self.flat:
# In flat mode, all stage items will be the children of root.
if item == self._root:
children = self._get_all_stage_items_from_cache()
else:
children = []
else:
children = self.__get_stage_item_children(item.path)
if self.__has_filters():
children = [child for child in children if (child.filtered or child.child_filtered)]
# Sort children
if self.__items_sort_func:
children.sort(key=self.__items_sort_func, reverse=self.__items_sort_reversed)
elif self.__items_sort_reversed:
children.reverse()
return children
@carb.profiler.profile
@Trace.TraceFunction
def can_item_have_children(self, item):
"""
By default, if can_item_have_children is not provided,
it will call get_item_children to get the count of children, so implementing
this function to make sure we do lazy load for all items.
"""
if item is None:
item = self._root
if not item or not item.prim:
return False
# Non-root item in flat mode has no children.
if self.flat and item != self._root:
return False
prim = item.prim
if self.load_payloads and not prim.IsLoaded():
# Lazy load payloads
prim.Load(Usd.LoadWithoutDescendants)
display_predicate = Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)
children_iterator = prim.GetFilteredChildren(display_predicate)
for child_prim in children_iterator:
if should_prim_be_excluded_from_tree_view(child_prim, self.__exclusion_types):
continue
if self.__has_filters():
child_item = self._get_stage_item_from_cache(child_prim.GetPath(), False)
if child_item and (child_item.filtered or child_item.child_filtered):
return True
else:
return True
return False
def get_item_value_model_count(self, item):
"""Reimplemented from AbstractItemModel"""
return self.__stage_item_value_model_count
def set_item_value_model_count(self, count):
"""Internal method to set column count."""
self.__stage_item_value_model_count = count
self._item_changed(None)
def drop_accepted(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called to highlight target when drag and drop."""
return self.__drag_and_drop_handler.drop_accepted(target_item, source, drop_location)
def drop(self, target_item, source, drop_location=-1):
"""
Reimplemented from AbstractItemModel. Called when dropping something to the item.
When drop_location is -1, it means to drop the source item on top of the target item.
When drop_location is not -1, it means to drop the source item between items.
"""
return self.__drag_and_drop_handler.drop(target_item, source, drop_location)
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
# As we don't do Drag and Drop to the operating system, we return the string.
return str(item.path) if item else "/"
def __has_filters(self):
return self.__filter_name_text or self.__filters
def filter_by_text(self, filter_name_text):
"""Filter stage by text. Currently, only single word that's case-insensitive or prim path are supported."""
if not self._root:
return
"""Specify the filter string that is used to reduce the model"""
if self.__filter_name_text == filter_name_text:
return
self.__filter_name_text = filter_name_text.strip() if filter_name_text else None
should_update_items = self.__prefilter(Sdf.Path.absoluteRootPath)
self.__refresh_stage_items([], should_update_items)
def filter(self, add=None, remove=None, clear=None):
"""
Set filtering by type. In most cases we need to filter with several types, so this method allows to add, remove
and set list of types and update the items if it's necessary.
Args:
add: The dictionary of this form: {"type_name_string", lambda prim: True}. When lambda is True, the prim
will be shown.
remove: Can be str, dict, list, set. Removes filter by name.
clear: Removes all the filters. When using with `add`, it will remove the filters first and then will add
the given ones.
Returns:
True if the model has filters. False otherwise.
"""
if not self._root:
return
changed = False
if clear:
if self.__filters:
self.__filters.clear()
changed = True
if remove:
if isinstance(remove, str):
remove = [remove]
for key in remove:
if key in self.__filters:
self.__filters.pop(key, None)
changed = True
if add:
self.__filters.update(add)
changed = True
if changed:
should_update_items = self.__prefilter(Sdf.Path.absoluteRootPath)
self.__refresh_stage_items([], should_update_items)
return not not self.__filters
def get_filters(self):
"""Return dict of filters"""
return self.__filters
def reset(self):
"""Force full re-update"""
if self._root:
self.__clear_stage_item_cache()
self._item_changed(None)
def destroy(self):
self.__drag_and_drop_handler = None
self.__on_stage_items_destroyed.clear()
self.__stage = None
if self._root:
self._root.destroy()
self._root = None
self.__layers_event_subs = []
if self.__stage_listener:
self.__stage_listener.Revoke()
self.__stage_listener = None
if self.__layer_listener:
self.__layer_listener.Revoke()
self.__layer_listener = None
self.__dirty_prim_paths = set()
if self.__prim_changed_task_or_future:
self.__prim_changed_task_or_future.cancel()
self.__prim_changed_task_or_future = None
self.__setting_sub = None
self.__clear_stage_item_cache()
self.layers_state_interface = None
self.__items_builtin_sort_policy = StageItemSortPolicy.DEFAULT
self.__items_sort_func = None
self.__items_sort_reversed = False
def __clear_filter_states(self, prim_path=None):
should_update_items = []
should_update_items.append(self.root)
for stage_item in self.__stage_item_cache.values():
if prim_path and not stage_item.path.HasPrefix(prim_path):
continue
if stage_item.filtered or stage_item.child_filtered:
should_update_items.append(stage_item)
stage_item.filtered = False
stage_item.child_filtered = False
return should_update_items
def __filter_prim(self, prim: Usd.Prim):
if not prim:
return False
if (
self.__filter_name_text
and Sdf.Path.IsValidPathString(self.__filter_name_text)
and Sdf.Path.IsAbsolutePath(Sdf.Path(self.__filter_name_text))
):
filter_text_is_prim_path = True
filter_path = Sdf.Path(self.__filter_name_text)
prim = self.__stage.GetPrimAtPath(filter_path)
if not prim:
return False
else:
filter_text_is_prim_path = False
filter_path = self.__filter_name_text.lower() if self.__filter_name_text else ""
# Has the search string in the name
if filter_text_is_prim_path:
filtered_with_string = prim.GetPath().HasPrefix(filter_path)
else:
filtered_with_string = filter_path in prim.GetName().lower() if filter_path else True
# Has the given type
if self.__filters:
filtered_with_lambda = False
for _, fn in self.__filters.items():
if fn(prim):
filtered_with_lambda = True
break
else:
filtered_with_lambda = True
# The result filter
return filtered_with_string and filtered_with_lambda
def __prefilter(self, prim_path: Sdf.Path):
"""Recursively mark items that meet the filtering rule"""
prim_path = Sdf.Path(prim_path)
prim = self.__stage.GetPrimAtPath(prim_path)
if not prim:
return set()
# Clears all filter states.
old_filtered_items = set(self.__clear_filter_states(prim_path))
should_update_items = set()
if self.__has_filters():
# Root should be refreshed always
should_update_items.add(self.root)
# and then creates stage items on demand when they are filtered to avoid
# perf issue to create stage items for whole stage.
display_predicate = Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate)
children_iterator = iter(Usd.PrimRange(prim, display_predicate))
for child_prim in children_iterator:
if should_prim_be_excluded_from_tree_view(child_prim, self.__exclusion_types):
children_iterator.PruneChildren()
continue
if self.load_payloads and not prim.IsLoaded():
# Lazy load payloads
prim.Load(Usd.LoadWithoutDescendants)
filtered = self.__filter_prim(child_prim)
if not filtered:
continue
# Optimization: only prim path that's filtered will create corresponding
# stage item instead of whole subtree.
child_prim_path = child_prim.GetPath()
stage_item = self._get_stage_item_from_cache(child_prim_path, True)
if not stage_item:
continue
stage_item.filtered = True
stage_item.child_filtered = False
if not self.flat:
should_update_items.add(stage_item)
old_filtered_items.discard(stage_item)
parent_path = child_prim_path.GetParentPath()
# Creates all parents if they are not there and mark their children filtered.
while parent_path:
parent_item = self._get_stage_item_from_cache(parent_path, True)
if not parent_item or parent_item.child_filtered:
break
should_update_items.add(parent_item)
old_filtered_items.discard(parent_item)
parent_item.child_filtered = True
parent_path = parent_path.GetParentPath()
else:
self.root.child_filtered = True
should_update_items.update(old_filtered_items)
return should_update_items
def __on_exclusion_types_changed(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType):
"""Called when the exclusion list is changed"""
if event_type == carb.settings.ChangeEventType.CHANGED:
settings = carb.settings.get_settings()
self.__exclusion_types = settings.get(EXCLUSION_TYPES_SETTING)
elif event_type == carb.settings.ChangeEventType.DESTROYED:
self.__exclusion_types = None
else:
return
self.reset()
@property
def children_reorder_supported(self):
"""Whether to support reorder children by drag and drop."""
return self.__drag_and_drop_handler.children_reorder_supported
@children_reorder_supported.setter
def children_reorder_supported(self, value):
self.__drag_and_drop_handler.children_reorder_supported = value
@property
def show_prim_displayname(self):
"""Instructs stage delegate to show prim's displayName from USD or path name."""
return self.__show_prim_displayname
@show_prim_displayname.setter
def show_prim_displayname(self, value):
if value != self.__show_prim_displayname:
self.__show_prim_displayname = value
all_stage_items = self._get_all_stage_items_from_cache()
self.__refresh_stage_items(all_stage_items)
def subscribe_stage_items_destroyed(self, fn: Callable[[List[StageItem]], None]) -> EventSubscription:
"""
Subscribe changes when stage items are destroyed.
Return the object that will automatically unsubscribe when destroyed.
"""
return EventSubscription(self.__on_stage_items_destroyed, fn)
def rename_prim(self, prim_path: Sdf.Path, new_name: str):
"""Rename prim to new name."""
if not self.stage or not self.stage.GetPrimAtPath(prim_path):
return False
if not Tf.IsValidIdentifier(new_name):
carb.log_error(f"Cannot rename prim {prim_path} to name {new_name} as new name is invalid.")
return False
if prim_path.name == new_name:
return True
parent_path = prim_path.GetParentPath()
created_path = parent_path.AppendElementString(new_name)
if self.stage.GetPrimAtPath(created_path):
carb.log_error(f"Cannot rename prim {prim_path} to name {new_name} as new prim exists already.")
return False
def prim_renamed(old_prim_name: Sdf.Path, new_prim_name: Sdf.Path):
async def select_prim(prim_path):
# Waits for two frames until stage item is created
app = omni.kit.app.get_app()
await app.next_update_async()
await app.next_update_async()
if self.__usd_context:
self.__usd_context.get_selection().set_selected_prim_paths(
[prim_path.pathString], True
)
run_coroutine(select_prim(new_prim_name))
stage_item = self._get_stage_item_from_cache(prim_path)
on_move_fn = prim_renamed if stage_item else None
# Move the prim to the new name
try:
self.__renaming_prim = True
move_dict = {prim_path: created_path.pathString}
omni.kit.commands.execute("MovePrims", paths_to_move=move_dict, on_move_fn=on_move_fn, destructive=False)
# If stage item exists.
if stage_item:
self.__stage_item_cache.pop(stage_item.path, None)
# Change internal path and refresh old path.
stage_item._path = created_path
stage_item.update_flags()
# Cache new path
self._cache_stage_item(stage_item)
# Refreshes search list
if (
self.__has_filters() and not stage_item.child_filtered and
stage_item.filtered and not self.__filter_prim(stage_item.prim)
):
stage_item.filtered = False
if self.flat:
self._item_changed(None)
else:
parent_path = prim_path.GetParentPath()
parent_item = self._get_stage_item_from_cache(parent_path)
if parent_item:
self.__refresh_stage_items([], children_refreshed_items=[parent_item])
else:
self.__refresh_stage_items([], children_refreshed_items=[stage_item])
except Exception as e:
import traceback
carb.log_error(traceback.format_exc())
carb.log_error(f"Failed to rename prim {prim_path}: {str(e)}")
return False
finally:
self.__renaming_prim = False
return True
def set_items_sort_key_func(self, key_fn: Callable[[StageItem], None], reverse=False):
"""
Sets key function to sort item children.
Args:
key_fn (Callable[[StageItem], None]): The function that's used to sort children of item, which
be passed to list.sort as key function, for example, `lambda item: item.name`. If `key_fn` is
None and `reverse` is True, it will reverse items only. Or if `key_fn` is None and `reverse` is
False, it will clear sort function.
reverse (bool): By default, it's ascending order to sort with key_fn. If this flag is True,
it will sort children in reverse order.
clear_existing (bool): If it's True, it will clear all existing sort key functions, including
resetting builtin column sort policy to StageItemSortPolicy.DEFAULT. False by default.
Returns:
Handle that maintains the lifecycle of the sort function. Releasing it will remove the sort function
and trigger widget refresh.
"""
notify = False
if not self.__settings_builtin_sort_policy and self.__items_builtin_sort_policy != StageItemSortPolicy.DEFAULT:
self.__items_builtin_sort_policy = StageItemSortPolicy.DEFAULT
if self.__items_sort_func:
self.__items_sort_func = None
notify = True
if self.__items_sort_func or self.__items_sort_reversed:
self.__items_sort_func = None
self.__items_sort_reversed = False
notify = True
if key_fn or reverse:
self.__items_sort_func = key_fn
self.__items_sort_reversed = reverse
notify = True
# Refresh all items to sort their children
if notify:
all_stage_items = self._get_all_stage_items_from_cache()
all_stage_items.append(self.root)
self.__refresh_stage_items([], all_stage_items)
def set_items_sort_policy(self, items_sort_policy: StageItemSortPolicy):
"""
This is old way to sort builtin columns (name, type, and visibility), which can only sort one
builtin column at the same time, and it will clear all existing sorting functions customized by
append_column_sort_key_func and only sort column specified by `items_sort_policy`. For more advanced sort,
see function `append_column_sort_key_func`, which supports to chain sort for multiple columns.
"""
try:
self.__settings_builtin_sort_policy = True
if self.__items_builtin_sort_policy != items_sort_policy:
self.__items_builtin_sort_policy = items_sort_policy
if self.__items_builtin_sort_policy == StageItemSortPolicy.NAME_COLUMN_NEW_TO_OLD:
self.set_items_sort_key_func(None, True)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.NAME_COLUMN_A_TO_Z:
self.set_items_sort_key_func(lambda item: (item.name_model._name_prefix, item.name_model._suffix_order), False)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.NAME_COLUMN_Z_TO_A:
self.set_items_sort_key_func(lambda item: (item.name_model._name_prefix, item.name_model._suffix_order), True)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.TYPE_COLUMN_A_TO_Z:
self.set_items_sort_key_func(lambda item: item.type_name.lower(), False)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.TYPE_COLUMN_Z_TO_A:
self.set_items_sort_key_func(lambda item: item.type_name.lower(), True)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE:
self.set_items_sort_key_func(lambda item: 1 if item.visible else 0, False)
elif self.__items_builtin_sort_policy == StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE:
self.set_items_sort_key_func(lambda item: 0 if item.visible else 1, False)
else:
self.set_items_sort_key_func(None, False)
finally:
self.__settings_builtin_sort_policy = False
def get_items_sort_policy(self) -> StageItemSortPolicy:
"""Gets builtin columns sort policy."""
return self.__items_builtin_sort_policy
# Deprecated APIs
def refresh_item_names(self): # pragma: no cover
"""Deprecated."""
for item in self.__stage_item_cache.values():
item.name_model.rebuild()
self._item_changed(item)
@property
def check_missing_references(self): # pragma: no cover
"""Deprecated: It will always check missing references now."""
return True
@check_missing_references.setter
def check_missing_references(self, value): # pragma: no cover
"""Deprecated."""
pass
| 41,453 | Python | 37.960526 | 131 | 0.599667 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/stage_filter.py | from functools import partial
from typing import Optional
from pxr import UsdGeom, UsdSkel, OmniAudioSchema, UsdLux, UsdShade, OmniSkelSchema, UsdPhysics
from omni.kit.widget.filter import FilterButton
from omni.kit.widget.options_menu import OptionItem, OptionSeparator
class StageFilterButton(FilterButton):
"""
Filter button used in stage widget.
Args:
filter_provider: Provider where filter functions defined. Use stage widget.
"""
def __init__(self, filter_provider):
self.__filter_provider = filter_provider
items = [
OptionItem("Hidden", on_value_changed_fn=self._filter_by_visibility),
OptionSeparator(),
OptionItem("Animations", on_value_changed_fn=partial(self._filter_by_type, UsdSkel.Animation)),
OptionItem("Audio", on_value_changed_fn=partial(self._filter_by_type, OmniAudioSchema.OmniSound)),
OptionItem("Cameras", on_value_changed_fn=partial(self._filter_by_type, UsdGeom.Camera)),
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
OptionItem(
"Lights",
on_value_changed_fn=partial(self._filter_by_api_type, UsdLux.LightAPI) if hasattr(UsdLux, 'LightAPI') else partial(self._filter_by_type, UsdLux.Light)
),
OptionItem("Materials",on_value_changed_fn=partial(self._filter_by_type, [UsdShade.Material, UsdShade.Shader])),
OptionItem("Meshes", on_value_changed_fn=partial(self._filter_by_type, UsdGeom.Mesh)),
OptionItem("Xforms", on_value_changed_fn=partial(self._filter_by_type, UsdGeom.Xform)),
OptionSeparator(),
OptionItem("Material Flattener Base Meshes", on_value_changed_fn=self._filter_by_flattener_basemesh),
OptionItem("Material Flattener Decals", on_value_changed_fn=self._filter_by_flattener_decal),
OptionSeparator(),
OptionItem("Physics Articulation Roots",on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.ArticulationRootAPI)),
OptionItem("Physics Colliders", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.CollisionAPI)),
OptionItem("Physics Collision Groups", on_value_changed_fn=partial(self._filter_by_type, UsdPhysics.CollisionGroup)),
OptionItem("Physics Filtered Pairs", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.FilteredPairsAPI)),
OptionItem("Physics Joints", on_value_changed_fn=partial(self._filter_by_type, UsdPhysics.Joint)),
OptionItem("Physics Drives", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.DriveAPI)),
OptionItem("Physics Materials", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.MaterialAPI)),
OptionItem("Physics Rigid Bodies", on_value_changed_fn=partial(self._filter_by_api_type, UsdPhysics.RigidBodyAPI)),
OptionItem("Physics Scenes", on_value_changed_fn=partial(self._filter_by_type, UsdPhysics.Scene)),
OptionSeparator(),
OptionItem("Skeleton", on_value_changed_fn=partial(self._filter_by_type, [UsdSkel.Skeleton, OmniSkelSchema.OmniSkelBaseType, OmniSkelSchema.OmniJoint]) or partial(self._filter_by_api_type, [OmniSkelSchema.OmniSkelBaseAPI, OmniSkelSchema.OmniJointLimitsAPI])),
]
super().__init__(items, width=20, height=20)
def enable_filters(self, usd_type_list: list) -> list:
"""
Enable filters.
Args:
usd_type_list (list): List of usd types to be enabled.
Returns:
returns usd types not supported
"""
self.model.reset()
unknown_usd_types = []
for usd_type in usd_type_list:
name = None
if usd_type == UsdSkel.Animation:
name = "Animations"
elif usd_type == OmniAudioSchema.OmniSound:
name = "Audio"
elif usd_type == UsdGeom.Camera:
name = "Cameras"
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
elif (hasattr(UsdLux, 'LightAPI') and usd_type == UsdLux.LightAPI) or (hasattr(UsdLux, 'Light') and usd_type == UsdLux.Light):
name = "Lights"
elif usd_type == UsdShade.Material or usd_type == UsdShade.Shader:
name = "Materials"
elif usd_type == UsdGeom.Mesh:
name = "Meshes"
elif usd_type == UsdGeom.Xform:
name = "Xforms"
elif usd_type == UsdPhysics.ArticulationRootAPI:
name = "Physics Articulation Roots"
elif usd_type == UsdPhysics.CollisionAPI:
name = "Physics Colliders"
elif usd_type == UsdPhysics.CollisionGroup:
name = "Physics Collision Groups"
elif usd_type == UsdPhysics.FilteredPairsAPI:
name = "Physics Filtered Pairs"
elif usd_type == UsdPhysics.Joint:
name = "Physics Joints"
elif usd_type == UsdPhysics.DriveAPI:
name = "Physics Drives"
elif usd_type == UsdPhysics.MaterialAPI:
name = "Physics Materials"
elif usd_type == UsdPhysics.RigidBodyAPI:
name = "Physics Rigid Bodies"
elif usd_type == UsdPhysics.Scene:
name = "Physics Scenes"
elif usd_type == OmniSkelSchema.OmniSkelBaseType or usd_type == OmniSkelSchema.OmniSkelBaseAPI or usd_type == OmniSkelSchema.OmniJoint or usd_type == OmniSkelSchema.OmniJointLimitsAPI:
name = "Skeleton"
item = self._get_item(name) if name else None
if item:
item.value = True
else:
unknown_usd_types.append(usd_type)
# If there is any unknow usd types, unhide filter button
if unknown_usd_types and self.button:
self.button.visible = False
return unknown_usd_types
def _filter_by_visibility(self, enabled):
"""Filter Hidden On/Off"""
self.__filter_provider._filter_by_visibility(enabled)
def _filter_by_type(self, usd_types, enabled):
"""
Set filtering by USD type.
Args:
usd_types: The type or the list of types it's necessary to add or remove from filters.
enabled: True to add to filters, False to remove them from the filter list.
"""
self.__filter_provider._filter_by_type(usd_types, enabled)
def _filter_by_api_type(self, api_types, enabled):
"""
Set filtering by USD api type.
Args:
api_types: The api type or the list of types it's necessary to add or remove from filters.
enabled: True to add to filters, False to remove them from the filter list.
"""
self.__filter_provider._filter_by_api_type(api_types, enabled)
def _filter_by_flattener_basemesh(self, enabled):
self.__filter_provider._filter_by_flattener_basemesh(enabled)
def _filter_by_flattener_decal(self, enabled):
self.__filter_provider._filter_by_flattener_decal(enabled)
def _get_item(self, name: str) -> Optional[OptionItem]:
for item in self.model.get_item_children():
if item.name == name:
return item
return None
| 7,471 | Python | 48.157894 | 271 | 0.630572 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/usd_property_watch.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .stage_helper import UsdStageHelper
from pxr import Sdf
from pxr import Tf
from pxr import Trace
from pxr import Usd
from typing import Any
from typing import Dict
from typing import List
from typing import Optional, Union
from typing import Type
import asyncio
import carb
import functools
import omni.kit.app
from omni.kit.async_engine import run_coroutine
import omni.kit.commands
import omni.ui as ui
import traceback
import concurrent.futures
def handle_exception(func): # pragma: no cover
"""
Decorator to print exception in async functions
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
class UsdPropertyWatchModel(ui.AbstractValueModel, UsdStageHelper): # pragma: no cover
"""
DEPRECATED: A helper model of UsdPropertyWatch that behaves like a model that watches
a USD property. It doesn't work properly if UsdPropertyWatch does not
create it.
"""
def __init__(self, stage: Usd.Stage, path: Sdf.Path):
"""
## Arguments:
`stage`: USD Stage
`path`: The full path to the watched property
"""
ui.AbstractValueModel.__init__(self)
UsdStageHelper.__init__(self, stage)
if stage:
prop = stage.GetObjectAtPath(path)
else:
prop = None
if prop:
self._path = path
self._type = prop.GetTypeName().type
else:
self._path = None
self._type = None
def destroy(self):
"""Called before destroying"""
pass
def _get_prop(self):
"""Get the property this model holds"""
if not self._path:
return
stage = self._get_stage()
if not stage:
return
return stage.GetObjectAtPath(self._path)
def on_usd_changed(self):
"""Called by the stage model when the visibility is changed"""
self._value_changed()
def get_value_as_bool(self) -> Optional[bool]:
"""Reimplemented get bool"""
prop = self._get_prop()
if not prop:
return
return not not prop.Get()
def get_value_as_float(self) -> Optional[float]:
"""Reimplemented get bool"""
prop = self._get_prop()
if not prop:
return
return float(prop.Get())
def get_value_as_int(self) -> Optional[int]:
"""Reimplemented get bool"""
prop = self._get_prop()
if not prop:
return
return int(prop.Get())
def get_value_as_string(self) -> Optional[str]:
"""Reimplemented get bool"""
prop = self._get_prop()
if not prop:
return
return str(prop.Get())
def set_value(self, value: Any):
"""Reimplemented set bool"""
prop = self._get_prop()
if not prop:
return
omni.kit.commands.execute("ChangeProperty", prop_path=self._path, value=value)
class UsdPropertyWatch(UsdStageHelper): # pragma: no cover
"""
DEPRECATED: The purpose of this class is to keep a large number of models.
`Usd.Notice.ObjectsChanged` is pretty slow, and to remain fast, we need
to register as few `Tf.Notice` as possible. Thus, we can't put the
`Tf.Notice` logic to the model. Instead, this class creates and
coordinates the models.
"""
def __init__(
self,
stage: Usd.Stage,
property_name: str,
model_type: Type[UsdPropertyWatchModel] = UsdPropertyWatchModel,
):
"""
## Arguments:
`stage`: USD Stage
`property_name`: The name of the property to watch
`model_type`: The name of the property to watch
"""
UsdStageHelper.__init__(self, stage)
self.__prim_changed_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None
self.__dirty_property_paths: List[Sdf.Path] = []
self.__watch_property: str = property_name
self.__model_type: Type[UsdPropertyWatchModel] = model_type
self.__stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_objects_changed, stage)
self.__models: Dict[str, UsdPropertyWatchModel] = {}
def destroy(self):
"""Called before destroying"""
self.__stage_listener = None
for _, model in self.__models.items():
model.destroy()
self.__models = {}
if self.__prim_changed_task_or_future is not None:
self.__prim_changed_task_or_future.cancel()
self.__prim_changed_task_or_future = None
@Trace.TraceFunction
def _on_objects_changed(self, notice, sender):
"""Called by Tf.Notice"""
# We only watch the property self.__watch_property
prims_resynced = [
p for p in notice.GetChangedInfoOnlyPaths() if p.IsPropertyPath() and p.name == self.__watch_property
]
if prims_resynced:
# It's important to return as soon as possible, because
# Usd.Notice.ObjectsChanged can be called thousands times a frame.
# We collect the paths change and will work with them the next
# frame at once.
self.__dirty_property_paths += prims_resynced
if self.__prim_changed_task_or_future is None or self.__prim_changed_task_or_future.done():
self.__prim_changed_task_or_future = run_coroutine(self.__delayed_prim_changed())
# TODO: Do something when the watched object is removed
@handle_exception
@Trace.TraceFunction
async def __delayed_prim_changed(self):
"""Called in the next frame when the object is changed"""
await omni.kit.app.get_app().next_update_async()
# Pump the changes to the model.
self.update_dirty()
self.__prim_changed_task_or_future = None
def update_dirty(self):
"""
Create/remove dirty items that was collected from TfNotice. Can be
called any time to pump changes.
"""
dirty_property_paths = set(self.__dirty_property_paths)
self.__dirty_property_paths = []
dirty_prim_paths = [p.GetParentPath() for p in dirty_property_paths]
for path in dirty_prim_paths:
model = self.__models.get(path, None)
if model is None:
continue
model.on_usd_changed()
def _create_model(self, path: Sdf.Path):
"""Creates a new model and puts in to the cache"""
model = self.__model_type(self._get_stage(), path.AppendProperty(self.__watch_property))
self.__models[path] = model
return model
def get_model(self, path):
model = self.__models.get(path, None)
if model is None:
model = self._create_model(path)
return model
| 7,502 | Python | 30.792373 | 113 | 0.61317 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/models/type_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TypeModel"]
import omni.ui as ui
class TypeModel(ui.AbstractValueModel):
def __init__(self, stage_item):
super().__init__()
self.__stage_item = stage_item
def destroy(self):
self.__stage_item = None
def get_value_as_string(self) -> str:
return self.__stage_item.type_name
def set_value(self, value: str):
pass
| 817 | Python | 29.296295 | 76 | 0.70257 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/models/visibility_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["VisibilityModel"]
import omni.ui as ui
import omni.usd
class VisibilityModel(ui.AbstractValueModel):
def __init__(self, stage_item):
super().__init__()
self.__stage_item = stage_item
def destroy(self):
self.__stage_item = None
def get_value_as_bool(self) -> bool:
"""Reimplemented get bool"""
# Invisible when it's checked.
return not self.__stage_item.visible
def set_value(self, value: bool):
"""Reimplemented set bool"""
prim = self.__stage_item.prim
if not prim:
return
usd_context = omni.usd.get_context_from_stage(prim.GetStage())
if usd_context:
selection_paths = usd_context.get_selection().get_selected_prim_paths()
else:
selection_paths = []
# If the updating prim path is one of the selection path, we change all selected path. Otherwise, only change itself
prim_path = prim.GetPath()
stage = prim.GetStage()
update_paths = selection_paths if prim_path in selection_paths else [prim_path]
omni.kit.commands.execute(
"ToggleVisibilitySelectedPrims", selected_paths=update_paths, stage=stage
)
| 1,665 | Python | 33.708333 | 124 | 0.664264 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/models/name_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["PrimNameModel"]
import omni.ui as ui
from pxr import Sdf, Tf
class PrimNameModel(ui.AbstractValueModel):
"""The model that changes the prim name"""
def __init__(self, stage_item):
super().__init__()
self.__stage_item = stage_item
self.__label_on_begin = None
self.__old_label = None
self.__name_prefix = None
self.__suffix_order = None
self.rebuild()
self.__refresh_name_prefix_and_suffix()
def __refresh_name_prefix_and_suffix(self):
parts = self.__stage_item.name.rpartition("_")
self.__name_prefix = None
self.__suffix_order = None
if parts and len(parts) > 1:
suffix_order = parts[-1]
are_all_digits = True
for c in suffix_order:
if not c.isdigit():
are_all_digits = False
break
if are_all_digits and suffix_order:
self.__name_prefix = parts[0].lower()
self.__suffix_order = int(suffix_order)
if self.__suffix_order is None:
self.__name_prefix = self.__stage_item.name.lower()
self.__suffix_order = 0
@property
def _prim_path(self):
"""DEPRECATED: to ensure back-compatibility."""
return self.path
@property
def _name_prefix(self):
"""Name prefix without suffix number, e.g, `abc_01` will return abc. It's used for column sort."""
return self.__name_prefix
@property
def _suffix_order(self):
"""Number suffix, e.g, `abc_01` will return 01. It's used for column sort."""
return self.__suffix_order
@property
def path(self):
return self.__stage_item.path
def destroy(self):
self.__stage_item = None
def get_value_as_string(self):
"""Reimplemented get string"""
return self.__label
def rebuild(self):
if self.__stage_item.stage_model.flat:
self.__label = str(self.__stage_item.path)
else:
if self.__stage_item.path == Sdf.Path.absoluteRootPath:
self.__label = "Root:"
elif self.__stage_item.stage_model.show_prim_displayname:
self.__label = self.__stage_item.display_name
else:
self.__label = self.__stage_item.name
def begin_edit(self):
self.__old_label = self.__label
self.__label_on_begin = self.__stage_item.name
self.__label = self.__label_on_begin
if self.__old_label != self.__label:
self._value_changed()
def set_value(self, value):
"""Reimplemented set"""
try:
value = str(value)
except ValueError:
value = ""
if value != self.__label:
self.__label = value
self._value_changed()
def end_edit(self):
if self.__label_on_begin == self.__label:
if self.__label != self.__old_label:
self.__label = self.__old_label
self._value_changed()
return
# Get the unique name
# replacing invalid characters with '_' if it's to display path name.
parent_path = self.__stage_item.path.GetParentPath()
valid_label_identifier = Tf.MakeValidIdentifier(self.__label)
new_prim_name = valid_label_identifier
counter = 1
while True:
created_path = parent_path.AppendElementString(new_prim_name)
if not self.__stage_item.stage.GetPrimAtPath(created_path):
break
new_prim_name = "{}_{:02d}".format(valid_label_identifier, counter)
counter += 1
stage_model = self.__stage_item.stage_model
if stage_model.rename_prim(self.__stage_item.path, new_prim_name):
self.__refresh_name_prefix_and_suffix()
self._value_changed()
if not stage_model.show_prim_displayname:
self.__label = new_prim_name
| 4,442 | Python | 32.156716 | 106 | 0.576317 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_drag_drop.py | import pathlib
import omni.kit.test
from pxr import UsdShade
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class TestStageDragDrop(OmniUiTest):
async def setUp(self):
await super().setUp()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests")
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_prim_reparent(self):
app = omni.kit.app.get_app()
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
stage = usd_context.get_stage()
world_prim = stage.DefinePrim("/World2", "Xform")
cube_prim = stage.DefinePrim("/cube", "Cube")
await app.next_update_async()
await app.next_update_async()
stage_window = ui_test.find("Stage")
await stage_window.focus()
stage_window.window._stage_widget._tree_view.root_visible=True
await app.next_update_async()
await app.next_update_async()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
absolute_prim_item = stage_tree.find("**/Label[*].text=='Root:'")
world_prim_item = stage_tree.find("**/Label[*].text=='World2'")
cube_prim_item = stage_tree.find("**/Label[*].text=='cube'")
self.assertTrue(absolute_prim_item)
self.assertTrue(cube_prim_item)
self.assertTrue(world_prim_item)
await cube_prim_item.drag_and_drop(world_prim_item.center)
await app.next_update_async()
await app.next_update_async()
self.assertTrue(stage.GetPrimAtPath("/World2/cube"))
self.assertFalse(stage.GetPrimAtPath("/cube"))
cube_prim_item = stage_tree.find("**/Label[*].text=='cube'")
self.assertTrue(cube_prim_item)
await cube_prim_item.drag_and_drop(absolute_prim_item.center)
await app.next_update_async()
await app.next_update_async()
self.assertFalse(stage.GetPrimAtPath("/World2/cube"))
self.assertTrue(stage.GetPrimAtPath("/cube"))
async def test_material_drag_drop_preview(self):
await arrange_windows(hide_viewport=True)
usd_context = omni.usd.get_context()
test_file_path = self._test_path.joinpath("usd/cube.usda").absolute()
test_material_path = self._test_path.joinpath("mtl/mahogany_floorboards.mdl").absolute()
await usd_context.open_stage_async(str(test_file_path))
await ui_test.human_delay()
# get cube prim
stage = omni.usd.get_context().get_stage()
world_prim = stage.GetPrimAtPath("/World")
cube_prim = stage.GetPrimAtPath("/World/Cube")
# select cube prim to expand the stage list...
usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True)
await ui_test.human_delay()
usd_context.get_selection().clear_selected_prim_paths()
await ui_test.human_delay()
# check bound material
bound_material, _ = UsdShade.MaterialBindingAPI(cube_prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
stage_window = ui_test.find("Stage")
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
await content_browser_helper.drag_and_drop_tree_view(str(test_material_path), drag_target=drag_target)
# select new material prim
mahogany_prim = stage.GetPrimAtPath("/World/Looks/mahogany_floorboards")
self.assertTrue(mahogany_prim.GetPrim().IsValid())
await ui_test.human_delay()
# check /World isn't bound
bound_material, _ = UsdShade.MaterialBindingAPI(world_prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# check /World/Cube isn't bound
bound_material, _ = UsdShade.MaterialBindingAPI(cube_prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
for widget in stage_tree.find_all("**/Label[*].text=='Cube'"):
await content_browser_helper.drag_and_drop_tree_view(str(test_material_path), drag_target=widget.center)
break
# select cube prim
usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True)
await ui_test.human_delay()
# check bound material
bound_material, _ = UsdShade.MaterialBindingAPI(cube_prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid())
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == "/World/Looks/mahogany_floorboards_01")
# check /World isn't bound
bound_material, _ = UsdShade.MaterialBindingAPI(world_prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
| 5,432 | Python | 42.814516 | 120 | 0.658689 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/drag_drop_path.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import os
import omni.kit.app
import omni.usd
import carb
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class DragDropFileStagePath(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows(hide_viewport=True)
await open_stage(get_test_data_path(__name__, "usd/cube.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
async def test_l1_drag_drop_path_usd_stage_absolute(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
stage_window = ui_test.find("Stage")
await stage_window.focus()
# drag/drop from content browser to stage window
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertTrue(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_usd_stage_relative(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
stage_window = ui_test.find("Stage")
await stage_window.focus()
# drag/drop from content browser to stage window
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertFalse(os.path.isabs(asset.path))
| 3,407 | Python | 45.054053 | 119 | 0.706487 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_export_selected.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 os
import omni.kit.app
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper
from omni.kit.window.file_exporter import get_instance as get_file_exporter
class TestExportSelected(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
stage_window = ui_test.find("Stage")
await stage_window.focus()
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_stage_menu_export_selected_single_prim(self):
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Cone"]
test_file = os.path.join(omni.kit.test.get_test_output_path(), "save_single_selected_prim.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# load created file
await open_stage(test_file)
await wait_stage_loading()
# verify prims
stage = omni.usd.get_context().get_stage()
prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(prims, ['/Root', '/Root/Cone'])
# close stage & delete file
await omni.usd.get_context().new_stage_async()
async def test_l1_stage_menu_export_selected_multiple_prims(self):
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Cone", "/World/Cube", "/World/Sphere", "/World/Cylinder"]
test_file = os.path.join(omni.kit.test.get_test_output_path(), "save_multiple_selected_prim.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# load created file
await open_stage(test_file)
await wait_stage_loading()
# verify prims
stage = omni.usd.get_context().get_stage()
prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(prims, ['/Root', '/Root/Cone', '/Root/Cone/Cone', '/Root/Cube', '/Root/Cube/Cube', '/Root/Sphere', '/Root/Sphere/Sphere', '/Root/Cylinder', '/Root/Cylinder/Cylinder'])
# close stage & delete file
await omni.usd.get_context().new_stage_async()
async def test_l1_stage_menu_export_selected_single_material(self):
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Looks/OmniPBR"]
test_file = os.path.join(omni.kit.test.get_test_output_path(), "save_single_selected_material.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# load created file
await open_stage(test_file)
await wait_stage_loading()
# verify prims
stage = omni.usd.get_context().get_stage()
prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(prims, ['/Root', '/Root/OmniPBR', '/Root/OmniPBR/Shader'])
# close stage & delete file
await omni.usd.get_context().new_stage_async()
async def test_l1_stage_menu_export_selected_multiple_materials(self):
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Looks/OmniPBR", "/World/Looks/OmniGlass", "/World/Looks/OmniSurface_Plastic"]
test_file = os.path.join(omni.kit.test.get_test_output_path(), "save_multiple_selected_material.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# load created file
await open_stage(test_file)
await wait_stage_loading()
# verify prims
stage = omni.usd.get_context().get_stage()
prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(prims, ['/Root', '/Root/OmniPBR', '/Root/OmniPBR/Shader', '/Root/OmniGlass', '/Root/OmniGlass/Shader', '/Root/OmniSurface_Plastic', '/Root/OmniSurface_Plastic/Shader'])
# close stage & delete file
await omni.usd.get_context().new_stage_async()
async def test_stage_menu_export_selected_prefill(self):
"""Test that export selected pre-fill prim name and save directory."""
stage = omni.usd.get_context().get_stage()
to_select = ["/World/Cone", "/World/Cube", "/World/Sphere", "/World/Cylinder"]
output_dir = omni.kit.test.get_test_output_path()
test_file = os.path.join(output_dir, "test_prefill.usd")
# select prims
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
# check that prim name is pre-fill with the first prim name
exporter = get_file_exporter()
filename = exporter._dialog.get_filename()
self.assertEqual(filename, "Cone")
# check that current directory is the same as the stage directory
dirname = exporter._dialog.get_current_directory()
self.assertEqual(dirname.rstrip("/").lower(),
os.path.dirname(stage.GetRootLayer().realPath).replace("\\", "/").lower())
await file_export_helper.click_apply_async(filename_url=test_file)
await wait_stage_loading()
# right click again, now the default directory for save should update to the last save directory
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
exporter = get_file_exporter()
# check that current directory is the same as the stage directory
dirname = exporter._dialog.get_current_directory()
self.assertEqual(dirname.rstrip("/").lower(), output_dir.replace("\\", "/").lower())
await file_export_helper.click_cancel_async()
# load another file
output_dir = get_test_data_path(__name__, "usd")
await open_stage(os.path.join(output_dir, "cube.usda"))
await wait_stage_loading()
stage = omni.usd.get_context().get_stage()
# check that current directory is the same as the stage directory
to_select = ["/World/Cube"]
await select_prims(to_select)
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{to_select[0]}'").right_click()
# click on context menu item & save
async with FileExporterTestHelper() as file_export_helper:
await ui_test.select_context_menu("Save Selected")
await file_export_helper.wait_for_popup()
# check that prim name is pre-fill with the selected prim name
exporter = get_file_exporter()
filename = exporter._dialog.get_filename()
self.assertEqual(filename, "Cube")
# check that current directory is the same as the stage directory
dirname = exporter._dialog.get_current_directory()
self.assertEqual(dirname.rstrip("/").lower(),
os.path.dirname(stage.GetRootLayer().realPath).replace("\\", "/").lower())
await file_export_helper.click_cancel_async()
# close stage & delete file
await omni.usd.get_context().new_stage_async() | 10,890 | Python | 46.147186 | 193 | 0.645087 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/drag_drop_single.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import omni.usd
from pxr import UsdGeom
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
get_prims,
wait_stage_loading,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropFileStageSingle(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows(hide_viewport=True)
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_drag_drop_single_usd_stage(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
await ui_test.find("Content").focus()
await ui_test.find("Stage").focus()
# verify prims
paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader'])
# drag/drop files to stage window
async with ContentBrowserTestHelper() as content_browser_helper:
stage_window = ui_test.find("Stage")
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
for file_path in ["4Lights.usda", "quatCube.usda"]:
await content_browser_helper.drag_and_drop_tree_view(get_test_data_path(__name__, file_path), drag_target=drag_target)
# verify prims
paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader', '/World/_Lights', '/World/_Lights/SphereLight_01', '/World/_Lights/SphereLight_02', '/World/_Lights/SphereLight_03', '/World/_Lights/SphereLight_00', '/World/_Lights/Cube', '/World/quatCube', '/World/quatCube/Cube'])
async def test_drag_drop_to_default_prim(self):
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
await ui_test.find("Content").focus()
await ui_test.find("Stage").focus()
stage = usd_context.get_stage()
prim = stage.DefinePrim("/test", "Xform")
prim2 = stage.DefinePrim("/test2", "Xform")
prim3 = UsdGeom.Mesh.Define(stage, "/test3").GetPrim()
total_root_prims = 3
"""
OM-66707
Rules:
1. When it has no default prim, it will create pseudo root prim reference.
2. When it has default prim, it will create reference under default prim.
3. When the default prim is a gprim, it will create reference under pseudo root prim too as gprims
cannot have children.
"""
for default_prim in [None, prim, prim2, prim3]:
if default_prim:
stage.SetDefaultPrim(default_prim)
else:
stage.ClearDefaultPrim()
# drag/drop files to stage window
async with ContentBrowserTestHelper() as content_browser_helper:
stage_window = ui_test.find("Stage")
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32)
for file_path in ["4Lights.usda", "quatCube.usda"]:
await content_browser_helper.drag_and_drop_tree_view(get_test_data_path(__name__, file_path), drag_target=drag_target)
if default_prim and default_prim != prim3:
self.assertEqual(len(prim.GetChildren()), 2)
else:
total_root_prims += 2
all_root_prims = [prim for prim in stage.GetPseudoRoot().GetChildren() if not omni.usd.is_hidden_type(prim)]
self.assertEqual(len(all_root_prims), total_root_prims)
| 4,963 | Python | 46.730769 | 557 | 0.659279 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_stage_widget.py | import carb
import omni
import omni.kit.test
import omni.usd
import omni.client
import omni.kit.widget.stage
import omni.kit.app
import omni.kit.ui_test as ui_test
from omni.kit.test_suite.helpers import arrange_windows
from pxr import UsdGeom
class TestStageWidget(omni.kit.test.AsyncTestCase):
async def setUp(self):
self.app = omni.kit.app.get_app()
await arrange_windows("Stage", 800, 600)
self.usd_context = omni.usd.get_context()
await self.usd_context.new_stage_async()
self.stage = omni.usd.get_context().get_stage()
async def tearDown(self):
pass
async def wait(self, frames=4):
for i in range(frames):
await self.app.next_update_async()
async def test_visibility_toggle(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
prim = self.stage.DefinePrim("/prim0", "Xform")
await self.wait()
prim_visibility_widget = stage_tree.find("**/ToolButton[*].name=='visibility'")
self.assertTrue(prim_visibility_widget)
await prim_visibility_widget.click()
await self.wait()
self.assertEqual(UsdGeom.Imageable(prim).ComputeVisibility(), UsdGeom.Tokens.invisible)
prim_visibility_widget = stage_tree.find("**/ToolButton[*].name=='visibility'")
self.assertTrue(prim_visibility_widget)
await prim_visibility_widget.click()
await self.wait()
self.assertEqual(UsdGeom.Imageable(prim).ComputeVisibility(), UsdGeom.Tokens.inherited)
async def test_search_widget(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
self.assertTrue(stage_tree)
stage_model = stage_tree.widget.model
search_field = ui_test.find("Stage//Frame/**/StringField[*].name=='search'")
self.assertTrue(search_field)
prim1 = self.stage.DefinePrim("/prim", "Xform")
prim2 = self.stage.DefinePrim("/prim/prim1", "Xform")
prim3 = self.stage.DefinePrim("/prim/prim2", "Xform")
prim4 = self.stage.DefinePrim("/other", "Xform")
await self.wait()
await search_field.input("prim")
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await self.wait()
all_children = stage_model.get_item_children(None)
all_names = [child.name for child in all_children]
search_field.widget.model.set_value("")
await search_field.input("")
await self.wait()
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await self.wait()
self.assertTrue(prim4.GetName() not in all_names)
| 2,703 | Python | 36.041095 | 95 | 0.659267 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_stage_model.py | import carb
import os
import tempfile
import omni
import omni.kit.test
import omni.usd
import omni.client
import string
import random
import omni.ui as ui
# Don't remove. Including those two deprecated modules for code coverage.
from omni.kit.widget.stage.stage_helper import *
from omni.kit.widget.stage.usd_property_watch import *
from omni.kit.widget.stage import StageWidget
from omni.kit.widget.stage import StageItem, StageItemSortPolicy
from omni.kit.widget.stage import StageColumnDelegateRegistry, AbstractStageColumnDelegate, StageColumnItem
from pxr import Sdf, Usd, UsdGeom, Gf
SETTINGS_KEEP_CHILDREN_ORDER = "/persistent/ext/omni.usd/keep_children_order"
class TestColumnDelegate(AbstractStageColumnDelegate):
def __init__(self):
super().__init__()
def destroy(self):
pass
@property
def initial_width(self):
"""The width of the column"""
return ui.Pixel(20)
def build_header(self, **kwargs):
"""Build the header"""
pass
async def build_widget(self, item: StageColumnItem, **kwargs):
pass
class TestStageModel(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self.usd_context = omni.usd.get_context()
await self.usd_context.new_stage_async()
self.stage = self.usd_context.get_stage()
self.stage.GetRootLayer().Clear()
self.stage_widget = StageWidget(self.stage)
self.app = omni.kit.app.get_app()
self.old_keep_children_order = carb.settings.get_settings().get(SETTINGS_KEEP_CHILDREN_ORDER)
async def tearDown(self):
if self.old_keep_children_order is not None:
carb.settings.get_settings().set(SETTINGS_KEEP_CHILDREN_ORDER, self.old_keep_children_order)
self.stage_widget.destroy()
self.stage_widget = None
await self.usd_context.close_stage_async()
async def test_prim_item_api(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
self.assertTrue(root_stage_item.visibility_model)
self.assertTrue(root_stage_item.type_model)
self.assertTrue(root_stage_item.name_model)
async def test_show_prim_displayname(self):
self.stage_widget.show_prim_display_name = False
prim = self.stage.DefinePrim("/test", "Xform")
self.stage.DefinePrim("/test100", "Xform")
self.stage.DefinePrim("/test200", "Xform")
omni.usd.editor.set_display_name(prim, "display name test")
await self.app.next_update_async()
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
stage_items = stage_model.get_item_children(root_stage_item)
self.assertTrue(stage_items)
prim_item = stage_items[0]
self.assertTrue(prim_item)
self.assertEqual(prim_item.name, "test")
self.assertEqual(prim_item.display_name, "display name test")
self.assertEqual(prim_item.name_model.get_value_as_string(), "test")
# Change it to display name will show its display name instead
self.stage_widget.show_prim_display_name = True
await self.app.next_update_async()
await self.app.next_update_async()
self.assertEqual(prim_item.name, "test")
self.assertEqual(prim_item.display_name, "display name test")
self.assertEqual(prim_item.name_model.get_value_as_string(), prim_item.display_name)
# Empty display name will show path name instead
omni.usd.editor.set_display_name(prim, "")
await self.app.next_update_async()
self.assertEqual(prim_item.name, "test")
self.assertEqual(prim_item.display_name, prim_item.name)
self.assertEqual(prim_item.name_model.get_value_as_string(), prim_item.display_name)
# Emulate rename, it will rename prim name even it shows display name.
stage_items = stage_model.get_item_children(root_stage_item)
omni.usd.editor.set_display_name(prim, "display name test")
await self.app.next_update_async()
prim_item.name_model.begin_edit()
prim_item.name_model.set_value("test3")
prim_item.name_model.end_edit()
await self.app.next_update_async()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertTrue(stage_items)
prim_item = stage_items[-1]
self.assertEqual(prim_item.name, "test3")
self.assertEqual(prim_item.display_name, "display name test")
self.assertEqual(prim_item.name_model.get_value_as_string(), prim_item.display_name)
# Make sure change display name will not influence prim path.
self.assertFalse(self.stage.GetPrimAtPath("/test"))
self.assertTrue(self.stage.GetPrimAtPath("/test3"))
self.assertEqual(stage_items[0].path, Sdf.Path("/test100"))
self.assertEqual(stage_items[1].path, Sdf.Path("/test200"))
self.assertEqual(stage_items[2].path, Sdf.Path("/test3"))
self.stage_widget.show_prim_display_name = False
prim_item.name_model.begin_edit()
prim_item.name_model.set_value("test2")
prim_item.name_model.end_edit()
await self.app.next_update_async()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertTrue(stage_items)
prim_item = stage_items[-1]
self.assertEqual(prim_item.name, "test2")
self.assertEqual(prim_item.display_name, "display name test")
self.assertEqual(prim_item.name_model.get_value_as_string(), prim_item.name)
self.assertFalse(self.stage.GetPrimAtPath("/test3"))
self.assertTrue(self.stage.GetPrimAtPath("/test2"))
def create_flat_prims(self, stage, parent_path, num):
prim_paths = set([])
for i in range(num):
prim = stage.DefinePrim(parent_path.AppendElementString(f"xform{i}"), "Xform")
translation = Gf.Vec3d(-200, 0.0, 0.0)
common_api = UsdGeom.XformCommonAPI(prim)
common_api.SetTranslate(translation)
prim_paths.add(prim.GetPath())
return prim_paths
def get_all_stage_items(self, stage_item: StageItem):
stage_items = set([])
q = [stage_item]
if stage_item.path != Sdf.Path.absoluteRootPath:
stage_items.add(stage_item)
while len(q) > 0:
item = q.pop()
# Populating it if it's not.
children = item.stage_model.get_item_children(item)
for child in children:
stage_items.add(child)
q.append(child)
return stage_items
def get_all_stage_item_paths(self, stage_item):
stage_items = self.get_all_stage_items(stage_item)
paths = [item.path for item in stage_items]
return set(paths)
def create_prims(self, stage, parent_prim_path, level=[]):
if not level:
return set([])
prim_paths = self.create_flat_prims(stage, parent_prim_path, level[0])
all_child_paths = set([])
for prim_path in prim_paths:
all_child_paths.update(self.create_prims(stage, prim_path, level[1:]))
prim_paths.update(all_child_paths)
return prim_paths
def check_prim_children(self, prim_item: StageItem, expected_children_prim_paths):
paths = set({})
children = prim_item.stage_model.get_item_children(prim_item)
for child in children:
paths.add(child.path)
if children:
self.assertTrue(prim_item.stage_model.can_item_have_children(prim_item))
else:
self.assertFalse(prim_item.stage_model.can_item_have_children(prim_item))
self.assertEqual(paths, set(expected_children_prim_paths))
def check_prim_tree(self, prim_item: StageItem, expected_prim_paths):
paths = self.get_all_stage_item_paths(prim_item)
self.assertEqual(set(paths), set(expected_prim_paths))
async def test_prims_create(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, prim_paths)
async def test_prims_edits(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
await self.app.next_update_async()
# Populate children of root prim
stage_model.get_item_children(None)
prim1_of_root = root_stage_item.children[0].path
omni.kit.commands.execute(
"DeletePrims",
paths=[prim1_of_root]
)
await self.app.next_update_async()
changed_prims = prim_paths.copy()
for path in prim_paths:
if path.HasPrefix(prim1_of_root):
changed_prims.discard(path)
self.check_prim_tree(root_stage_item, changed_prims)
omni.kit.undo.undo()
await self.app.next_update_async()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, prim_paths)
async def test_layer_flush(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, prim_paths)
self.stage.GetRootLayer().Clear()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, set([]))
async def test_parenting_prim_refresh(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
# Creates 3 prims
prim_paths = list(self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [3]))
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, set(prim_paths))
# Moves first two prims as the children of the 3rd one.
new_path0 = prim_paths[2].AppendElementString(prim_paths[0].name)
new_path1 = prim_paths[2].AppendElementString(prim_paths[1].name)
omni.kit.commands.execute("MovePrim", path_from=prim_paths[0], path_to=new_path0)
omni.kit.commands.execute("MovePrim", path_from=prim_paths[1], path_to=new_path1)
await self.app.next_update_async()
await self.app.next_update_async()
self.assertEqual(len(root_stage_item.children), 1)
self.assertEqual(root_stage_item.children[0].path, prim_paths[2])
self.check_prim_children(root_stage_item.children[0], set([new_path0, new_path1]))
omni.kit.undo.undo()
await self.app.next_update_async()
self.check_prim_children(root_stage_item, set(prim_paths[1:3]))
self.check_prim_tree(root_stage_item, set([new_path0, prim_paths[1], prim_paths[2]]))
omni.kit.undo.undo()
await self.app.next_update_async()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, set(prim_paths))
async def test_filter_prim(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
await self.app.next_update_async()
# Flat search
stage_model.flat = True
stage_model.filter_by_text("xform")
self.check_prim_children(root_stage_item, prim_paths)
children = root_stage_item.children
for child in children:
self.assertTrue(not child.children)
children = stage_model.get_item_children(root_stage_item)
paths = []
for child in children:
paths.append(child.path)
self.assertEqual(set(paths), set(prim_paths))
expected_paths = set([])
for path in prim_paths:
if str(path).endswith("xform0"):
expected_paths.add(path)
stage_model.filter_by_text("xform0")
children = stage_model.get_item_children(root_stage_item)
paths = []
for child in children:
paths.append(child.path)
self.assertEqual(set(paths), set(expected_paths))
# Non-flat search
stage_model.flat = False
stage_model.filter_by_text("xform")
self.check_prim_tree(root_stage_item, prim_paths)
children = root_stage_item.children
for child in children:
self.assertFalse(not child.children)
# Filtering with lambda
# Reset all states
stage_model.filter_by_text(None)
stage_model.filter(add={"Camera" : lambda prim: prim.IsA(UsdGeom.Camera)})
self.check_prim_tree(root_stage_item, [])
stage_model.filter(remove=["Camera"])
self.check_prim_tree(root_stage_item, prim_paths)
children = root_stage_item.children
for child in children:
self.assertFalse(not child.children)
stage_model.filter(add={"Xform" : lambda prim: prim.IsA(UsdGeom.Xform)})
self.check_prim_tree(root_stage_item, prim_paths)
camera = self.stage.DefinePrim("/new_group/camera0", "Camera")
await self.app.next_update_async()
await self.app.next_update_async()
# Adds new camera will still not be filtered as only xform is filtered currently
self.check_prim_tree(root_stage_item, prim_paths)
# Filters camera also
stage_model.filter(add={"Camera" : lambda prim: prim.IsA(UsdGeom.Camera)})
all_paths = []
all_paths.extend(prim_paths)
all_paths.append(camera.GetPath())
# Needs to add parent also as it's in non-flat mode
all_paths.append(camera.GetPath().GetParentPath())
self.check_prim_tree(root_stage_item, all_paths)
# Creates another camera and filter it.
camera1 = self.stage.DefinePrim("/new_group2/camera1", "Camera")
all_paths.append(camera1.GetPath())
all_paths.append(camera1.GetPath().GetParentPath())
await self.app.next_update_async()
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, all_paths)
# Filters with both types and texts.
stage_model.filter_by_text("camera")
all_paths = [
camera.GetPath(), camera.GetPath().GetParentPath(),
camera1.GetPath(), camera1.GetPath().GetParentPath()
]
self.check_prim_tree(root_stage_item, all_paths)
# Add new reference layer will be filtered also
reference_layer = Sdf.Layer.CreateAnonymous()
ref_stage = Usd.Stage.Open(reference_layer)
prim = ref_stage.DefinePrim("/root/camera_reference", "Camera")
default_prim = prim.GetParent()
ref_stage.SetDefaultPrim(default_prim)
reference_prim = self.stage.DefinePrim("/root", "Xform")
reference_prim.GetReferences().AddReference(reference_layer.identifier)
await self.app.next_update_async()
await self.app.next_update_async()
all_paths.append(prim.GetPath())
all_paths.append(default_prim.GetPath())
self.check_prim_tree(root_stage_item, all_paths)
# Add new sublayer too.
reference_layer = Sdf.Layer.CreateAnonymous()
sublayer_stage = Usd.Stage.Open(reference_layer)
prim = sublayer_stage.DefinePrim("/root/camera_sublayer", "Camera")
self.stage.GetRootLayer().subLayerPaths.append(reference_layer.identifier)
await self.app.next_update_async()
await self.app.next_update_async()
all_paths.append(prim.GetPath())
self.check_prim_tree(root_stage_item, all_paths)
# Clear all
stage_model.filter(clear=True)
stage_model.filter_by_text("")
prim_paths.update(all_paths)
self.check_prim_tree(root_stage_item, prim_paths)
async def test_find_full_chain(self):
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
prim_paths = self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [10, 5, 4, 2])
await self.app.next_update_async()
await self.app.next_update_async()
path = Sdf.Path("/xform0/xform0/xform0/xform0")
full_chain = stage_model.find_full_chain("/xform0/xform0/xform0/xform0")
self.assertEqual(len(full_chain), 5)
self.assertEqual(full_chain[0], root_stage_item)
prefixes = path.GetPrefixes()
for i in range(len(prefixes)):
self.assertEqual(full_chain[i + 1].path, prefixes[i])
async def test_has_missing_references(self):
stage_model = self.stage_widget.get_model()
self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [1])
path = Sdf.Path("/xform0")
full_chain = stage_model.find_full_chain(path)
self.assertEqual(len(full_chain), 2)
# Prim /xform0
prim_item = full_chain[1]
self.assertFalse(prim_item.has_missing_references)
prim = self.stage.GetPrimAtPath(path)
prim.GetReferences().AddReference("./face-invalid-non-existed-file.usd")
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(prim_item.has_missing_references)
async def test_instanceable_flag_change(self):
# OM-70714: Change instanceable flag will refresh children's instance_proxy flag.
with tempfile.TemporaryDirectory() as tmpdirname:
# save the file
tmp_file_path = os.path.join(tmpdirname, "tmp.usda")
result = await omni.usd.get_context().save_as_stage_async(tmp_file_path)
self.assertTrue(result)
stage = omni.usd.get_context().get_stage()
prim = stage.DefinePrim("/World/cube", "Xform")
stage.SetDefaultPrim(prim)
stage.Save()
await omni.usd.get_context().new_stage_async()
stage = omni.usd.get_context().get_stage()
prim = stage.DefinePrim("/World/Reference", "Xform")
prim.GetReferences().AddReference(tmp_file_path)
omni.kit.commands.execute("CopyPrim", path_from="/World/Reference", path_to="/World/Reference2")
prim2 = stage.GetPrimAtPath("/World/Reference2")
self.assertTrue(prim2)
prim.SetInstanceable(True)
prim2.SetInstanceable(True)
await self.app.next_update_async()
await self.app.next_update_async()
self.stage_widget = StageWidget(stage)
stage_model = self.stage_widget.get_model()
# Populate all childrens
stage_model.find_full_chain("/World/Reference/cube")
stage_model.find_full_chain("/World/Reference2/cube")
reference_item = stage_model.find("/World/Reference")
reference2_item = stage_model.find("/World/Reference2")
self.assertTrue(reference_item and reference2_item)
for item in [reference_item, reference2_item]:
self.assertTrue(item.instanceable)
for child in item.children:
self.assertTrue(child.instance_proxy)
prim2.SetInstanceable(False)
await self.app.next_update_async()
for child in reference_item.children:
self.assertTrue(child.instance_proxy)
for child in reference2_item.children:
self.assertFalse(child.instance_proxy)
async def _test_sorting_internal(self, prim_paths, sort_policy, sort_func, reverse):
self.stage_widget = StageWidget(self.stage)
stage_model = self.stage_widget.get_model()
stage_model.set_items_sort_policy(sort_policy)
await self.app.next_update_async()
await self.app.next_update_async()
# Checkes all items to see if their children are sorted correctly.
root_stage_item = stage_model.root
queue = [root_stage_item]
while queue:
item = queue.pop()
children = stage_model.get_item_children(item)
if not children:
continue
queue.extend(children)
if item == root_stage_item:
expected_children_paths = list(prim_paths.keys())
else:
expected_children_paths = list(prim_paths[str(item.path)])
if sort_func:
expected_children_paths.sort(key=sort_func, reverse=reverse)
elif reverse:
expected_children_paths.reverse()
children_paths = [str(child.path) for child in children]
self.assertEqual(children_paths, expected_children_paths)
async def test_sorting(self):
# Generating test data
prim_paths = {}
types = ["Cube", "Cone", "Sphere", "Xform", "Cylinder", "Capsule"]
prim_types = {}
prim_visibilities = {}
with Sdf.ChangeBlock():
for i in range(0, 26):
letter = random.choice(string.ascii_letters)
parent_path = f"/{letter}{i}"
prim_type = random.choice(types)
spec = Sdf.CreatePrimInLayer(self.stage.GetRootLayer(), parent_path)
spec.typeName = prim_type
children_paths = []
prim_types[parent_path] = prim_type
prim_visibilities[parent_path] = True
for j in range(0, 100):
letter = random.choice(string.ascii_letters)
prim_type = random.choice(types)
spec = Sdf.CreatePrimInLayer(self.stage.GetRootLayer(), f"{parent_path}/{letter}{j}")
spec.typeName = prim_type
children_paths.append(str(spec.path))
prim_types[str(spec.path)] = prim_type
visible = random.choice([True, False])
prim_visibilities[str(spec.path)] = visible
prim_paths[parent_path] = children_paths
for path, value in prim_visibilities.items():
prim = self.stage.GetPrimAtPath(path)
if prim:
imageable = UsdGeom.Imageable(prim)
if not value:
imageable.MakeInvisible()
visiblity = imageable.ComputeVisibility()
await self._test_sorting_internal(prim_paths, StageItemSortPolicy.DEFAULT, None, False)
await self._test_sorting_internal(prim_paths, StageItemSortPolicy.NAME_COLUMN_OLD_TO_NEW, None, False)
await self._test_sorting_internal(prim_paths, StageItemSortPolicy.NAME_COLUMN_NEW_TO_OLD, None, True)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.NAME_COLUMN_A_TO_Z, lambda x: Sdf.Path(x).name.lower(), False
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.NAME_COLUMN_Z_TO_A, lambda x: Sdf.Path(x).name.lower(), True
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.TYPE_COLUMN_A_TO_Z,
lambda x, p=prim_types: p[x].lower(),
False
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.TYPE_COLUMN_Z_TO_A,
lambda x, p=prim_types: p[x].lower(),
True,
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE,
lambda x, p=prim_visibilities: 1 if p[x] else 0,
False
)
await self._test_sorting_internal(
prim_paths,
StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE,
lambda x, p=prim_visibilities: 0 if p[x] else 1,
False
)
async def test_column_delegate(self):
sub = StageColumnDelegateRegistry().register_column_delegate("test", TestColumnDelegate)
self.assertEqual(StageColumnDelegateRegistry().get_column_delegate("test"), TestColumnDelegate)
names = StageColumnDelegateRegistry().get_column_delegate_names()
self.assertTrue("test" in names)
async def test_item_destroy(self):
destroyed_paths = []
def on_items_destroyed(items):
nonlocal destroyed_paths
for item in items:
destroyed_paths.append(item.path)
stage_model = self.stage_widget.get_model()
prim_paths = list(self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [3]))
root_stage_item = stage_model.root
# Populate root node
stage_model.get_item_children(root_stage_item)
sub = stage_model.subscribe_stage_items_destroyed(on_items_destroyed)
self.stage.RemovePrim(prim_paths[0])
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(len(destroyed_paths) == 1)
self.assertEqual(destroyed_paths[0], prim_paths[0])
async def test_stage_item_properties(self):
stage_model = self.stage_widget.get_model()
stage = stage_model.stage
xform_prim = stage.DefinePrim("/test_prim", "Xform")
await self.app.next_update_async()
await self.app.next_update_async()
# Populate root node
stage_model.get_item_children(stage_model.root)
stage_item = stage_model.find(xform_prim.GetPath())
self.assertTrue(stage_item)
self.assertEqual(stage_item.name, "test_prim")
self.assertEqual(stage_item.type_name, "Xform")
self.assertTrue(stage_item.active)
self.assertFalse(stage_item.has_missing_references)
self.assertFalse(stage_item.payrefs)
self.assertFalse(stage_item.is_default)
self.assertFalse(stage_item.is_outdated)
self.assertFalse(stage_item.in_session)
self.assertFalse(stage_item.auto_reload)
self.assertEqual(stage_item.root_identifier, stage.GetRootLayer().identifier)
self.assertFalse(stage_item.instance_proxy)
self.assertFalse(stage_item.instanceable)
self.assertTrue(stage_item.visible)
self.assertFalse(stage_item.payloads)
self.assertFalse(stage_item.references)
self.assertTrue(stage_item.prim)
stage.SetDefaultPrim(xform_prim)
xform_prim.SetInstanceable(True)
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(stage_item.is_default)
self.assertTrue(stage_item.instanceable)
xform_prim.SetActive(False)
await self.app.next_update_async()
await self.app.next_update_async()
self.assertFalse(stage_item.active)
xform_prim = stage.GetPrimAtPath("/test_prim")
xform_prim.SetActive(True)
xform_prim = stage.GetPrimAtPath("/test_prim")
# Changes active property will resync stage_item
stage_model.get_item_children(stage_model.root)
stage_item = stage_model.find(xform_prim.GetPath())
UsdGeom.Imageable(xform_prim).MakeInvisible()
await self.app.next_update_async()
await self.app.next_update_async()
self.assertFalse(stage_item.visible)
UsdGeom.Imageable(xform_prim).MakeVisible()
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(stage_item.visible)
xform_prim.GetReferences().AddReference("__non_existed_reference.usd")
xform_prim.GetReferences().AddInternalReference("/non_existed_prim")
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(stage_item.has_missing_references)
self.assertEqual(stage_item.payrefs, ["__non_existed_reference.usd"])
self.assertTrue(stage_item.references)
self.assertFalse(stage_item.payloads)
xform_prim.GetPayloads().AddPayload("__non_existed_payload.usd")
await self.app.next_update_async()
await self.app.next_update_async()
self.assertTrue(stage_item.has_missing_references)
# Internal references will not be listed.
self.assertEqual(
set(stage_item.payrefs),
set(["__non_existed_reference.usd", "__non_existed_payload.usd"])
)
self.assertTrue(stage_item.references)
self.assertTrue(stage_item.payloads)
async def test_reorder_prim(self):
self.stage_widget.children_reorder_supported = True
stage_model = self.stage_widget.get_model()
root_stage_item = stage_model.root
# Creates 3 prims
prim_paths = list(self.create_prims(self.stage, Sdf.Path.absoluteRootPath, [3]))
await self.app.next_update_async()
self.check_prim_tree(root_stage_item, set(prim_paths))
# Moves first two prims as the children of the 3rd one.
self.assertTrue(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=2))
self.assertTrue(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=1))
self.assertFalse(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=-1))
children = root_stage_item.children
prim_paths = [item.path for item in children]
stage_model.drop(root_stage_item, root_stage_item.children[0], drop_location=2)
await self.app.next_update_async()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 3)
self.assertEqual(stage_items[0].path, prim_paths[1])
self.assertEqual(stage_items[1].path, prim_paths[0])
self.assertEqual(stage_items[2].path, prim_paths[2])
omni.kit.undo.undo()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 3)
self.assertEqual(stage_items[0].path, prim_paths[0])
self.assertEqual(stage_items[1].path, prim_paths[1])
self.assertEqual(stage_items[2].path, prim_paths[2])
# Disable reorder
self.stage_widget.children_reorder_supported = False
self.assertFalse(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=2))
self.assertFalse(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=1))
self.assertFalse(stage_model.drop_accepted(root_stage_item, root_stage_item.children[0], drop_location=-1))
self.stage_widget.children_reorder_supported = True
# Renaming prim will still keep the location of prim.
# Enable setting to keep children order after rename.
carb.settings.get_settings().set(SETTINGS_KEEP_CHILDREN_ORDER, True)
stage_item = root_stage_item.children[0]
stage_item.name_model.begin_edit()
stage_item.name_model.set_value("renamed_item")
stage_item.name_model.end_edit()
await self.app.next_update_async()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 3)
self.assertEqual(stage_items[0].path, Sdf.Path("/renamed_item"))
self.assertEqual(stage_items[1].path, prim_paths[1])
self.assertEqual(stage_items[2].path, prim_paths[2])
omni.kit.undo.undo()
await self.app.next_update_async()
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 3)
self.assertEqual(stage_items[0].path, prim_paths[0])
self.assertEqual(stage_items[1].path, prim_paths[1])
self.assertEqual(stage_items[2].path, prim_paths[2])
with tempfile.TemporaryDirectory() as tmpdirname:
# save the file
tmp_file_path = os.path.join(tmpdirname, "tmp.usda")
layer = Sdf.Layer.CreateNew(tmp_file_path)
stage = Usd.Stage.Open(layer)
prim = stage.DefinePrim("/World/cube", "Xform")
stage.SetDefaultPrim(prim)
stage.Save()
stage = None
layer = None
stage_model.drop(root_stage_item, tmp_file_path, drop_location=3)
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 4)
self.assertEqual(stage_items[0].path, prim_paths[0])
self.assertEqual(stage_items[1].path, prim_paths[1])
self.assertEqual(stage_items[2].path, prim_paths[2])
self.assertEqual(stage_items[3].path, Sdf.Path("/tmp"))
stage_model.drop(root_stage_item, tmp_file_path, drop_location=1)
stage_items = stage_model.get_item_children(root_stage_item)
self.assertEqual(len(stage_items), 5)
self.assertEqual(stage_items[1].path, Sdf.Path("/tmp_01"))
await omni.usd.get_context().new_stage_async()
| 33,311 | Python | 40.901887 | 115 | 0.636727 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_helper.py | import unittest
import pathlib
import carb
import omni.kit.test
from pxr import UsdShade
from omni.ui.tests.test_base import OmniUiTest
from .inspector_query import InspectorQuery
class TestMouseUIHelper(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests")
self._inspector_query = InspectorQuery()
# After running each test
async def tearDown(self):
await super().tearDown()
async def wait_for_update(self, usd_context=omni.usd.get_context(), wait_frames=10):
max_loops = 0
while max_loops < wait_frames:
_, files_loaded, total_files = usd_context.get_stage_loading_status()
await omni.kit.app.get_app().next_update_async()
if files_loaded or total_files:
continue
max_loops = max_loops + 1
async def _simulate_mouse(self, data):
import omni.appwindow
import omni.ui as ui
mouse = omni.appwindow.get_default_app_window().get_mouse()
input_provider = carb.input.acquire_input_provider()
window_width = ui.Workspace.get_main_window_width()
window_height = ui.Workspace.get_main_window_height()
for type, x, y in data:
input_provider.buffer_mouse_event(mouse, type, (x / window_width, y / window_height), 0, (x, y))
await self.wait_for_update()
async def _debug_capture(self, image_name: str):
from pathlib import Path
import omni.renderer_capture
capture_next_frame = omni.renderer_capture.acquire_renderer_capture_interface().capture_next_frame_swapchain(image_name)
await self.wait_for_update()
wait_async_capture = omni.renderer_capture.acquire_renderer_capture_interface().wait_async_capture()
await self.wait_for_update()
| 2,027 | Python | 37.999999 | 128 | 0.662062 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_context_menu.py | import carb
import omni
import omni.kit.test
import omni.usd
import omni.client
import omni.kit.widget.stage
import omni.kit.app
import omni.kit.ui_test as ui_test
import pathlib
from omni.kit.test_suite.helpers import arrange_windows
from pxr import Sdf, UsdShade
class TestContextMenu(omni.kit.test.AsyncTestCase):
async def setUp(self):
await arrange_windows("Stage", 800, 600)
self.app = omni.kit.app.get_app()
self.usd_context = omni.usd.get_context()
await self.usd_context.new_stage_async()
self.stage = omni.usd.get_context().get_stage()
self.layer = Sdf.Layer.CreateAnonymous()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests")
self._cube_usd_path = str(self._test_path.joinpath("usd/cube.usda"))
self.ref_prim = self.stage.DefinePrim("/reference0", "Xform")
self.ref_prim.GetReferences().AddReference(self.layer.identifier)
self.child_prim = self.stage.DefinePrim("/reference0/child0", "Xform")
self.payload_prim = self.stage.DefinePrim("/payload0", "Xform")
self.payload_prim.GetPayloads().AddPayload(self.layer.identifier)
self.rf_prim = self.stage.DefinePrim("/reference_and_payload0", "Xform")
self.rf_prim.GetReferences().AddReference(self.layer.identifier)
self.rf_prim.GetPayloads().AddPayload(self.layer.identifier)
await self.wait()
async def tearDown(self):
pass
async def wait(self, frames=10):
for i in range(frames):
await self.app.next_update_async()
async def _find_all_prim_items(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
reference_widget = stage_tree.find("**/Label[*].text=='reference0'")
payload_widget = stage_tree.find("**/Label[*].text=='payload0'")
reference_and_payload_widget = stage_tree.find("**/Label[*].text=='reference_and_payload0'")
return reference_widget, payload_widget, reference_and_payload_widget
async def test_expand_collapse_tree(self):
rf_widget, _, _ = await self._find_all_prim_items()
for name in ["All", "Component", "Group", "Assembly", "SubComponent"]:
await rf_widget.right_click()
await ui_test.select_context_menu(f"Collapse/{name}")
await rf_widget.right_click()
await ui_test.select_context_menu(f"Expand/{name}")
async def test_default_prim(self):
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu("Clear Default Prim")
await rf_widget.right_click()
await ui_test.select_context_menu("Set as Default Prim")
await self.wait()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
ref_widget = stage_tree.find("**/Label[*].text=='reference0 (defaultPrim)'")
self.assertTrue(ref_widget)
ref_widget_old = stage_tree.find("**/Label[*].text=='reference0'")
self.assertFalse(ref_widget_old)
with self.assertRaises(Exception):
await ui_test.select_context_menu("Set as Default Prim")
await rf_widget.right_click()
await ui_test.select_context_menu("Clear Default Prim")
await self.wait()
ref_widget_old = stage_tree.find("**/Label[*].text=='reference0 (defaultPrim)'")
self.assertFalse(ref_widget_old)
ref_widget = stage_tree.find("**/Label[*].text=='reference0'")
self.assertTrue(ref_widget)
async def test_find_in_browser(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath())], True
)
await self.wait()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
# If there are no on-disk references
with self.assertRaises(Exception):
await ui_test.select_context_menu("Find in Content Browser")
# Adds a reference that's on disk.
self.ref_prim.GetReferences().ClearReferences()
self.ref_prim.GetReferences().AddReference(self._cube_usd_path)
await self.wait()
await rf_widget.right_click()
await ui_test.select_context_menu("Find in Content Browser")
async def test_group_selected(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath()), str(self.payload_prim.GetPath())], True
)
await self.wait()
old_ref_path = self.ref_prim.GetPath()
old_payload_path = self.payload_prim.GetPath()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
await ui_test.select_context_menu("Group Selected")
await self.wait()
new_ref_path = Sdf.Path("/Group").AppendElementString(old_ref_path.name)
new_payload_path = Sdf.Path("/Group").AppendElementString(old_payload_path.name)
self.assertFalse(self.stage.GetPrimAtPath(old_ref_path))
self.assertFalse(self.stage.GetPrimAtPath(old_payload_path))
self.assertTrue(self.stage.GetPrimAtPath(new_ref_path))
self.assertTrue(self.stage.GetPrimAtPath(new_payload_path))
self.usd_context.get_selection().set_selected_prim_paths(
[str(new_ref_path), str(new_payload_path)], True
)
await self.wait()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
ref_widget = stage_tree.find("**/Label[*].text=='reference0'")
self.assertTrue(ref_widget)
await rf_widget.right_click()
await ui_test.select_context_menu("Ungroup Selected")
await self.wait()
self.assertTrue(self.stage.GetPrimAtPath(old_ref_path))
self.assertTrue(self.stage.GetPrimAtPath(old_payload_path))
self.assertFalse(self.stage.GetPrimAtPath(new_ref_path))
self.assertFalse(self.stage.GetPrimAtPath(new_payload_path))
async def test_duplicate_prim(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath()), str(self.payload_prim.GetPath())], True
)
await self.wait()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
await ui_test.select_context_menu("Duplicate")
self.assertTrue(self.stage.GetPrimAtPath("/reference0_01"))
self.assertTrue(self.stage.GetPrimAtPath("/payload0_01"))
async def test_delete_prim(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath()), str(self.payload_prim.GetPath())], True
)
await self.wait()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
await ui_test.select_context_menu("Delete")
self.assertFalse(self.ref_prim)
self.assertFalse(self.payload_prim)
async def test_refresh_reference_or_payload(self):
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath())], True
)
await self.wait()
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
await ui_test.select_context_menu("Refresh Reference")
async def test_convert_between_ref_and_payload(self):
rf_widget, payload_widget, ref_and_payload_widget = await self._find_all_prim_items()
await rf_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu("Convert Payloads to References")
await rf_widget.right_click()
await ui_test.select_context_menu("Convert References to Payloads")
ref_prim = self.stage.GetPrimAtPath("/reference0")
ref_and_layers = omni.usd.get_composed_references_from_prim(ref_prim)
payload_and_layers = omni.usd.get_composed_payloads_from_prim(ref_prim)
self.assertTrue(len(ref_and_layers) == 0)
self.assertTrue(len(payload_and_layers) == 1)
await payload_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu("Convert References to Payloads")
await payload_widget.right_click()
await ui_test.select_context_menu("Convert Payloads to References")
payload_prim = self.stage.GetPrimAtPath("/payload0")
ref_and_layers = omni.usd.get_composed_references_from_prim(payload_prim)
payload_and_layers = omni.usd.get_composed_payloads_from_prim(payload_prim)
self.assertTrue(len(ref_and_layers) == 1)
self.assertTrue(len(payload_and_layers) == 0)
await ref_and_payload_widget.right_click()
await ui_test.select_context_menu("Convert References to Payloads")
prim = self.stage.GetPrimAtPath("/reference_and_payload0")
ref_and_layers = omni.usd.get_composed_references_from_prim(prim)
payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim)
self.assertEqual(len(ref_and_layers), 0)
self.assertEqual(len(payload_and_layers), 1)
await ref_and_payload_widget.right_click()
await ui_test.select_context_menu("Convert Payloads to References")
prim = self.stage.GetPrimAtPath("/reference_and_payload0")
ref_and_layers = omni.usd.get_composed_references_from_prim(prim)
payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim)
self.assertEqual(len(ref_and_layers), 1)
self.assertEqual(len(payload_and_layers), 0)
async def test_select_bound_objects(self):
menu_name = "Select Bound Objects"
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu(menu_name)
material = UsdShade.Material.Define(self.stage, "/material0")
UsdShade.MaterialBindingAPI(self.payload_prim).Bind(material)
await self.wait()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
material_widget = stage_tree.find("**/Label[*].text=='material0'")
await material_widget.right_click()
await ui_test.select_context_menu(menu_name)
await self.wait()
self.assertEqual(omni.usd.get_context().get_selection().get_selected_prim_paths(), [str(self.payload_prim.GetPath())])
async def test_binding_material(self):
menu_name = "Bind Material To Selected Objects"
rf_widget, _, _ = await self._find_all_prim_items()
await rf_widget.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu(menu_name)
material = UsdShade.Material.Define(self.stage, "/material0")
UsdShade.MaterialBindingAPI(self.payload_prim).Bind(material)
await self.wait()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
material_widget = stage_tree.find("**/Label[*].text=='material0'")
await material_widget.right_click()
# No valid selection
with self.assertRaises(Exception):
await ui_test.select_context_menu(menu_name)
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.payload_prim.GetPath())], True
)
await self.wait()
await material_widget.right_click()
await ui_test.select_context_menu(menu_name)
await self.wait()
selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
self.assertEqual(selected_paths, [str(self.payload_prim.GetPath())])
async def test_set_kind(self):
rf_widget, _, _ = await self._find_all_prim_items()
self.usd_context.get_selection().set_selected_prim_paths(
[str(self.ref_prim.GetPath())], True
)
await self.wait()
for name in ["Assembly", "Group", "Component", "Subcomponent"]:
await rf_widget.right_click()
await ui_test.select_context_menu(f"Set Kind/{name}")
async def test_lock_specs(self):
rf_widget, _, _ = await self._find_all_prim_items()
for menu_name in ["Lock Selected", "Unlock Selected", "Lock Selected Hierarchy", "Unlock Selected Hierarchy"]:
await rf_widget.right_click()
await ui_test.select_context_menu(f"Locks/{menu_name}")
await rf_widget.right_click()
await ui_test.select_context_menu("Locks/Lock Selected Hierarchy")
await rf_widget.right_click()
await ui_test.select_context_menu("Locks/Select Locked Prims")
await self.wait()
selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
self.assertEqual(selected_paths, [str(self.ref_prim.GetPath()), str(self.child_prim.GetPath())])
async def test_assign_material(self):
menu_name = "Assign Material"
rf_widget, _, _ = await self._find_all_prim_items()
material = UsdShade.Material.Define(self.stage, "/material0")
UsdShade.MaterialBindingAPI(self.payload_prim).Bind(material)
await self.wait()
await rf_widget.right_click()
await ui_test.select_context_menu(menu_name)
dialog = ui_test.find("Bind material to reference0###context_menu_bind")
self.assertTrue(dialog)
button = dialog.find("**/Button[*].text=='Ok'")
self.assertTrue(button)
await button.click()
async def test_rename_prim(self):
await ui_test.find("Stage").focus()
menu_name = "Rename"
rf_widget, _, _ = await self._find_all_prim_items()
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await rf_widget.right_click(rf_widget.center)
await ui_test.select_context_menu(menu_name)
await self.wait(10)
string_fields = stage_tree.find_all("**/StringField[*].identifier=='rename_field'")
self.assertTrue(len(string_fields) > 0)
string_field = string_fields[0]
# FIXME: Cannot make it visible in tests, but have to do it manually
string_field.widget.visible = True
await string_field.input("test")
self.assertTrue(self.stage.GetPrimAtPath("/reference0test"))
self.assertFalse(self.stage.GetPrimAtPath("/reference0"))
| 14,680 | Python | 42.95509 | 126 | 0.64673 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_stage.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from pathlib import Path
from omni.kit.widget.stage import StageWidget
from omni.kit.widget.stage.stage_icons import StageIcons
from omni.ui.tests.test_base import OmniUiTest
from pxr import Usd, UsdGeom
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows, wait_stage_loading
import omni.kit.app
CURRENT_PATH = Path(__file__).parent
REPO_PATH = CURRENT_PATH
for i in range(10):
REPO_PATH = REPO_PATH.parent
BOWL_STAGE = REPO_PATH.joinpath("data/usd/tests/bowl.usd")
STYLE = {"Field": {"background_color": 0xFF24211F, "border_radius": 2}}
class TestStage(OmniUiTest):
# Before running each test
async def setUp(self):
await arrange_windows(hide_viewport=True)
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_general(self):
"""Testing general look of StageWidget"""
StageIcons()._icons = {}
window = await self.create_test_window()
stage = Usd.Stage.Open(f"{BOWL_STAGE}")
if not stage:
self.fail(f"Stage {BOWL_STAGE} doesn't exist")
return
with window.frame:
stage_widget = StageWidget(stage, style=STYLE)
# 5 frames to rasterize the icons
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_visibility(self):
"""Testing visibility of StageWidget"""
StageIcons()._icons = {}
window = await self.create_test_window()
stage = Usd.Stage.CreateInMemory("test.usd")
with window.frame:
stage_widget = StageWidget(stage, style=STYLE)
UsdGeom.Mesh.Define(stage, "/A")
UsdGeom.Mesh.Define(stage, "/A/B")
UsdGeom.Mesh.Define(stage, "/C").MakeInvisible()
# 5 frames to rasterize the icons
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_dynamic(self):
"""Testing the ability to watch the stage"""
StageIcons()._icons = {}
window = await self.create_test_window()
stage = Usd.Stage.CreateInMemory("test.usd")
with window.frame:
stage_widget = StageWidget(stage, style=STYLE)
UsdGeom.Mesh.Define(stage, "/A")
# Wait one frame to be sure other objects created after initialization
await omni.kit.app.get_app().next_update_async()
UsdGeom.Mesh.Define(stage, "/B")
mesh = UsdGeom.Mesh.Define(stage, "/C")
# Wait one frame to be sure other objects created after initialization
await omni.kit.app.get_app().next_update_async()
mesh.MakeInvisible()
UsdGeom.Mesh.Define(stage, "/D")
# 5 frames to rasterize the icons
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_instanceable(self):
"""Testing the ability to watch the instanceable state"""
StageIcons()._icons = {}
window = await self.create_test_window()
stage = Usd.Stage.CreateInMemory("test.usd")
with window.frame:
stage_widget = StageWidget(stage, style=STYLE)
UsdGeom.Xform.Define(stage, "/A")
UsdGeom.Mesh.Define(stage, "/A/Shape")
prim = UsdGeom.Xform.Define(stage, "/B").GetPrim()
prim.GetReferences().AddInternalReference("/A")
# Wait one frame to be sure other objects created after initialization
await omni.kit.app.get_app().next_update_async()
stage_widget.expand("/B")
await omni.kit.app.get_app().next_update_async()
prim.SetInstanceable(True)
# 5 frames to rasterize the icons
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
| 4,390 | Python | 30.141844 | 78 | 0.645103 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/drag_drop_multi.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
get_prims,
wait_stage_loading,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropFileStageMulti(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_drag_drop_multi_usd_stage(self):
from carb.input import KeyboardInput
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
stage_window = ui_test.find("Stage")
await stage_window.focus()
# verify prims
paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader'])
# drag/drop files to stage window
drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 96)
async with ContentBrowserTestHelper() as content_browser_helper:
usd_path = get_test_data_path(__name__)
await content_browser_helper.drag_and_drop_tree_view(
usd_path, names=["4Lights.usda", "quatCube.usda"], drag_target=drag_target)
# verify prims
paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)]
self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader', '/World/_Lights', '/World/_Lights/SphereLight_01', '/World/_Lights/SphereLight_02', '/World/_Lights/SphereLight_03', '/World/_Lights/SphereLight_00', '/World/_Lights/Cube', '/World/quatCube', '/World/quatCube/Cube'])
| 3,064 | Python | 49.245901 | 557 | 0.698107 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/test_header.py | import carb
import omni
import omni.kit.test
import omni.usd
import omni.client
import omni.kit.widget.stage
import omni.kit.app
import omni.kit.ui_test as ui_test
from omni.kit.test_suite.helpers import arrange_windows
from ..stage_model import StageItemSortPolicy
class TestHeader(omni.kit.test.AsyncTestCase):
async def setUp(self):
self.app = omni.kit.app.get_app()
await arrange_windows("Stage", 800, 600)
async def tearDown(self):
pass
async def wait(self, frames=4):
for i in range(frames):
await self.app.next_update_async()
async def test_name_header(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
self.assertTrue(stage_tree)
stage_model = stage_tree.widget.model
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
name_label = stage_tree.find("**/Label[*].text=='Name (Old to New)'")
self.assertTrue(name_label)
await name_label.click()
await self.wait()
name_label = stage_tree.find("**/Label[*].text=='Name (A to Z)'")
self.assertTrue(name_label)
await name_label.click()
await self.wait()
name_label = stage_tree.find("**/Label[*].text=='Name (Z to A)'")
self.assertTrue(name_label)
await name_label.click()
await self.wait()
name_label = stage_tree.find("**/Label[*].text=='Name (New to Old)'")
self.assertTrue(name_label)
await name_label.click()
await self.wait()
name_label = stage_tree.find("**/Label[*].text=='Name (Old to New)'")
self.assertTrue(name_label)
async def test_visibility_header(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
self.assertTrue(stage_tree)
stage_model = stage_tree.widget.model
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.DEFAULT)
visibility_image = stage_tree.find("**/Image[*].name=='visibility_header'")
self.assertTrue(visibility_image)
await visibility_image.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE)
await visibility_image.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE)
await visibility_image.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.DEFAULT)
async def test_type_header(self):
stage_tree = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
self.assertTrue(stage_tree)
stage_model = stage_tree.widget.model
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.DEFAULT)
type_label = stage_tree.find("**/Label[*].text=='Type'")
self.assertTrue(type_label)
await type_label.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.TYPE_COLUMN_A_TO_Z)
await type_label.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.TYPE_COLUMN_Z_TO_A)
await type_label.click()
await self.wait()
self.assertEqual(stage_model.get_items_sort_policy(), StageItemSortPolicy.DEFAULT)
| 3,679 | Python | 36.938144 | 121 | 0.660506 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/tests/inspector_query.py | from typing import Optional, Union
import omni.ui as ui
import carb
class InspectorQuery:
def __init__(self) -> None:
pass
@classmethod
def child_widget(cls, widget: ui.Widget, predicate: str, last=False) -> Union[ui.Widget, None]:
adjusted_predicate = predicate
# when we don't have index we assume it is the first one
index = None
if "[" in adjusted_predicate:
index = int(adjusted_predicate.split("[")[-1].split("]")[0])
adjusted_predicate = adjusted_predicate.split("[")[0]
if last and index is None:
if widget.__class__.__name__ == adjusted_predicate:
return widget
else:
carb.log_warn(f"Widget {widget} is not matching predicate {adjusted_predicate}")
return None
if not widget.__class__.__name__ == adjusted_predicate:
carb.log_warn(f"Widget {widget} is not matching predicate {adjusted_predicate}")
return None
children = ui.Inspector.get_children(widget)
if not index:
index = 0
if index >= len(children):
carb.log_warn(f"Widget {widget} only as {len(children)}, asked for index {index}")
return None
return children[index]
@classmethod
def find_widget_path(cls, window: ui.Window, widget: ui.Widget) -> Union[str, None]:
def traverse_widget_tree_for_match(
location: ui.Widget, current_path: str, searched_widget: ui.Widget
) -> Union[str, None]:
current_index = 0
current_children = ui.Inspector.get_children(location)
for a_child in current_children:
class_name = a_child.__class__.__name__
if a_child == widget:
return f"{current_path}[{current_index}]/{class_name}"
if isinstance(a_child, ui.Container):
path = traverse_widget_tree_for_match(
a_child, f"{current_path}[{current_index}]/{class_name}", searched_widget
)
if path:
return path
current_index = current_index + 1
return None
if window:
start_path = f"{window.title}/Frame"
return traverse_widget_tree_for_match(window.frame, start_path, widget)
else:
return None
@classmethod
def find_menu_item(cls, query: str) -> Optional[ui.Widget]:
from omni.kit.mainwindow import get_main_window
main_menu_bar = get_main_window().get_main_menu_bar()
if not main_menu_bar:
carb.log_warn("Current App doesn't have a MainMenuBar")
return None
tokens = query.split("/")
current_children = main_menu_bar
for i in range(1, len(tokens)):
last = i == len(tokens) - 1
child = InspectorQuery.child_widget(current_children, tokens[i], last)
if not child:
carb.log_warn(f"Failed to find Child Widget at level {tokens[i]}")
return None
current_children = child
return current_children
@classmethod
def find_context_menu_item(cls, query: str, menu_root: ui.Menu) -> Optional[ui.Widget]:
menu_items = ui.Inspector.get_children(menu_root)
for menu_item in menu_items:
if isinstance(menu_item, ui.MenuItem):
if query in menu_item.text:
return menu_item
return None
@classmethod
def find_widget(cls, query: str) -> Union[ui.Widget, None]:
if not query:
return None
tokens = query.split("/")
window = ui.Workspace.get_window(tokens[0])
if not window:
carb.log_warn(f"Failed to find window: {tokens[0]}")
return None
if not isinstance(window, ui.Window):
carb.log_warn(f"window: {tokens[0]} is not a ui.Window, query only work on ui.Window")
return None
if not (tokens[1] == "Frame" or tokens[1] == "Frame[0]"):
carb.log_warn("Query currently only Support '<WindowName>/Frame/* or <WindowName>/Frame[0]/ type of query")
return None
frame = window.frame
if len(tokens) == 2:
return frame
if tokens[-1] == "":
tokens = tokens[:-1]
current_children = ui.Inspector.get_children(frame)[0]
for i in range(2, len(tokens)):
last = i == len(tokens) - 1
child = InspectorQuery.child_widget(current_children, tokens[i], last)
if not child:
carb.log_warn(f"Failed to find Child Widget at level {tokens[i]}")
return None
current_children = child
return current_children
| 4,854 | Python | 33.928057 | 119 | 0.559333 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/delegates/type_column_delegate.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TypeColumnDelegate"]
from ..abstract_stage_column_delegate import AbstractStageColumnDelegate
from ..stage_model import StageModel, StageItemSortPolicy
from ..stage_item import StageItem
from typing import List
from enum import Enum
import omni.ui as ui
class TypeColumnSortPolicy(Enum):
DEFAULT = 0
A_TO_Z = 1
Z_TO_A = 2
class TypeColumnDelegate(AbstractStageColumnDelegate):
"""The column delegate that represents the type column"""
def __init__(self):
super().__init__()
self.__name_label_layout = None
self.__name_label = None
self.__items_sort_policy = TypeColumnSortPolicy.DEFAULT
self.__stage_model: StageModel = None
def destroy(self):
if self.__name_label_layout:
self.__name_label_layout.set_mouse_pressed_fn(None)
@property
def initial_width(self):
"""The width of the column"""
return ui.Pixel(100)
def __initialize_policy_from_model(self):
stage_model = self.__stage_model
if not stage_model:
return
if stage_model.get_items_sort_policy() == StageItemSortPolicy.TYPE_COLUMN_A_TO_Z:
self.__items_sort_policy = TypeColumnSortPolicy.A_TO_Z
elif stage_model.get_items_sort_policy() == StageItemSortPolicy.TYPE_COLUMN_Z_TO_A:
self.__items_sort_policy = TypeColumnSortPolicy.Z_TO_A
else:
self.__items_sort_policy = TypeColumnSortPolicy.DEFAULT
self.__update_label_from_policy()
def __update_label_from_policy(self):
if not self.__name_label:
return
if self.__name_label:
if self.__items_sort_policy == TypeColumnSortPolicy.A_TO_Z:
name = "Type (A to Z)"
elif self.__items_sort_policy == TypeColumnSortPolicy.Z_TO_A:
name = "Type (Z to A)"
else:
name = "Type"
self.__name_label.text = name
def __on_policy_changed(self):
stage_model = self.__stage_model
if not stage_model:
return
if self.__items_sort_policy == TypeColumnSortPolicy.A_TO_Z:
stage_model.set_items_sort_policy(StageItemSortPolicy.TYPE_COLUMN_A_TO_Z)
elif self.__items_sort_policy == TypeColumnSortPolicy.Z_TO_A:
stage_model.set_items_sort_policy(StageItemSortPolicy.TYPE_COLUMN_Z_TO_A)
else:
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
self.__update_label_from_policy()
def __on_name_label_clicked(self, x, y, b, m):
stage_model = self.__stage_model
if b != 0 or not stage_model:
return
if self.__items_sort_policy == TypeColumnSortPolicy.A_TO_Z:
self.__items_sort_policy = TypeColumnSortPolicy.Z_TO_A
elif self.__items_sort_policy == TypeColumnSortPolicy.Z_TO_A:
self.__items_sort_policy = TypeColumnSortPolicy.DEFAULT
else:
self.__items_sort_policy = TypeColumnSortPolicy.A_TO_Z
self.__on_policy_changed()
def build_header(self, **kwargs):
"""Build the header"""
stage_model = kwargs.get("stage_model", None)
self.__stage_model = stage_model
if stage_model:
self.__name_label_layout = ui.HStack()
with self.__name_label_layout:
ui.Spacer(width=10)
self.__name_label = ui.Label(
"Type", name="columnname", style_type_name_override="TreeView.Header"
)
self.__initialize_policy_from_model()
self.__name_label_layout.set_mouse_pressed_fn(self.__on_name_label_clicked)
else:
self.__name_label_layout.set_mouse_pressed_fn(None)
with ui.HStack():
ui.Spacer(width=10)
ui.Label("Type", name="columnname", style_type_name_override="TreeView.Header")
async def build_widget(self, _, **kwargs):
"""Build the type widget"""
item = kwargs.get("stage_item", None)
if not item or not item.stage:
return
prim = item.stage.GetPrimAtPath(item.path)
if not prim or not prim.IsValid():
return
with ui.HStack(enabled=not item.instance_proxy, spacing=4, height=20):
ui.Spacer(width=4)
ui.Label(item.type_name, width=0, name="object_name", style_type_name_override="TreeView.Item")
def on_stage_items_destroyed(self, items: List[StageItem]):
pass
@property
def sortable(self):
return True
@property
def order(self):
return -100
@property
def minimum_width(self):
return ui.Pixel(20)
| 5,139 | Python | 33.039735 | 107 | 0.616852 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/delegates/visibility_column_delegate.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["VisibilityColumnDelegate"]
from ..abstract_stage_column_delegate import AbstractStageColumnDelegate
from ..stage_model import StageModel, StageItemSortPolicy
from ..stage_item import StageItem
from pxr import UsdGeom
from typing import List
from functools import partial
from enum import Enum
import weakref
import omni.ui as ui
class VisibilityColumnSortPolicy(Enum):
DEFAULT = 0
INVISIBLE_TO_VISIBLE = 1
VISIBLE_TO_INVISIBLE = 2
class VisibilityColumnDelegate(AbstractStageColumnDelegate):
"""The column delegate that represents the visibility column"""
def __init__(self):
super().__init__()
self.__visibility_layout = None
self.__items_sort_policy = VisibilityColumnSortPolicy.DEFAULT
self.__stage_model: StageModel = None
def destroy(self):
if self.__visibility_layout:
self.__visibility_layout.set_mouse_pressed_fn(None)
self.__visibility_layout = None
self.__stage_model = None
@property
def initial_width(self):
"""The width of the column"""
return ui.Pixel(24)
def __initialize_policy_from_model(self):
stage_model = self.__stage_model
if not stage_model:
return
if stage_model.get_items_sort_policy() == StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE:
self.__items_sort_policy = VisibilityColumnSortPolicy.INVISIBLE_TO_VISIBLE
elif stage_model.get_items_sort_policy() == StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE:
self.__items_sort_policy = VisibilityColumnSortPolicy.VISIBLE_TO_INVISIBLE
else:
self.__items_sort_policy = VisibilityColumnSortPolicy.DEFAULT
def __on_policy_changed(self):
stage_model = self.__stage_model
if not stage_model:
return
if self.__items_sort_policy == VisibilityColumnSortPolicy.INVISIBLE_TO_VISIBLE:
stage_model.set_items_sort_policy(StageItemSortPolicy.VISIBILITY_COLUMN_INVISIBLE_TO_VISIBLE)
elif self.__items_sort_policy == VisibilityColumnSortPolicy.VISIBLE_TO_INVISIBLE:
stage_model.set_items_sort_policy(StageItemSortPolicy.VISIBILITY_COLUMN_VISIBLE_TO_INVISIBLE)
else:
stage_model.set_items_sort_policy(StageItemSortPolicy.DEFAULT)
def __on_visiblity_clicked(self, x, y, b, m):
if b != 0 or not self.__stage_model:
return
if self.__items_sort_policy == VisibilityColumnSortPolicy.VISIBLE_TO_INVISIBLE:
self.__items_sort_policy = VisibilityColumnSortPolicy.INVISIBLE_TO_VISIBLE
elif self.__items_sort_policy == VisibilityColumnSortPolicy.INVISIBLE_TO_VISIBLE:
self.__items_sort_policy = VisibilityColumnSortPolicy.DEFAULT
else:
self.__items_sort_policy = VisibilityColumnSortPolicy.VISIBLE_TO_INVISIBLE
self.__on_policy_changed()
def build_header(self, **kwargs):
"""Build the header"""
stage_model = kwargs.get("stage_model", None)
self.__stage_model = stage_model
self.__initialize_policy_from_model()
if stage_model:
with ui.ZStack():
ui.Rectangle(name="hovering", style_type_name_override="TreeView.Header")
self.__visibility_layout = ui.HStack()
with self.__visibility_layout:
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=22, height=14, name="visibility_header", style_type_name_override="TreeView.Header")
ui.Spacer()
ui.Spacer()
self.__visibility_layout.set_mouse_pressed_fn(self.__on_visiblity_clicked)
else:
with ui.HStack():
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=22, height=14, name="visibility_header", style_type_name_override="TreeView.Header")
ui.Spacer()
ui.Spacer()
async def build_widget(self, _, **kwargs):
"""Build the eye widget"""
item = kwargs.get("stage_item", None)
if not item or not item.prim or not item.prim.IsA(UsdGeom.Imageable):
return
with ui.ZStack(height=20):
# Min size
ui.Spacer(width=22)
# TODO the way to make this widget grayed out
ui.ToolButton(item.visibility_model, enabled=not item.instance_proxy, name="visibility")
@property
def order(self):
# Ensure it's always to the leftmost column except the name column.
return -101
@property
def sortable(self):
return True
def on_stage_items_destroyed(self, items: List[StageItem]):
pass
@property
def minimum_width(self):
return ui.Pixel(20)
| 5,352 | Python | 36.964539 | 123 | 0.640882 |
omniverse-code/kit/exts/omni.kit.widget.stage/omni/kit/widget/stage/delegates/name_column_delegate.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["NameColumnDelegate"]
import asyncio
import math
import omni.ui as ui
from ..abstract_stage_column_delegate import AbstractStageColumnDelegate
from ..stage_model import StageModel, StageItemSortPolicy
from ..stage_item import StageItem
from ..stage_icons import StageIcons
from functools import partial
from typing import List
from enum import Enum
class NameColumnSortPolicy(Enum):
NEW_TO_OLD = 0
OLD_TO_NEW = 1
A_TO_Z = 2
Z_TO_A = 3
def split_selection(text, selection):
"""
Split given text to substrings to draw selected text. Result starts with unselected text.
Example: "helloworld" "o" -> ["hell", "o", "w", "o", "rld"]
Example: "helloworld" "helloworld" -> ["", "helloworld"]
"""
if not selection or text == selection:
return ["", text]
selection = selection.lower()
selection_len = len(selection)
result = []
while True:
found = text.lower().find(selection)
result.append(text if found < 0 else text[:found])
if found < 0:
break
else:
result.append(text[found : found + selection_len])
text = text[found + selection_len :]
return result
class NameColumnDelegate(AbstractStageColumnDelegate):
"""The column delegate that represents the type column"""
def __init__(self):
super().__init__()
self.__name_label_layout = None
self.__name_label = None
self.__drop_down_layout = None
self.__name_sort_options_menu = None
self.__items_sort_policy = NameColumnSortPolicy.OLD_TO_NEW
self.__highlighting_enabled = None
# Text that is highlighted in flat mode
self.__highlighting_text = None
self.__stage_model: StageModel = None
def set_highlighting(self, enable: bool = None, text: str = None):
"""
Specify if the widgets should consider highlighting. Also set the text that should be highlighted in flat mode.
"""
if enable is not None:
self.__highlighting_enabled = enable
if text is not None:
self.__highlighting_text = text.lower()
@property
def sort_policy(self):
return self.__items_sort_policy
@sort_policy.setter
def sort_policy(self, value):
if self.__items_sort_policy != value:
self.__items_sort_policy = value
self.__on_policy_changed()
def destroy(self):
if self.__name_label_layout:
self.__name_label_layout.set_mouse_pressed_fn(None)
if self.__drop_down_layout:
self.__drop_down_layout.set_mouse_pressed_fn(None)
self.__drop_down_layout = None
self.__name_sort_options_menu = None
if self.__name_label_layout:
self.__name_label_layout.set_mouse_pressed_fn(None)
self.__name_label_layout = None
self.__stage_model = None
@property
def initial_width(self):
"""The width of the column"""
return ui.Fraction(1)
def __initialize_policy_from_model(self):
stage_model = self.__stage_model
if not stage_model:
return
if stage_model.get_items_sort_policy() == StageItemSortPolicy.NAME_COLUMN_NEW_TO_OLD:
self.__items_sort_policy = NameColumnSortPolicy.NEW_TO_OLD
elif stage_model.get_items_sort_policy() == StageItemSortPolicy.NAME_COLUMN_A_TO_Z:
self.__items_sort_policy = NameColumnSortPolicy.A_TO_Z
elif stage_model.get_items_sort_policy() == StageItemSortPolicy.NAME_COLUMN_Z_TO_A:
self.__items_sort_policy = NameColumnSortPolicy.Z_TO_A
else:
self.__items_sort_policy = NameColumnSortPolicy.OLD_TO_NEW
self.__update_label_from_policy()
def __update_label_from_policy(self):
if not self.__name_label:
return
if self.__items_sort_policy == NameColumnSortPolicy.NEW_TO_OLD:
name = "Name (New to Old)"
elif self.__items_sort_policy == NameColumnSortPolicy.A_TO_Z:
name = "Name (A to Z)"
elif self.__items_sort_policy == NameColumnSortPolicy.Z_TO_A:
name = "Name (Z to A)"
else:
name = "Name (Old to New)"
self.__name_label.text = name
def __on_policy_changed(self):
stage_model = self.__stage_model
if not stage_model:
return
if self.__items_sort_policy == NameColumnSortPolicy.NEW_TO_OLD:
stage_model.set_items_sort_policy(StageItemSortPolicy.NAME_COLUMN_NEW_TO_OLD)
elif self.__items_sort_policy == NameColumnSortPolicy.A_TO_Z:
stage_model.set_items_sort_policy(StageItemSortPolicy.NAME_COLUMN_A_TO_Z)
elif self.__items_sort_policy == NameColumnSortPolicy.Z_TO_A:
stage_model.set_items_sort_policy(StageItemSortPolicy.NAME_COLUMN_Z_TO_A)
else:
stage_model.set_items_sort_policy(StageItemSortPolicy.NAME_COLUMN_OLD_TO_NEW)
self.__update_label_from_policy()
def __on_name_label_clicked(self, x, y, b, m):
if b != 0 or not self.__stage_model:
return
if self.__items_sort_policy == NameColumnSortPolicy.A_TO_Z:
self.__items_sort_policy = NameColumnSortPolicy.Z_TO_A
elif self.__items_sort_policy == NameColumnSortPolicy.Z_TO_A:
self.__items_sort_policy = NameColumnSortPolicy.NEW_TO_OLD
elif self.__items_sort_policy == NameColumnSortPolicy.NEW_TO_OLD:
self.__items_sort_policy = NameColumnSortPolicy.OLD_TO_NEW
else:
self.__items_sort_policy = NameColumnSortPolicy.A_TO_Z
self.__on_policy_changed()
def build_header(self, **kwargs):
"""Build the header"""
style_type_name = "TreeView.Header"
stage_model = kwargs.get("stage_model", None)
self.__stage_model = stage_model
if stage_model:
with ui.HStack():
self.__name_label_layout = ui.HStack()
self.__name_label_layout.set_mouse_pressed_fn(self.__on_name_label_clicked)
with self.__name_label_layout:
ui.Spacer(width=10)
self.__name_label = ui.Label(
"Name", name="columnname", style_type_name_override=style_type_name
)
self.__initialize_policy_from_model()
ui.Spacer()
with ui.ZStack(width=16):
ui.Rectangle(name="drop_down_hovered_area", style_type_name_override=style_type_name)
self.__drop_down_layout = ui.ZStack(width=0)
with self.__drop_down_layout:
ui.Rectangle(width=16, name="drop_down_background", style_type_name_override=style_type_name)
with ui.HStack():
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer(height=4)
ui.Triangle(
name="drop_down_button",
width=8, height=8,
style_type_name_override=style_type_name,
alignment=ui.Alignment.CENTER_BOTTOM
)
ui.Spacer(height=2)
ui.Spacer()
ui.Spacer(width=4)
def on_sort_policy_changed(policy, value):
if self.sort_policy != policy:
self.sort_policy = policy
self.__on_policy_changed()
def on_mouse_pressed_fn(x, y, b, m):
if b != 0:
return
items_sort_policy = self.__items_sort_policy
self.__name_sort_options_menu = ui.Menu("Sort Options")
with self.__name_sort_options_menu:
ui.MenuItem("Sort By", enabled=False)
ui.Separator()
ui.MenuItem(
"New to Old",
checkable=True,
checked=items_sort_policy == NameColumnSortPolicy.NEW_TO_OLD,
checked_changed_fn=partial(
on_sort_policy_changed,
NameColumnSortPolicy.NEW_TO_OLD
),
hide_on_click=False,
)
ui.MenuItem(
"Old to New",
checkable=True,
checked=items_sort_policy == NameColumnSortPolicy.OLD_TO_NEW,
checked_changed_fn=partial(
on_sort_policy_changed,
NameColumnSortPolicy.OLD_TO_NEW
),
hide_on_click=False,
)
ui.MenuItem(
"A to Z",
checkable=True,
checked=items_sort_policy == NameColumnSortPolicy.A_TO_Z,
checked_changed_fn=partial(
on_sort_policy_changed,
NameColumnSortPolicy.A_TO_Z
),
hide_on_click=False
)
ui.MenuItem(
"Z to A",
checkable=True,
checked=items_sort_policy == NameColumnSortPolicy.Z_TO_A,
checked_changed_fn=partial(
on_sort_policy_changed,
NameColumnSortPolicy.Z_TO_A
),
hide_on_click=False
)
self.__name_sort_options_menu.show()
self.__drop_down_layout.set_mouse_pressed_fn(on_mouse_pressed_fn)
self.__drop_down_layout.visible = False
else:
self.__name_label_layout.set_mouse_pressed_fn(None)
with ui.HStack():
ui.Spacer(width=10)
ui.Label("Name", name="columnname", style_type_name_override="TreeView.Header")
def get_type_icon(self, node_type):
"""Convert USD Type to icon file name"""
icons = StageIcons()
if node_type in ["DistantLight", "SphereLight", "RectLight", "DiskLight", "CylinderLight", "DomeLight"]:
return icons.get(node_type, "Light")
if node_type == "":
node_type = "Xform"
return icons.get(node_type, "Prim")
async def build_widget(self, _, **kwargs):
self.build_widget_async(_, **kwargs)
def __get_all_icons_to_draw(self, item: StageItem, item_is_native):
# Get the node type
node_type = item.type_name if item != item.stage_model.root else None
icon_filenames = [self.get_type_icon(node_type)]
# Get additional icons based on the properties of StageItem
if item_is_native:
if item.references:
icon_filenames.append(StageIcons().get("Reference"))
if item.payloads:
icon_filenames.append(StageIcons().get("Payload"))
if item.instanceable:
icon_filenames.append(StageIcons().get("Instance"))
return icon_filenames
def __draw_all_icons(self, item: StageItem, item_is_native, is_highlighted):
icon_filenames = self.__get_all_icons_to_draw(item, item_is_native)
# Gray out the icon if the filter string is not in the text
iconname = "object_icon" if is_highlighted else "object_icon_grey"
parent_layout = ui.ZStack(width=20, height=20)
with parent_layout:
for icon_filename in icon_filenames:
ui.Image(icon_filename, name=iconname, style_type_name_override="TreeView.Image")
if item.instance_proxy:
parent_layout.set_tooltip("Instance Proxy")
def __build_rename_field(self, item: StageItem, name_labels, parent_stack):
def on_end_edit(name_labels, field):
for label in name_labels:
label.visible = True
field.visible = False
self.end_edit_subscription = None
def on_mouse_double_clicked(button, name_labels, field):
if button != 0 or item.instance_proxy:
return
for label in name_labels:
label.visible = False
field.visible = True
self.end_edit_subscription = field.model.subscribe_end_edit_fn(lambda _: on_end_edit(name_labels, field))
import omni.kit.app
async def focus(field):
await omni.kit.app.get_app().next_update_async()
field.focus_keyboard()
asyncio.ensure_future(focus(field))
field = ui.StringField(item.name_model, identifier="rename_field", visible=False)
parent_stack.set_mouse_double_clicked_fn(
lambda x, y, b, _: on_mouse_double_clicked(b, name_labels, field)
)
item._ui_widget = parent_stack
def build_widget_sync(self, _, **kwargs):
"""Build the type widget"""
# True if it's StageItem. We need it to determine if it's a Root item (which is None).
model = kwargs.get("stage_model", None)
item = kwargs.get("stage_item", None)
if not item:
item = model.root
item_is_native = False
else:
item_is_native = True
if not item:
return
# If highlighting disabled completley, all the items should be light
is_highlighted = not self.__highlighting_enabled and not self.__highlighting_text
if not is_highlighted:
# If it's not disabled completley
is_highlighted = item_is_native and item.filtered
with ui.HStack(enabled=not item.instance_proxy, spacing=4, height=20):
# Draw all icons on top of each other
self.__draw_all_icons(item, item_is_native, is_highlighted)
value_model = item.name_model
text = value_model.get_value_as_string()
stack = ui.HStack()
name_labels = []
# We have three different text draw model depending on the column and on the highlighting state
if item_is_native and model.flat:
# Flat search mode. We need to highlight only the part that is is the search field
selection_chain = split_selection(text, self.__highlighting_text)
labelnames_chain = ["object_name_grey", "object_name"]
# Extend the label names depending on the size of the selection chain. Example, if it was [a, b]
# and selection_chain is [z,y,x,w], it will become [a, b, a, b].
labelnames_chain *= int(math.ceil(len(selection_chain) / len(labelnames_chain)))
with stack:
for current_text, current_name in zip(selection_chain, labelnames_chain):
if not current_text:
continue
label = ui.Label(
current_text,
name=current_name,
width=0,
style_type_name_override="TreeView.Item",
hide_text_after_hash=False
)
name_labels.append(label)
if hasattr(item, "_callback_id"):
item._callback_id = None
else:
with stack:
if item.has_missing_references:
name = "object_name_missing"
else:
name = "object_name" if is_highlighted else "object_name_grey"
if item.is_outdated:
name = "object_name_outdated"
if item.in_session:
name = "object_name_live"
if item.is_outdated:
style_override = "TreeView.Item.Outdated"
elif item.in_session:
style_override = "TreeView.Item.Live"
else:
style_override = "TreeView.Item"
text = value_model.get_value_as_string()
if item.is_default:
text += " (defaultPrim)"
label = ui.Label(
text, hide_text_after_hash=False,
name=name, style_type_name_override=style_override
)
if item.has_missing_references:
label.set_tooltip("Missing references found.")
name_labels.append(label)
# The hidden field for renaming the prim
if item != model.root and not item.instance_proxy:
self.__build_rename_field(item, name_labels, stack)
elif hasattr(item, "_ui_widget"):
item._ui_widget = None
def rename_item(self, item: StageItem):
if not item or not hasattr(item, "_ui_widget") or not item._ui_widget or item.instance_proxy:
return
item._ui_widget.call_mouse_double_clicked_fn(0, 0, 0, 0)
def on_stage_items_destroyed(self, items: List[StageItem]):
for item in items:
if hasattr(item, "_ui_widget"):
item._ui_widget = None
def on_header_hovered(self, hovered):
self.__drop_down_layout.visible = hovered
@property
def sortable(self):
return True
@property
def order(self):
return -100000
@property
def minimum_width(self):
return ui.Pixel(40)
| 18,548 | Python | 38.050526 | 119 | 0.537578 |
omniverse-code/kit/exts/omni.kit.widget.stage/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [2.7.24] - 2023-02-21
### Fixed
- OM-82577: Drag&drop of flowusd presets will call flowusd command to add a reference.
## [2.7.23] - 2023-02-16
### Fixed
- OM-81767: Drag&drop behaviour of sbsar files now consistent with viewport's behaviour.
## [2.7.22] - 2023-01-11
### Updated
- Allow to select children under instance.
- Fix selection issue after clearing search text.
- Move SelectionWatch from omni.kit.window.stage to provide default implementation.
## [2.7.21] - 2022-12-9
### Updated
- Fixed issue where drag & drop material urls with encoded subidentifiers were not being handled.
## [2.7.20] - 2022-12-14
### Updated
- Improve drag and drop style.
## [2.7.19] - 2022-12-09
### Updated
- Improve filter and search.
- Fix issue that creates new prims will not be filtered when it's in filtering mode.
- Add support to search with prim path.
## [2.7.18] - 2022-12-08
### Updated
- Fix style of search results in stage window.
## [2.7.17] - 2022-11-29
### Updated
- Don't show context menu for converting references or payloads if they are not in the local layer stack.
## [2.7.16] - 2022-11-29
### Updated
- Don't show context menu for header of stage widget.
## [2.7.15] - 2022-11-15
### Updated
- Fixed issue with context menu & not hovering over label
## [2.7.14] - 2022-11-14
### Updated
- Supports sorting by name/visibility/type.
## [2.7.13] - 2022-11-14
### Updated
- Fix issue to search or filter stage window.
## [2.7.12] - 2022-11-07
### Updated
- Optimize more loading time to avoid populating tree item when it's to get children count.
## [2.7.11] - 2022-11-04
### Updated
- Refresh prim handle when it's resyced to avoid access staled prim.
## [2.7.10] - 2022-11-03
### Updated
- Support to show 'displayName' of prim from metadata.
## [2.7.9] - 2022-11-02
### Updated
- Drag and drop assets to default prim from content browser if default prim is existed.
## [2.7.8] - 2022-11-01
### Updated
- Fix rename issue.
## [2.7.7] - 2022-10-25
### Updated
- More optimization to stage window refresh without traversing.
## [2.7.6] - 2022-09-13
### Updated
- Don't use "use_hovered" for context menu objects when user click nowhere
## [2.7.5] - 2022-09-10
- Add TreeView drop style to show hilighting.
## [2.7.4] - 2022-09-08
### Updated
- Added "use_hovered" to context menu objects so menu can create child prims
## [2.7.3] - 2022-08-31
### Fixed
- Moved eye icon to front of ZStack to receive mouse clicks.
## [2.7.2] - 2022-08-12
### Fixed
- Updated context menu behaviour
## [2.7.1] - 2022-08-13
- Fix prims filter.
- Clear prims filter after stage switching.
## [2.7.0] - 2022-08-06
- Refactoring stage model to improve perf and fix issue of refresh.
## [2.6.26] - 2022-08-04
- Support multi-selection for toggling visibility
## [2.6.25] - 2022-08-02
### Fixed
- Show non-defined prims as well.
## [2.6.24] - 2022-07-28
### Fixed
- Fix regression to drag and drop prim to absolute root.
## [2.6.23] - 2022-07-28
### Fixed
- Ensure rename operation non-destructive.
## [2.6.23] - 2022-07-25
### Changes
- Refactored unittests to make use of content_browser test helpers
## [2.6.22] - 2022-07-18
### Fixed
- Restored the arguments of ExportPrimUSD
## [2.6.21] - 2022-07-05
- Replaced filepicker dialog with file exporter
## [2.6.20] - 2022-06-23
- Make material paths relative if "/persistent/app/material/dragDropMaterialPath" is set to "relative"
## [2.6.19] - 2022-06-22
- Multiple drag and drop support.
## [2.6.18] - 2022-05-31
- Changed "Export Selected" to "Save Selected"
## [2.6.17] - 2022-05-20
- Support multi-selection for toggling visibility
## [2.6.16] - 2022-05-17
- Support multi-file drag & drop
## [2.6.15] - 2022-04-28
- Drag & Drop can create payload or reference based on /persistent/app/stage/dragDropImport setting
## [2.6.14] - 2022-03-09
- Updated unittests to retrieve the treeview widget from content browser.
## [2.6.13] - 2022-03-07
- Expand default prim
## [2.6.12] - 2022-02-09
- Fix stage window refresh after sublayer is inserted/removed.
## [2.6.11] - 2022-01-26
- Fix the columns item not able to reorder
## [2.6.10] - 2022-01-05
- Support drag/drop from material browser
## [2.6.9] - 2021-11-03
- Updated to use new omni.kit.material.library `get_subidentifier_from_mdl`
## [2.6.8] - 2021-09-24
- Fix export selected prims if it has external dependences outside of the copy prim tree.
## [2.6.7] - 2021-09-17
- Copy axis after export selected prims.
## [2.6.6] - 2021-08-11
- Updated drag/drop material to no-prim to not bind to /World
- Added drag/drop test
## [2.6.5] - 2021-08-11
- Updated to lastest omni.kit.material.library
## [2.6.4] - 2021-07-26
- Added "Refesh Payload" to context menu
- Added Payload icon
- Added "Convert Payloads to References" to context menu
- Added "Convert References to Payloads" to context menu
## [2.6.3] - 2021-07-21
- Added "Refesh Reference" to context menu
## [2.6.2] - 2021-06-30
- Changed "Assign Material" to use async show function as it could be slow on large scenes
## [2.6.1] - 2021-06-02
- Changed export prim as usd, postfix name now lowercase
## [2.6.0] - 2021-06-16
### Added
- "Show Missing Reference" that is off by default. When it's on, missing
references are displayed with red color in the tree.
### Changed
- Indentation level. There is no offset on the left anymore.
## [2.5.0] - 2021-06-02
- Added export prim as usd
## [2.4.2] - 2021-04-29
- Use sub-material selector on material import
## [2.4.1] - 2021-04-09
### Fixed
- Context menu in extensions that are not omni.kit.window.stage
## [2.4.0] - 2021-03-19
### Added
- Supported accepting drag and drop to create versioned reference.
## [2.3.7] - 2021-03-17
### Changed
- Updated to new context_menu and how custom functions are added
## [2.3.6] - 2021-03-01
### Changed
- Additional check if the stage and prim are still valid
## [2.3.5] - 2021-02-23
### Added
- Exclusion list allows to hide prims of specific types silently. To hide the
prims of specific type, set the string array setting
`ext/omni.kit.widget.stage/exclusion/types`
```
[settings]
ext."omni.kit.widget.stage".exclusion.types = ["Mesh"]
```
## [2.3.4] - 2021-02-10
### Changes
- Updated StyleUI handling
## [2.3.3] - 2020-11-16
### Changed
- Updated Find In Browser
## [2.3.2] - 2020-11-13
### Changed
- Fixed disappearing the "eye" icon when searched objects are toggled off
## [2.3.1] - 2020-10-22
### Added
- An interface to add and remove the icons in the TreeView dependin on the prim type
### Removed
- The standard prim icons are moved to omni.kit.widget.stage_icons
## [2.3.0] - 2020-09-16
### Changed
- Split to two parts: omni.kit.widget.stage and omni.kit.window.stage
## [2.2.0] - 2020-09-15
### Changed - Detached from Editor and using UsdNotice for notifications
| 6,926 | Markdown | 25.438931 | 105 | 0.6838 |
omniverse-code/kit/exts/omni.kit.test_suite.layout/omni/kit/test_suite/layout/tests/__init__.py | from .compare_layout import *
from .verify_dockspace import *
| 62 | Python | 19.999993 | 31 | 0.774194 |
omniverse-code/kit/exts/omni.kit.test_suite.layout/omni/kit/test_suite/layout/tests/verify_dockspace.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import carb
import omni.kit.test
import omni.kit.app
import omni.ui as ui
import omni.kit.commands
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows
class VerifyDockspace(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 256)
await omni.usd.get_context().new_stage_async()
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere", select_new_prim=True)
# After running each test
async def tearDown(self):
pass
async def test_verify_dockspace(self):
# verify "Dockspace" window doesn't disapear when a prim is selected as this breaks layout load/save
omni.usd.get_context().get_selection().set_selected_prim_paths([], True)
await ui_test.human_delay(100)
self.assertNotEqual(ui.Workspace.get_window("DockSpace"), None)
omni.usd.get_context().get_selection().set_selected_prim_paths(["/Sphere"], True)
await ui_test.human_delay(100)
self.assertNotEqual(ui.Workspace.get_window("DockSpace"), None)
async def test_verify_dockspace_shutdown(self):
self._hooks = []
self._hooks.append(omni.kit.app.get_app().get_shutdown_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.POST_QUIT_EVENT_TYPE,
self._on_shutdown_handler,
name="omni.create.app.setup shutdown for layout",
order=0))
omni.usd.get_context().get_selection().set_selected_prim_paths(["/Sphere"], True)
await ui_test.human_delay(100)
def _on_shutdown_handler(self, e: carb.events.IEvent):
# verify "Dockspace" window hasn't disapeared as prims are selected as this breaks layout load/save
print("running _on_shutdown_handler test")
self.assertNotEqual(ui.Workspace.get_window("DockSpace"), None)
| 2,418 | Python | 42.981817 | 113 | 0.702233 |
omniverse-code/kit/exts/omni.kit.test_suite.layout/omni/kit/test_suite/layout/tests/compare_layout.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import omni.ui as ui
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows
from omni.kit.quicklayout import QuickLayout
from omni.ui.workspace_utils import CompareDelegate
class CompareLayout(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 256)
# After running each test
async def tearDown(self):
pass
async def test_compare_layout(self):
layout_path = get_test_data_path(__name__, "layout.json")
# compare layout, this should fail
result = QuickLayout.compare_file(layout_path)
self.assertNotEqual(result, [])
# load layout
QuickLayout.load_file(layout_path)
# need to pause as load_file does some async stuff
await ui_test.human_delay(10)
# compare layout, this should pass
result = QuickLayout.compare_file(layout_path)
self.assertEqual(result, [])
async def test_compare_layout_delegate(self):
called_delegate = False
layout_path = get_test_data_path(__name__, "layout.json")
class TestCompareDelegate(CompareDelegate):
def failed_get_window(self, error_list: list, target: dict):
nonlocal called_delegate
called_delegate = True
return super().failed_get_window(error_list, target)
def failed_window_key(self, error_list: list, key: str, target: dict, target_window: ui.Window):
nonlocal called_delegate
called_delegate = True
return super().failed_window_key(error_list, key, target, target_window)
def failed_window_value(self, error_list: list, key: str, value, target: dict, target_window: ui.Window):
nonlocal called_delegate
called_delegate = True
return super().failed_window_value(error_list, key, value, target, target_window)
def compare_value(self, key:str, value, target):
nonlocal called_delegate
called_delegate = True
return super().compare_value(key, value, target)
self.assertFalse(called_delegate)
# compare layout, this should fail
result = QuickLayout.compare_file(layout_path, compare_delegate=TestCompareDelegate())
self.assertNotEqual(result, [])
# load layout
QuickLayout.load_file(layout_path)
# need to pause as load_file does some async stuff
await ui_test.human_delay(10)
# compare layout, this should pass
result = QuickLayout.compare_file(layout_path, compare_delegate=TestCompareDelegate())
self.assertEqual(result, [])
self.assertTrue(called_delegate)
| 3,328 | Python | 36.829545 | 117 | 0.666166 |
omniverse-code/kit/exts/omni.kit.test_suite.layout/docs/index.rst | omni.kit.test_suite.layout
############################
layout tests
.. toctree::
:maxdepth: 1
CHANGELOG
| 114 | reStructuredText | 10.499999 | 28 | 0.508772 |
omniverse-code/kit/exts/omni.resourcemonitor/config/extension.toml | [package]
title = "Resource Monitor"
description = "Monitor utility for device and host memory"
authors = ["NVIDIA"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
category = "Internal"
preview_image = "data/preview.png"
icon = "data/icon.png"
version = "1.0.0"
[dependencies]
"omni.kit.renderer.core" = {}
"omni.kit.window.preferences" = {}
[[python.module]]
name = "omni.resourcemonitor"
[[native.plugin]]
path = "bin/*.plugin"
# Additional python module with tests, to make them discoverable by test system
[[python.module]]
name = "omni.resourcemonitor.tests"
[[test]]
timeout = 300
| 603 | TOML | 20.571428 | 79 | 0.713101 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/_resourceMonitor.pyi | """pybind11 omni.resourcemonitor bindings"""
from __future__ import annotations
import omni.resourcemonitor._resourceMonitor
import typing
import carb.events._events
__all__ = [
"IResourceMonitor",
"ResourceMonitorEventType",
"acquire_resource_monitor_interface",
"deviceMemoryWarnFractionSettingName",
"deviceMemoryWarnMBSettingName",
"hostMemoryWarnFractionSettingName",
"hostMemoryWarnMBSettingName",
"release_resource_monitor_interface",
"sendDeviceMemoryWarningSettingName",
"sendHostMemoryWarningSettingName",
"timeBetweenQueriesSettingName"
]
class IResourceMonitor():
def get_available_device_memory(self, arg0: int) -> int: ...
def get_available_host_memory(self) -> int: ...
def get_event_stream(self) -> carb.events._events.IEventStream: ...
def get_total_device_memory(self, arg0: int) -> int: ...
def get_total_host_memory(self) -> int: ...
pass
class ResourceMonitorEventType():
"""
ResourceMonitor notification.
Members:
DEVICE_MEMORY
HOST_MEMORY
LOW_DEVICE_MEMORY
LOW_HOST_MEMORY
"""
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
"""
DEVICE_MEMORY: omni.resourcemonitor._resourceMonitor.ResourceMonitorEventType # value = <ResourceMonitorEventType.DEVICE_MEMORY: 0>
HOST_MEMORY: omni.resourcemonitor._resourceMonitor.ResourceMonitorEventType # value = <ResourceMonitorEventType.HOST_MEMORY: 1>
LOW_DEVICE_MEMORY: omni.resourcemonitor._resourceMonitor.ResourceMonitorEventType # value = <ResourceMonitorEventType.LOW_DEVICE_MEMORY: 2>
LOW_HOST_MEMORY: omni.resourcemonitor._resourceMonitor.ResourceMonitorEventType # value = <ResourceMonitorEventType.LOW_HOST_MEMORY: 3>
__members__: dict # value = {'DEVICE_MEMORY': <ResourceMonitorEventType.DEVICE_MEMORY: 0>, 'HOST_MEMORY': <ResourceMonitorEventType.HOST_MEMORY: 1>, 'LOW_DEVICE_MEMORY': <ResourceMonitorEventType.LOW_DEVICE_MEMORY: 2>, 'LOW_HOST_MEMORY': <ResourceMonitorEventType.LOW_HOST_MEMORY: 3>}
pass
def acquire_resource_monitor_interface(plugin_name: str = None, library_path: str = None) -> IResourceMonitor:
pass
def release_resource_monitor_interface(arg0: IResourceMonitor) -> None:
pass
deviceMemoryWarnFractionSettingName = '/persistent/resourcemonitor/deviceMemoryWarnFraction'
deviceMemoryWarnMBSettingName = '/persistent/resourcemonitor/deviceMemoryWarnMB'
hostMemoryWarnFractionSettingName = '/persistent/resourcemonitor/hostMemoryWarnFraction'
hostMemoryWarnMBSettingName = '/persistent/resourcemonitor/hostMemoryWarnMB'
sendDeviceMemoryWarningSettingName = '/persistent/resourcemonitor/sendDeviceMemoryWarning'
sendHostMemoryWarningSettingName = '/persistent/resourcemonitor/sendHostMemoryWarning'
timeBetweenQueriesSettingName = '/persistent/resourcemonitor/timeBetweenQueries'
| 3,333 | unknown | 40.674999 | 288 | 0.712571 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/scripts/extension.py | import omni.ext
from .._resourceMonitor import *
class PublicExtension(omni.ext.IExt):
def on_startup(self):
self._resourceMonitor = acquire_resource_monitor_interface()
def on_shutdown(self):
release_resource_monitor_interface(self._resourceMonitor)
| 277 | Python | 26.799997 | 68 | 0.729242 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/scripts/resource_monitor_page.py | import omni.ui as ui
from omni.kit.window.preferences import PreferenceBuilder, SettingType
from .. import _resourceMonitor
class ResourceMonitorPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Resource Monitor")
def build(self):
""" Resource Monitor """
with ui.VStack(height=0):
with self.add_frame("Resource Monitor"):
with ui.VStack():
self.create_setting_widget(
"Time Between Queries",
_resourceMonitor.timeBetweenQueriesSettingName,
SettingType.FLOAT,
)
self.create_setting_widget(
"Send Device Memory Warnings",
_resourceMonitor.sendDeviceMemoryWarningSettingName,
SettingType.BOOL,
)
self.create_setting_widget(
"Device Memory Warning Threshold (MB)",
_resourceMonitor.deviceMemoryWarnMBSettingName,
SettingType.INT,
)
self.create_setting_widget(
"Device Memory Warning Threshold (Fraction)",
_resourceMonitor.deviceMemoryWarnFractionSettingName,
SettingType.FLOAT,
range_from=0.,
range_to=1.,
)
self.create_setting_widget(
"Send Host Memory Warnings",
_resourceMonitor.sendHostMemoryWarningSettingName,
SettingType.BOOL
)
self.create_setting_widget(
"Host Memory Warning Threshold (MB)",
_resourceMonitor.hostMemoryWarnMBSettingName,
SettingType.INT,
)
self.create_setting_widget(
"Host Memory Warning Threshold (Fraction)",
_resourceMonitor.hostMemoryWarnFractionSettingName,
SettingType.FLOAT,
range_from=0.,
range_to=1.,
)
| 2,300 | Python | 41.61111 | 77 | 0.475652 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/tests/__init__.py | """
Presence of this file allows the tests directory to be imported as a module so that all of its contents
can be scanned to automatically add tests that are placed into this directory.
"""
scan_for_test_modules = True
| 220 | Python | 35.833327 | 103 | 0.777273 |
omniverse-code/kit/exts/omni.resourcemonitor/omni/resourcemonitor/tests/test_resource_monitor.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 numpy as np
import carb.settings
import omni.kit.test
import omni.resourcemonitor as rm
class TestResourceSettings(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self._savedSettings = {}
self._rm_interface = rm.acquire_resource_monitor_interface()
self._settings = carb.settings.get_settings()
# Save current settings
self._savedSettings[rm.timeBetweenQueriesSettingName] = \
self._settings.get_as_float(rm.timeBetweenQueriesSettingName)
self._savedSettings[rm.sendDeviceMemoryWarningSettingName] = \
self._settings.get_as_bool(rm.sendDeviceMemoryWarningSettingName)
self._savedSettings[rm.deviceMemoryWarnMBSettingName] = \
self._settings.get_as_int(rm.deviceMemoryWarnMBSettingName)
self._savedSettings[rm.deviceMemoryWarnFractionSettingName] = \
self._settings.get_as_float(rm.deviceMemoryWarnFractionSettingName)
self._savedSettings[rm.sendHostMemoryWarningSettingName] = \
self._settings.get_as_bool(rm.sendHostMemoryWarningSettingName)
self._savedSettings[rm.hostMemoryWarnMBSettingName] = \
self._settings.get_as_int(rm.hostMemoryWarnMBSettingName)
self._savedSettings[rm.hostMemoryWarnFractionSettingName] = \
self._settings.get_as_float(rm.hostMemoryWarnFractionSettingName)
# After running each test
async def tearDown(self):
# Restore settings
self._settings.set_float(
rm.timeBetweenQueriesSettingName,
self._savedSettings[rm.timeBetweenQueriesSettingName])
self._settings.set_bool(
rm.sendDeviceMemoryWarningSettingName,
self._savedSettings[rm.sendDeviceMemoryWarningSettingName])
self._settings.set_int(
rm.deviceMemoryWarnMBSettingName,
self._savedSettings[rm.deviceMemoryWarnMBSettingName])
self._settings.set_float(
rm.deviceMemoryWarnFractionSettingName,
self._savedSettings[rm.deviceMemoryWarnFractionSettingName])
self._settings.set_bool(
rm.sendHostMemoryWarningSettingName,
self._savedSettings[rm.sendHostMemoryWarningSettingName])
self._settings.set_int(
rm.hostMemoryWarnMBSettingName,
self._savedSettings[rm.hostMemoryWarnMBSettingName])
self._settings.set_float(
rm.hostMemoryWarnFractionSettingName,
self._savedSettings[rm.hostMemoryWarnFractionSettingName])
async def test_resource_monitor(self):
"""
Test host memory warnings by setting the warning threshold to slightly
less than 10 GB below current memory usage then allocating a 10 GB buffer
"""
hostBytesAvail = self._rm_interface.get_available_host_memory()
memoryToAlloc = 10 * 1024 * 1024 * 1024
queryTime = 0.1
fudge = 512 * 1024 * 1024 # make sure we go below the warning threshold
warnHostThresholdBytes = hostBytesAvail - memoryToAlloc + fudge
self._settings.set_float(
rm.timeBetweenQueriesSettingName,
queryTime)
self._settings.set_bool(
rm.sendHostMemoryWarningSettingName,
True)
self._settings.set_int(
rm.hostMemoryWarnMBSettingName,
warnHostThresholdBytes // (1024 * 1024)) # bytes to MB
hostMemoryWarningOccurred = False
def on_rm_update(event):
nonlocal hostMemoryWarningOccurred
hostBytesAvail = self._rm_interface.get_available_host_memory()
if event.type == int(rm.ResourceMonitorEventType.LOW_HOST_MEMORY):
hostMemoryWarningOccurred = True
sub = self._rm_interface.get_event_stream().create_subscription_to_pop(on_rm_update, name='resource monitor update')
self.assertIsNotNone(sub)
# allocate something
numElements = memoryToAlloc // np.dtype(np.int64).itemsize
array = np.zeros(numElements, dtype=np.int64)
array[:] = 1
time = 0.
while time < 2. * queryTime: # give time for a resourcemonitor event to come through
dt = await omni.kit.app.get_app().next_update_async()
time = time + dt
self.assertTrue(hostMemoryWarningOccurred)
| 4,789 | Python | 37.015873 | 124 | 0.683441 |
omniverse-code/kit/exts/omni.resourcemonitor/docs/CHANGELOG.md | # CHANGELOG
## [1.0.0] - 2021-09-14
### Added
- Initial implementation.
- Provide event stream for low memory warnings.
- Provide convenience functions for host and device memory queries.
| 189 | Markdown | 22.749997 | 67 | 0.740741 |
omniverse-code/kit/exts/omni.resourcemonitor/docs/README.md | # [omni.resourcemonitor]
Utility extension for host and device memory updates.
Clients can subscribe to this extension's event stream to receive updates on available memory and/or receive warnings when available memory falls below specified thresholds.
| 254 | Markdown | 49.99999 | 173 | 0.830709 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnVersionedDeformerPy.rst | .. _omni_graph_examples_python_VersionedDeformerPy_2:
.. _omni_graph_examples_python_VersionedDeformerPy:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: VersionedDeformerPy
:keywords: lang-en omnigraph node examples python versioned-deformer-py
VersionedDeformerPy
===================
.. <description>
Test node to confirm version upgrading works. Performs a basic deformation on some points.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:points", "``pointf[3][]``", "Set of points to be deformed", "[]"
"inputs:wavelength", "``float``", "Wavelength of sinusodal deformer function", "50.0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:points", "``pointf[3][]``", "Set of deformed points", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.VersionedDeformerPy"
"Version", "2"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "VersionedDeformerPy"
"Categories", "examples"
"Generated Class Name", "OgnVersionedDeformerPyDatabase"
"Python Module", "omni.graph.examples.python"
| 1,775 | reStructuredText | 24.73913 | 115 | 0.590986 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnPyUniversalAdd.rst | .. _omni_graph_examples_python_UniversalAdd_1:
.. _omni_graph_examples_python_UniversalAdd:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Universal Add For All Types (Python)
:keywords: lang-en omnigraph node examples python universal-add
Universal Add For All Types (Python)
====================================
.. <description>
Python-based universal add node for all types. This file is generated using UniversalAddGenerator.py
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:bool_0", "``bool``", "Input of type bool", "False"
"inputs:bool_1", "``bool``", "Input of type bool", "False"
"inputs:bool_arr_0", "``bool[]``", "Input of type bool[]", "[]"
"inputs:bool_arr_1", "``bool[]``", "Input of type bool[]", "[]"
"inputs:colord3_0", "``colord[3]``", "Input of type colord[3]", "[0.0, 0.0, 0.0]"
"inputs:colord3_1", "``colord[3]``", "Input of type colord[3]", "[0.0, 0.0, 0.0]"
"inputs:colord3_arr_0", "``colord[3][]``", "Input of type colord[3][]", "[]"
"inputs:colord3_arr_1", "``colord[3][]``", "Input of type colord[3][]", "[]"
"inputs:colord4_0", "``colord[4]``", "Input of type colord[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colord4_1", "``colord[4]``", "Input of type colord[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colord4_arr_0", "``colord[4][]``", "Input of type colord[4][]", "[]"
"inputs:colord4_arr_1", "``colord[4][]``", "Input of type colord[4][]", "[]"
"inputs:colorf3_0", "``colorf[3]``", "Input of type colorf[3]", "[0.0, 0.0, 0.0]"
"inputs:colorf3_1", "``colorf[3]``", "Input of type colorf[3]", "[0.0, 0.0, 0.0]"
"inputs:colorf3_arr_0", "``colorf[3][]``", "Input of type colorf[3][]", "[]"
"inputs:colorf3_arr_1", "``colorf[3][]``", "Input of type colorf[3][]", "[]"
"inputs:colorf4_0", "``colorf[4]``", "Input of type colorf[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colorf4_1", "``colorf[4]``", "Input of type colorf[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colorf4_arr_0", "``colorf[4][]``", "Input of type colorf[4][]", "[]"
"inputs:colorf4_arr_1", "``colorf[4][]``", "Input of type colorf[4][]", "[]"
"inputs:colorh3_0", "``colorh[3]``", "Input of type colorh[3]", "[0.0, 0.0, 0.0]"
"inputs:colorh3_1", "``colorh[3]``", "Input of type colorh[3]", "[0.0, 0.0, 0.0]"
"inputs:colorh3_arr_0", "``colorh[3][]``", "Input of type colorh[3][]", "[]"
"inputs:colorh3_arr_1", "``colorh[3][]``", "Input of type colorh[3][]", "[]"
"inputs:colorh4_0", "``colorh[4]``", "Input of type colorh[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colorh4_1", "``colorh[4]``", "Input of type colorh[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:colorh4_arr_0", "``colorh[4][]``", "Input of type colorh[4][]", "[]"
"inputs:colorh4_arr_1", "``colorh[4][]``", "Input of type colorh[4][]", "[]"
"inputs:double2_0", "``double[2]``", "Input of type double[2]", "[0.0, 0.0]"
"inputs:double2_1", "``double[2]``", "Input of type double[2]", "[0.0, 0.0]"
"inputs:double2_arr_0", "``double[2][]``", "Input of type double[2][]", "[]"
"inputs:double2_arr_1", "``double[2][]``", "Input of type double[2][]", "[]"
"inputs:double3_0", "``double[3]``", "Input of type double[3]", "[0.0, 0.0, 0.0]"
"inputs:double3_1", "``double[3]``", "Input of type double[3]", "[0.0, 0.0, 0.0]"
"inputs:double3_arr_0", "``double[3][]``", "Input of type double[3][]", "[]"
"inputs:double3_arr_1", "``double[3][]``", "Input of type double[3][]", "[]"
"inputs:double4_0", "``double[4]``", "Input of type double[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:double4_1", "``double[4]``", "Input of type double[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:double4_arr_0", "``double[4][]``", "Input of type double[4][]", "[]"
"inputs:double4_arr_1", "``double[4][]``", "Input of type double[4][]", "[]"
"inputs:double_0", "``double``", "Input of type double", "0.0"
"inputs:double_1", "``double``", "Input of type double", "0.0"
"inputs:double_arr_0", "``double[]``", "Input of type double[]", "[]"
"inputs:double_arr_1", "``double[]``", "Input of type double[]", "[]"
"inputs:float2_0", "``float[2]``", "Input of type float[2]", "[0.0, 0.0]"
"inputs:float2_1", "``float[2]``", "Input of type float[2]", "[0.0, 0.0]"
"inputs:float2_arr_0", "``float[2][]``", "Input of type float[2][]", "[]"
"inputs:float2_arr_1", "``float[2][]``", "Input of type float[2][]", "[]"
"inputs:float3_0", "``float[3]``", "Input of type float[3]", "[0.0, 0.0, 0.0]"
"inputs:float3_1", "``float[3]``", "Input of type float[3]", "[0.0, 0.0, 0.0]"
"inputs:float3_arr_0", "``float[3][]``", "Input of type float[3][]", "[]"
"inputs:float3_arr_1", "``float[3][]``", "Input of type float[3][]", "[]"
"inputs:float4_0", "``float[4]``", "Input of type float[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:float4_1", "``float[4]``", "Input of type float[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:float4_arr_0", "``float[4][]``", "Input of type float[4][]", "[]"
"inputs:float4_arr_1", "``float[4][]``", "Input of type float[4][]", "[]"
"inputs:float_0", "``float``", "Input of type float", "0.0"
"inputs:float_1", "``float``", "Input of type float", "0.0"
"inputs:float_arr_0", "``float[]``", "Input of type float[]", "[]"
"inputs:float_arr_1", "``float[]``", "Input of type float[]", "[]"
"inputs:frame4_0", "``frame[4]``", "Input of type frame[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:frame4_1", "``frame[4]``", "Input of type frame[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:frame4_arr_0", "``frame[4][]``", "Input of type frame[4][]", "[]"
"inputs:frame4_arr_1", "``frame[4][]``", "Input of type frame[4][]", "[]"
"inputs:half2_0", "``half[2]``", "Input of type half[2]", "[0.0, 0.0]"
"inputs:half2_1", "``half[2]``", "Input of type half[2]", "[0.0, 0.0]"
"inputs:half2_arr_0", "``half[2][]``", "Input of type half[2][]", "[]"
"inputs:half2_arr_1", "``half[2][]``", "Input of type half[2][]", "[]"
"inputs:half3_0", "``half[3]``", "Input of type half[3]", "[0.0, 0.0, 0.0]"
"inputs:half3_1", "``half[3]``", "Input of type half[3]", "[0.0, 0.0, 0.0]"
"inputs:half3_arr_0", "``half[3][]``", "Input of type half[3][]", "[]"
"inputs:half3_arr_1", "``half[3][]``", "Input of type half[3][]", "[]"
"inputs:half4_0", "``half[4]``", "Input of type half[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:half4_1", "``half[4]``", "Input of type half[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:half4_arr_0", "``half[4][]``", "Input of type half[4][]", "[]"
"inputs:half4_arr_1", "``half[4][]``", "Input of type half[4][]", "[]"
"inputs:half_0", "``half``", "Input of type half", "0.0"
"inputs:half_1", "``half``", "Input of type half", "0.0"
"inputs:half_arr_0", "``half[]``", "Input of type half[]", "[]"
"inputs:half_arr_1", "``half[]``", "Input of type half[]", "[]"
"inputs:int2_0", "``int[2]``", "Input of type int[2]", "[0, 0]"
"inputs:int2_1", "``int[2]``", "Input of type int[2]", "[0, 0]"
"inputs:int2_arr_0", "``int[2][]``", "Input of type int[2][]", "[]"
"inputs:int2_arr_1", "``int[2][]``", "Input of type int[2][]", "[]"
"inputs:int3_0", "``int[3]``", "Input of type int[3]", "[0, 0, 0]"
"inputs:int3_1", "``int[3]``", "Input of type int[3]", "[0, 0, 0]"
"inputs:int3_arr_0", "``int[3][]``", "Input of type int[3][]", "[]"
"inputs:int3_arr_1", "``int[3][]``", "Input of type int[3][]", "[]"
"inputs:int4_0", "``int[4]``", "Input of type int[4]", "[0, 0, 0, 0]"
"inputs:int4_1", "``int[4]``", "Input of type int[4]", "[0, 0, 0, 0]"
"inputs:int4_arr_0", "``int[4][]``", "Input of type int[4][]", "[]"
"inputs:int4_arr_1", "``int[4][]``", "Input of type int[4][]", "[]"
"inputs:int64_0", "``int64``", "Input of type int64", "0"
"inputs:int64_1", "``int64``", "Input of type int64", "0"
"inputs:int64_arr_0", "``int64[]``", "Input of type int64[]", "[]"
"inputs:int64_arr_1", "``int64[]``", "Input of type int64[]", "[]"
"inputs:int_0", "``int``", "Input of type int", "0"
"inputs:int_1", "``int``", "Input of type int", "0"
"inputs:int_arr_0", "``int[]``", "Input of type int[]", "[]"
"inputs:int_arr_1", "``int[]``", "Input of type int[]", "[]"
"inputs:matrixd2_0", "``matrixd[2]``", "Input of type matrixd[2]", "[[0.0, 0.0], [0.0, 0.0]]"
"inputs:matrixd2_1", "``matrixd[2]``", "Input of type matrixd[2]", "[[0.0, 0.0], [0.0, 0.0]]"
"inputs:matrixd2_arr_0", "``matrixd[2][]``", "Input of type matrixd[2][]", "[]"
"inputs:matrixd2_arr_1", "``matrixd[2][]``", "Input of type matrixd[2][]", "[]"
"inputs:matrixd3_0", "``matrixd[3]``", "Input of type matrixd[3]", "[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]"
"inputs:matrixd3_1", "``matrixd[3]``", "Input of type matrixd[3]", "[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]"
"inputs:matrixd3_arr_0", "``matrixd[3][]``", "Input of type matrixd[3][]", "[]"
"inputs:matrixd3_arr_1", "``matrixd[3][]``", "Input of type matrixd[3][]", "[]"
"inputs:matrixd4_0", "``matrixd[4]``", "Input of type matrixd[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:matrixd4_1", "``matrixd[4]``", "Input of type matrixd[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:matrixd4_arr_0", "``matrixd[4][]``", "Input of type matrixd[4][]", "[]"
"inputs:matrixd4_arr_1", "``matrixd[4][]``", "Input of type matrixd[4][]", "[]"
"inputs:normald3_0", "``normald[3]``", "Input of type normald[3]", "[0.0, 0.0, 0.0]"
"inputs:normald3_1", "``normald[3]``", "Input of type normald[3]", "[0.0, 0.0, 0.0]"
"inputs:normald3_arr_0", "``normald[3][]``", "Input of type normald[3][]", "[]"
"inputs:normald3_arr_1", "``normald[3][]``", "Input of type normald[3][]", "[]"
"inputs:normalf3_0", "``normalf[3]``", "Input of type normalf[3]", "[0.0, 0.0, 0.0]"
"inputs:normalf3_1", "``normalf[3]``", "Input of type normalf[3]", "[0.0, 0.0, 0.0]"
"inputs:normalf3_arr_0", "``normalf[3][]``", "Input of type normalf[3][]", "[]"
"inputs:normalf3_arr_1", "``normalf[3][]``", "Input of type normalf[3][]", "[]"
"inputs:normalh3_0", "``normalh[3]``", "Input of type normalh[3]", "[0.0, 0.0, 0.0]"
"inputs:normalh3_1", "``normalh[3]``", "Input of type normalh[3]", "[0.0, 0.0, 0.0]"
"inputs:normalh3_arr_0", "``normalh[3][]``", "Input of type normalh[3][]", "[]"
"inputs:normalh3_arr_1", "``normalh[3][]``", "Input of type normalh[3][]", "[]"
"inputs:pointd3_0", "``pointd[3]``", "Input of type pointd[3]", "[0.0, 0.0, 0.0]"
"inputs:pointd3_1", "``pointd[3]``", "Input of type pointd[3]", "[0.0, 0.0, 0.0]"
"inputs:pointd3_arr_0", "``pointd[3][]``", "Input of type pointd[3][]", "[]"
"inputs:pointd3_arr_1", "``pointd[3][]``", "Input of type pointd[3][]", "[]"
"inputs:pointf3_0", "``pointf[3]``", "Input of type pointf[3]", "[0.0, 0.0, 0.0]"
"inputs:pointf3_1", "``pointf[3]``", "Input of type pointf[3]", "[0.0, 0.0, 0.0]"
"inputs:pointf3_arr_0", "``pointf[3][]``", "Input of type pointf[3][]", "[]"
"inputs:pointf3_arr_1", "``pointf[3][]``", "Input of type pointf[3][]", "[]"
"inputs:pointh3_0", "``pointh[3]``", "Input of type pointh[3]", "[0.0, 0.0, 0.0]"
"inputs:pointh3_1", "``pointh[3]``", "Input of type pointh[3]", "[0.0, 0.0, 0.0]"
"inputs:pointh3_arr_0", "``pointh[3][]``", "Input of type pointh[3][]", "[]"
"inputs:pointh3_arr_1", "``pointh[3][]``", "Input of type pointh[3][]", "[]"
"inputs:quatd4_0", "``quatd[4]``", "Input of type quatd[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quatd4_1", "``quatd[4]``", "Input of type quatd[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quatd4_arr_0", "``quatd[4][]``", "Input of type quatd[4][]", "[]"
"inputs:quatd4_arr_1", "``quatd[4][]``", "Input of type quatd[4][]", "[]"
"inputs:quatf4_0", "``quatf[4]``", "Input of type quatf[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quatf4_1", "``quatf[4]``", "Input of type quatf[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quatf4_arr_0", "``quatf[4][]``", "Input of type quatf[4][]", "[]"
"inputs:quatf4_arr_1", "``quatf[4][]``", "Input of type quatf[4][]", "[]"
"inputs:quath4_0", "``quath[4]``", "Input of type quath[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quath4_1", "``quath[4]``", "Input of type quath[4]", "[0.0, 0.0, 0.0, 0.0]"
"inputs:quath4_arr_0", "``quath[4][]``", "Input of type quath[4][]", "[]"
"inputs:quath4_arr_1", "``quath[4][]``", "Input of type quath[4][]", "[]"
"inputs:texcoordd2_0", "``texcoordd[2]``", "Input of type texcoordd[2]", "[0.0, 0.0]"
"inputs:texcoordd2_1", "``texcoordd[2]``", "Input of type texcoordd[2]", "[0.0, 0.0]"
"inputs:texcoordd2_arr_0", "``texcoordd[2][]``", "Input of type texcoordd[2][]", "[]"
"inputs:texcoordd2_arr_1", "``texcoordd[2][]``", "Input of type texcoordd[2][]", "[]"
"inputs:texcoordd3_0", "``texcoordd[3]``", "Input of type texcoordd[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordd3_1", "``texcoordd[3]``", "Input of type texcoordd[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordd3_arr_0", "``texcoordd[3][]``", "Input of type texcoordd[3][]", "[]"
"inputs:texcoordd3_arr_1", "``texcoordd[3][]``", "Input of type texcoordd[3][]", "[]"
"inputs:texcoordf2_0", "``texcoordf[2]``", "Input of type texcoordf[2]", "[0.0, 0.0]"
"inputs:texcoordf2_1", "``texcoordf[2]``", "Input of type texcoordf[2]", "[0.0, 0.0]"
"inputs:texcoordf2_arr_0", "``texcoordf[2][]``", "Input of type texcoordf[2][]", "[]"
"inputs:texcoordf2_arr_1", "``texcoordf[2][]``", "Input of type texcoordf[2][]", "[]"
"inputs:texcoordf3_0", "``texcoordf[3]``", "Input of type texcoordf[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordf3_1", "``texcoordf[3]``", "Input of type texcoordf[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordf3_arr_0", "``texcoordf[3][]``", "Input of type texcoordf[3][]", "[]"
"inputs:texcoordf3_arr_1", "``texcoordf[3][]``", "Input of type texcoordf[3][]", "[]"
"inputs:texcoordh2_0", "``texcoordh[2]``", "Input of type texcoordh[2]", "[0.0, 0.0]"
"inputs:texcoordh2_1", "``texcoordh[2]``", "Input of type texcoordh[2]", "[0.0, 0.0]"
"inputs:texcoordh2_arr_0", "``texcoordh[2][]``", "Input of type texcoordh[2][]", "[]"
"inputs:texcoordh2_arr_1", "``texcoordh[2][]``", "Input of type texcoordh[2][]", "[]"
"inputs:texcoordh3_0", "``texcoordh[3]``", "Input of type texcoordh[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordh3_1", "``texcoordh[3]``", "Input of type texcoordh[3]", "[0.0, 0.0, 0.0]"
"inputs:texcoordh3_arr_0", "``texcoordh[3][]``", "Input of type texcoordh[3][]", "[]"
"inputs:texcoordh3_arr_1", "``texcoordh[3][]``", "Input of type texcoordh[3][]", "[]"
"inputs:timecode_0", "``timecode``", "Input of type timecode", "0.0"
"inputs:timecode_1", "``timecode``", "Input of type timecode", "0.0"
"inputs:timecode_arr_0", "``timecode[]``", "Input of type timecode[]", "[]"
"inputs:timecode_arr_1", "``timecode[]``", "Input of type timecode[]", "[]"
"inputs:token_0", "``token``", "Input of type token", "default_token"
"inputs:token_1", "``token``", "Input of type token", "default_token"
"inputs:token_arr_0", "``token[]``", "Input of type token[]", "[]"
"inputs:token_arr_1", "``token[]``", "Input of type token[]", "[]"
"inputs:transform4_0", "``transform[4]``", "Input of type transform[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:transform4_1", "``transform[4]``", "Input of type transform[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"inputs:transform4_arr_0", "``transform[4][]``", "Input of type transform[4][]", "[]"
"inputs:transform4_arr_1", "``transform[4][]``", "Input of type transform[4][]", "[]"
"inputs:uchar_0", "``uchar``", "Input of type uchar", "0"
"inputs:uchar_1", "``uchar``", "Input of type uchar", "0"
"inputs:uchar_arr_0", "``uchar[]``", "Input of type uchar[]", "[]"
"inputs:uchar_arr_1", "``uchar[]``", "Input of type uchar[]", "[]"
"inputs:uint64_0", "``uint64``", "Input of type uint64", "0"
"inputs:uint64_1", "``uint64``", "Input of type uint64", "0"
"inputs:uint64_arr_0", "``uint64[]``", "Input of type uint64[]", "[]"
"inputs:uint64_arr_1", "``uint64[]``", "Input of type uint64[]", "[]"
"inputs:uint_0", "``uint``", "Input of type uint", "0"
"inputs:uint_1", "``uint``", "Input of type uint", "0"
"inputs:uint_arr_0", "``uint[]``", "Input of type uint[]", "[]"
"inputs:uint_arr_1", "``uint[]``", "Input of type uint[]", "[]"
"inputs:vectord3_0", "``vectord[3]``", "Input of type vectord[3]", "[0.0, 0.0, 0.0]"
"inputs:vectord3_1", "``vectord[3]``", "Input of type vectord[3]", "[0.0, 0.0, 0.0]"
"inputs:vectord3_arr_0", "``vectord[3][]``", "Input of type vectord[3][]", "[]"
"inputs:vectord3_arr_1", "``vectord[3][]``", "Input of type vectord[3][]", "[]"
"inputs:vectorf3_0", "``vectorf[3]``", "Input of type vectorf[3]", "[0.0, 0.0, 0.0]"
"inputs:vectorf3_1", "``vectorf[3]``", "Input of type vectorf[3]", "[0.0, 0.0, 0.0]"
"inputs:vectorf3_arr_0", "``vectorf[3][]``", "Input of type vectorf[3][]", "[]"
"inputs:vectorf3_arr_1", "``vectorf[3][]``", "Input of type vectorf[3][]", "[]"
"inputs:vectorh3_0", "``vectorh[3]``", "Input of type vectorh[3]", "[0.0, 0.0, 0.0]"
"inputs:vectorh3_1", "``vectorh[3]``", "Input of type vectorh[3]", "[0.0, 0.0, 0.0]"
"inputs:vectorh3_arr_0", "``vectorh[3][]``", "Input of type vectorh[3][]", "[]"
"inputs:vectorh3_arr_1", "``vectorh[3][]``", "Input of type vectorh[3][]", "[]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:bool_0", "``bool``", "Output of type bool", "False"
"outputs:bool_arr_0", "``bool[]``", "Output of type bool[]", "[]"
"outputs:colord3_0", "``colord[3]``", "Output of type colord[3]", "[0.0, 0.0, 0.0]"
"outputs:colord3_arr_0", "``colord[3][]``", "Output of type colord[3][]", "[]"
"outputs:colord4_0", "``colord[4]``", "Output of type colord[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:colord4_arr_0", "``colord[4][]``", "Output of type colord[4][]", "[]"
"outputs:colorf3_0", "``colorf[3]``", "Output of type colorf[3]", "[0.0, 0.0, 0.0]"
"outputs:colorf3_arr_0", "``colorf[3][]``", "Output of type colorf[3][]", "[]"
"outputs:colorf4_0", "``colorf[4]``", "Output of type colorf[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:colorf4_arr_0", "``colorf[4][]``", "Output of type colorf[4][]", "[]"
"outputs:colorh3_0", "``colorh[3]``", "Output of type colorh[3]", "[0.0, 0.0, 0.0]"
"outputs:colorh3_arr_0", "``colorh[3][]``", "Output of type colorh[3][]", "[]"
"outputs:colorh4_0", "``colorh[4]``", "Output of type colorh[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:colorh4_arr_0", "``colorh[4][]``", "Output of type colorh[4][]", "[]"
"outputs:double2_0", "``double[2]``", "Output of type double[2]", "[0.0, 0.0]"
"outputs:double2_arr_0", "``double[2][]``", "Output of type double[2][]", "[]"
"outputs:double3_0", "``double[3]``", "Output of type double[3]", "[0.0, 0.0, 0.0]"
"outputs:double3_arr_0", "``double[3][]``", "Output of type double[3][]", "[]"
"outputs:double4_0", "``double[4]``", "Output of type double[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:double4_arr_0", "``double[4][]``", "Output of type double[4][]", "[]"
"outputs:double_0", "``double``", "Output of type double", "0.0"
"outputs:double_arr_0", "``double[]``", "Output of type double[]", "[]"
"outputs:float2_0", "``float[2]``", "Output of type float[2]", "[0.0, 0.0]"
"outputs:float2_arr_0", "``float[2][]``", "Output of type float[2][]", "[]"
"outputs:float3_0", "``float[3]``", "Output of type float[3]", "[0.0, 0.0, 0.0]"
"outputs:float3_arr_0", "``float[3][]``", "Output of type float[3][]", "[]"
"outputs:float4_0", "``float[4]``", "Output of type float[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:float4_arr_0", "``float[4][]``", "Output of type float[4][]", "[]"
"outputs:float_0", "``float``", "Output of type float", "0.0"
"outputs:float_arr_0", "``float[]``", "Output of type float[]", "[]"
"outputs:frame4_0", "``frame[4]``", "Output of type frame[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"outputs:frame4_arr_0", "``frame[4][]``", "Output of type frame[4][]", "[]"
"outputs:half2_0", "``half[2]``", "Output of type half[2]", "[0.0, 0.0]"
"outputs:half2_arr_0", "``half[2][]``", "Output of type half[2][]", "[]"
"outputs:half3_0", "``half[3]``", "Output of type half[3]", "[0.0, 0.0, 0.0]"
"outputs:half3_arr_0", "``half[3][]``", "Output of type half[3][]", "[]"
"outputs:half4_0", "``half[4]``", "Output of type half[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:half4_arr_0", "``half[4][]``", "Output of type half[4][]", "[]"
"outputs:half_0", "``half``", "Output of type half", "0.0"
"outputs:half_arr_0", "``half[]``", "Output of type half[]", "[]"
"outputs:int2_0", "``int[2]``", "Output of type int[2]", "[0, 0]"
"outputs:int2_arr_0", "``int[2][]``", "Output of type int[2][]", "[]"
"outputs:int3_0", "``int[3]``", "Output of type int[3]", "[0, 0, 0]"
"outputs:int3_arr_0", "``int[3][]``", "Output of type int[3][]", "[]"
"outputs:int4_0", "``int[4]``", "Output of type int[4]", "[0, 0, 0, 0]"
"outputs:int4_arr_0", "``int[4][]``", "Output of type int[4][]", "[]"
"outputs:int64_0", "``int64``", "Output of type int64", "0"
"outputs:int64_arr_0", "``int64[]``", "Output of type int64[]", "[]"
"outputs:int_0", "``int``", "Output of type int", "0"
"outputs:int_arr_0", "``int[]``", "Output of type int[]", "[]"
"outputs:matrixd2_0", "``matrixd[2]``", "Output of type matrixd[2]", "[[0.0, 0.0], [0.0, 0.0]]"
"outputs:matrixd2_arr_0", "``matrixd[2][]``", "Output of type matrixd[2][]", "[]"
"outputs:matrixd3_0", "``matrixd[3]``", "Output of type matrixd[3]", "[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]"
"outputs:matrixd3_arr_0", "``matrixd[3][]``", "Output of type matrixd[3][]", "[]"
"outputs:matrixd4_0", "``matrixd[4]``", "Output of type matrixd[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"outputs:matrixd4_arr_0", "``matrixd[4][]``", "Output of type matrixd[4][]", "[]"
"outputs:normald3_0", "``normald[3]``", "Output of type normald[3]", "[0.0, 0.0, 0.0]"
"outputs:normald3_arr_0", "``normald[3][]``", "Output of type normald[3][]", "[]"
"outputs:normalf3_0", "``normalf[3]``", "Output of type normalf[3]", "[0.0, 0.0, 0.0]"
"outputs:normalf3_arr_0", "``normalf[3][]``", "Output of type normalf[3][]", "[]"
"outputs:normalh3_0", "``normalh[3]``", "Output of type normalh[3]", "[0.0, 0.0, 0.0]"
"outputs:normalh3_arr_0", "``normalh[3][]``", "Output of type normalh[3][]", "[]"
"outputs:pointd3_0", "``pointd[3]``", "Output of type pointd[3]", "[0.0, 0.0, 0.0]"
"outputs:pointd3_arr_0", "``pointd[3][]``", "Output of type pointd[3][]", "[]"
"outputs:pointf3_0", "``pointf[3]``", "Output of type pointf[3]", "[0.0, 0.0, 0.0]"
"outputs:pointf3_arr_0", "``pointf[3][]``", "Output of type pointf[3][]", "[]"
"outputs:pointh3_0", "``pointh[3]``", "Output of type pointh[3]", "[0.0, 0.0, 0.0]"
"outputs:pointh3_arr_0", "``pointh[3][]``", "Output of type pointh[3][]", "[]"
"outputs:quatd4_0", "``quatd[4]``", "Output of type quatd[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:quatd4_arr_0", "``quatd[4][]``", "Output of type quatd[4][]", "[]"
"outputs:quatf4_0", "``quatf[4]``", "Output of type quatf[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:quatf4_arr_0", "``quatf[4][]``", "Output of type quatf[4][]", "[]"
"outputs:quath4_0", "``quath[4]``", "Output of type quath[4]", "[0.0, 0.0, 0.0, 0.0]"
"outputs:quath4_arr_0", "``quath[4][]``", "Output of type quath[4][]", "[]"
"outputs:texcoordd2_0", "``texcoordd[2]``", "Output of type texcoordd[2]", "[0.0, 0.0]"
"outputs:texcoordd2_arr_0", "``texcoordd[2][]``", "Output of type texcoordd[2][]", "[]"
"outputs:texcoordd3_0", "``texcoordd[3]``", "Output of type texcoordd[3]", "[0.0, 0.0, 0.0]"
"outputs:texcoordd3_arr_0", "``texcoordd[3][]``", "Output of type texcoordd[3][]", "[]"
"outputs:texcoordf2_0", "``texcoordf[2]``", "Output of type texcoordf[2]", "[0.0, 0.0]"
"outputs:texcoordf2_arr_0", "``texcoordf[2][]``", "Output of type texcoordf[2][]", "[]"
"outputs:texcoordf3_0", "``texcoordf[3]``", "Output of type texcoordf[3]", "[0.0, 0.0, 0.0]"
"outputs:texcoordf3_arr_0", "``texcoordf[3][]``", "Output of type texcoordf[3][]", "[]"
"outputs:texcoordh2_0", "``texcoordh[2]``", "Output of type texcoordh[2]", "[0.0, 0.0]"
"outputs:texcoordh2_arr_0", "``texcoordh[2][]``", "Output of type texcoordh[2][]", "[]"
"outputs:texcoordh3_0", "``texcoordh[3]``", "Output of type texcoordh[3]", "[0.0, 0.0, 0.0]"
"outputs:texcoordh3_arr_0", "``texcoordh[3][]``", "Output of type texcoordh[3][]", "[]"
"outputs:timecode_0", "``timecode``", "Output of type timecode", "0.0"
"outputs:timecode_arr_0", "``timecode[]``", "Output of type timecode[]", "[]"
"outputs:token_0", "``token``", "Output of type token", "default_token"
"outputs:token_arr_0", "``token[]``", "Output of type token[]", "[]"
"outputs:transform4_0", "``transform[4]``", "Output of type transform[4]", "[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]"
"outputs:transform4_arr_0", "``transform[4][]``", "Output of type transform[4][]", "[]"
"outputs:uchar_0", "``uchar``", "Output of type uchar", "0"
"outputs:uchar_arr_0", "``uchar[]``", "Output of type uchar[]", "[]"
"outputs:uint64_0", "``uint64``", "Output of type uint64", "0"
"outputs:uint64_arr_0", "``uint64[]``", "Output of type uint64[]", "[]"
"outputs:uint_0", "``uint``", "Output of type uint", "0"
"outputs:uint_arr_0", "``uint[]``", "Output of type uint[]", "[]"
"outputs:vectord3_0", "``vectord[3]``", "Output of type vectord[3]", "[0.0, 0.0, 0.0]"
"outputs:vectord3_arr_0", "``vectord[3][]``", "Output of type vectord[3][]", "[]"
"outputs:vectorf3_0", "``vectorf[3]``", "Output of type vectorf[3]", "[0.0, 0.0, 0.0]"
"outputs:vectorf3_arr_0", "``vectorf[3][]``", "Output of type vectorf[3][]", "[]"
"outputs:vectorh3_0", "``vectorh[3]``", "Output of type vectorh[3]", "[0.0, 0.0, 0.0]"
"outputs:vectorh3_arr_0", "``vectorh[3][]``", "Output of type vectorh[3][]", "[]"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.UniversalAdd"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "usd"
"uiName", "Universal Add For All Types (Python)"
"Categories", "examples"
"Generated Class Name", "OgnPyUniversalAddDatabase"
"Python Module", "omni.graph.examples.python"
| 27,714 | reStructuredText | 72.320106 | 169 | 0.526665 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnBouncingCubesGpu.rst | .. _omni_graph_examples_python_BouncingCubesGpu_1:
.. _omni_graph_examples_python_BouncingCubesGpu:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Deprecated Node - Bouncing Cubes (GPU)
:keywords: lang-en omnigraph node examples python bouncing-cubes-gpu
Deprecated Node - Bouncing Cubes (GPU)
======================================
.. <description>
Deprecated node - no longer supported
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.BouncingCubesGpu"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cuda"
"Generated Code Exclusions", "usd, test"
"uiName", "Deprecated Node - Bouncing Cubes (GPU)"
"__memoryType", "cuda"
"Categories", "examples"
"Generated Class Name", "OgnBouncingCubesGpuDatabase"
"Python Module", "omni.graph.examples.python"
| 1,346 | reStructuredText | 25.411764 | 115 | 0.57578 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnCountTo.rst | .. _omni_graph_examples_python_CountTo_1:
.. _omni_graph_examples_python_CountTo:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Count To
:keywords: lang-en omnigraph node examples python count-to
Count To
========
.. <description>
Example stateful node that counts to countTo by a certain increment
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:countTo", "``double``", "The ceiling to count to", "3"
"inputs:increment", "``double``", "Increment to count by", "0.1"
"inputs:reset", "``bool``", "Whether to reset the count", "False"
"inputs:trigger", "``double[3]``", "Position to be used as a trigger for the counting", "[0.0, 0.0, 0.0]"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:count", "``double``", "The current count", "0.0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.CountTo"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Count To"
"Categories", "examples"
"Generated Class Name", "OgnCountToDatabase"
"Python Module", "omni.graph.examples.python"
| 1,784 | reStructuredText | 24.140845 | 115 | 0.567265 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnPositionToColor.rst | .. _omni_graph_examples_python_PositionToColor_1:
.. _omni_graph_examples_python_PositionToColor:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: PositionToColor
:keywords: lang-en omnigraph node examples python position-to-color
PositionToColor
===============
.. <description>
This node takes positional data (double3) and converts to a color, and outputs as color3f[] (which seems to be the default color connection in USD)
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:color_offset", "``colorf[3]``", "Offset added to the scaled color to get the final result", "[0.0, 0.0, 0.0]"
"inputs:position", "``double[3]``", "Position to be converted to a color", "[0.0, 0.0, 0.0]"
"inputs:scale", "``float``", "Constant by which to multiply the position to get the color", "1.0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:color", "``colorf[3][]``", "Color value extracted from the position", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.PositionToColor"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "PositionToColor"
"Categories", "examples"
"Generated Class Name", "OgnPositionToColorDatabase"
"Python Module", "omni.graph.examples.python"
| 1,967 | reStructuredText | 27.114285 | 148 | 0.593798 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnDeformerYAxis.rst | .. _omni_graph_examples_python_DeformerYAxis_1:
.. _omni_graph_examples_python_DeformerYAxis:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sine Wave Deformer Y-axis (Python)
:keywords: lang-en omnigraph node examples python deformer-y-axis
Sine Wave Deformer Y-axis (Python)
==================================
.. <description>
Example node applying a sine wave deformation to a set of points, written in Python. Deforms along Y-axis instead of Z
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:multiplier", "``double``", "The multiplier for the amplitude of the sine wave", "1"
"inputs:offset", "``double``", "The offset of the sine wave", "0"
"inputs:points", "``pointf[3][]``", "The input points to be deformed", "[]"
"inputs:wavelength", "``double``", "The wavelength of the sine wave", "1"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:points", "``pointf[3][]``", "The deformed output points", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.DeformerYAxis"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Sine Wave Deformer Y-axis (Python)"
"Categories", "examples"
"Generated Class Name", "OgnDeformerYAxisDatabase"
"Python Module", "omni.graph.examples.python"
| 1,995 | reStructuredText | 27.112676 | 119 | 0.582957 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnComposeDouble3.rst | .. _omni_graph_examples_python_ComposeDouble3_1:
.. _omni_graph_examples_python_ComposeDouble3:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Compose Double3 (Python)
:keywords: lang-en omnigraph node examples python compose-double3
Compose Double3 (Python)
========================
.. <description>
Example node that takes in the components of three doubles and outputs a double3
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:x", "``double``", "The x component of the input double3", "0"
"inputs:y", "``double``", "The y component of the input double3", "0"
"inputs:z", "``double``", "The z component of the input double3", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:double3", "``double[3]``", "Output double3", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.ComposeDouble3"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Compose Double3 (Python)"
"Categories", "examples"
"Generated Class Name", "OgnComposeDouble3Database"
"Python Module", "omni.graph.examples.python"
| 1,805 | reStructuredText | 24.8 | 115 | 0.577839 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnMultDouble.rst | .. _omni_graph_examples_python_MultDouble_1:
.. _omni_graph_examples_python_MultDouble:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Multiply Double (Python)
:keywords: lang-en omnigraph node examples python mult-double
Multiply Double (Python)
========================
.. <description>
Example node that multiplies 2 doubles together
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:a", "``double``", "Input a", "0"
"inputs:b", "``double``", "Input b", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:out", "``double``", "The result of a * b", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.MultDouble"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Multiply Double (Python)"
"Categories", "examples"
"Generated Class Name", "OgnMultDoubleDatabase"
"Python Module", "omni.graph.examples.python"
| 1,618 | reStructuredText | 22.463768 | 115 | 0.556242 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnDynamicSwitch.rst | .. _omni_graph_examples_python_DynamicSwitch_1:
.. _omni_graph_examples_python_DynamicSwitch:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Dynamic Switch
:keywords: lang-en omnigraph node examples python dynamic-switch
Dynamic Switch
==============
.. <description>
A switch node that will enable the left side or right side depending on the input. Requires dynamic scheduling to work
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:left_value", "``int``", "Left value to output", "-1"
"inputs:right_value", "``int``", "Right value to output", "1"
"inputs:switch", "``int``", "Enables right value if greater than 0, else left value", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:left_out", "``int``", "Left side output", "0"
"outputs:right_out", "``int``", "Right side output", "0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.DynamicSwitch"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "usd"
"uiName", "Dynamic Switch"
"Categories", "examples"
"Generated Class Name", "OgnDynamicSwitchDatabase"
"Python Module", "omni.graph.examples.python"
| 1,856 | reStructuredText | 25.154929 | 119 | 0.579741 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnBouncingCubesCpu.rst | .. _omni_graph_examples_python_BouncingCubes_1:
.. _omni_graph_examples_python_BouncingCubes:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Deprecated Node - Bouncing Cubes (GPU)
:keywords: lang-en omnigraph node examples python bouncing-cubes
Deprecated Node - Bouncing Cubes (GPU)
======================================
.. <description>
Deprecated node - no longer supported
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Translations (*state:translations*)", "``float[3][]``", "Set of translation attributes gathered from the inputs. Translations have velocities applied to them each evaluation.", "None"
"Velocities (*state:velocities*)", "``float[]``", "Set of velocity attributes gathered from the inputs", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.BouncingCubes"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Deprecated Node - Bouncing Cubes (GPU)"
"Categories", "examples"
"Generated Class Name", "OgnBouncingCubesCpuDatabase"
"Python Module", "omni.graph.examples.python"
| 1,716 | reStructuredText | 27.616666 | 188 | 0.594406 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnExecSwitch.rst | .. _omni_graph_examples_python_ExecSwitch_1:
.. _omni_graph_examples_python_ExecSwitch:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Exec Switch
:keywords: lang-en omnigraph node examples python exec-switch
Exec Switch
===========
.. <description>
A switch node that will enable the left side or right side depending on the input
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Exec In (*inputs:execIn*)", "``execution``", "Trigger the output", "None"
"inputs:switch", "``bool``", "Enables right value if greater than 0, else left value", "False"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:execLeftOut", "``execution``", "Left execution", "None"
"outputs:execRightOut", "``execution``", "Right execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.ExecSwitch"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "usd"
"uiName", "Exec Switch"
"Categories", "examples"
"Generated Class Name", "OgnExecSwitchDatabase"
"Python Module", "omni.graph.examples.python"
| 1,764 | reStructuredText | 24.214285 | 115 | 0.579932 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnTestInitNode.rst | .. _omni_graph_examples_python_TestInitNode_1:
.. _omni_graph_examples_python_TestInitNode:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: TestInitNode
:keywords: lang-en omnigraph node examples python test-init-node
TestInitNode
============
.. <description>
Test Init Node
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:value", "``float``", "Value", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.TestInitNode"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "TestInitNode"
"Categories", "examples"
"Generated Class Name", "OgnTestInitNodeDatabase"
"Python Module", "omni.graph.examples.python"
| 1,332 | reStructuredText | 21.59322 | 115 | 0.563814 |
omniverse-code/kit/exts/omni.graph.examples.python/ogn/docs/OgnIntCounter.rst | .. _omni_graph_examples_python_IntCounter_1:
.. _omni_graph_examples_python_IntCounter:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Int Counter
:keywords: lang-en omnigraph node examples python int-counter
Int Counter
===========
.. <description>
Example stateful node that increments every time it's evaluated
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.examples.python<ext_omni_graph_examples_python>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:increment", "``int``", "Increment to count by", "1"
"inputs:reset", "``bool``", "Whether to reset the count", "False"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:count", "``int``", "The current count", "0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.examples.python.IntCounter"
"Version", "1"
"Extension", "omni.graph.examples.python"
"Has State?", "False"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Int Counter"
"Categories", "examples"
"Generated Class Name", "OgnIntCounterDatabase"
"Python Module", "omni.graph.examples.python"
| 1,620 | reStructuredText | 22.492753 | 115 | 0.567901 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.