file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnTickDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnTick
Executes an output execution pulse at a regular multiple of the refresh rate
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnTickDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnTick
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.framePeriod
inputs.onlyPlayback
Outputs:
outputs.absoluteSimTime
outputs.deltaSeconds
outputs.frame
outputs.isPlaying
outputs.tick
outputs.time
outputs.timeSinceStart
State:
state.accumulatedSeconds
state.frameCount
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:framePeriod', 'uint', 0, 'Update Period (Ticks)', 'The number of updates between each output pulse.\nThe default 0 means every update, 1 means every other update.\nThis can be used to rate-limit updates.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:absoluteSimTime', 'double', 0, 'Absolute Simulation Time (Seconds)', 'The accumulated total of elapsed times between rendered frames', {}, True, None, False, ''),
('outputs:deltaSeconds', 'double', 0, 'Delta (Seconds)', 'The number of seconds elapsed since the last output pulse', {}, True, None, False, ''),
('outputs:frame', 'double', 0, 'Animation Time (Frames)', 'The global animation time in frames, equivalent to (time * fps), during playback', {}, True, None, False, ''),
('outputs:isPlaying', 'bool', 0, 'Is Playing', 'True during global animation timeline playback', {}, True, None, False, ''),
('outputs:tick', 'execution', 0, 'Tick', 'The execution output', {}, True, None, False, ''),
('outputs:time', 'double', 0, 'Animation Time (Seconds)', 'The global animation time in seconds during playback', {}, True, None, False, ''),
('outputs:timeSinceStart', 'double', 0, 'Time Since Start (Seconds)', 'Elapsed time since the App started', {}, True, None, False, ''),
('state:accumulatedSeconds', 'double', 0, None, 'Accumulated time since the last output pulse', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
('state:frameCount', 'uint', 0, None, 'Accumulated frames since the last output pulse', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.outputs.tick = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def framePeriod(self):
data_view = og.AttributeValueHelper(self._attributes.framePeriod)
return data_view.get()
@framePeriod.setter
def framePeriod(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.framePeriod)
data_view = og.AttributeValueHelper(self._attributes.framePeriod)
data_view.set(value)
@property
def onlyPlayback(self):
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
return data_view.get()
@onlyPlayback.setter
def onlyPlayback(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.onlyPlayback)
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def absoluteSimTime(self):
data_view = og.AttributeValueHelper(self._attributes.absoluteSimTime)
return data_view.get()
@absoluteSimTime.setter
def absoluteSimTime(self, value):
data_view = og.AttributeValueHelper(self._attributes.absoluteSimTime)
data_view.set(value)
@property
def deltaSeconds(self):
data_view = og.AttributeValueHelper(self._attributes.deltaSeconds)
return data_view.get()
@deltaSeconds.setter
def deltaSeconds(self, value):
data_view = og.AttributeValueHelper(self._attributes.deltaSeconds)
data_view.set(value)
@property
def frame(self):
data_view = og.AttributeValueHelper(self._attributes.frame)
return data_view.get()
@frame.setter
def frame(self, value):
data_view = og.AttributeValueHelper(self._attributes.frame)
data_view.set(value)
@property
def isPlaying(self):
data_view = og.AttributeValueHelper(self._attributes.isPlaying)
return data_view.get()
@isPlaying.setter
def isPlaying(self, value):
data_view = og.AttributeValueHelper(self._attributes.isPlaying)
data_view.set(value)
@property
def tick(self):
data_view = og.AttributeValueHelper(self._attributes.tick)
return data_view.get()
@tick.setter
def tick(self, value):
data_view = og.AttributeValueHelper(self._attributes.tick)
data_view.set(value)
@property
def time(self):
data_view = og.AttributeValueHelper(self._attributes.time)
return data_view.get()
@time.setter
def time(self, value):
data_view = og.AttributeValueHelper(self._attributes.time)
data_view.set(value)
@property
def timeSinceStart(self):
data_view = og.AttributeValueHelper(self._attributes.timeSinceStart)
return data_view.get()
@timeSinceStart.setter
def timeSinceStart(self, value):
data_view = og.AttributeValueHelper(self._attributes.timeSinceStart)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
@property
def accumulatedSeconds(self):
data_view = og.AttributeValueHelper(self._attributes.accumulatedSeconds)
return data_view.get()
@accumulatedSeconds.setter
def accumulatedSeconds(self, value):
data_view = og.AttributeValueHelper(self._attributes.accumulatedSeconds)
data_view.set(value)
@property
def frameCount(self):
data_view = og.AttributeValueHelper(self._attributes.frameCount)
return data_view.get()
@frameCount.setter
def frameCount(self, value):
data_view = og.AttributeValueHelper(self._attributes.frameCount)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnOnTickDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnTickDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnTickDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,439 | Python | 44.991189 | 312 | 0.648051 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnForLoopDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.ForLoop
Executes the a loop body once for each value within a range. When step is positive, the values in the range are determined
by the formula:
r[i] = start + step*i, i >= 0 & r[i] < stop.
When step is negative the constraint is instead r[i] > stop.
A step of zero is an error.
The break input can be used to break out of the loop before the last index. The finished output
is executed after all iterations are complete, or when the loop was broken
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnForLoopDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.ForLoop
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.breakLoop
inputs.execIn
inputs.start
inputs.step
inputs.stop
Outputs:
outputs.finished
outputs.index
outputs.loopBody
outputs.value
State:
state.i
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:breakLoop', 'execution', 0, 'Break', 'Breaks out of the loop when the loop body traversal reaches it', {}, True, None, False, ''),
('inputs:execIn', 'execution', 0, 'In', 'Input execution', {}, True, None, False, ''),
('inputs:start', 'int', 0, 'Start', 'The first value in the range', {}, True, 0, False, ''),
('inputs:step', 'int', 0, 'Step', 'The step size of the range', {ogn.MetadataKeys.DEFAULT: '1'}, True, 1, False, ''),
('inputs:stop', 'int', 0, 'Stop', 'The limiting value of the range', {}, True, 0, False, ''),
('outputs:finished', 'execution', 0, None, 'Executed when the loop is finished', {}, True, None, False, ''),
('outputs:index', 'int', 0, None, 'The current or last index within the range', {}, True, None, False, ''),
('outputs:loopBody', 'execution', 0, None, 'Executed for each index in the range', {}, True, None, False, ''),
('outputs:value', 'int', 0, None, 'The current or last value of the range', {}, True, None, False, ''),
('state:i', 'int', 0, None, 'The next position in the range or -1 when loop is not active', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.breakLoop = og.AttributeRole.EXECUTION
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.finished = og.AttributeRole.EXECUTION
role_data.outputs.loopBody = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def breakLoop(self):
data_view = og.AttributeValueHelper(self._attributes.breakLoop)
return data_view.get()
@breakLoop.setter
def breakLoop(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.breakLoop)
data_view = og.AttributeValueHelper(self._attributes.breakLoop)
data_view.set(value)
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
@property
def start(self):
data_view = og.AttributeValueHelper(self._attributes.start)
return data_view.get()
@start.setter
def start(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.start)
data_view = og.AttributeValueHelper(self._attributes.start)
data_view.set(value)
@property
def step(self):
data_view = og.AttributeValueHelper(self._attributes.step)
return data_view.get()
@step.setter
def step(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.step)
data_view = og.AttributeValueHelper(self._attributes.step)
data_view.set(value)
@property
def stop(self):
data_view = og.AttributeValueHelper(self._attributes.stop)
return data_view.get()
@stop.setter
def stop(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.stop)
data_view = og.AttributeValueHelper(self._attributes.stop)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def finished(self):
data_view = og.AttributeValueHelper(self._attributes.finished)
return data_view.get()
@finished.setter
def finished(self, value):
data_view = og.AttributeValueHelper(self._attributes.finished)
data_view.set(value)
@property
def index(self):
data_view = og.AttributeValueHelper(self._attributes.index)
return data_view.get()
@index.setter
def index(self, value):
data_view = og.AttributeValueHelper(self._attributes.index)
data_view.set(value)
@property
def loopBody(self):
data_view = og.AttributeValueHelper(self._attributes.loopBody)
return data_view.get()
@loopBody.setter
def loopBody(self, value):
data_view = og.AttributeValueHelper(self._attributes.loopBody)
data_view.set(value)
@property
def value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
data_view = og.AttributeValueHelper(self._attributes.value)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
@property
def i(self):
data_view = og.AttributeValueHelper(self._attributes.i)
return data_view.get()
@i.setter
def i(self, value):
data_view = og.AttributeValueHelper(self._attributes.i)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnForLoopDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnForLoopDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnForLoopDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 9,946 | Python | 42.060606 | 155 | 0.632013 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnStageEvent.py | """
This is the implementation of the OGN node defined in OgnOnStageEvent.ogn
"""
from contextlib import suppress
import carb
import omni.graph.core as og
import omni.kit.app
import omni.usd
from omni.graph.action import get_interface
from omni.graph.action.ogn.OgnOnStageEventDatabase import OgnOnStageEventDatabase
# global map of the token to python enum, should match the allowedTokens
event_name_to_enum = {
"Assets Loaded": omni.usd.StageEventType.ASSETS_LOADED,
"Assets Load Aborted": omni.usd.StageEventType.ASSETS_LOAD_ABORTED,
"Closed": omni.usd.StageEventType.CLOSED,
"Closing": omni.usd.StageEventType.CLOSING,
"Gizmo Tracking Changed": omni.usd.StageEventType.GIZMO_TRACKING_CHANGED,
"MDL Param Loaded": omni.usd.StageEventType.MDL_PARAM_LOADED,
"Opened": omni.usd.StageEventType.OPENED,
"Open Failed": omni.usd.StageEventType.OPEN_FAILED,
"Saved": omni.usd.StageEventType.SAVED,
"Save Failed": omni.usd.StageEventType.SAVE_FAILED,
"Selection Changed": omni.usd.StageEventType.SELECTION_CHANGED,
"Hierarchy Changed": omni.usd.StageEventType.HIERARCHY_CHANGED,
"Settings Loaded": omni.usd.StageEventType.SETTINGS_LOADED,
"Settings Saving": omni.usd.StageEventType.SETTINGS_SAVING,
"OmniGraph Start Play": omni.usd.StageEventType.OMNIGRAPH_START_PLAY,
"OmniGraph Stop Play": omni.usd.StageEventType.OMNIGRAPH_STOP_PLAY,
"Simulation Start Play": omni.usd.StageEventType.SIMULATION_START_PLAY,
"Simulation Stop Play": omni.usd.StageEventType.SIMULATION_STOP_PLAY,
"Animation Start Play": omni.usd.StageEventType.ANIMATION_START_PLAY,
"Animation Stop Play": omni.usd.StageEventType.ANIMATION_STOP_PLAY,
}
class OgnOnStageEventInternalState:
"""Convenience class for maintaining per-node state information"""
def __init__(self):
"""Instantiate the per-node state information."""
# This subscription object controls the lifetime of our callback, we will clean it up upon release
self.sub = None
# Set when the callback has triggered
self.is_set = False
# The last payload received
self.payload: carb.dictionary.Item = None
# The event_name we used to subscribe
self.sub_event_type = ""
# The node instance handle
self.node = None
# Counter to determine when an animation pause was detected
self._was_paused = 0
# cache of the int-valued event types
self._stop_play_events = [
int(e)
for e in (
omni.usd.StageEventType.OMNIGRAPH_STOP_PLAY,
omni.usd.StageEventType.SIMULATION_STOP_PLAY,
omni.usd.StageEventType.ANIMATION_STOP_PLAY,
)
]
self._start_play_events = [
int(e)
for e in (
omni.usd.StageEventType.OMNIGRAPH_START_PLAY,
omni.usd.StageEventType.SIMULATION_START_PLAY,
omni.usd.StageEventType.ANIMATION_START_PLAY,
)
]
self._timeline = omni.timeline.get_timeline_interface()
def _on_stage_event(self, e: carb.events.IEvent):
"""The event callback"""
if e is None:
return
# Maintain book-keeping for pause/resume so we can ignore them
if e.type in self._stop_play_events:
is_stopped = self._timeline.is_stopped()
if not is_stopped:
# This is actually a PAUSE, because the timeline is not stopped
self._was_paused += 1
return
elif (e.type in self._start_play_events) and (self._was_paused > 0):
# This is actually an UNPAUSE, because we previously detected a PAUSE
self._was_paused -= 1
return
if e.type != int(self.sub_event_type):
return
self.is_set = True
self.payload = e.payload
# Tell the evaluator we need to be computed
if self.node.is_valid():
self.node.request_compute()
def first_time_subscribe(self, node: og.Node, event_type: omni.usd.StageEventType) -> bool:
"""Checked call to set up carb subscription
Args:
node: The node instance
event_type: The stage event type
Returns:
True if we subscribed, False if we are already subscribed
"""
if self.sub is not None and self.sub_event_type != event_type:
# event name changed since we last subscribed, unsubscribe
self.sub.unsubscribe()
self.sub = None
if self.sub is None:
# Add a subscription for the given event type. This is a pop subscription, so we expect a 1-frame
# lag between send and receive
self.sub = (
omni.usd.get_context()
.get_stage_event_stream()
.create_subscription_to_pop(
self._on_stage_event, name=f"omni.graph.action.__onstageevent.{node.node_id()}"
)
)
self.sub_event_type = event_type
self.node = node
return True
return False
def try_pop_event(self):
"""Pop the payload of the last event received, or None if there is no event to pop"""
if self.is_set:
self.is_set = False
payload = self.payload
self.payload = None
return payload
return None
# ======================================================================
class OgnOnStageEvent:
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnOnStageEventInternalState()
@staticmethod
def release(node):
# Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing
# after the node has been released.
with suppress(og.OmniGraphError):
state = OgnOnStageEventDatabase.per_node_internal_state(node)
if state.sub:
state.sub.unsubscribe()
state.sub = None
@staticmethod
def compute(db) -> bool:
event_name = db.inputs.eventName
if not event_name:
return True
state = db.internal_state
# Check the validity of the input
try:
event_type = event_name_to_enum[event_name]
except KeyError:
db.log_error(f"{event_name} is not a recognized Stage Event")
return False
if state.first_time_subscribe(db.node, event_type):
return True
payload = state.try_pop_event()
# Drop events if we are disabled, unless we are a 'stop' event - this is a special case because STOP only comes
# after we are no longer playing.
if (
db.inputs.onlyPlayback
and (not db.node.get_graph().get_default_graph_context().get_is_playing())
and (
event_type
not in (
omni.usd.StageEventType.OMNIGRAPH_STOP_PLAY,
omni.usd.StageEventType.SIMULATION_STOP_PLAY,
omni.usd.StageEventType.ANIMATION_STOP_PLAY,
)
)
):
return True
if payload is None:
return True
get_interface().set_execution_enabled("outputs:execOut")
return True
# ----------------------------------------------------------------------------
@staticmethod
def update_node_version(context: og.GraphContext, node: og.Node, old_version: int, new_version: int):
if old_version < new_version and old_version < 2:
# We added inputs:onlyPlayback default true - to maintain previous behavior we should set this to false
node.create_attribute(
"inputs:onlyPlayback",
og.Type(og.BaseDataType.BOOL),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
False,
)
return True
| 8,061 | Python | 37.390476 | 119 | 0.602531 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnSendCustomEvent.py | """
This is the implementation of the OGN node defined in OgnSendCustomEvent.ogn
"""
import codecs
import pickle
import carb.events
import omni.kit.app
from omni.graph.action import get_interface
def registered_event_name(event_name):
"""Returns the internal name used for the given custom event name"""
n = "omni.graph.action." + event_name
return carb.events.type_from_string(n)
payload_path = "!path"
# ======================================================================
class OgnSendCustomEvent:
"""
This node triggers when the specified message bus event is received
"""
@staticmethod
def compute(db) -> bool:
"""Compute the outputs from the current input"""
event_name = db.inputs.eventName
if not event_name:
return True
path = db.inputs.path
input_bundle = db.inputs.bundle
reg_event_name = registered_event_name(event_name)
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
payload = {}
if input_bundle.valid:
# Copy the contents of the input bundle into the event dict
for attr in input_bundle.attributes:
tp = attr.type
arg_obj = (tp, attr.value)
# Since we are python at both ends, easiest to pickle the attrib values so we
# can re-animate them on the other side
as_str = codecs.encode(pickle.dumps(arg_obj), "base64").decode()
payload[attr.name] = as_str
if path:
payload[payload_path] = path
message_bus.push(reg_event_name, payload=payload)
get_interface().set_execution_enabled("outputs:execOut")
return True
| 1,744 | Python | 27.606557 | 93 | 0.599197 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnCustomEvent.py | """
This is the implementation of the OGN node defined in OgnOnCustomEvent.ogn
"""
import codecs
import pickle
from contextlib import suppress
import carb.events
import omni.graph.core as og
import omni.kit.app
from omni.graph.action import get_interface
from omni.graph.action.ogn.OgnOnCustomEventDatabase import OgnOnCustomEventDatabase
def registered_event_name(event_name):
"""Returns the internal name used for the given custom event name"""
n = "omni.graph.action." + event_name
return carb.events.type_from_string(n)
payload_path = "!path"
class OgnOnCustomEventInternalState:
"""Convenience class for maintaining per-node state information"""
def __init__(self):
"""Instantiate the per-node state information."""
# This subscription object controls the lifetime of our callback, it will be
# cleaned up automatically when our node is destroyed
self.sub = None
# Set when the callback has triggered
self.is_set = False
# The last payload received
self.payload = None
# The event_name we used to subscribe
self.sub_event_name = ""
# The node instance handle
self.node = None
def on_event(self, custom_event):
"""The event callback"""
if custom_event is None:
return
self.is_set = True
self.payload = custom_event.payload
# Tell the evaluator we need to be computed
if self.node.is_valid():
self.node.request_compute()
def first_time_subscribe(self, node: og.Node, event_name: str) -> bool:
"""Checked call to set up carb subscription
Args:
node: The node instance
event_name: The name of the carb event
Returns:
True if we subscribed, False if we are already subscribed
"""
if self.sub is not None and self.sub_event_name != event_name:
# event name changed since we last subscribed, unsubscribe
self.sub.unsubscribe()
self.sub = None
if self.sub is None:
# Add a subscription for the given event name. This is a pop subscription, so we expect a 1-frame
# lag between send and receive
reg_event_name = registered_event_name(event_name)
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self.sub = message_bus.create_subscription_to_pop_by_type(reg_event_name, self.on_event)
self.sub_event_name = event_name
self.node = node
return True
return False
def try_pop_event(self):
"""Pop the payload of the last event received, or None if there is no event to pop"""
if self.is_set:
self.is_set = False
payload = self.payload
self.payload = None
return payload
return None
# ======================================================================
class OgnOnCustomEvent:
"""
This node triggers when the specified message bus event is received
"""
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnOnCustomEventInternalState()
@staticmethod
def compute(db) -> bool:
event_name = db.inputs.eventName
if not event_name:
return True
state = db.internal_state
if state.first_time_subscribe(db.node, event_name):
return True
# Drop events if we are disabled
if db.inputs.onlyPlayback and (not db.node.get_graph().get_default_graph_context().get_is_playing()):
state.try_pop_event()
return True
payload = state.try_pop_event()
if payload is None:
return True
# Copy the event dict contents into the output bundle
db.outputs.bundle.clear()
for name in payload.get_keys():
# Special 'path' entry gets copied to output attrib
if name == payload_path:
db.outputs.path = payload[name]
continue
as_str = payload[name]
arg_obj = pickle.loads(codecs.decode(as_str.encode(), "base64"))
attr_type, attr_value = arg_obj
new_attr = db.outputs.bundle.insert((attr_type, name))
new_attr.value = attr_value
get_interface().set_execution_enabled("outputs:execOut")
return True
# ----------------------------------------------------------------------------
@staticmethod
def release(node):
# Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing
# after the node has been released.
with suppress(og.OmniGraphError):
state = OgnOnCustomEventDatabase.per_node_internal_state(node)
if state.sub:
state.sub.unsubscribe()
state.sub = None
# ----------------------------------------------------------------------------
@staticmethod
def update_node_version(context: og.GraphContext, node: og.Node, old_version: int, new_version: int):
if old_version < new_version and old_version < 2:
# We added inputs:onlyPlayback default true - to maintain previous behavior we should set this to false
node.create_attribute(
"inputs:onlyPlayback",
og.Type(og.BaseDataType.BOOL),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
False,
)
return True
| 5,593 | Python | 34.18239 | 115 | 0.590917 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnTickN.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.
#
from dataclasses import dataclass
import omni.graph.core as og
# Set True to enable verbose debugging prints to console
DEBUG_PRINT = False
# ==============================================================================================================
@dataclass
class OgnTickNState:
count: int
# --------------------------------------------------------------------------------------------------------------
class OgnTickN:
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnTickNState(-1)
@staticmethod
def compute(db) -> bool:
def print_state(state_string: str):
print(f"{db.node.get_prim_path()} {state_string}")
count = db.internal_state.count
count += 1
if count == 0:
_ = DEBUG_PRINT and print_state("START")
finished, tick = og.ExecutionAttributeState.LATENT_PUSH, og.ExecutionAttributeState.DISABLED
else:
duration = db.inputs.duration
if duration < count:
# Finished
finished, tick = og.ExecutionAttributeState.LATENT_FINISH, og.ExecutionAttributeState.DISABLED
count = -1
_ = DEBUG_PRINT and print_state("FINISHED")
else:
# Still ticking
finished = og.ExecutionAttributeState.DISABLED
if (count % db.inputs.period) == 0: # noqa: S001
tick = og.ExecutionAttributeState.ENABLED
else:
tick = og.ExecutionAttributeState.DISABLED
_ = DEBUG_PRINT and print_state("TICK")
# Write outputs
db.outputs.finished = finished
db.outputs.tick = tick
db.internal_state.count = count
return True
| 2,263 | Python | 36.114754 | 112 | 0.572249 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnCountdown.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
# Set True to enable verbose debugging prints to console
DEBUG_PRINT = False
# ==============================================================================================================
class OgnCountdown:
@staticmethod
def initialize(_, node):
og.Controller.attribute("state:count", node).set(-1)
@staticmethod
def compute(db) -> bool:
def print_state(state_string: str):
print(f"{db.node.get_prim_path()} {state_string}")
count = db.state.count
duration = db.inputs.duration
count += 1
tick_value = 1
alpha = 0
if count == 0:
if DEBUG_PRINT:
print_state("START")
finished, tick = og.ExecutionAttributeState.LATENT_PUSH, og.ExecutionAttributeState.DISABLED
else:
if duration < count:
# Finished
finished, tick = og.ExecutionAttributeState.LATENT_FINISH, og.ExecutionAttributeState.DISABLED
tick_value = count - 1
alpha = 1.0
count = -1
if DEBUG_PRINT:
print_state("FINISHED")
else:
# Still ticking
finished = og.ExecutionAttributeState.DISABLED
tick_value = count
alpha = count / max(duration, 1)
period = db.inputs.period
if (period == 0) or ((count % db.inputs.period) == 0): # noqa: S001
tick = og.ExecutionAttributeState.ENABLED
else:
tick = og.ExecutionAttributeState.DISABLED
if DEBUG_PRINT:
print_state("TICK")
# Write outputs
db.outputs.finished = finished
db.outputs.tick = tick
db.state.count = count
db.outputs.alpha = alpha
db.outputs.tickValue = tick_value
return True
| 2,377 | Python | 34.492537 | 112 | 0.55995 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/nodes/OgnOnMessageBusEvent.py | """
This is the implementation of the OGN node defined in OgnOnMessageBusEvent.ogn
"""
from contextlib import suppress
from typing import Optional
import carb
import carb.dictionary
import carb.events
import numpy as np
import omni.graph.core as og
import omni.kit.app
from omni.graph.action import get_interface
from omni.graph.action.ogn.OgnOnMessageBusEventDatabase import OgnOnMessageBusEventDatabase
class OgnOnMessageBusEventInternalState:
"""Convenience class for maintaining per-node state information"""
def __init__(self):
# This subscription object controls the lifetime of our callback, it will be
# cleaned up automatically when our node is destroyed
self.sub: carb.events.ISubscription = None
# Set when the callback has triggered
self.is_set = False
# The last payload received
self.payload: carb.dictionary.Item = None
# The event_name we used to subscribe
self.sub_event_name = ""
# The node instance handle
self.node: og.Node = None
def on_event(self, custom_event: carb.events.IEvent):
if custom_event is None:
return
self.is_set = True
self.payload = custom_event.payload
# Tell the evaluator we need to be computed
if self.node.is_valid():
self.node.request_compute()
def first_time_subscribe(self, node: og.Node, event_name: str) -> bool:
"""Checked call to set up carb subscription
Args:
node: The node instance
event_name: The name of the carb event
Returns:
True if we subscribed, False if we are already subscribed
"""
if self.sub is not None and self.sub_event_name != event_name:
# event name changed since we last subscribed, unsubscribe
self.sub.unsubscribe()
self.sub = None
if self.sub is None:
# Add a subscription for the given event name. This is a pop subscription, so we expect a 1-frame
# lag between send and receive
reg_event_name = carb.events.type_from_string(event_name)
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self.sub = message_bus.create_subscription_to_pop_by_type(reg_event_name, self.on_event)
self.sub_event_name = event_name
self.node = node
return True
return False
def try_pop_event(self) -> Optional[carb.dictionary.Item]:
"""Pop the payload of the last event received, or None if there is no event to pop"""
if self.is_set:
self.is_set = False
payload = self.payload
self.payload = None
return payload
return None
# ======================================================================
class OgnOnMessageBusEvent:
"""
This node triggers when the specified message bus event is received
"""
@staticmethod
def internal_state():
"""Returns an object that will contain per-node state information"""
return OgnOnMessageBusEventInternalState()
@staticmethod
def compute(db) -> bool:
event_name = db.inputs.eventName
if not event_name:
return True
state = db.internal_state
if state.first_time_subscribe(db.node, event_name):
return True
# Drop events if we are disabled
if db.inputs.onlyPlayback and (not db.node.get_graph().get_default_graph_context().get_is_playing()):
state.try_pop_event()
return True
payload = state.try_pop_event()
if payload is None:
return True
node: og.Node = db.node
# Copy the event dict contents into dynamic attributes if they exist
for key in payload.get_keys():
attr_name = f"outputs:{key}"
if not node.get_attribute_exists(attr_name):
continue
attrib = node.get_attribute(attr_name)
if attrib:
value = payload[key]
og_type: og.Type = attrib.get_resolved_type()
is_array = og_type.array_depth > 0
is_tuple = og_type.tuple_count > 1
is_matrix = is_tuple and (
og_type.role in (og.AttributeRole.FRAME, og.AttributeRole.MATRIX, og.AttributeRole.TRANSFORM)
)
if is_array:
if is_matrix:
dim = 2 if og_type.tuple_count == 4 else 3 if og_type.tuple_count == 9 else 4
value = np.array(value).reshape((-1, dim, dim))
elif is_tuple:
dim = og_type.tuple_count
value = np.array(value).reshape((-1, dim))
elif is_matrix:
dim = 2 if og_type.tuple_count == 4 else 3 if og_type.tuple_count == 9 else 4
value = np.array(value).reshape((dim, dim))
try:
og.Controller.set(attrib, value)
except TypeError as exc:
db.log_error(f"Failed to copy payload data {key} to attribute {attr_name}:\n{exc}")
return False
get_interface().set_execution_enabled("outputs:execOut")
return True
# ----------------------------------------------------------------------------
@staticmethod
def release(node):
# Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing
# after the node has been released.
with suppress(og.OmniGraphError):
state = OgnOnMessageBusEventDatabase.per_node_internal_state(node)
if state.sub:
state.sub.unsubscribe()
state.sub = None
| 5,839 | Python | 36.435897 | 113 | 0.578352 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/tests/TestOgnCounter.py | import omni.kit.test
import omni.graph.core as og
import omni.graph.core.tests as ogts
import os
class TestOgn(ogts.OmniGraphTestCase):
async def test_generated(self):
test_data = [{'inputs': [['inputs:execIn', 1, False]], 'outputs': [['outputs:count', 1, False]], 'state_set': [['state:count', 0, False]]}, {'inputs': [['inputs:execIn', 1, False]], 'outputs': [['outputs:count', 2, False]], 'state_set': [['state:count', 1, False]]}, {'inputs': [['inputs:execIn', 0, False], ['inputs:reset', 1, False]], 'outputs': [['outputs:count', 0, False]], 'state_set': [['state:count', 1, False]], 'state_get': [['state:count', 0, False]]}]
test_node = None
test_graph = None
for i, test_run in enumerate(test_data):
inputs = test_run.get('inputs', [])
outputs = test_run.get('outputs', [])
state_set = test_run.get('state_set', [])
state_get = test_run.get('state_get', [])
setup = test_run.get('setup', None)
if setup is None or setup:
await omni.usd.get_context().new_stage_async()
test_graph = None
elif not setup:
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test")
if setup:
(test_graph, test_nodes, _, _) = og.Controller.edit("/TestGraph", setup)
self.assertTrue(test_nodes)
test_node = test_nodes[0]
elif setup is None:
if test_graph is None:
test_graph = og.Controller.create_graph("/TestGraph")
self.assertTrue(test_graph is not None and test_graph.is_valid())
test_node = og.Controller.create_node(
("TestNode_omni_graph_action_Counter", test_graph), "omni.graph.action.Counter"
)
self.assertTrue(test_graph is not None and test_graph.is_valid(), "Test graph invalid")
self.assertTrue(test_node is not None and test_node.is_valid(), "Test node invalid")
await og.Controller.evaluate(test_graph)
values_to_set = inputs + state_set
if values_to_set:
for attribute_name, attribute_value, _ in inputs + state_set:
og.Controller((attribute_name, test_node)).set(attribute_value)
await og.Controller.evaluate(test_graph)
for attribute_name, expected_value, _ in outputs + state_get:
attribute = og.Controller.attribute(attribute_name, test_node)
actual_output = og.Controller.get(attribute)
expected_type = None
if isinstance(expected_value, dict):
expected_type = expected_value["type"]
expected_value = expected_value["value"]
ogts.verify_values(expected_value, actual_output, f"omni.graph.action.Counter User test case #{i+1}: {attribute_name} attribute value error")
if expected_type:
tp = og.AttributeType.type_from_ogn_type_name(expected_type)
actual_type = attribute.get_resolved_type()
if tp != actual_type:
raise ValueError(f"omni.graph.action.Counter User tests - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}")
async def test_data_access(self):
from omni.graph.action.ogn.OgnCounterDatabase import OgnCounterDatabase
test_file_name = "OgnCounterTemplate.usda"
usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name)
if not os.path.exists(usd_path):
self.assertTrue(False, f"{usd_path} not found for loading test")
(result, error) = await ogts.load_test_file(usd_path)
self.assertTrue(result, f'{error} on {usd_path}')
test_node = og.Controller.node("/TestGraph/Template_omni_graph_action_Counter")
database = OgnCounterDatabase(test_node)
self.assertTrue(test_node.is_valid())
node_type_name = test_node.get_type_name()
self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1)
def _attr_error(attribute: og.Attribute, usd_test: bool) -> str:
test_type = "USD Load" if usd_test else "Database Access"
return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
self.assertTrue(test_node.get_attribute_exists("inputs:execIn"))
attribute = test_node.get_attribute("inputs:execIn")
db_value = database.inputs.execIn
self.assertTrue(test_node.get_attribute_exists("inputs:reset"))
attribute = test_node.get_attribute("inputs:reset")
db_value = database.inputs.reset
self.assertTrue(test_node.get_attribute_exists("outputs:count"))
attribute = test_node.get_attribute("outputs:count")
db_value = database.outputs.count
self.assertTrue(test_node.get_attribute_exists("outputs:execOut"))
attribute = test_node.get_attribute("outputs:execOut")
db_value = database.outputs.execOut
self.assertTrue(test_node.get_attribute_exists("state:count"))
attribute = test_node.get_attribute("state:count")
db_value = database.state.count
| 5,356 | Python | 55.389473 | 471 | 0.60717 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/_impl/templates/template_omni.graph.action.SwitchToken.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.
#
from pathlib import Path
from typing import List
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from omni.kit.window.property.templates import HORIZONTAL_SPACING
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.controller = og.Controller()
self.add_button: ui.Button = None
self.remove_button: ui.Button = None
self.node = self.controller.node(self.compute_node_widget._payload[-1])
def _get_input_attrib_names(self) -> List[str]:
"""Return the list of dynamic input attribs"""
all_attribs = self.node.get_attributes()
input_attrib_names = []
for attrib in all_attribs:
attrib_name = attrib.get_name()
name_prefix = attrib_name[:13]
if name_prefix == "inputs:branch":
input_attrib_names.append(attrib_name)
return input_attrib_names
def _get_max_suffix(self) -> int:
"""Return the maximum suffix of dynamic inputs or -1 if there are none"""
names = self._get_input_attrib_names()
if not names:
return -1
return max(int(name[13:]) for name in names)
def _on_click_add(self):
next_suffix = f"{self._get_max_suffix() + 1:02}"
new_attr = self.controller.create_attribute(
self.node,
f"inputs:branch{next_suffix}",
og.Type(og.BaseDataType.TOKEN, 1, 0, og.AttributeRole.NONE),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
)
new_attr.set_metadata(og.MetadataKeys.LITERAL_ONLY, "1")
self.controller.create_attribute(
self.node,
f"outputs:output{next_suffix}",
og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
self.compute_node_widget.rebuild_window()
self.remove_button.enabled = True
def _on_click_remove(self):
max_suffix = self._get_max_suffix()
if max_suffix < 0:
return
attrib_to_remove = self.node.get_attribute(f"outputs:output{max_suffix:02}")
self.controller.remove_attribute(attrib_to_remove)
attrib_to_remove = self.node.get_attribute(f"inputs:branch{max_suffix:02}")
self.controller.remove_attribute(attrib_to_remove)
self.compute_node_widget.rebuild_window()
self.remove_button.enabled = max_suffix > 0
def _controls_build_fn(self, *args):
max_suffix = self._get_max_suffix()
icons_path = Path(__file__).absolute().parent.parent.parent.parent.parent.parent.joinpath("icons")
with ui.HStack(height=0, spacing=HORIZONTAL_SPACING):
ui.Spacer()
self.add_button = ui.Button(
image_url=f"{icons_path.joinpath('add.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
clicked_fn=self._on_click_add,
tooltip_fn=lambda: ui.Label("Add New Branch"),
)
self.remove_button = ui.Button(
image_url=f"{icons_path.joinpath('remove.svg')}",
width=22,
height=22,
style={"Button": {"background_color": 0x1F2124}},
enabled=(max_suffix > 0),
clicked_fn=self._on_click_remove,
tooltip_fn=lambda: ui.Label("Remove Branch"),
)
def apply(self, props):
# Called by compute_node_widget to apply UI when selection changes
def find_prop(name):
return next((p for p in props if p.prop_name == name), None)
frame = CustomLayoutFrame(hide_extra=True)
names = self._get_input_attrib_names()
with frame:
with CustomLayoutGroup("Inputs"):
for name in names:
prop = find_prop(name)
CustomLayoutProperty(prop.prop_name)
CustomLayoutProperty(None, None, build_fn=self._controls_build_fn)
return frame.apply(props)
| 4,701 | Python | 40.610619 | 113 | 0.61689 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_nodes_02.py | """Action Graph Node Tests, Part 2"""
import random
from functools import partial
from typing import List
import carb
import carb.input
import numpy as np
import omni.client
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.tools.ogn as ogn
import omni.kit.app
import omni.kit.test
from carb.input import GamepadInput, KeyboardEventType, KeyboardInput
from omni.graph.core import ThreadsafetyTestUtils
# ======================================================================
class TestActionGraphNodes(ogts.OmniGraphTestCase):
"""Tests action graph node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
keys = og.Controller.Keys
E = og.ExecutionAttributeState.ENABLED
D = og.ExecutionAttributeState.DISABLED
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_ongamepadinput_node(self, test_instance_id: int = 0):
"""Test OnGamepadInput node"""
# Obtain an interface to a few gamepads and carb input provider.
input_provider = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, carb.input.acquire_input_provider()
)
gamepad_list = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
[
input_provider.create_gamepad("Gamepad 0", "0"),
input_provider.create_gamepad("Gamepad 1", "1"),
input_provider.create_gamepad("Gamepad 2", "2"),
],
)
# Connect the gamepads.
for gamepad in gamepad_list:
self.assertIsNotNone(gamepad)
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(input_provider.set_gamepad_connected, gamepad, True)
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_gamepad_input_node,), _, _) = og.Controller.edit(
graph_path, {self.keys.CREATE_NODES: ("OnGamepadInput", "omni.graph.action.OnGamepadInput")}
)
# Obtain necessary attributes.
in_onlyplayback_attr = on_gamepad_input_node.get_attribute("inputs:onlyPlayback")
in_gamepadid_attr = on_gamepad_input_node.get_attribute("inputs:gamepadId")
in_gamepad_element_attr = on_gamepad_input_node.get_attribute("inputs:gamepadElementIn")
out_pressed_attr = on_gamepad_input_node.get_attribute("outputs:pressed")
out_released_attr = on_gamepad_input_node.get_attribute("outputs:released")
out_ispressed_attr = on_gamepad_input_node.get_attribute("outputs:isPressed")
# Define a list of all possible gamepad inputs.
# FIXME: Note that the commented-out gamepad inputs produce errors in the OnGamepadInput's
# compute method because those specific inputs are not being considered. Maybe change to
# include these inputs and/or not spit out scary-looking error messages to users?
possible_gamepad_inputs = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
[
GamepadInput.A,
GamepadInput.B,
# GamepadInput.COUNT,
GamepadInput.DPAD_DOWN,
GamepadInput.DPAD_LEFT,
GamepadInput.DPAD_RIGHT,
GamepadInput.DPAD_UP,
GamepadInput.LEFT_SHOULDER,
GamepadInput.LEFT_STICK,
# GamepadInput.LEFT_STICK_DOWN,
# GamepadInput.LEFT_STICK_LEFT,
# GamepadInput.LEFT_STICK_RIGHT,
# GamepadInput.LEFT_STICK_UP,
# GamepadInput.LEFT_TRIGGER,
GamepadInput.MENU1,
GamepadInput.MENU2,
GamepadInput.RIGHT_SHOULDER,
GamepadInput.RIGHT_STICK,
# GamepadInput.RIGHT_STICK_DOWN,
# GamepadInput.RIGHT_STICK_LEFT,
# GamepadInput.RIGHT_STICK_RIGHT,
# GamepadInput.RIGHT_STICK_UP,
# GamepadInput.RIGHT_TRIGGER,
GamepadInput.X,
GamepadInput.Y,
],
)
# Define a dict of all valid inputs:gamepadElementIn tokens, along with
# their corresponding gamepad input. NOTE: The node's allowed token names
# are a bit different from the carb.input.GamepadInput values, might make
# sense to have them be the same?
allowed_gamepad_element_tokens = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
{
"Face Button Bottom": GamepadInput.A,
"Face Button Right": GamepadInput.B,
"Face Button Left": GamepadInput.X,
"Face Button Top": GamepadInput.Y,
"Left Shoulder": GamepadInput.LEFT_SHOULDER,
"Right Shoulder": GamepadInput.RIGHT_SHOULDER,
"Special Left": GamepadInput.MENU1,
"Special Right": GamepadInput.MENU2,
"Left Stick Button": GamepadInput.LEFT_STICK,
"Right Stick Button": GamepadInput.RIGHT_STICK,
"D-Pad Up": GamepadInput.DPAD_UP,
"D-Pad Right": GamepadInput.DPAD_RIGHT,
"D-Pad Down": GamepadInput.DPAD_DOWN,
"D-Pad Left": GamepadInput.DPAD_LEFT,
},
)
# Wrap main driver code in the following generator (in order to leverage
# the ThreadsafetyTestUtils.make_threading_test decorator). Note that for simplicity's sake the
# fake gamepad IDs correspond directly with their index in the gamepad_list.
def _test_ongamepadinput_node(quick_run: bool = True, num_inputs_to_test: int = 5):
_possible_gamepad_inputs = []
_allowed_gamepad_element_tokens = {}
# Codepath for accelerated test (won't take as long and still provide some code coverage).
if quick_run:
# Make sure that the input flags make sense.
if num_inputs_to_test < 1:
num_inputs_to_test = 1
elif num_inputs_to_test > 14:
num_inputs_to_test = 14
# Define two sets of random indices that'll determine the combination of inputs:gamepadElementIn
# tokens and emulated key inputs that we'll test for the current function call. Note that the
# inputs:gamepadElementIn tokens we choose and the emulated keys need not coincide, resulting
# in no output being generated by the OnGamepadInput node. Also note that because we want to
# use the same set of random indices in each test instance (so that all test graph instances
# run their tests/comparisons using the same combination of buttons/inputs), we add said indices
# (or more specifically an internal method that's used to create those indices, so that they're
# only created once for all test instances) to the overall threading cache.
def create_random_indices():
rand_indices_0 = set()
while len(rand_indices_0) < num_inputs_to_test:
rand_indices_0.add(random.randrange(len(possible_gamepad_inputs)))
rand_indices_1 = set()
while len(rand_indices_1) < num_inputs_to_test:
rand_indices_1.add(random.randrange(len(allowed_gamepad_element_tokens)))
return rand_indices_0, rand_indices_1
rand_indices_0, rand_indices_1 = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, create_random_indices()
)
# Convert the sets into lists so that their elements can be accessible by index.
rand_indices_0 = list(rand_indices_0)
rand_indices_1 = list(rand_indices_1)
# Create an abbreviated list of possible gamepad input elements.
for r_i in rand_indices_0:
_possible_gamepad_inputs.append(possible_gamepad_inputs[r_i])
# Create an abbreviated dict of allowed token-key input pairs.
temp_keys_list = list(allowed_gamepad_element_tokens)
temp_values_list = list(allowed_gamepad_element_tokens.values())
for r_i in rand_indices_1:
_allowed_gamepad_element_tokens[temp_keys_list[r_i]] = temp_values_list[r_i]
# Codepath for full test.
else:
_possible_gamepad_inputs = possible_gamepad_inputs
_allowed_gamepad_element_tokens = allowed_gamepad_element_tokens
# Set the gamepad id on each OnGamepadInput node. Note that multiple gamepad nodes are set to
# track the same gamepad to look for potential concurrency issues.
# for on_gamepad_input_node in on_gamepad_input_nodes:
in_gamepadid_attr.set(test_instance_id % len(gamepad_list)) # noqa S001
# Loop through each allowed gamepad element token, and set it on the OnGamepadInput nodes'
# corresponding input attributes.
for allowed_token, allowed_input in _allowed_gamepad_element_tokens.items():
in_gamepad_element_attr.set(allowed_token)
# Loop through each possible gamepad input, which we will emulate.
for emulated_input in _possible_gamepad_inputs:
# Loop through each possible input event type (0 == key is released, 1 == key is pressed)
for event_type in [1, 0]:
# Trigger each gamepad input.
input_provider.buffer_gamepad_event(
gamepad_list[test_instance_id % len(gamepad_list)], emulated_input, event_type # noqa S001
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# If the current emulated input matches the inputs:gamepadElementsIn attribute setting,
# check that the nodes reacted appropriately. Otherwise check that the nodes did not
# register the input.
if emulated_input == allowed_input:
if event_type == 1:
self.assertEqual(out_pressed_attr.get(), self.E)
self.assertEqual(out_released_attr.get(), self.D)
self.assertTrue(out_ispressed_attr.get())
elif event_type == 0:
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
else:
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertFalse(out_ispressed_attr.get())
# Test that the OnGamepadInput nodes works correctly when the onlyPlayback input is disabled.
in_onlyplayback_attr.set(False)
for _ in _test_ongamepadinput_node():
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# Test that the OnGamepadInput nodes works correctly when the onlyPlayback input is enabled.
in_onlyplayback_attr.set(True)
timeline = omni.timeline.get_timeline_interface()
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
timeline.play()
for _ in _test_ongamepadinput_node():
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
timeline.stop()
# Delete the gamepad node before destroying the gamepads themselves so that the nodes don't throw
# any warnings about having invalid gamepadIds.
og.Controller.delete_node(on_gamepad_input_node)
# Disconnect and destroy the gamepads.
for gamepad in gamepad_list:
ThreadsafetyTestUtils.single_evaluation_last_test_instance(
test_instance_id, partial(input_provider.set_gamepad_connected, gamepad, False)
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
ThreadsafetyTestUtils.single_evaluation_last_test_instance(
test_instance_id, partial(input_provider.destroy_gamepad, gamepad)
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# ----------------------------------------------------------------------
# The OnImpulseEvent node ALSO has a built-in test construct in its .ogn file located
# at ../../nodes/OgnOnImpulseEvent.ogn (relative to the source location of the currently-
# opened testing script).
@ThreadsafetyTestUtils.make_threading_test
def test_onimpulseevent_node(self, test_instance_id: int = 0):
"""Test OnImpulseEvent node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (_, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False)],
self.keys.CONNECT: (
"OnImpulse.outputs:execOut",
"Counter.inputs:execIn",
),
},
)
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
# After several updates, there should have been no compute calls.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(counter_controller.get(), 0)
# Change the OnImpulse node's state attribute. The node should now request compute.
og.Controller.edit(graph_path, {self.keys.SET_VALUES: (graph_path + "/OnImpulse.state:enableImpulse", True)})
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(counter_controller.get(), 1)
# More updates should not result in more computes.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(counter_controller.get(), 1)
# ----------------------------------------------------------------------
async def test_onkeyboardinput_node(self):
"""Test OnKeyboardInput node"""
app = omni.kit.app.get_app()
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, (on_keyboard_input_node,), _, _) = og.Controller.edit(
self.TEST_GRAPH_PATH, {self.keys.CREATE_NODES: ("OnKeyboardInput", "omni.graph.action.OnKeyboardInput")}
)
# Obtain necessary attributes.
in_keyin_attr = on_keyboard_input_node.get_attribute("inputs:keyIn")
in_playbackonly_attr = on_keyboard_input_node.get_attribute("inputs:onlyPlayback")
out_keyout_attr = on_keyboard_input_node.get_attribute("outputs:keyOut")
out_pressed_attr = on_keyboard_input_node.get_attribute("outputs:pressed")
out_released_attr = on_keyboard_input_node.get_attribute("outputs:released")
out_ispressed_attr = on_keyboard_input_node.get_attribute("outputs:isPressed")
# Obtain an interface to the keyboard and carb input provider.
keyboard = omni.appwindow.get_default_app_window().get_keyboard()
input_provider = carb.input.acquire_input_provider()
self.assertIsNotNone(keyboard)
# Define a list of all possible carb.input.KeyboardInput inputs. Note that not all possible
# keys are necessarily detectable by the OnKeyboardInput node (this list also includes the
# UNKNOWN key).
possible_key_inputs = [
KeyboardInput.A,
KeyboardInput.APOSTROPHE,
KeyboardInput.B,
KeyboardInput.BACKSLASH,
KeyboardInput.BACKSPACE,
KeyboardInput.C,
KeyboardInput.CAPS_LOCK,
KeyboardInput.COMMA,
KeyboardInput.D,
KeyboardInput.DEL,
KeyboardInput.DOWN,
KeyboardInput.E,
KeyboardInput.END,
KeyboardInput.ENTER,
KeyboardInput.EQUAL,
KeyboardInput.ESCAPE,
KeyboardInput.F,
KeyboardInput.F1,
KeyboardInput.F10,
KeyboardInput.F11,
KeyboardInput.F12,
KeyboardInput.F2,
KeyboardInput.F3,
KeyboardInput.F4,
KeyboardInput.F5,
KeyboardInput.F6,
KeyboardInput.F7,
KeyboardInput.F8,
KeyboardInput.F9,
KeyboardInput.G,
KeyboardInput.GRAVE_ACCENT,
KeyboardInput.H,
KeyboardInput.HOME,
KeyboardInput.I,
KeyboardInput.INSERT,
KeyboardInput.J,
KeyboardInput.K,
KeyboardInput.KEY_0,
KeyboardInput.KEY_1,
KeyboardInput.KEY_2,
KeyboardInput.KEY_3,
KeyboardInput.KEY_4,
KeyboardInput.KEY_5,
KeyboardInput.KEY_6,
KeyboardInput.KEY_7,
KeyboardInput.KEY_8,
KeyboardInput.KEY_9,
KeyboardInput.L,
KeyboardInput.LEFT,
KeyboardInput.LEFT_ALT,
KeyboardInput.LEFT_BRACKET,
KeyboardInput.LEFT_CONTROL,
KeyboardInput.LEFT_SHIFT,
KeyboardInput.LEFT_SUPER,
KeyboardInput.M,
KeyboardInput.MENU,
KeyboardInput.MINUS,
KeyboardInput.N,
KeyboardInput.NUMPAD_0,
KeyboardInput.NUMPAD_1,
KeyboardInput.NUMPAD_2,
KeyboardInput.NUMPAD_3,
KeyboardInput.NUMPAD_4,
KeyboardInput.NUMPAD_5,
KeyboardInput.NUMPAD_6,
KeyboardInput.NUMPAD_7,
KeyboardInput.NUMPAD_8,
KeyboardInput.NUMPAD_9,
KeyboardInput.NUMPAD_ADD,
KeyboardInput.NUMPAD_DEL,
KeyboardInput.NUMPAD_DIVIDE,
KeyboardInput.NUMPAD_ENTER,
KeyboardInput.NUMPAD_EQUAL,
KeyboardInput.NUMPAD_MULTIPLY,
KeyboardInput.NUMPAD_SUBTRACT,
KeyboardInput.NUM_LOCK,
KeyboardInput.O,
KeyboardInput.P,
KeyboardInput.PAGE_DOWN,
KeyboardInput.PAGE_UP,
KeyboardInput.PAUSE,
KeyboardInput.PERIOD,
KeyboardInput.PRINT_SCREEN,
KeyboardInput.Q,
KeyboardInput.R,
KeyboardInput.RIGHT,
KeyboardInput.RIGHT_ALT,
KeyboardInput.RIGHT_BRACKET,
KeyboardInput.RIGHT_CONTROL,
KeyboardInput.RIGHT_SHIFT,
KeyboardInput.RIGHT_SUPER,
KeyboardInput.S,
KeyboardInput.SCROLL_LOCK,
KeyboardInput.SEMICOLON,
KeyboardInput.SLASH,
KeyboardInput.SPACE,
KeyboardInput.T,
KeyboardInput.TAB,
KeyboardInput.U,
KeyboardInput.UNKNOWN,
KeyboardInput.UP,
KeyboardInput.V,
KeyboardInput.W,
KeyboardInput.X,
KeyboardInput.Y,
KeyboardInput.Z,
]
# Define a dictionary of token keys representing the possible inputs to the OnKeyboardInput node's
# "keyIn" attribute, and values representing the corresponding carb.input.KeyboardInput. Note that
# not all possible keys are necessarily allowed for detection by the OnKeyboardInput node (e.g.
# "Unknown")
allowed_token_key_inputs = {
"A": KeyboardInput.A,
"B": KeyboardInput.B,
"C": KeyboardInput.C,
"D": KeyboardInput.D,
"E": KeyboardInput.E,
"F": KeyboardInput.F,
"G": KeyboardInput.G,
"H": KeyboardInput.H,
"I": KeyboardInput.I,
"J": KeyboardInput.J,
"K": KeyboardInput.K,
"L": KeyboardInput.L,
"M": KeyboardInput.M,
"N": KeyboardInput.N,
"O": KeyboardInput.O,
"P": KeyboardInput.P,
"Q": KeyboardInput.Q,
"R": KeyboardInput.R,
"S": KeyboardInput.S,
"T": KeyboardInput.T,
"U": KeyboardInput.U,
"V": KeyboardInput.V,
"W": KeyboardInput.W,
"X": KeyboardInput.X,
"Y": KeyboardInput.Y,
"Z": KeyboardInput.Z,
"Apostrophe": KeyboardInput.APOSTROPHE,
"Backslash": KeyboardInput.BACKSLASH,
"Backspace": KeyboardInput.BACKSPACE,
"CapsLock": KeyboardInput.CAPS_LOCK,
"Comma": KeyboardInput.COMMA,
"Del": KeyboardInput.DEL,
"Down": KeyboardInput.DOWN,
"End": KeyboardInput.END,
"Enter": KeyboardInput.ENTER,
"Equal": KeyboardInput.EQUAL,
"Escape": KeyboardInput.ESCAPE,
"F1": KeyboardInput.F1,
"F10": KeyboardInput.F10,
"F11": KeyboardInput.F11,
"F12": KeyboardInput.F12,
"F2": KeyboardInput.F2,
"F3": KeyboardInput.F3,
"F4": KeyboardInput.F4,
"F5": KeyboardInput.F5,
"F6": KeyboardInput.F6,
"F7": KeyboardInput.F7,
"F8": KeyboardInput.F8,
"F9": KeyboardInput.F9,
"GraveAccent": KeyboardInput.GRAVE_ACCENT,
"Home": KeyboardInput.HOME,
"Insert": KeyboardInput.INSERT,
"Key0": KeyboardInput.KEY_0,
"Key1": KeyboardInput.KEY_1,
"Key2": KeyboardInput.KEY_2,
"Key3": KeyboardInput.KEY_3,
"Key4": KeyboardInput.KEY_4,
"Key5": KeyboardInput.KEY_5,
"Key6": KeyboardInput.KEY_6,
"Key7": KeyboardInput.KEY_7,
"Key8": KeyboardInput.KEY_8,
"Key9": KeyboardInput.KEY_9,
"Left": KeyboardInput.LEFT,
"LeftAlt": KeyboardInput.LEFT_ALT,
"LeftBracket": KeyboardInput.LEFT_BRACKET,
"LeftControl": KeyboardInput.LEFT_CONTROL,
"LeftShift": KeyboardInput.LEFT_SHIFT,
"LeftSuper": KeyboardInput.LEFT_SUPER,
"Menu": KeyboardInput.MENU,
"Minus": KeyboardInput.MINUS,
"NumLock": KeyboardInput.NUM_LOCK,
"Numpad0": KeyboardInput.NUMPAD_0,
"Numpad1": KeyboardInput.NUMPAD_1,
"Numpad2": KeyboardInput.NUMPAD_2,
"Numpad3": KeyboardInput.NUMPAD_3,
"Numpad4": KeyboardInput.NUMPAD_4,
"Numpad5": KeyboardInput.NUMPAD_5,
"Numpad6": KeyboardInput.NUMPAD_6,
"Numpad7": KeyboardInput.NUMPAD_7,
"Numpad8": KeyboardInput.NUMPAD_8,
"Numpad9": KeyboardInput.NUMPAD_9,
"NumpadAdd": KeyboardInput.NUMPAD_ADD,
"NumpadDel": KeyboardInput.NUMPAD_DEL,
"NumpadDivide": KeyboardInput.NUMPAD_DIVIDE,
"NumpadEnter": KeyboardInput.NUMPAD_ENTER,
"NumpadEqual": KeyboardInput.NUMPAD_EQUAL,
"NumpadMultiply": KeyboardInput.NUMPAD_MULTIPLY,
"NumpadSubtract": KeyboardInput.NUMPAD_SUBTRACT,
"PageDown": KeyboardInput.PAGE_DOWN,
"PageUp": KeyboardInput.PAGE_UP,
"Pause": KeyboardInput.PAUSE,
"Period": KeyboardInput.PERIOD,
"PrintScreen": KeyboardInput.PRINT_SCREEN,
"Right": KeyboardInput.RIGHT,
"RightAlt": KeyboardInput.RIGHT_ALT,
"RightBracket": KeyboardInput.RIGHT_BRACKET,
"RightControl": KeyboardInput.RIGHT_CONTROL,
"RightShift": KeyboardInput.RIGHT_SHIFT,
"RightSuper": KeyboardInput.RIGHT_SUPER,
"ScrollLock": KeyboardInput.SCROLL_LOCK,
"Semicolon": KeyboardInput.SEMICOLON,
"Slash": KeyboardInput.SLASH,
"Space": KeyboardInput.SPACE,
"Tab": KeyboardInput.TAB,
"Up": KeyboardInput.UP,
}
# Define a list of all possible keyboard event types (for convenience).
# We won't consider KEY_REPEAT and CHAR events here.
keyboard_event_types = [
KeyboardEventType.KEY_PRESS,
KeyboardEventType.KEY_RELEASE,
]
# Create a list of all possible keyboard modifier combinations. Don't need permutations
# since bitwise OR operator is commutative and associative.
modifier_combinations = [
0, # 0
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT, # 1
carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, # 2
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, # 3
carb.input.KEYBOARD_MODIFIER_FLAG_ALT, # 4
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_ALT, # 5
carb.input.KEYBOARD_MODIFIER_FLAG_ALT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, # 6
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT
| carb.input.KEYBOARD_MODIFIER_FLAG_ALT
| carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, # 7
]
# Create a list of tuples of lists of tuples and indices of all possible input key modifier
# settings on the OnKeyboardInput node.
node_input_modifier_attribute_combinations = [
([("inputs:shiftIn", False), ("inputs:altIn", False), ("inputs:ctrlIn", False)], 0),
([("inputs:shiftIn", True), ("inputs:altIn", False), ("inputs:ctrlIn", False)], 1),
([("inputs:shiftIn", False), ("inputs:altIn", False), ("inputs:ctrlIn", True)], 2),
([("inputs:shiftIn", True), ("inputs:altIn", False), ("inputs:ctrlIn", True)], 3),
([("inputs:shiftIn", False), ("inputs:altIn", True), ("inputs:ctrlIn", False)], 4),
([("inputs:shiftIn", True), ("inputs:altIn", True), ("inputs:ctrlIn", False)], 5),
([("inputs:shiftIn", False), ("inputs:altIn", True), ("inputs:ctrlIn", True)], 6),
([("inputs:shiftIn", True), ("inputs:altIn", True), ("inputs:ctrlIn", True)], 7),
]
# NOTE: Although the below test confirms that the OnKeyboardInput node works for all
# input combinations, it takes a while to run and times out the test (which is typically
# set to automatically crash after 300s). To account for this, each time we run the test
# a random subset of allowed input tokens and input keys are chosen with which
# we perform the test; this cuts down on computation time and still provides some
# decent code coverage.
# Wrap main test driver code in the following method. Note that in addition to testing
# whether specific buttons activate their corresponding code path, we also check that
# no other buttons can activate code paths they don't belong to. Check for all possible
# key + special modifier press/release permutations.
async def _test_onkeyboardinput_node(
quick_run: bool = True, num_keys_to_test: int = 10, num_modifiers_to_test: int = 1
):
_possible_key_inputs = []
_allowed_token_key_inputs = {}
_modifier_combinations = []
_node_input_modifier_attribute_combinations = []
# Codepath for accelerated test (won't time out and still provide some code coverage).
if quick_run:
# Make sure that the input flags make sense.
if num_keys_to_test < 1:
num_keys_to_test = 1
elif num_keys_to_test > 105:
num_keys_to_test = 105
if num_modifiers_to_test < 1:
num_modifiers_to_test = 1
elif num_modifiers_to_test > 8:
num_modifiers_to_test = 8
# Define three sets of random indices that'll determine the combination of inputs:keyIn
# tokens, emulated key inputs, and modifier values that we'll test for the current function call.
# Note that the inputs:keyIn tokens we choose and the emulated keys need not coincide, resulting
# in no output being generated by the OnKeyboardInput node.
rand_indices_0 = set()
while len(rand_indices_0) < num_keys_to_test:
rand_indices_0.add(random.randrange(len(possible_key_inputs)))
rand_indices_1 = set()
while len(rand_indices_1) < num_keys_to_test:
rand_indices_1.add(random.randrange(len(allowed_token_key_inputs)))
rand_indices_2 = set()
while len(rand_indices_2) < num_modifiers_to_test:
rand_indices_2.add(random.randrange(len(modifier_combinations)))
# Convert the sets into lists so that their elements can be accessible by index.
rand_indices_0 = list(rand_indices_0)
rand_indices_1 = list(rand_indices_1)
rand_indices_2 = list(rand_indices_2)
# Create an abbreviated list of possible key inputs.
for i in range(0, num_keys_to_test):
_possible_key_inputs.append(possible_key_inputs[rand_indices_0[i]])
# Create an abbreviated dict of allowed token-key input pairs.
temp_keys_list = list(allowed_token_key_inputs)
temp_values_list = list(allowed_token_key_inputs.values())
for i in range(0, num_keys_to_test):
_allowed_token_key_inputs[temp_keys_list[rand_indices_1[i]]] = temp_values_list[rand_indices_1[i]]
# Create abbreviated lists of modifier values and corresponing input attribute-value pairs.
for rand_idx in rand_indices_2:
_modifier_combinations.append(modifier_combinations[rand_idx])
_node_input_modifier_attribute_combinations.append(
node_input_modifier_attribute_combinations[rand_idx]
)
# Codepath for full test.
else:
_possible_key_inputs = possible_key_inputs
_allowed_token_key_inputs = allowed_token_key_inputs
_modifier_combinations = modifier_combinations
_node_input_modifier_attribute_combinations = node_input_modifier_attribute_combinations
# Loop through each possible inputs:keyIn token, and the set the inputs:keyIn attribute on the
# OnKeyboardInput node.
for token, _ in _allowed_token_key_inputs.items(): # noqa PLR1702
in_keyin_attr.set(token)
# Loop through each possible modification combination, and set the corresponding input attributes
# on the OnKeyboardInput node. Also store an index to represent the current modification state.
for node_input_modifier_attribute_tuple in _node_input_modifier_attribute_combinations:
node_input_modifier_attribute_list_in_tuple = node_input_modifier_attribute_tuple[0]
for input_attr_value_modifier_pair in node_input_modifier_attribute_list_in_tuple:
og.Controller.set(
og.Controller.attribute(input_attr_value_modifier_pair[0], on_keyboard_input_node),
input_attr_value_modifier_pair[1],
)
# Loop through each possible input key.
for key in _possible_key_inputs:
# Loop through all possible modification combinations.
for modifier in _modifier_combinations:
# Loop through each possible keyboard event type.
for event_type in keyboard_event_types:
# Trigger the current keyboard event.
input_provider.buffer_keyboard_key_event(keyboard, event_type, key, modifier)
await app.next_update_async()
# If the currently-pressed key matches the currently-set inputs:keyIn token's
# corresponding KeyboardInput + modifiers, check that the OnKeyboardInput node gets
# correctly activated.
if (
_allowed_token_key_inputs[token] == key # noqa PLR1733
and node_input_modifier_attribute_tuple[1] == modifier
):
# If the key has been pressed, check for the corresponding expected conditions.
if event_type == KeyboardEventType.KEY_PRESS:
self.assertEqual(out_keyout_attr.get(), token)
self.assertEqual(out_pressed_attr.get(), self.E)
self.assertEqual(out_released_attr.get(), self.D)
self.assertTrue(out_ispressed_attr.get())
# If the key has been released, check for the corresponding expected conditions.
elif event_type == KeyboardEventType.KEY_RELEASE:
self.assertEqual(out_keyout_attr.get(), token)
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
else:
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertFalse(out_ispressed_attr.get())
# Test that the OnKeyboardInput node works correctly when its onlyPlayback input is disabled.
in_playbackonly_attr.set(False)
await _test_onkeyboardinput_node()
# Test that the OnKeyboardInput node works correctly when its onlyPlayback input is enabled.
in_playbackonly_attr.set(True)
timeline = omni.timeline.get_timeline_interface()
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
timeline.play()
await _test_onkeyboardinput_node()
timeline.stop()
# ----------------------------------------------------------------------
# NOTE: Even though the OnLoaded node is threadsafe (its compute method is very simple),
# we don't adapt the below test to check for thread-safety conditions because it relies
# on other nodes (omni.graph.action.SendCustomEvent) which are NOT threadsafe.
async def test_onloaded_node(self):
"""Test OnLoaded node"""
def registered_event_name(event_name):
"""Returns the internal name used for the given custom event name"""
name = "omni.graph.action." + event_name
return carb.events.type_from_string(name)
events = []
def on_event(event):
events.append(event.payload["!path"])
reg_event_name = registered_event_name("foo")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_push_by_type(reg_event_name, on_event)
self.assertIsNotNone(sub)
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("OnLoaded", "omni.graph.action.OnLoaded"),
("Send1", "omni.graph.action.SendCustomEvent"),
("Send2", "omni.graph.action.SendCustomEvent"),
],
self.keys.CONNECT: [
("OnLoaded.outputs:execOut", "Send1.inputs:execIn"),
("OnTick.outputs:tick", "Send2.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Send1.inputs:eventName", "foo"),
("Send2.inputs:eventName", "foo"),
("Send1.inputs:path", "Loaded"),
("Send2.inputs:path", "Tick"),
],
},
)
# Evaluate once so that graph is in steady state.
await og.Controller.evaluate()
# Verify Loaded came before OnTick.
self.assertListEqual(events, ["Loaded", "Tick"])
# ----------------------------------------------------------------------
async def test_onmessagebusevent_node(self):
"""Test OnMessageBusEvent node"""
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, (on_custom_event, _), _, _,) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnCustomEvent", "omni.graph.action.OnMessageBusEvent"),
("Counter1", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnCustomEvent.outputs:execOut", "Counter1.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnCustomEvent.inputs:onlyPlayback", False),
("OnCustomEvent.inputs:eventName", "testEvent"),
],
},
)
# One compute for the first-time subscribe.
await omni.kit.app.get_app().next_update_async()
def get_all_supported_types() -> List[str]:
"""Helper to get all the types supported by the node"""
types = []
for attr_type in ogn.supported_attribute_type_names():
if (
attr_type in ("any", "transform", "bundle", "target", "execution")
or (attr_type[:9] == "transform")
or attr_type.startswith("objectId")
or attr_type.startswith("frame")
):
continue
types.append(attr_type)
return types
def assert_are_equal(expected_val, val):
"""Helper to assert two values are equal, sequence container type need not match"""
if isinstance(expected_val, (list, tuple, np.ndarray)):
for left, right in zip(expected_val, val):
return assert_are_equal(left, right)
if isinstance(val, np.ndarray):
self.assertListEqual(expected_val, list(val))
else:
self.assertEqual(expected_val, val)
return True
msg = carb.events.type_from_string("testEvent")
payload = {}
expected_vals = []
for sup_type in sorted(get_all_supported_types()):
payload = {}
name = sup_type.replace("[", "_").replace("]", "_")
manager = ogn.get_attribute_manager_type(sup_type)
# Create a dynamic output attribute on the node which matches the type of the test payload.
og_type = og.AttributeType.type_from_ogn_type_name(sup_type)
attrib = og.Controller.create_attribute(
on_custom_event, f"outputs:{name}", sup_type, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT
)
# Get a sample value in python format (nested tuples/lists).
sample_val = manager.sample_values()[0]
is_array = og_type.array_depth > 0
is_tuple = og_type.tuple_count > 1
is_matrix = is_tuple and (
og_type.role in (og.AttributeRole.FRAME, og.AttributeRole.MATRIX, og.AttributeRole.TRANSFORM)
)
payload_val = sample_val
# Convert the sample value into numpy format for use with OG API.
if is_array:
if is_matrix:
payload_val = np.array(sample_val).flatten().flatten().tolist()
elif is_tuple:
payload_val = np.array(sample_val).flatten().tolist()
elif is_matrix:
payload_val = np.array(sample_val).flatten().tolist()
payload[name] = payload_val
expected_vals.append((attrib, sample_val))
# Push the message to kit message bus.
omni.kit.app.get_app().get_message_bus_event_stream().push(msg, payload=payload)
# Wait for one kit update to allow the event-push mechanism to trigger the node callback.
await omni.kit.app.get_app().next_update_async()
# Verify the value.
out_val = og.Controller.get(attrib)
try:
assert_are_equal(out_val, out_val)
except AssertionError as exc:
raise AssertionError(f"{sample_val} != {out_val}") from exc
| 43,381 | Python | 49.561772 | 131 | 0.577234 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_evaluation2.py | """Action Graph Evaluation Tests Part 2"""
import json
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.usd
# ======================================================================
class TestActionGraphEvaluation2(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_retrigger_latent(self):
"""Test that latent nodes can be re-triggered"""
want_debug = False
e_state = og.ExecutionAttributeState
tick_count = 0
boop_count = 0
exec_in_latent_count = 0
max_ticks = 20
class CancelTickerPy:
"""Helper node type which does latent ticking and can be canceled, and has an independent counter "boop" """
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
nonlocal tick_count
nonlocal boop_count
nonlocal exec_in_latent_count
exec_in = node.get_attribute("inputs:execIn")
exec_in_val = og.Controller.get(exec_in)
cancel = node.get_attribute("inputs:cancel")
cancel_val = og.Controller.get(cancel)
boop = node.get_attribute("inputs:boop")
boop_val = og.Controller.get(boop)
want_debug and print(
f"### {tick_count} execIn={exec_in_val} cancel={cancel_val} boop={boop_val}"
) # noqa: expression-not-assigned
if cancel_val == e_state.ENABLED:
# Finish latent by cancel
og.Controller.set(node.get_attribute("outputs:canceled"), e_state.LATENT_FINISH)
self.assertEqual(exec_in_val, e_state.DISABLED)
self.assertEqual(boop_val, e_state.DISABLED)
tick_count = 0
return True
if exec_in_val == e_state.ENABLED:
self.assertEqual(cancel_val, e_state.DISABLED)
self.assertEqual(boop_val, e_state.DISABLED)
if tick_count > 0:
# execIn triggered while in latent - should not be possible
exec_in_latent_count += 1
else:
og.Controller.set(node.get_attribute("outputs:tick"), e_state.LATENT_PUSH)
return True
# we are ticking
self.assertEqual(cancel_val, e_state.DISABLED)
tick_count += 1
if tick_count < max_ticks:
og.Controller.set(node.get_attribute("outputs:tick"), e_state.ENABLED)
else:
# Finish latent naturally
og.Controller.set(node.get_attribute("outputs:execOut"), e_state.LATENT_FINISH)
tick_count = 0
if boop_val == e_state.ENABLED:
# We get here during latent ticking, if the boop input is enabled
self.assertEqual(exec_in_val, e_state.DISABLED)
self.assertEqual(cancel_val, e_state.DISABLED)
boop_count += 1
return True
@staticmethod
def get_node_type() -> str:
return "omni.graph.test.CancelTickerPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
node_type.add_input(
"inputs:execIn",
"execution",
True,
)
node_type.add_input(
"inputs:cancel",
"execution",
True,
)
node_type.add_input(
"inputs:boop",
"execution",
True,
)
node_type.add_output("outputs:tick", "execution", True)
node_type.add_output("outputs:canceled", "execution", True)
node_type.add_output("outputs:execOut", "execution", True)
return True
og.register_node_type(CancelTickerPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (ticker, start, _, cancel, boop, _, _, counter), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Ticker", "omni.graph.test.CancelTickerPy"),
("Start", "omni.graph.action.OnImpulseEvent"),
("Start2", "omni.graph.action.OnImpulseEvent"),
("Cancel", "omni.graph.action.OnImpulseEvent"),
("Boop", "omni.graph.action.OnImpulseEvent"),
("Once", "omni.graph.action.Once"),
("Once2", "omni.graph.action.Once"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("Start.outputs:execOut", "Ticker.inputs:execIn"),
("Start2.outputs:execOut", "Ticker.inputs:execIn"),
("Cancel.outputs:execOut", "Once.inputs:execIn"),
("Once.outputs:once", "Ticker.inputs:cancel"),
("Once.outputs:after", "Ticker.inputs:cancel"),
("Cancel.outputs:execOut", "Once2.inputs:execIn"),
("Boop.outputs:execOut", "Ticker.inputs:boop"),
("Once2.outputs:once", "Ticker.inputs:cancel"),
("Once2.outputs:after", "Ticker.inputs:cancel"),
("Ticker.outputs:tick", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("Start.inputs:onlyPlayback", False),
("Start2.inputs:onlyPlayback", False),
("Cancel.inputs:onlyPlayback", False),
("Boop.inputs:onlyPlayback", False),
],
},
)
# cancel, check nothing happens
og.Controller.set(controller.attribute("state:enableImpulse", cancel), True)
await controller.evaluate(graph)
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.DISABLED)
# start ticking
og.Controller.set(controller.attribute("state:enableImpulse", start), True)
await controller.evaluate(graph) # Starts latent state
await controller.evaluate(graph) # Tick 1
self.assertEqual(tick_count, 1)
# Verify the tick has started
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.ENABLED)
await controller.evaluate(graph) # Tick 2
self.assertEqual(tick_count, 2)
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.ENABLED)
await controller.evaluate(graph) # Tick 3
self.assertEqual(tick_count, 3)
# Boop - node keeps ticking
og.Controller.set(controller.attribute("state:enableImpulse", boop), True)
# Boop will trigger a compute, which increments boop + ticks AND the normal latent tick
await controller.evaluate(graph)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 5)
# Now check that the next tick can run WITHOUT inputs:boop being high
await controller.evaluate(graph)
self.assertEqual(boop_count, 1) # No change in boop count (OM-64856)
self.assertEqual(tick_count, 6)
# Now check that we can't re-trigger execIn
self.assertEqual(exec_in_latent_count, 0)
og.Controller.set(controller.attribute("state:enableImpulse", start), True)
# Start will not trigger any compute because the node is latent
await controller.evaluate(graph)
self.assertEqual(exec_in_latent_count, 0)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 7)
# Now check the normal tick proceeds as normal
await controller.evaluate(graph)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 8)
# Cancel
counter_attr = controller.attribute("outputs:count", counter)
count_0 = og.Controller.get(counter_attr)
og.Controller.set(controller.attribute("state:enableImpulse", cancel), True)
await controller.evaluate(graph) # latent finish
await controller.evaluate(graph) # no action
await controller.evaluate(graph) # no action
count_1 = og.Controller.get(counter_attr)
self.assertEqual(count_0 + 1, count_1)
# ----------------------------------------------------------------------
async def test_cycle_break(self):
"""test that an illegal cycle issues a warning"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (on_impulse, count_a, count_b), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("A", "omni.graph.action.Counter"),
("B", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "A.inputs:execIn"),
("A.outputs:execOut", "B.inputs:execIn"),
("B.outputs:execOut", "A.inputs:execIn"),
],
keys.SET_VALUES: [
("OnImpulse.state:enableImpulse", True),
("OnImpulse.inputs:onlyPlayback", False),
],
},
)
with ogts.ExpectedError():
await controller.evaluate(graph)
og.Controller.set(controller.attribute("state:enableImpulse", on_impulse), True)
with ogts.ExpectedError():
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", count_a)), 2)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", count_b)), 2)
# ----------------------------------------------------------------------
async def test_dep_sort_fan_out(self):
"""Test that dependency sort works when there is data fan-out"""
# +-------------+
# +-------->| |
# | | SwitchTokenA|
# | +--->+-------------+
# +----------+ |
# |OnImpulse + | +--------------+
# +----------+ | | SwitchTokenB |
# | +^-------------+
# +------+-+ +--------+ |
# | ConstA +--->AppendB +---+
# +--------+ +--------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, const_a, _, switch_a, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ConstA", "omni.graph.nodes.ConstantToken"),
("AppendB", "omni.graph.nodes.AppendString"),
("SwitchTokenA", "omni.graph.action.SwitchToken"),
("SwitchTokenB", "omni.graph.action.SwitchToken"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "SwitchTokenA.inputs:execIn"),
("ConstA.inputs:value", "SwitchTokenA.inputs:value"),
("ConstA.inputs:value", "AppendB.inputs:value"),
("AppendB.outputs:value", "SwitchTokenB.inputs:value"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("AppendB.inputs:suffix", {"value": "Foo", "type": "token"}),
],
},
)
await controller.evaluate(graph)
graph_state = og.OmniGraphInspector().as_json(graph, flags=["evaluation"])
graph_state_obj = json.loads(graph_state)
trace = graph_state_obj["Evaluator"]["LastNonEmptyEvaluation"]["Trace"]
# Verify the evaluation trace includes exactly what we expect
expected_trace = [
const_a.get_prim_path(),
switch_a.get_prim_path(),
]
self.assertListEqual(expected_trace, trace)
# ----------------------------------------------------------------------
async def test_exec_fan_out_shared_deps(self):
"""Test that dependency sort works when there is shared data in exec fan-out"""
# +---------+
# +---------->| Write1 |
# | +----^----+
# | |
# | +----------+
# | |
# +-----------+ | |
# | OnImpulse +-----+-----+----> +---------+
# +-----------+ | | | Write2 |
# | +----->+---------+
# | |
# | | +---------+
# +-----+----->| Write3 |
# | +---------+
# | ^
# +-------+ +---+----+---+
# | Const +----->| Inc |
# +-------+ +--------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Const", "omni.graph.nodes.ConstantDouble"),
("Inc", "omni.graph.nodes.Increment"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
("Write2", "omni.graph.nodes.WritePrimAttribute"),
("Write3", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: [
("/World/TestPrim1", {"val": ("double", 1.0)}),
("/World/TestPrim2", {"val": ("double", 2.0)}),
("/World/TestPrim3", {"val": ("double", 3.0)}),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Write1.inputs:execIn"),
("OnImpulse.outputs:execOut", "Write2.inputs:execIn"),
("OnImpulse.outputs:execOut", "Write3.inputs:execIn"),
("Const.inputs:value", "Inc.inputs:value"),
("Inc.outputs:result", "Write1.inputs:value"),
("Inc.outputs:result", "Write2.inputs:value"),
("Inc.outputs:result", "Write3.inputs:value"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("Const.inputs:value", 41.0),
("Inc.inputs:increment", 1.0),
("Write1.inputs:primPath", "/World/TestPrim1"),
("Write1.inputs:usePath", True),
("Write1.inputs:name", "val"),
("Write2.inputs:primPath", "/World/TestPrim2"),
("Write2.inputs:usePath", True),
("Write2.inputs:name", "val"),
("Write3.inputs:primPath", "/World/TestPrim3"),
("Write3.inputs:usePath", True),
("Write3.inputs:name", "val"),
],
},
)
await controller.evaluate(graph)
stage = omni.usd.get_context().get_stage()
for i in (1, 2, 3):
self.assertEqual(stage.GetAttributeAtPath(f"/World/TestPrim{i}.val").Get(), 42.0)
# ----------------------------------------------------------------------
async def test_exec_fan_out_shared_deps2(self):
"""Test that dependency sort works when there is shared data in exec fan-out"""
# ┌───────┐ ┌────────┐
# │Const1 ├───────────►│Append1 │
# └───────┘ │ ├──────────►┌───────────┐
# ┌──►└────────┘ │ WriteVar1 │
# ┌─────────────┐ │ ┌────►└───────────┘
# │ GraphTarget ├───┤ │
# └─────────────┘ └─►┌─────────┐ │ ┌───────────┐
# │ Append2 ├─────┼────►│ WriteVar2 │
# ┌────────┐ ┌─►└─────────┘ │ └───────────┘
# │ Const2 ├────────┘ │ ▲
# └────────┘ │ │
# │ │
# ┌──────────┐ │ │
# │ OnImpulse├────┴──────┘
# └──────────┘
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Const1", "omni.graph.nodes.ConstantToken"),
("Const2", "omni.graph.nodes.ConstantToken"),
("Append1", "omni.graph.nodes.AppendPath"),
("Append2", "omni.graph.nodes.AppendPath"),
("GraphTarget", "omni.graph.nodes.GraphTarget"),
("WriteVar1", "omni.graph.core.WriteVariable"),
("WriteVar2", "omni.graph.core.WriteVariable"),
],
keys.CREATE_VARIABLES: [
("path1", og.Type(og.BaseDataType.TOKEN)),
("path2", og.Type(og.BaseDataType.TOKEN)),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "WriteVar1.inputs:execIn"),
("OnImpulse.outputs:execOut", "WriteVar2.inputs:execIn"),
("GraphTarget.outputs:primPath", "Append1.inputs:path"),
("GraphTarget.outputs:primPath", "Append2.inputs:path"),
("Const1.inputs:value", "Append1.inputs:suffix"),
("Const2.inputs:value", "Append2.inputs:suffix"),
("Append1.outputs:path", "WriteVar1.inputs:value"),
("Append2.outputs:path", "WriteVar2.inputs:value"),
],
keys.SET_VALUES: [
("WriteVar1.inputs:variableName", "path1"),
("WriteVar2.inputs:variableName", "path2"),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("Const1.inputs:value", "A"),
("Const2.inputs:value", "B"),
],
},
)
await controller.evaluate(graph)
context = graph.get_default_graph_context()
graph_path = self.TEST_GRAPH_PATH
variable = graph.find_variable("path1")
self.assertEquals(variable.get(context), f"{graph_path}/A")
variable = graph.find_variable("path2")
self.assertEquals(variable.get(context), f"{graph_path}/B")
| 19,995 | Python | 45.719626 | 120 | 0.464766 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_nodes_03.py | """Action Graph Node Tests, Part 3"""
import random
from functools import partial
import carb.input
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.app
import omni.kit.test
import omni.usd
from carb.input import MouseEventType
from omni.graph.core import ThreadsafetyTestUtils
from pxr import Gf, OmniGraphSchemaTools, Sdf
# ======================================================================
class TestActionGraphNodes(ogts.OmniGraphTestCase):
"""Tests action graph node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
keys = og.Controller.Keys
E = og.ExecutionAttributeState.ENABLED
D = og.ExecutionAttributeState.DISABLED
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_onmouseinput_node(self, test_instance_id: int = 0):
"""Test OnMouseInput node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_mouse_input_node,), _, _) = og.Controller.edit(
graph_path,
{self.keys.CREATE_NODES: ("OnMouseInput", "omni.graph.action.OnMouseInput")},
)
# Obtain necessary attributes.
in_onlyplayback_attr = on_mouse_input_node.get_attribute("inputs:onlyPlayback")
in_mouse_element_attr = on_mouse_input_node.get_attribute("inputs:mouseElement")
out_pressed_attr = on_mouse_input_node.get_attribute("outputs:pressed")
out_released_attr = on_mouse_input_node.get_attribute("outputs:released")
out_valuechanged_attr = on_mouse_input_node.get_attribute("outputs:valueChanged")
out_ispressed_attr = on_mouse_input_node.get_attribute("outputs:isPressed")
out_value_attr = on_mouse_input_node.get_attribute("outputs:value")
# Obtain an interface to the mouse and carb input provider.
mouse = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, omni.appwindow.get_default_app_window().get_mouse()
)
input_provider = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, carb.input.acquire_input_provider()
)
# Define a list of tokens representing the possible inputs to the OnMouseInput node's "mouseElement" attribute.
mouse_tokens = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
["Left Button", "Middle Button", "Right Button", "Normalized Move", "Pixel Move", "Scroll"],
)
# Define a list of all possible mouse event types (for convenience).
mouse_event_types = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
[
MouseEventType.LEFT_BUTTON_DOWN,
MouseEventType.LEFT_BUTTON_UP,
MouseEventType.MIDDLE_BUTTON_DOWN,
MouseEventType.MIDDLE_BUTTON_UP,
MouseEventType.RIGHT_BUTTON_DOWN,
MouseEventType.RIGHT_BUTTON_UP,
MouseEventType.MOVE,
MouseEventType.SCROLL,
],
)
# Define some imaginary window dimensions for testing purposes.
window_width = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, 1440)
window_height = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, 720)
# Wrap main test driver code in the following generator (to leverage the
# ThreadsafetyTestUtils.make_threading_test decorator to its fullest). Note that
# in addition to testing whether specific buttons activate their corresponding code
# path, we also check that no other buttons can activate code paths they don't belong
# to (e.g. that pressing the left mouse button doesn't get registered as a button
# press when "inputs:mouseElement" is set to "Right Button").
def _test_onmouseinput_node():
# Loop through each possible "inputs.mouseElement" token, and set the input attribute
# on the OnMouseInput nodes in each graph.
for token in mouse_tokens:
in_mouse_element_attr.set(token)
# Loop through each possible mouse event type.
for event_type in mouse_event_types:
# Generate a new random test position for the mouse cursor. Note that we
# add it to the threading cache so that each test graph instance runs
# its tests/comparisons against the same randomly-generated position.
pos = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, (random.randint(0, window_width), random.randint(0, window_height))
)
# Trigger the current mouse event.
input_provider.buffer_mouse_event(
mouse, event_type, (pos[0] / window_width, pos[1] / window_height), 0, pos
)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# Test left/middle/right mouse button pressed functionality. Only left/middle/right
# mouse button presses should activate this codepath.
if (
(event_type == MouseEventType.LEFT_BUTTON_DOWN and token == "Left Button")
or (event_type == MouseEventType.MIDDLE_BUTTON_DOWN and token == "Middle Button")
or (event_type == MouseEventType.RIGHT_BUTTON_DOWN and token == "Right Button")
):
self.assertEqual(out_pressed_attr.get(), self.E)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.D)
self.assertTrue(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertEqual(out_value_attr.get()[0], 0)
self.assertEqual(out_value_attr.get()[1], 0)
# Test left/middle/right mouse button released functionality. Only left/middle/right mouse
# button releases should activate this codepath.
elif (
(event_type == MouseEventType.LEFT_BUTTON_UP and token == "Left Button")
or (event_type == MouseEventType.MIDDLE_BUTTON_UP and token == "Middle Button")
or (event_type == MouseEventType.RIGHT_BUTTON_UP and token == "Right Button")
):
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.E)
self.assertEqual(out_valuechanged_attr.get(), self.D)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertEqual(out_value_attr.get()[0], 0)
self.assertEqual(out_value_attr.get()[1], 0)
# Test mouse movement functionality with the "Normalized Move" option enabled. Only mouse movement
# should activate this codepath.
elif event_type == MouseEventType.MOVE and token == "Normalized Move":
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertAlmostEqual(out_value_attr.get()[0], pos[0] / window_width)
self.assertAlmostEqual(out_value_attr.get()[1], pos[1] / window_height)
# Test mouse movement functionality with the "Pixel Move" option enabled. Only mouse movement
# should activate this codepath.
elif event_type == MouseEventType.MOVE and token == "Pixel Move":
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertEqual(out_value_attr.get()[0], pos[0])
self.assertEqual(out_value_attr.get()[1], pos[1])
# Test mouse scrolling functionality with the "Scroll" option enabled. Only mouse scrolling
# should activate this codepath.
elif event_type == MouseEventType.SCROLL and token == "Scroll":
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.E)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertAlmostEqual(out_value_attr.get()[0], pos[0] / window_width)
self.assertAlmostEqual(out_value_attr.get()[1], pos[1] / window_height)
# Non-activated codepath.
else:
self.assertEqual(out_pressed_attr.get(), self.D)
self.assertEqual(out_released_attr.get(), self.D)
self.assertEqual(out_valuechanged_attr.get(), self.D)
self.assertFalse(out_ispressed_attr.get())
self.assertEqual(len(out_value_attr.get()), 2)
self.assertEqual(out_value_attr.get()[0], 0)
self.assertEqual(out_value_attr.get()[1], 0)
# Test that the OnMouseInput node works correctly when its onlyPlayback input is disabled.
in_onlyplayback_attr.set(False)
for _ in _test_onmouseinput_node():
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
# Test that the OnMouseInput node works correctly when its onlyPlayback input is enabled.
in_onlyplayback_attr.set(True)
timeline = omni.timeline.get_timeline_interface()
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
timeline.play()
for _ in _test_onmouseinput_node():
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
timeline.stop()
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_onobjectchange_node(self, test_instance_id: int = 0):
"""Test OnObjectChange node"""
usd_context = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, omni.usd.get_context())
stage = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, usd_context.get_stage())
cube = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, ogts.create_cube(stage, "Cube", (0.6, 0.4, 0.0))
)
attr_position = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, cube.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False)
)
attr_rotation = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, cube.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Float3, False)
)
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(graph, (on_object_change_node, flip_flop_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
(graph_path + "/OnObjectChange", "omni.graph.action.OnObjectChange"),
(graph_path + "/FlipFlop", "omni.graph.action.FlipFlop"),
],
self.keys.SET_VALUES: [
(graph_path + "/OnObjectChange.inputs:onlyPlayback", False),
(graph_path + "/OnObjectChange.inputs:prim", attr_position.GetPrimPath()),
(graph_path + "/OnObjectChange.inputs:name", attr_position.GetName()),
],
self.keys.CONNECT: (
graph_path + "/OnObjectChange.outputs:changed",
graph_path + "/FlipFlop.inputs:execIn",
),
},
)
outa = og.Controller.attribute("outputs:a", flip_flop_node)
# Check the current FlipFlop state, and that it isn't changing until we move the cube.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
ff_a_state_1 = og.Controller.get(outa)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(outa), ff_a_state_1)
# Try changing a different (non-translate) attribute - should not trigger.
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(attr_rotation.Set, Gf.Vec3f(180.0, 0.0, 0.0))
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(outa), ff_a_state_1)
# Now change the translate attribute - should trigger.
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(attr_position.Set, Gf.Vec3f(1.0, 0.0, 0.0))
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
ff_a_state_2 = og.Controller.get(outa)
self.assertEqual(ff_a_state_2, 1 if not ff_a_state_1 else 0)
property_path = og.Controller.get(og.Controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_position.GetName())
# Look at the prim itself.
og.Controller.edit(
graph,
{self.keys.SET_VALUES: (graph_path + "/OnObjectChange.inputs:name", "")},
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Now change the rotate attribute - should trigger.
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(attr_rotation.Set, Gf.Vec3f(245.0, 0.0, 0.0))
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
ff_a_state_1 = og.Controller.get(outa)
self.assertEqual(ff_a_state_1, 1 if not ff_a_state_2 else 0)
property_path = og.Controller.get(og.Controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_rotation.GetName())
# Now use the path input instead of the target. Do this for all OnObjectChange nodes!
og.Controller.edit(
graph,
{
self.keys.SET_VALUES: [
(graph_path + "/OnObjectChange.inputs:path", cube.GetPath().pathString),
(graph_path + "/OnObjectChange.inputs:prim", []),
]
},
)
# Compute once to set up the inputs.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Change the rotate attribute - should trigger.
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(attr_rotation.Set, Gf.Vec3f(0.0, 0.0, 0.0))
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
ff_a_state_2 = og.Controller.get(outa)
self.assertEqual(ff_a_state_2, 1 if not ff_a_state_1 else 0)
property_path = og.Controller.get(og.Controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_rotation.GetName())
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_onplaybacktick_node(self, test_instance_id: int = 0):
"""Test OnPlaybackTick node"""
timeline = omni.timeline.get_timeline_interface()
# The stage's default stage is probably 60, set to 30 for this specific case
stage = omni.usd.get_context().get_stage()
fps = 30.0
stage.SetTimeCodesPerSecond(fps)
stage.SetStartTimeCode(1.0)
stage.SetEndTimeCode(10.0)
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_p_tick_node, _), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnPTick", "omni.graph.action.OnPlaybackTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
self.keys.CONNECT: [
("OnPTick.outputs:tick", "FlipFlop.inputs:execIn"),
],
},
)
# Obtain necessary attributes.
tick_time_attr = on_p_tick_node.get_attribute("outputs:time")
tick_frame_attr = on_p_tick_node.get_attribute("outputs:frame")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Check that the OnPlaybackTick node doesn't trigger when playback is not active.
self.assertEqual(tick_time_attr.get(), 0)
self.assertEqual(tick_frame_attr.get(), 0)
# Check that the OnPlaybackTick node does trigger when playback is active, and the values are correct.
timeline.play()
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertAlmostEqual(tick_time_attr.get(), timeline.get_current_time(), places=5)
self.assertAlmostEqual(tick_frame_attr.get(), tick_time_attr.get() * fps, places=5)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_ontick_node(self, test_instance_id: int = 0):
"""Test OnTick node"""
timeline = omni.timeline.get_timeline_interface()
# The stage's default stage is probably 60, set to 30 for this specific case
stage = omni.usd.get_context().get_stage()
fps = 30.0
stage.SetTimeCodesPerSecond(fps)
stage.SetStartTimeCode(1.0)
stage.SetEndTimeCode(10.0)
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_tick_node, _), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "FlipFlop.inputs:execIn"),
],
self.keys.SET_VALUES: ("OnTick.inputs:onlyPlayback", True),
},
)
# Obtain necessary attributes.
ontick_time_attr = on_tick_node.get_attribute("outputs:time")
ontick_frame_attr = on_tick_node.get_attribute("outputs:frame")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Check that the OnTick node doesn't trigger when playback is not active.
self.assertEqual(ontick_time_attr.get(), 0)
self.assertEqual(ontick_frame_attr.get(), 0)
# Check that the OnTick node does trigger when playback is active, and the values are correct.
timeline.play()
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertAlmostEqual(ontick_time_attr.get(), timeline.get_current_time(), places=5)
self.assertAlmostEqual(ontick_frame_attr.get(), ontick_time_attr.get() * fps, places=5)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_onvariablechange_node(self, test_instance_id: int = 0):
"""Test OnVariableChange node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(graph, (on_variable_change_node, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnVariableChange", "omni.graph.action.OnVariableChange"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [
("OnVariableChange.inputs:onlyPlayback", False),
],
self.keys.CONNECT: [("OnVariableChange.outputs:changed", "Counter.inputs:execIn")],
},
)
graph_context = graph.get_default_graph_context()
# Create a new float variable on each graph, and set the OnVariableChange nodes to track this single variable.
var_name = "myVar" + str(test_instance_id)
my_var = og.Controller.create_variable(graph, var_name, "FLOAT")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
og.Controller.set(og.Controller.attribute("inputs:variableName", on_variable_change_node), var_name)
# Check that the execution output is still set to zero.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.D)
# Change the variable's value, check that the execution reads true now.
my_var.set(graph_context, 5.2)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.E)
# Evaluate a second time to check that the execution gets set back to zero.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.D)
# Make sure that the output execution remains off if we try setting the variable
# to the same previous value.
my_var.set(graph_context, 5.2)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.D)
# Check that setting the inputs:variableName to a nonexistant variable results in the output
# execution pin remaining zero.
og.Controller.set(og.Controller.attribute("inputs:variableName", on_variable_change_node), "nonexistant_name")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:changed", on_variable_change_node)), self.D)
# Set the onlyPlayback flag to true, run a similar set of tests to ensure that this setting
# still works with the node. Note that a Counter node is used here to detect the variable change
# because it's trickier to check against outputs:changed directly (harder to time everything with
# all of the async stuff + when the timeline is running).
og.Controller.set(og.Controller.attribute("inputs:variableName", on_variable_change_node), var_name)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
og.Controller.set(og.Controller.attribute("inputs:onlyPlayback", on_variable_change_node), True)
timeline = ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id, omni.timeline.get_timeline_interface()
)
ThreadsafetyTestUtils.single_evaluation_first_test_instance(
test_instance_id, partial(timeline.set_target_framerate, timeline.get_time_codes_per_seconds())
)
ThreadsafetyTestUtils.single_evaluation_first_test_instance(test_instance_id, partial(timeline.play))
my_var.set(graph_context, 4.6)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
my_var.set(graph_context, 4.6)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
my_var.set(graph_context, 4.6)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
og.Controller.set(og.Controller.attribute("inputs:variableName", on_variable_change_node), "nonexistant_name_2")
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
ThreadsafetyTestUtils.single_evaluation_last_test_instance(test_instance_id, partial(timeline.stop))
# ----------------------------------------------------------------------
async def _run_test_variable_of_type(self, graph_id, var_type: og.Type, initial_value, changed_value):
"""Helper method to run a variable test with different variable types"""
graph_path = self.TEST_GRAPH_PATH + graph_id
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(graph, (_, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnVariableChange", "omni.graph.action.OnVariableChange"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [
("OnVariableChange.inputs:onlyPlayback", False),
("OnVariableChange.inputs:variableName", "var"),
],
self.keys.CONNECT: [("OnVariableChange.outputs:changed", "Counter.inputs:execIn")],
self.keys.CREATE_VARIABLES: [
("var", var_type),
],
},
)
# test that nothing triggered on the initial run
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 0)
var = graph.find_variable("var")
# set the initial value, expected a trigger
var.set(graph.get_context(), initial_value)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 1)
ogts.verify_values(var.get(graph.get_context()), initial_value, "expected initial value to be set")
# change the value of the variable and makes sure the OnVariableChange triggers
var.set(graph.get_context(), changed_value)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(og.Controller.attribute("outputs:count", counter_node)), 2)
ogts.verify_values(var.get(graph.get_context()), changed_value, "expeected changed value to be set")
# ----------------------------------------------------------------------
async def test_onvariablechanged_by_type(self):
"""Tests OnVariableChange for different types of variables, including strings and arrays"""
await self._run_test_variable_of_type("_int", og.Type(og.BaseDataType.INT), 1, 2)
await self._run_test_variable_of_type("_int_array", og.Type(og.BaseDataType.INT, 1, 1), [1, 2, 3], [3, 4, 5])
await self._run_test_variable_of_type(
"_int_array_size", og.Type(og.BaseDataType.INT, 1, 1), [1, 2, 3, 4, 5], [1, 2, 3]
)
await self._run_test_variable_of_type("_tuple", og.Type(og.BaseDataType.INT, 3, 0), (1, 2, 3), (3, 4, 5))
await self._run_test_variable_of_type(
"_string", og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.TEXT), "init", "changed"
)
await self._run_test_variable_of_type(
"_tuple_array", og.Type(og.BaseDataType.INT, 3, 1), [(1, 2, 3), (4, 5, 6)], [(3, 4, 5)]
)
# ----------------------------------------------------------------------
async def test_onvariablechange_node_instances(self):
"""Tests that OnVariableChange node works with instancing"""
controller = og.Controller()
keys = og.Controller.Keys
int_range = range(1, 100)
stage = omni.usd.get_context().get_stage()
for i in int_range:
prim_name = f"/World/Prim_{i}"
prim = stage.DefinePrim(prim_name)
OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, self.TEST_GRAPH_PATH)
prim.CreateAttribute("graph:variable:int_var", Sdf.ValueTypeNames.Int).Set(0)
prim.CreateAttribute("graph_output", Sdf.ValueTypeNames.Int).Set(i)
(_, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnVariableChange", "omni.graph.action.OnVariableChange"),
("GraphTarget", "omni.graph.nodes.GraphTarget"),
("ReadPrimAttr", "omni.graph.nodes.ReadPrimAttribute"),
("WritePrimAttr", "omni.graph.nodes.WritePrimAttribute"),
("Add", "omni.graph.nodes.Add"),
("ConstantInt", "omni.graph.nodes.ConstantInt"),
],
keys.CONNECT: [
("OnVariableChange.outputs:changed", "WritePrimAttr.inputs:execIn"),
("GraphTarget.outputs:primPath", "WritePrimAttr.inputs:primPath"),
("GraphTarget.outputs:primPath", "ReadPrimAttr.inputs:primPath"),
("ReadPrimAttr.outputs:value", "Add.inputs:a"),
("ConstantInt.inputs:value", "Add.inputs:b"),
("Add.outputs:sum", "WritePrimAttr.inputs:value"),
],
keys.CREATE_VARIABLES: [("int_var", og.Type(og.BaseDataType.INT))],
keys.SET_VALUES: [
("OnVariableChange.inputs:onlyPlayback", False),
("OnVariableChange.inputs:variableName", "int_var"),
("WritePrimAttr.inputs:usePath", True),
("WritePrimAttr.inputs:name", "graph_output"),
("ReadPrimAttr.inputs:usePath", True),
("ReadPrimAttr.inputs:name", "graph_output"),
("ConstantInt.inputs:value", 1),
],
},
)
await omni.kit.app.get_app().next_update_async()
# Setting value of int_var from 0 to 1.
for i in int_range:
prim_path = f"/World/Prim_{i}"
prev_val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get()
stage.GetPrimAtPath(prim_path).GetAttribute("graph:variable:int_var").Set(1)
await omni.kit.app.get_app().next_update_async()
val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get()
self.assertEqual(val, prev_val + 1, msg=f"{prim_path}")
# Setting value of int_var from 1 to 1.
for i in int_range:
prim_path = f"/World/Prim_{i}"
prev_val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get()
stage.GetPrimAtPath(prim_path).GetAttribute("graph:variable:int_var").Set(1)
await omni.kit.app.get_app().next_update_async()
val = stage.GetPrimAtPath(prim_path).GetAttribute("graph_output").Get()
self.assertEqual(val, prev_val + 1, msg=f"{prim_path}")
# ----------------------------------------------------------------------
# The SendCustomEvent node is tested in tandem with the OnCustomEvent node above; it is also used
# extensively in other tests, so we skip adding another dedicated test here.
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_sequence_node(self, test_instance_id: int = 0):
"""Test Sequence node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (_, sequence_node, counter0_node, counter1_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Sequence", "omni.graph.action.Sequence"),
("Counter0", "omni.graph.action.Counter"),
("Counter1", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Sequence.inputs:execIn"),
("Sequence.outputs:a", "Counter0.inputs:execIn"),
("Sequence.outputs:b", "Counter1.inputs:execIn"),
],
},
)
# Obtain necessary attributes.
in_exec_attr_0 = counter0_node.get_attribute("inputs:execIn")
out_cnt_attr_0 = counter0_node.get_attribute("outputs:count")
out_cnt_attr_1 = counter1_node.get_attribute("outputs:count")
out_a_attr = sequence_node.get_attribute("outputs:a")
out_b_attr = sequence_node.get_attribute("outputs:b")
# Check that the Sequence node correctly executes through its outputs when input
# execution is enabled via the OnTick node. This is done by checking whether
# each counter has been incremented by 1, and if the last output pin on the Sequence
# nodes remain enabled (regardless of the fact that they're not connected downstream).
# Similar test to the Multisequence node.
self.assertEqual(out_cnt_attr_0.get(), 0)
self.assertEqual(out_cnt_attr_1.get(), 0)
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 1)
self.assertEqual(out_cnt_attr_1.get(), 1)
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.E)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 2)
self.assertEqual(out_cnt_attr_1.get(), 2)
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.E)
# Connect output pin b to the Counter1 node. This is because both pins a and b share
# the same terminal input attribute, so both must have the same value. Since
# b is the last attribute and must be set to 1 (due to logic inside this node's
# compute method), output a must also take on this value.
og.Controller.connect(out_b_attr, in_exec_attr_0)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 4)
self.assertEqual(out_cnt_attr_1.get(), 3)
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.E)
# ----------------------------------------------------------------------
async def test_setprimactive_node(self):
await self._setprimactive_node(False)
# ----------------------------------------------------------------------
async def test_setprimactive_node_with_target(self):
await self._setprimactive_node(True)
# ----------------------------------------------------------------------
async def _setprimactive_node(self, use_target_inputs):
"""
Test SetPrimActive node. If use_target_inputs is true, will use the prim target inputs rather than prim path
"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
(_, (_, set_prim_active_node), _, _,) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("SetPrimActive", "omni.graph.action.SetPrimActive"),
],
self.keys.CREATE_PRIMS: [
("/TestPrim", {}),
],
self.keys.CONNECT: [("OnTick.outputs:tick", "SetPrimActive.inputs:execIn")],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("SetPrimActive.inputs:prim", "/TestPrim"),
("SetPrimActive.inputs:active", True),
],
},
)
await og.Controller.evaluate()
if use_target_inputs:
rel = stage.GetRelationshipAtPath(f"{self.TEST_GRAPH_PATH}/SetPrimActive.inputs:primTarget")
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target="/TestPrim")
await og.Controller.evaluate()
# Check that the prim we're pointing to remains active when we trigger
# graph evaluation.
prim = stage.GetPrimAtPath("/TestPrim")
self.assertTrue(prim.IsActive())
await og.Controller.evaluate()
self.assertTrue(prim.IsActive())
# Now set the prim to be inactive.
og.Controller.set(og.Controller.attribute("inputs:active", set_prim_active_node), False)
await og.Controller.evaluate()
self.assertFalse(prim.IsActive())
await og.Controller.evaluate()
self.assertFalse(prim.IsActive())
# Again set to be active, make sure that the prim gets reactivated.
og.Controller.set(og.Controller.attribute("inputs:active", set_prim_active_node), True)
await og.Controller.evaluate()
self.assertTrue(prim.IsActive())
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_switchtoken_node(self, test_instance_id: int = 0):
"""Test SwitchToken node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (_, switch_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Switch", "omni.graph.action.SwitchToken"),
],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Switch.inputs:execIn"),
],
},
)
# Test that an execution connection is correctly triggering the downstream nodes once per evaluation.
def add_input(index: int):
og.Controller.create_attribute(
switch_node,
f"inputs:branch{index:02}",
"token",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
)
og.Controller.create_attribute(
switch_node,
f"outputs:output{index:02}",
"execution",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
og.Controller.set(og.Controller.attribute(f"inputs:branch{index:02}", switch_node), f"{index:02}")
for index in range(5):
add_input(index)
for index in range(5):
og.Controller.set(og.Controller.attribute("inputs:value", switch_node), f"{index:02}")
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
for index2 in range(5):
expected_val = (
og.ExecutionAttributeState.DISABLED if index2 != index else og.ExecutionAttributeState.ENABLED
)
self.assertEqual(
og.Controller.get(og.Controller.attribute(f"outputs:output{index2:02}", switch_node)),
expected_val,
)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_syncgate_node(self, test_instance_id: int = 0):
"""Test SyncGate node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(
_,
(on_impulse0_node, on_impulse1_node, on_impulse2_node, on_impulse3_node, sync_gate_node, counter_node),
_,
_,
) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnImpulse0", "omni.graph.action.OnImpulseEvent"),
("OnImpulse1", "omni.graph.action.OnImpulseEvent"),
("OnImpulse2", "omni.graph.action.OnImpulseEvent"),
("OnImpulse3", "omni.graph.action.OnImpulseEvent"),
("SyncGate", "omni.graph.action.SyncGate"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnImpulse0.outputs:execOut", "SyncGate.inputs:execIn"),
("OnImpulse1.outputs:execOut", "SyncGate.inputs:execIn"),
("OnImpulse2.outputs:execOut", "SyncGate.inputs:execIn"),
("OnImpulse3.outputs:execOut", "SyncGate.inputs:execIn"),
("SyncGate.outputs:execOut", "Counter.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnImpulse0.inputs:onlyPlayback", False),
("OnImpulse1.inputs:onlyPlayback", False),
("OnImpulse2.inputs:onlyPlayback", False),
("OnImpulse3.inputs:onlyPlayback", False),
("SyncGate.inputs:syncValue", 5),
],
},
)
# Obtain necessary attributes.
state_enable_impulse_attr_0 = on_impulse0_node.get_attribute("state:enableImpulse")
state_enable_impulse_attr_1 = on_impulse1_node.get_attribute("state:enableImpulse")
state_enable_impulse_attr_2 = on_impulse2_node.get_attribute("state:enableImpulse")
state_enable_impulse_attr_3 = on_impulse3_node.get_attribute("state:enableImpulse")
in_syncvalue_attr = sync_gate_node.get_attribute("inputs:syncValue")
out_syncvalue_attr = sync_gate_node.get_attribute("outputs:syncValue")
out_cnt_attr = counter_node.get_attribute("outputs:count")
# First check that the SyncGate node only gets unblocked when it detects 4+ input
# enabled executions, at which point the Counter node will begin to be incremented.
# Also check that after the 1st graph evaluation the SyncGate's output syncValue gets
# set to its input syncValue.
state_enable_impulse_attr_0.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 0)
state_enable_impulse_attr_1.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 0)
state_enable_impulse_attr_2.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 0)
state_enable_impulse_attr_3.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 1)
state_enable_impulse_attr_0.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 5)
self.assertEqual(out_cnt_attr.get(), 2)
# Now reset the SyncGate node's syncValue. Check that we once again need 4+ input executions
# with the "enabled" status flowing into the SyncGate in order to unlock it. Also note
# that we don't technically need each separate OnImpulse node to trigger to unlock the gate;
# we could have a single OnImpulse node (per graph) send 4 separate impulses to open each gate
# in each graph, since that would reach the threshold number of accumulated execIn states for
# this setup (equal to 4 since we have 4 nodes connected to the SyncGate's inputs:execIn pin).
in_syncvalue_attr.set(9)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
for i in range(0, 5):
state_enable_impulse_attr_0.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 9)
if i < 3:
self.assertEqual(out_cnt_attr.get(), 2)
else:
self.assertEqual(out_cnt_attr.get(), 2 + (i - 2))
# Now reset the syncValue again per node. This time only send 2 input impulses, then reset the syncValue
# immediately after. Check that we'll again need to send 4 input impulses to open the corresponding gate
# (which was essentially "relocked" with the syncValue change).
in_syncvalue_attr.set(21)
state_enable_impulse_attr_0.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 21)
self.assertEqual(out_cnt_attr.get(), 4)
state_enable_impulse_attr_2.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 21)
self.assertEqual(out_cnt_attr.get(), 4)
in_syncvalue_attr.set(25)
for i in range(0, 5):
state_enable_impulse_attr_2.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_syncvalue_attr.get(), 25)
if i < 3:
self.assertEqual(out_cnt_attr.get(), 4)
else:
self.assertEqual(out_cnt_attr.get(), 4 + (i - 2))
# ----------------------------------------------------------------------
async def test_countdown_node(self):
"""Test Countdown node"""
duration = 5
period = 3
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, (_, _, counter0_node, counter1_node), _, _,) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Countdown", "omni.graph.action.Countdown"),
("Counter0", "omni.graph.action.Counter"),
("Counter1", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Countdown.inputs:execIn"),
("Countdown.outputs:finished", "Counter0.inputs:execIn"),
("Countdown.outputs:tick", "Counter1.inputs:execIn"),
],
# Set the Countdown inputs so that the Counter0 node only gets incremented
# once 4 update ticks have passed since the graph creation, and so that
# the Counter1 node gets incremented every 2 ticks.
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Countdown.inputs:duration", duration),
("Countdown.inputs:period", period),
],
},
)
# Obtain necessary attributes.
out_cnt_attr_0 = counter0_node.get_attribute("outputs:count")
out_cnt_attr_1 = counter1_node.get_attribute("outputs:count")
# Test against a predetermined set of values to make sure that
# this node doesn't break in the future.
cnt0 = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
cnt1 = [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]
for i in range(0, 20):
await og.Controller.evaluate()
self.assertEqual(og.Controller.get(out_cnt_attr_0), cnt0[i])
self.assertEqual(og.Controller.get(out_cnt_attr_1), cnt1[i])
| 52,966 | Python | 54.462827 | 127 | 0.598629 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_actiongraph.py | """Basic tests of the action graph"""
import omni.client
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from pxr import Gf, Sdf
# ======================================================================
class TestActionGraphNodes(ogts.OmniGraphTestCase):
"""Tests action graph node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_basic(self):
"""exercise a basic network of execution nodes"""
controller = og.Controller()
keys = og.Controller.Keys
# Test that an execution connection is correctly triggering the downstream node once per evaluation
(graph, (_, flip_flop_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [("OnTick", "omni.graph.action.OnTick"), ("FlipFlop", "omni.graph.action.FlipFlop")],
keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
keys.CONNECT: ("OnTick.outputs:tick", "FlipFlop.inputs:execIn"),
},
)
outa = controller.attribute("outputs:a", flip_flop_node)
outb = controller.attribute("outputs:b", flip_flop_node)
outisa = controller.attribute("outputs:isA", flip_flop_node)
# first eval, 'a'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.ENABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.DISABLED)
self.assertTrue(og.Controller.get(outisa))
# second eval 'b'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.DISABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.ENABLED)
self.assertFalse(og.Controller.get(outisa))
# third eval 'a'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.ENABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.DISABLED)
self.assertTrue(og.Controller.get(outisa))
# Test that non-usd-backed node has execution attribute type correct
_, on_tick_no_usd = og.cmds.CreateNode(
graph=graph,
node_path=f"{self.TEST_GRAPH_PATH}/OnTickNoUSD",
node_type="omni.graph.action.OnTick",
create_usd=False,
)
og.cmds.CreateNode(
graph=graph,
node_path=f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD",
node_type="omni.graph.action.FlipFlop",
create_usd=False,
)
controller.attribute("inputs:onlyPlayback", on_tick_no_usd, graph).set(False)
og.cmds.ConnectAttrs(
src_attr=f"{self.TEST_GRAPH_PATH}/OnTickNoUSD.outputs:tick",
dest_attr=f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD.inputs:execIn",
modify_usd=False,
)
outa = controller.attribute("outputs:a", f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD")
outb = controller.attribute("outputs:b", f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD")
outisa = controller.attribute("outputs:isA", f"{self.TEST_GRAPH_PATH}/FlipFlopNoUSD")
# first eval, 'a'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.ENABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.DISABLED)
self.assertTrue(og.Controller.get(outisa))
# second eval 'b'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.DISABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.ENABLED)
self.assertFalse(og.Controller.get(outisa))
# third eval 'a'
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), og.ExecutionAttributeState.ENABLED)
self.assertEqual(og.Controller.get(outb), og.ExecutionAttributeState.DISABLED)
self.assertTrue(og.Controller.get(outisa))
# ----------------------------------------------------------------------
async def test_notice(self):
"""Tests the OnObjectChange node"""
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
cube = ogts.create_cube(stage, "Cube", (0.6, 0.4, 0.0))
attr_position = cube.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False)
attr_rotation = cube.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Float3, False)
(graph, (on_object_change_node, flip_flop_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnObjectChange", "omni.graph.action.OnObjectChange"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
keys.SET_VALUES: [
("OnObjectChange.inputs:onlyPlayback", False),
("OnObjectChange.inputs:path", attr_position.GetPath().pathString),
],
keys.CONNECT: ("OnObjectChange.outputs:changed", "FlipFlop.inputs:execIn"),
},
)
outa = controller.attribute("outputs:a", flip_flop_node)
# check current flipflop state, and that it isn't changing until we move the cube
await controller.evaluate(graph)
ff_a_state_1 = og.Controller.get(outa)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), ff_a_state_1)
# Try changing a different attr - should not trigger
attr_rotation.Set(Gf.Vec3f(180.0, 0.0, 0.0))
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(outa), ff_a_state_1)
# Now change the translate - should trigger
attr_position.Set(Gf.Vec3f(1.0, 0.0, 0.0))
await controller.evaluate(graph)
ff_a_state_2 = og.Controller.get(outa)
self.assertEqual(ff_a_state_2, 1 if not ff_a_state_1 else 0)
property_path = og.Controller.get(controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_position.GetName())
# Look at prim itself
controller.edit(graph, {keys.SET_VALUES: ("OnObjectChange.inputs:path", cube.GetPath().pathString)})
await controller.evaluate(graph)
# Now change the rotate - should trigger
attr_rotation.Set(Gf.Vec3f(245.0, 0.0, 0.0))
await controller.evaluate(graph)
ff_a_state_1 = og.Controller.get(outa)
self.assertEqual(ff_a_state_1, 1 if not ff_a_state_2 else 0)
property_path = og.Controller.get(controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_rotation.GetName())
# Now use a prim rel instead of the path input
inputs_prim = stage.GetPrimAtPath(on_object_change_node.get_prim_path()).GetRelationship("inputs:prim")
inputs_prim.AddTarget(cube.GetPath())
controller.edit(graph, {keys.SET_VALUES: ("OnObjectChange.inputs:path", "")})
# compute once to set up the inputs
await controller.evaluate(graph)
# change rotate - should trigger
attr_rotation.Set(Gf.Vec3f(0.0, 0.0, 0.0))
await controller.evaluate(graph)
ff_a_state_2 = og.Controller.get(outa)
self.assertEqual(ff_a_state_2, 1 if not ff_a_state_1 else 0)
property_path = og.Controller.get(controller.attribute("outputs:propertyName", on_object_change_node))
self.assertEqual(property_path, attr_rotation.GetName())
# ----------------------------------------------------------------------
async def test_onplaybacktick(self):
"""Test OnPlaybackTick and OnTick node"""
controller = og.Controller()
keys = og.Controller.Keys
app = omni.kit.app.get_app()
timeline = omni.timeline.get_timeline_interface()
timeline.set_start_time(1.0)
timeline.set_end_time(10.0)
fps = 24.0
timeline.set_time_codes_per_second(fps)
(graph, (on_p_tick_node, on_tick_node, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnPTick", "omni.graph.action.OnPlaybackTick"),
("OnTick", "omni.graph.action.OnTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
keys.CONNECT: [
("OnPTick.outputs:tick", "FlipFlop.inputs:execIn"),
("OnTick.outputs:tick", "FlipFlop.inputs:execIn"),
],
keys.SET_VALUES: ("OnTick.inputs:onlyPlayback", True),
},
)
await controller.evaluate(graph)
tick_time = controller.attribute("outputs:time", on_p_tick_node)
tick_frame = controller.attribute("outputs:frame", on_p_tick_node)
ontick_time = controller.attribute("outputs:time", on_tick_node)
ontick_frame = controller.attribute("outputs:frame", on_tick_node)
# Check that the OnPlaybackTick node doesn't trigger when playback is not active
self.assertEqual(og.Controller.get(tick_time), 0)
self.assertEqual(og.Controller.get(tick_frame), 0)
self.assertEqual(og.Controller.get(ontick_time), 0)
self.assertEqual(og.Controller.get(ontick_frame), 0)
# Check that the OnPlaybackTick node does trigger when playback is active, and the values are correct
timeline.play()
await app.next_update_async()
await controller.evaluate(graph)
t0 = og.Controller.get(tick_time)
f0 = og.Controller.get(tick_frame)
self.assertAlmostEqual(t0, timeline.get_current_time(), places=5)
self.assertAlmostEqual(f0, t0 * fps, places=5)
t0 = og.Controller.get(ontick_time)
f0 = og.Controller.get(ontick_frame)
self.assertAlmostEqual(t0, timeline.get_current_time(), places=5)
self.assertAlmostEqual(f0, t0 * fps, places=5)
# ----------------------------------------------------------------------
async def test_non_action_subgraph(self):
"""Tests subgraphs in action graph"""
controller = og.Controller()
keys = og.Controller.Keys
# Test that a push subgraph is ticked by the top level Action graph
subgraph_path = self.TEST_GRAPH_PATH + "/push_sub"
graph = omni.graph.core.get_current_graph()
graph.create_subgraph(subgraph_path, evaluator="push")
subgraph = graph.get_subgraph(subgraph_path)
self.assertTrue(subgraph.is_valid())
sub_ff_node = self.TEST_GRAPH_PATH + "/push_sub/FlipFlop"
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
keys.CONNECT: ("OnTick.outputs:tick", "FlipFlop.inputs:execIn"),
},
)
await og.Controller.evaluate()
controller.edit(subgraph, {keys.CREATE_NODES: (sub_ff_node, "omni.graph.action.FlipFlop")})
sub_flipflop_node = subgraph.get_node(sub_ff_node)
self.assertTrue(sub_flipflop_node.is_valid())
ffstate0 = og.Controller.get(controller.attribute("outputs:isA", sub_ff_node))
await og.Controller.evaluate()
ffstate1 = og.Controller.get(controller.attribute("outputs:isA", sub_ff_node))
self.assertNotEqual(ffstate0, ffstate1)
# ----------------------------------------------------------------------
async def test_custom_events(self):
"""Test SendCustomEvent and OnCustomEvent node"""
controller = og.Controller()
keys = og.Controller.Keys
await omni.kit.app.get_app().next_update_async()
(_, (_, _, event1_node, counter1_node, event2_node, counter2_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Send", "omni.graph.action.SendCustomEvent"),
("OnCustomEvent1", "omni.graph.action.OnCustomEvent"),
("Counter1", "omni.graph.action.Counter"),
("OnCustomEvent2", "omni.graph.action.OnCustomEvent"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Send.inputs:execIn"),
("OnCustomEvent1.outputs:execOut", "Counter1.inputs:execIn"),
("OnCustomEvent2.outputs:execOut", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [
("OnCustomEvent1.inputs:onlyPlayback", False),
("OnCustomEvent2.inputs:onlyPlayback", False),
("OnImpulse.inputs:onlyPlayback", False),
("Send.inputs:eventName", "foo"),
("Send.inputs:path", "Test Path"),
("OnCustomEvent1.inputs:eventName", "foo"),
("OnCustomEvent2.inputs:eventName", "foo"),
],
},
)
counter1_controller = og.Controller(og.Controller.attribute("outputs:count", counter1_node))
counter2_controller = og.Controller(og.Controller.attribute("outputs:count", counter2_node))
event1_controller = og.Controller(og.Controller.attribute("outputs:path", event1_node))
event2_controller = og.Controller(og.Controller.attribute("outputs:path", event2_node))
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 0)
# trigger graph once, this will queue up the event for the next evaluation
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
# Note that if this is a push subscription, the receivers will run this frame instead of next
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 0)
# This evaluation should trigger the receivers
await omni.kit.app.get_app().next_update_async()
# Verify that events were received
self.assertEqual(counter1_controller.get(), 1)
self.assertEqual(event1_controller.get(), "Test Path")
self.assertEqual(counter2_controller.get(), 1)
self.assertEqual(event2_controller.get(), "Test Path")
# Verify the contents of the associated bundle
# FIXME: Authored bundle is always empty?
# bundle_contents = og.BundleContents(graph.get_default_graph_context(), event1_node, "outputs:bundle", True)
# self.assertEqual(1, bundle_contents.size)
# Modify the event name one receiver and sender and ensure it still works
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.SET_VALUES: [("Send.inputs:eventName", "bar"), ("OnImpulse.state:enableImpulse", True)],
},
)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# We changed the sender event name, so counter should _not_ have triggered again
self.assertEqual(counter1_controller.get(), 1)
# Change the receiver name to match
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnCustomEvent1.inputs:eventName", "bar")})
await omni.kit.app.get_app().next_update_async()
# trigger send again and verify we get it (1 frame lag for pop)
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 2)
# ----------------------------------------------------------------------
async def test_request_driven_node(self):
"""Test that RequestDriven nodes are computed as expected"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Counter", "omni.graph.action.Counter"),
],
keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False)],
keys.CONNECT: ("OnImpulse.outputs:execOut", "Counter.inputs:execIn"),
},
)
# After several updates, there should have been no compute calls
await controller.evaluate(graph)
await controller.evaluate(graph)
await controller.evaluate(graph)
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
self.assertEqual(counter_controller.get(), 0)
# change OnImpulse state attrib. The node should now request compute
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 1)
# more updates should not result in more computes
await controller.evaluate(graph)
await controller.evaluate(graph)
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 1)
# ----------------------------------------------------------------------
async def test_stage_events(self):
"""Test OnStageEvent"""
controller = og.Controller()
keys = og.Controller.Keys
(_, (_, _, _, counter_node, counter2_node, counter3_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnStageEvent", "omni.graph.action.OnStageEvent"),
("OnStageEvent2", "omni.graph.action.OnStageEvent"),
("OnStageEvent3", "omni.graph.action.OnStageEvent"),
("Counter", "omni.graph.action.Counter"),
("Counter2", "omni.graph.action.Counter"),
("Counter3", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnStageEvent.outputs:execOut", "Counter.inputs:execIn"),
("OnStageEvent2.outputs:execOut", "Counter2.inputs:execIn"),
("OnStageEvent3.outputs:execOut", "Counter3.inputs:execIn"),
],
keys.SET_VALUES: [
("OnStageEvent.inputs:eventName", "Selection Changed"),
("OnStageEvent.inputs:onlyPlayback", False),
("OnStageEvent2.inputs:eventName", "Animation Stop Play"),
("OnStageEvent2.inputs:onlyPlayback", True),
("OnStageEvent3.inputs:eventName", "Animation Start Play"),
("OnStageEvent3.inputs:onlyPlayback", True),
],
},
)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 0)
selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([self.TEST_GRAPH_PATH + "/OnStageEvent"], False)
# 1 frame delay on the pop, 1 frame delay on the compute
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_node)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 0)
# Verify that start/stop events work when only-plackback is true
timeline = omni.timeline.get_timeline_interface()
timeline.set_start_time(1.0)
timeline.set_end_time(10.0)
timeline.play()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 1)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 0)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 1)
timeline.stop()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 1)
await controller.evaluate()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter3_node)), 1)
# -----------------------------------------------------------------------
async def test_add_prim_relationship(self):
"""Test AddPrimRelationship"""
controller = og.Controller()
# Check that we can add relationship to a prim and get that relationship
#
# +---------+ +---------------------+
# | ONTICK +-->| AddPrimRelationship +
# +---------+ +---------------------+
#
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("AddRel", "omni.graph.action.AddPrimRelationship"),
],
keys.CREATE_PRIMS: [
("/Test", {}),
("/Target", {}),
],
keys.CONNECT: [("OnTick.outputs:tick", "AddRel.inputs:execIn")],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("AddRel.inputs:path", "/Test"),
("AddRel.inputs:name", "rel"),
("AddRel.inputs:target", "/Target"),
],
},
)
prim = stage.GetPrimAtPath("/Test")
await controller.evaluate()
rel = prim.GetRelationship("rel")
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertTrue(str(targets[0]) == "/Target")
# ----------------------------------------------------------------------
async def test_switch(self):
"""Test the Switch nodes"""
controller = og.Controller()
keys = og.Controller.Keys
# Test that an execution connection is correctly triggering the downstream node once per evaluation
(graph, (_, switch_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Switch", "omni.graph.action.SwitchToken"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Switch.inputs:execIn"),
],
},
)
def add_input(index: int):
controller.create_attribute(
switch_node,
f"inputs:branch{index:02}",
"token",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
)
controller.create_attribute(
switch_node,
f"outputs:output{index:02}",
"execution",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
og.Controller.set(controller.attribute(f"inputs:branch{index:02}", switch_node), f"{index:02}")
for index in range(5):
add_input(index)
for index in range(5):
og.Controller.set(controller.attribute("inputs:value", switch_node), f"{index:02}")
await controller.evaluate(graph)
for index2 in range(5):
expected_val = (
og.ExecutionAttributeState.DISABLED if index2 != index else og.ExecutionAttributeState.ENABLED
)
self.assertEqual(
og.Controller.get(controller.attribute(f"outputs:output{index2:02}", switch_node)), expected_val
)
| 25,795 | Python | 45.987249 | 120 | 0.584028 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_compounds.py | """Action Graph with Compounds"""
import carb.events
import omni.graph.core as og
import omni.graph.core._unstable as ogu
import omni.graph.core.tests as ogts
import omni.kit.app
# ======================================================================
class TestActionGraphCompounds(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ------------------------------------------------------------------------
async def test_create_action_subgraph_with_command(self):
"""Validates the create compound subgraph command in an action graph"""
# "Add" will only compute if the subgraph is executed as a push graph OR
# is flattened into the parent graph
# ┌───────────────┐
# │Subgraph │
# ┌─────┐ │ ┌─────┐ │
# │Const├───►────► Add ├───►├────┐
# └─────┘ │ └──▲──┘ │ │
# │ │ │ │
# │ ┌─────┴┐ │ │
# │ │Const2│ │ │
# │ └──────┘ │ │
# │ │ │
# └───────────────┘ │
# ┌───────┐ ┌▼────────────┐
# │OnTick ├──────────────────────►WriteVariable│
# └───────┘ └─────────────┘
controller = og.Controller()
keys = controller.Keys
(graph, (_, _, const_2, add, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Const", "omni.graph.nodes.ConstantInt"),
("Const2", "omni.graph.nodes.ConstantInt"),
("Add", "omni.graph.nodes.Add"),
("WriteVariable", "omni.graph.core.WriteVariable"),
],
keys.CREATE_VARIABLES: [
("int_var", og.Type(og.BaseDataType.INT), 0),
],
keys.CONNECT: [
("Const.inputs:value", "Add.inputs:a"),
("Const2.inputs:value", "Add.inputs:b"),
("Add.outputs:sum", "WriteVariable.inputs:value"),
("OnTick.outputs:tick", "WriteVariable.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("WriteVariable.inputs:variableName", "int_var"),
],
},
)
await og.Controller.evaluate(graph)
self.assertEquals(graph.get_variables()[0].get(graph.get_default_graph_context()), 0)
controller.edit(
self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("Const.inputs:value", 22), ("Const2.inputs:value", 20)]}
)
ogu.cmds.ReplaceWithCompoundSubgraph(
nodes=[add.get_prim_path(), const_2.get_prim_path()], compound_name="Subgraph"
)
await og.Controller.evaluate(graph)
self.assertEquals(graph.get_variables()[0].get(graph.get_default_graph_context()), 42.0)
# ------------------------------------------------------------------------
async def test_event_node_in_subgraph(self):
"""
Test that a compute-on-request node inside a subgraph works
"""
controller = og.Controller(update_usd=True)
keys = controller.Keys
(graph, (compound_node,), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
(
"CompoundOuter",
{
keys.CREATE_NODES: [
(
"CompoundInner",
{
keys.CREATE_NODES: [
("OnEvent", "omni.graph.action.OnMessageBusEvent"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [("OnEvent.outputs:execOut", "Counter.inputs:execIn")],
keys.SET_VALUES: [
("OnEvent.inputs:onlyPlayback", False),
("OnEvent.inputs:eventName", "testEvent"),
],
},
)
]
},
),
],
},
)
# One compute for the first-time subscribe.
await omni.kit.app.get_app().next_update_async()
msg = carb.events.type_from_string("testEvent")
counter_attr = og.Controller.attribute(
f"{compound_node.get_prim_path()}/Subgraph/CompoundInner/Subgraph/Counter.outputs:count"
)
await og.Controller.evaluate(graph)
self.assertEqual(counter_attr.get(), 0)
omni.kit.app.get_app().get_message_bus_event_stream().push(msg)
# Wait for one kit update to allow the event-push mechanism to trigger the node callback.
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter_attr.get(), 1)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter_attr.get(), 1)
omni.kit.app.get_app().get_message_bus_event_stream().push(msg)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter_attr.get(), 2)
| 5,943 | Python | 43.358209 | 110 | 0.434629 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_evaluation_02.py | """Action Graph Evaluation Tests, Part 2"""
from enum import Enum, auto
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
from omni.graph.action import get_interface
from pxr import Gf
# ======================================================================
class TestActionGraphEvaluation(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_latent_fan_out(self):
"""Test latent nodes when part of parallel evaluation"""
# +------------+
# +---->|TickCounterA|
# | +------------+
# |
# +--------++ +----------+
# +-> TickA +--->|FinishedA |
# | +---------+ +----------+
# +---------+ +-----------+ |
# |OnImpulse+-->|TickCounter+-+
# +---------+ +-----------+ |
# | +---------+ +----------+
# +>| TickB +--->|FinishedB |
# +--------++ +----------+
# |
# | +------------+
# +---->|TickCounterB|
# +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.Countdown"),
("TickB", "omni.graph.action.Countdown"),
("TickCounter", "omni.graph.action.Counter"),
("TickCounterA", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickA.inputs:execIn"),
("TickCounter.outputs:execOut", "TickB.inputs:execIn"),
("TickA.outputs:tick", "TickCounterA.inputs:execIn"),
("TickB.outputs:tick", "TickCounterB.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, _, _, tick_counter, tick_counter_a, tick_counter_b, finish_counter_a, finish_counter_b) = nodes
def check_counts(t_def, t_a, t_b, f_a, f_b):
for node, expected in (
(tick_counter, t_def),
(tick_counter_a, t_a),
(tick_counter_b, t_b),
(finish_counter_a, f_a),
(finish_counter_b, f_b),
):
count = og.Controller.get(controller.attribute("outputs:count", node))
self.assertEqual(count, expected, node.get_prim_path())
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 0)
await controller.evaluate(graph)
check_counts(1, 1, 1, 0, 0)
await controller.evaluate(graph)
check_counts(1, 2, 2, 0, 0)
await controller.evaluate(graph)
check_counts(1, 2, 2, 1, 1)
# ----------------------------------------------------------------------
async def test_loop_cancel(self):
"""Test loop canceling"""
# Check that a loop can be canceled.
# We set up the loop to run for 7 iterations, but cancel when we hit iteration 2.
#
# +--------+
# +------------->|COUNTER2|
# | finish +--------+
# +---------+ +----------+ +----------+ +-------+ +---------+
# | IMPULSE +-->| FOR-LOOP +--->| COMPARE +--->|BRANCH +--->| COUNTER1|
# +---------+ +----------+ +----------+ +-------+ +---------+
# ^ |
# | cancel |
# +------------------------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, for_loop, _, _, count_1, count_2), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ForLoop", "omni.graph.action.ForLoop"),
("Compare", "omni.graph.nodes.Compare"),
("Branch", "omni.graph.action.Branch"),
("Counter1", "omni.graph.action.Counter"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "ForLoop.inputs:execIn"),
("ForLoop.outputs:loopBody", "Branch.inputs:execIn"),
("ForLoop.outputs:index", "Compare.inputs:a"),
("ForLoop.outputs:finished", "Counter2.inputs:execIn"),
("Compare.outputs:result", "Branch.inputs:condition"),
("Branch.outputs:execFalse", "Counter1.inputs:execIn"),
("Branch.outputs:execTrue", "ForLoop.inputs:breakLoop"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("Compare.inputs:b", 2, "int"),
("Compare.inputs:operation", "=="),
("ForLoop.inputs:stop", 6),
],
},
)
await controller.evaluate(graph)
# Trigger graph once.
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# Verify the loop body only counted 2 times, and finish once.
c_1 = og.Controller.get(og.Controller.attribute("outputs:count", count_1))
c_2 = og.Controller.get(og.Controller.attribute("outputs:count", count_2))
index = og.Controller.get(og.Controller.attribute("outputs:index", for_loop))
self.assertEqual(index, 2)
self.assertEqual(c_1, 2)
self.assertEqual(c_2, 1)
# ----------------------------------------------------------------------
async def test_loop_sideffects(self):
"""Test that nodes in loops can read results of external side effects"""
# +----------+ +---------+ +-------+ +--------------------+
# | OnImpulse+----->| ForLoop +----->| Add +------>| WritePrimAttribute |
# +----------+ +---------+ +-------+ +--------------------+
# ^
# +-----------------+ |
# |ReadPrimAttribute +---+
# +-----------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, prims, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Get", "omni.graph.nodes.ReadPrimAttribute"),
("ForLoop1", "omni.graph.action.ForLoop"),
("Add", "omni.graph.nodes.Add"),
("Set", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: ("/World/Accumulator", {"acc": ("int", 0)}),
keys.SET_VALUES: [
("Get.inputs:name", "acc"),
("Get.inputs:usePath", True),
("Get.inputs:primPath", "/World/Accumulator"),
("ForLoop1.inputs:start", 0),
("ForLoop1.inputs:stop", 5),
("Set.inputs:name", "acc"),
("Set.inputs:usePath", True),
("Set.inputs:primPath", "/World/Accumulator"),
("OnImpulse.inputs:onlyPlayback", False),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "Set.inputs:execIn"),
("Get.outputs:value", "Add.inputs:a"),
("ForLoop1.outputs:value", "Add.inputs:b"),
("Add.outputs:sum", "Set.inputs:value"),
],
},
)
await controller.evaluate(graph)
# Trigger graph evaluation once.
# Should result in sum = 0 + 0 + 1 + 2 + 3 + 4.
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: [("OnImpulse.state:enableImpulse", True)]})
await controller.evaluate(graph)
self.assertEqual(prims[0].GetAttribute("acc").Get(), 10)
# ----------------------------------------------------------------------
async def test_nested_forloop(self):
"""Test nested ForLoop nodes"""
keys = og.Controller.Keys
controller = og.Controller()
(graph, (_, _, _, _, _, _, write_node), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Const", "omni.graph.nodes.ConstantInt2"),
("Add", "omni.graph.nodes.Add"),
("Branch", "omni.graph.action.Branch"),
("For", "omni.graph.action.ForLoop"),
("For2", "omni.graph.action.ForLoop"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: (
"/World/TestPrim",
{
"val1": ("int[2]", Gf.Vec2i(1, 1)),
},
),
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Const.inputs:value", [1, 2]),
("Write1.inputs:name", "val1"),
("Write1.inputs:primPath", "/World/TestPrim"),
("Write1.inputs:usePath", True),
("For.inputs:stop", 3),
("For2.inputs:start", 4),
("For2.inputs:step", 2),
("For2.inputs:stop", 10),
("Branch.inputs:condition", True),
],
keys.CONNECT: [
("OnTick.outputs:tick", "For.inputs:execIn"),
("For.outputs:loopBody", "Branch.inputs:execIn"),
("Branch.outputs:execTrue", "For2.inputs:execIn"),
("For2.outputs:loopBody", "Write1.inputs:execIn"),
("For2.outputs:value", "Add.inputs:a"),
("Const.inputs:value", "Add.inputs:b"),
("Add.outputs:sum", "Write1.inputs:value"),
],
},
)
await controller.evaluate(graph)
context = omni.usd.get_context()
stage = context.get_stage()
# For2 should loop over the range [4, 6, 8, 10).
self.assertEqual(9, write_node.get_compute_count())
# [1, 2] + 8 = [9, 10].
self.assertListEqual([9, 10], list(stage.GetAttributeAtPath("/World/TestPrim.val1").Get()))
# ----------------------------------------------------------------------
async def test_om_63924(self):
"""Test OM-63924 bug is fixed"""
# The problem here was that if there was fan in to a node which was
# computed once and then totally unwound before the other history was
# processed, there would never be a deferred activation and so the 2nd
# compute would never happen. Instead we want to only unwind one history
# at a time to ensure each one is fully evaluated.
i = 2
class OnForEachEventPy:
"""Helper Python node that implements ForEach logic"""
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
"""Compute method"""
nonlocal i
inputs_go = node.get_attribute("inputs:go")
go_val = og.Controller.get(inputs_go)
if not go_val:
return True
if i > 0:
og.Controller.set(
node.get_attribute("outputs:execOut"), og.ExecutionAttributeState.ENABLED_AND_PUSH
)
og.Controller.set(node.get_attribute("outputs:syncValue"), i)
i -= 1
return True
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.test.OnForEachEventPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input(
"inputs:go",
"bool",
False,
)
node_type.add_output("outputs:execOut", "execution", True)
node_type.add_output("outputs:syncValue", "uint64", True)
return True
og.register_node_type(OnForEachEventPy, 1)
class NoOpPy:
"""Helper Python node that performs no internal operation"""
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
"""Compute method"""
og.Controller.set(node.get_attribute("outputs:execOut"), og.ExecutionAttributeState.ENABLED)
return True
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.test.NoOpPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input(
"inputs:execIn",
"execution",
True,
)
node_type.add_output("outputs:execOut", "execution", True)
return True
og.register_node_type(NoOpPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (for_each, _, _, _, _, no_op_2), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("PostProcessDispatcher", "omni.graph.test.OnForEachEventPy"),
("TSA1", "omni.graph.action.SyncGate"),
("TSA0", "omni.graph.action.SyncGate"),
("TestSyncAccum", "omni.graph.action.SyncGate"),
("TestPrimBbox", "omni.graph.test.NoOpPy"),
("NoOpPy2", "omni.graph.test.NoOpPy"),
],
keys.CONNECT: [
("PostProcessDispatcher.outputs:execOut", "TSA0.inputs:execIn"),
("PostProcessDispatcher.outputs:execOut", "TSA1.inputs:execIn"),
("TSA1.outputs:execOut", "TestSyncAccum.inputs:execIn"),
("TSA0.outputs:execOut", "TestPrimBbox.inputs:execIn"),
("TestPrimBbox.outputs:execOut", "TestSyncAccum.inputs:execIn"),
("TestSyncAccum.outputs:execOut", "NoOpPy2.inputs:execIn"),
("PostProcessDispatcher.outputs:syncValue", "TSA1.inputs:syncValue"),
("PostProcessDispatcher.outputs:syncValue", "TSA0.inputs:syncValue"),
("PostProcessDispatcher.outputs:syncValue", "TestSyncAccum.inputs:syncValue"),
],
},
)
og.Controller.set(controller.attribute("inputs:go", for_each), True)
await controller.evaluate(graph)
# Verify the final sync gate triggered due to being computed 2x.
exec_out = og.Controller.get(controller.attribute("outputs:execOut", no_op_2))
self.assertEqual(exec_out, og.ExecutionAttributeState.ENABLED)
# ----------------------------------------------------------------------
async def test_retrigger_latent(self):
"""Test that latent nodes can be re-triggered"""
want_debug = False
e_state = og.ExecutionAttributeState
tick_count = 0
boop_count = 0
exec_in_latent_count = 0
max_ticks = 20
class CancelTickerPy:
"""Helper node type which does latent ticking and can be canceled, and has an independent counter "boop" """
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
"""Compute method"""
nonlocal tick_count
nonlocal boop_count
nonlocal exec_in_latent_count
exec_in = node.get_attribute("inputs:execIn")
exec_in_val = og.Controller.get(exec_in)
cancel = node.get_attribute("inputs:cancel")
cancel_val = og.Controller.get(cancel)
boop = node.get_attribute("inputs:boop")
boop_val = og.Controller.get(boop)
if want_debug:
print(f"### {tick_count} execIn={exec_in_val} cancel={cancel_val} boop={boop_val}")
if cancel_val == e_state.ENABLED:
# Finish latent by cancel.
og.Controller.set(node.get_attribute("outputs:canceled"), e_state.LATENT_FINISH)
self.assertEqual(exec_in_val, e_state.DISABLED)
self.assertEqual(boop_val, e_state.DISABLED)
tick_count = 0
return True
if exec_in_val == e_state.ENABLED:
self.assertEqual(cancel_val, e_state.DISABLED)
self.assertEqual(boop_val, e_state.DISABLED)
if tick_count > 0:
# execIn triggered while in latent - should not be possible.
exec_in_latent_count += 1
else:
og.Controller.set(node.get_attribute("outputs:tick"), e_state.LATENT_PUSH)
return True
# We are ticking.
self.assertEqual(cancel_val, e_state.DISABLED)
tick_count += 1
if tick_count < max_ticks:
og.Controller.set(node.get_attribute("outputs:tick"), e_state.ENABLED)
else:
# Finish latent naturally.
og.Controller.set(node.get_attribute("outputs:execOut"), e_state.LATENT_FINISH)
tick_count = 0
if boop_val == e_state.ENABLED:
# We get here during latent ticking, if the boop input is enabled.
self.assertEqual(exec_in_val, e_state.DISABLED)
self.assertEqual(cancel_val, e_state.DISABLED)
boop_count += 1
return True
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.test.CancelTickerPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input(
"inputs:execIn",
"execution",
True,
)
node_type.add_input(
"inputs:cancel",
"execution",
True,
)
node_type.add_input(
"inputs:boop",
"execution",
True,
)
node_type.add_output("outputs:tick", "execution", True)
node_type.add_output("outputs:canceled", "execution", True)
node_type.add_output("outputs:execOut", "execution", True)
return True
og.register_node_type(CancelTickerPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (ticker, start, _, cancel, boop, _, _, counter), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("Ticker", "omni.graph.test.CancelTickerPy"),
("Start", "omni.graph.action.OnImpulseEvent"),
("Start2", "omni.graph.action.OnImpulseEvent"),
("Cancel", "omni.graph.action.OnImpulseEvent"),
("Boop", "omni.graph.action.OnImpulseEvent"),
("Once", "omni.graph.action.Once"),
("Once2", "omni.graph.action.Once"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("Start.outputs:execOut", "Ticker.inputs:execIn"),
("Start2.outputs:execOut", "Ticker.inputs:execIn"),
("Cancel.outputs:execOut", "Once.inputs:execIn"),
("Once.outputs:once", "Ticker.inputs:cancel"),
("Once.outputs:after", "Ticker.inputs:cancel"),
("Cancel.outputs:execOut", "Once2.inputs:execIn"),
("Boop.outputs:execOut", "Ticker.inputs:boop"),
("Once2.outputs:once", "Ticker.inputs:cancel"),
("Once2.outputs:after", "Ticker.inputs:cancel"),
("Ticker.outputs:tick", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("Start.inputs:onlyPlayback", False),
("Start2.inputs:onlyPlayback", False),
("Cancel.inputs:onlyPlayback", False),
("Boop.inputs:onlyPlayback", False),
],
},
)
# Cancel, check nothing happens.
og.Controller.set(controller.attribute("state:enableImpulse", cancel), True)
await controller.evaluate(graph)
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.DISABLED)
# Start ticking.
og.Controller.set(controller.attribute("state:enableImpulse", start), True)
await controller.evaluate(graph) # Starts latent state.
await controller.evaluate(graph) # Tick 1
self.assertEqual(tick_count, 1)
# Verify the tick has started.
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.ENABLED)
await controller.evaluate(graph) # Tick 2
self.assertEqual(tick_count, 2)
exec_out = og.Controller.get(controller.attribute("outputs:tick", ticker))
self.assertEqual(exec_out, e_state.ENABLED)
await controller.evaluate(graph) # Tick 3
self.assertEqual(tick_count, 3)
# Boop - node keeps ticking.
og.Controller.set(controller.attribute("state:enableImpulse", boop), True)
# Boop will trigger a compute, which increments boop + ticks AND the normal latent tick.
await controller.evaluate(graph)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 5)
# Now check that the next tick can run WITHOUT inputs:boop being high.
await controller.evaluate(graph)
self.assertEqual(boop_count, 1) # No change in boop count (OM-64856).
self.assertEqual(tick_count, 6)
# Now check that we can't re-trigger execIn.
self.assertEqual(exec_in_latent_count, 0)
og.Controller.set(controller.attribute("state:enableImpulse", start), True)
# Start will not trigger any compute because the node is latent.
await controller.evaluate(graph)
self.assertEqual(exec_in_latent_count, 0)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 7)
# Unset the impulse.
og.Controller.set(controller.attribute("state:enableImpulse", start), False)
# Now check the normal tick proceeds as normal.
await controller.evaluate(graph)
self.assertEqual(boop_count, 1)
self.assertEqual(tick_count, 8)
# Cancel.
counter_attr = controller.attribute("outputs:count", counter)
count_0 = og.Controller.get(counter_attr)
og.Controller.set(controller.attribute("state:enableImpulse", cancel), True)
await controller.evaluate(graph) # Latent finish.
await controller.evaluate(graph) # No action.
await controller.evaluate(graph) # No action.
count_1 = og.Controller.get(counter_attr)
self.assertEqual(count_0 + 1, count_1)
# ----------------------------------------------------------------------
async def test_simple_expression(self):
"""Test ActionGraph simple expression of add nodes"""
keys = og.Controller.Keys
controller = og.Controller()
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Const", "omni.graph.nodes.ConstantDouble3"),
("Add", "omni.graph.nodes.Add"),
("Add2", "omni.graph.nodes.Add"),
("Add3", "omni.graph.nodes.Add"),
("PostAdd", "omni.graph.nodes.Add"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
("Write2", "omni.graph.nodes.WritePrimAttribute"),
("Write3", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: (
"/World/TestPrim",
{
"val1": ("double[3]", Gf.Vec3d(1, 1, 1)),
"val2": ("double[3]", Gf.Vec3d(2, 2, 2)),
"val3": ("double[3]", Gf.Vec3d(2, 2, 2)),
},
),
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Const.inputs:value", [1, 2, 3]),
("Write1.inputs:name", "val1"),
("Write1.inputs:primPath", "/World/TestPrim"),
("Write1.inputs:usePath", True),
("Write2.inputs:name", "val2"),
("Write2.inputs:primPath", "/World/TestPrim"),
("Write2.inputs:usePath", True),
("Write3.inputs:name", "val3"),
("Write3.inputs:primPath", "/World/TestPrim"),
("Write3.inputs:usePath", True),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Write1.inputs:execIn"),
("Write1.outputs:execOut", "Write2.inputs:execIn"),
("Write2.outputs:execOut", "Write3.inputs:execIn"),
("Const.inputs:value", "Add.inputs:a"),
("Const.inputs:value", "Add.inputs:b"),
("Const.inputs:value", "Add2.inputs:a"),
("Const.inputs:value", "Add2.inputs:b"),
("Add.outputs:sum", "Add3.inputs:a"),
("Add2.outputs:sum", "Add3.inputs:b"),
("Add3.outputs:sum", "Write1.inputs:value"),
("Add3.outputs:sum", "Write2.inputs:value"),
("Add3.outputs:sum", "PostAdd.inputs:a"),
("Add3.outputs:sum", "PostAdd.inputs:b"),
("PostAdd.outputs:sum", "Write3.inputs:value"),
],
},
)
await controller.evaluate(graph)
context = omni.usd.get_context()
stage = context.get_stage()
await omni.kit.app.get_app().next_update_async()
self.assertListEqual([4, 8, 12], list(stage.GetAttributeAtPath("/World/TestPrim.val1").Get()))
self.assertListEqual([4, 8, 12], list(stage.GetAttributeAtPath("/World/TestPrim.val2").Get()))
self.assertListEqual([8, 16, 24], list(stage.GetAttributeAtPath("/World/TestPrim.val3").Get()))
# ----------------------------------------------------------------------
async def test_stateful_flowcontrol_evaluation(self):
"""Test that stateful flow control nodes are fully evaluated"""
# b
# +----------+ +---------+
# +--->| Sequence +-->|Counter1 |
# | +----------+ +---------+
# +-----------+ |
# | OnImpulse +-+
# +-----------+ |
# | +----------+ +----------+
# +--->| ForLoop1 +-->| Counter2 |
# +----------+ +----------+
# finished
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, counter1_node, _, counter2_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Sequence", "omni.graph.action.Sequence"),
("Counter1", "omni.graph.action.Counter"),
("ForLoop1", "omni.graph.action.ForLoop"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Sequence.inputs:execIn"),
("Sequence.outputs:b", "Counter1.inputs:execIn"),
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:finished", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False), ("ForLoop1.inputs:stop", 10)],
},
)
await controller.evaluate(graph)
# Trigger graph once.
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# Verify that counter was called in spite of sequence 'a' being disconnected.
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter1_node)), 1)
# Verify that counter was called in spite of there being no loopBody - execution evaluator has to still trigger
# the loop 11 times despite there being no downstream connection.
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 1)
# ----------------------------------------------------------------------
async def test_unresolve_on_disconnect(self):
"""Tests unresolving attribs when action node is disconnected"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, for_each_node, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("ForEach", "omni.graph.action.ForEach"),
("IntArrayPrim", "omni.graph.nodes.ReadPrimAttribute"),
("IntSinkPrim", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: [
("/World/IntArray", {"myintarray": ("int[]", range(10))}),
("/World/IntSink", {"myint": ("int", 0)}),
],
keys.CONNECT: [
("OnTick.outputs:tick", "ForEach.inputs:execIn"),
("IntArrayPrim.outputs:value", "ForEach.inputs:arrayIn"),
("ForEach.outputs:element", "IntSinkPrim.inputs:value"),
],
keys.SET_VALUES: [
("IntArrayPrim.inputs:name", "myintarray"),
("IntArrayPrim.inputs:primPath", "/World/IntArray"),
("IntArrayPrim.inputs:usePath", True),
("IntSinkPrim.inputs:name", "myint"),
("IntSinkPrim.inputs:primPath", "/World/IntSink"),
("IntSinkPrim.inputs:usePath", True),
("OnTick.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
array_attr = controller.attribute("inputs:arrayIn", for_each_node)
element_attr = controller.attribute("outputs:element", for_each_node)
self.assertEqual(element_attr.get_resolved_type(), og.Type(og.BaseDataType.INT, 1, 0))
# When we disconnect all data connections, they should unresolve even though we still
# have the execution connection in place.
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.DISCONNECT: [
("IntArrayPrim.outputs:value", "ForEach.inputs:arrayIn"),
("ForEach.outputs:element", "IntSinkPrim.inputs:value"),
]
},
)
await controller.evaluate(graph)
self.assertEqual(array_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN))
self.assertEqual(element_attr.get_resolved_type(), og.Type(og.BaseDataType.UNKNOWN))
async def test_actiongraph_abi(self):
"""Tests IActionGraph ABI functions"""
i_ag = get_interface()
g_exec_out = 0
class State(Enum):
ENABLED = auto()
ENABLED_AND_PUSH = auto()
START = auto()
END = auto()
class _TestActionGraphPy:
"""Helper node to test behavior"""
class _State:
val = None
instance_states = {}
@staticmethod
def initialize(context, node):
_TestActionGraphPy.instance_states[node] = _TestActionGraphPy._State()
@staticmethod
def compute(_: og.GraphContext, node: og.Node) -> bool:
"""Compute method"""
nonlocal g_exec_out
if not i_ag.get_latent_state():
self.assertTrue(i_ag.get_execution_enabled("inputs:execIn"))
self.assertFalse(i_ag.get_execution_enabled("inputs:execUnused"))
self.assertFalse(i_ag.get_execution_enabled("inputs:boolUnused"))
state = _TestActionGraphPy.instance_states[node]
if state.val == State.ENABLED_AND_PUSH:
# Must be re-entering
i_ag.set_execution_enabled("outputs:finished_from_pushed")
state.val = None
return True
if state.val == State.START:
# Must be in latent state tick
self.assertTrue(i_ag.get_latent_state())
i_ag.end_latent_state()
i_ag.set_execution_enabled("outputs:finished_from_latent")
state.val = None
return True
if g_exec_out == State.ENABLED:
i_ag.set_execution_enabled("outputs:execOut")
elif g_exec_out == State.ENABLED_AND_PUSH:
i_ag.set_execution_enabled_and_pushed("outputs:execOut")
elif g_exec_out == State.START:
self.assertFalse(i_ag.get_latent_state())
i_ag.start_latent_state()
elif g_exec_out == State.END:
i_ag.end_latent_state()
state.val = g_exec_out
return True
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.action._TestActionGraphPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input("inputs:execIn", "execution", True)
node_type.add_input("inputs:execUnused", "execution", True)
node_type.add_input("inputs:boolUnused", "bool", True)
node_type.add_output("outputs:execOut", "execution", True)
node_type.add_output("outputs:finished_from_latent", "execution", True)
node_type.add_output("outputs:finished_from_pushed", "execution", True)
og.register_node_type(_TestActionGraphPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Test", "omni.graph.action._TestActionGraphPy"),
("CounterOut", "omni.graph.action.Counter"),
("CounterLatent", "omni.graph.action.Counter"),
("CounterPushed", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Test.inputs:execIn"),
("Test.outputs:execOut", "CounterOut.inputs:execIn"),
("Test.outputs:finished_from_latent", "CounterLatent.inputs:execIn"),
("Test.outputs:finished_from_pushed", "CounterPushed.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 0)
g_exec_out = State.ENABLED
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 1)
g_exec_out = State.ENABLED_AND_PUSH
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 2)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterPushed.outputs:count"), 1)
g_exec_out = State.START
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 2)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterPushed.outputs:count"), 1)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterLatent.outputs:count"), 0)
g_exec_out = State.END
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterOut.outputs:count"), 2)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterPushed.outputs:count"), 1)
self.assertEqual(og.Controller.get(f"{self.TEST_GRAPH_PATH}/CounterLatent.outputs:count"), 1)
with ogts.ExpectedError():
with self.assertRaises(RuntimeError):
i_ag.start_latent_state()
# ------------------------------------------------------------------------
async def test_node_self_destruction(self):
"""Test that we don't crash if a very bad node causes a resync of the stage"""
# Executing this node may cause errors and fail the test as the underlying
# authoring node is destroyed while the task is executing. We just verify that only
# the expected error is generated.
class _TestBadNodePy:
@staticmethod
def compute(_: og.GraphContext, node: og.Node) -> bool:
context = omni.usd.get_context()
stage = context.get_stage()
stage.RemovePrim(node.get_prim_path())
@staticmethod
def get_node_type() -> str:
"""Get node type"""
return "omni.graph.action._TestBadNodePy"
@staticmethod
def initialize_type(node_type: og.NodeType):
"""Initialize node attributes"""
node_type.add_input("inputs:execIn", "execution", True)
node_type.add_output("outputs:execOut", "execution", True)
og.register_node_type(_TestBadNodePy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Test", "omni.graph.action._TestBadNodePy"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Test.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
},
)
with ogts.ExpectedError(): # Authoring node for Test was lost
await controller.evaluate(graph)
| 42,238 | Python | 45.776301 | 120 | 0.487168 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_nodes_01.py | """Action Graph Node Tests, Part 1"""
import time
import carb
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.app
import omni.kit.test
import omni.usd
from omni.graph.core import ThreadsafetyTestUtils
from pxr import Gf, OmniGraphSchemaTools, Sdf, Vt
# ======================================================================
class TestActionGraphNodes(ogts.OmniGraphTestCase):
"""Tests action graph node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
keys = og.Controller.Keys
E = og.ExecutionAttributeState.ENABLED
D = og.ExecutionAttributeState.DISABLED
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
# -----------------------------------------------------------------------
async def test_addprimrelationship_node(self):
"""Test AddPrimRelationship node"""
# Check that we can add a relationship to a prim and get that relationship.
#
# +---------+ +---------------------+
# | ONTICK +-->| AddPrimRelationship +
# +---------+ +---------------------+
#
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("AddRel", "omni.graph.action.AddPrimRelationship"),
],
self.keys.CREATE_PRIMS: [
("/Test", {}),
("/Target", {}),
],
self.keys.CONNECT: [("OnTick.outputs:tick", "AddRel.inputs:execIn")],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("AddRel.inputs:path", "/Test"),
("AddRel.inputs:name", "rel"),
("AddRel.inputs:target", "/Target"),
],
},
)
prim = stage.GetPrimAtPath("/Test")
await og.Controller.evaluate()
rel = prim.GetRelationship("rel")
targets = rel.GetTargets()
self.assertEqual(len(targets), 1)
self.assertTrue(str(targets[0]) == "/Target")
# ----------------------------------------------------------------------
# The Branch node has a built-in test construct in its .ogn file located at ../../nodes/OgnBranch.ogn
# (relative to the source location of the currently-opened testing script) AND is used in other testing
# methods, so we skip adding extra node-specific tests for it here.
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_counter_node(self, test_instance_id: int = 0):
"""Test Counter node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (ontick_node, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: ("OnTick.outputs:tick", "Counter.inputs:execIn"),
},
)
# Obtain necessary attributes.
in_exec_attr = counter_node.get_attribute("inputs:execIn")
in_reset_attr = counter_node.get_attribute("inputs:reset")
state_cnt_attr = counter_node.get_attribute("state:count")
out_exec_attr = counter_node.get_attribute("outputs:execOut")
out_cnt_attr = counter_node.get_attribute("outputs:count")
out_tick_attr = ontick_node.get_attribute("outputs:tick")
# Check that the counter node gets correctly incremented when executing.
self.assertEqual(state_cnt_attr.get(), 0)
self.assertEqual(out_cnt_attr.get(), 0)
self.assertEqual(out_exec_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(state_cnt_attr.get(), 1)
self.assertEqual(out_cnt_attr.get(), 1)
self.assertEqual(out_exec_attr.get(), self.E)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(state_cnt_attr.get(), 2)
self.assertEqual(out_cnt_attr.get(), 2)
self.assertEqual(out_exec_attr.get(), self.E)
# Check that the counter node doesn't increment when not executing.
og.Controller.disconnect(
out_tick_attr,
in_exec_attr,
)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(state_cnt_attr.get(), 2)
self.assertEqual(out_cnt_attr.get(), 2)
self.assertEqual(out_exec_attr.get(), self.E)
# Check that the reset flag for the Counter node instance works correctly when
# inputs:execIn is set to 0 (i.e. when the Counter node is NOT supposed to be
# executing).
og.Controller.connect(out_tick_attr, in_reset_attr)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(state_cnt_attr.get(), 0)
self.assertEqual(out_cnt_attr.get(), 0)
self.assertEqual(out_exec_attr.get(), self.E)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_delay_node(self, test_instance_id: int = 0):
"""Test Delay node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (on_impulse_node, _, counter_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Delay", "omni.graph.action.Delay"),
("Counter", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnImpulse.outputs:execOut", "Delay.inputs:execIn"),
("Delay.outputs:finished", "Counter.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("Delay.inputs:duration", 0.01),
],
},
)
# Obtain necessary attributes.
out_cnt_attr = counter_node.get_attribute("outputs:count")
state_enable_impulse_attr = on_impulse_node.get_attribute("state:enableImpulse")
# Trigger the graph(s) once.
state_enable_impulse_attr.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# Downstream execution is delayed, so the counter node won't be incremented.
self.assertEqual(out_cnt_attr.get(), 0)
# Wait to ensure that the delay finishes before checking that the counter node
# has indeed been incremented.
time.sleep(0.02)
yield ThreadsafetyTestUtils.EVALUATION_WAIT_FRAME # Yielding to compute by waiting for the next app frame.
self.assertEqual(out_cnt_attr.get(), 1)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_flipflop_node(self, test_instance_id: int = 0):
"""Test FlipFlop node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(graph, (_, flip_flop_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FlipFlop", "omni.graph.action.FlipFlop"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: (
"OnTick.outputs:tick",
"FlipFlop.inputs:execIn",
),
},
)
# Obtain necessary attributes.
out_a_attr = flip_flop_node.get_attribute("outputs:a")
out_b_attr = flip_flop_node.get_attribute("outputs:b")
out_isa_attr = flip_flop_node.get_attribute("outputs:isA")
# First eval, 'a'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.D)
self.assertTrue(out_isa_attr.get())
# Second eval 'b'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.E)
self.assertFalse(out_isa_attr.get())
# Third eval 'a'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.D)
self.assertTrue(out_isa_attr.get())
# Test that non-usd-backed FlipFlop nodes correctly
# set their execution-type attributes.
# Make sure that the node paths are prefaced with the path to the
# graph that they should reside in (so that each node creation command
# can be processed to produce unique nodes for each test instance)!
_, on_tick_no_usd = og.cmds.CreateNode(
graph=graph,
node_path=f"{graph_path}/OnTickNoUSD",
node_type="omni.graph.action.OnTick",
create_usd=False,
)
_, flip_flop_no_usd = og.cmds.CreateNode(
graph=graph,
node_path=f"{graph_path}/FlipFlopNoUSD",
node_type="omni.graph.action.FlipFlop",
create_usd=False,
)
# Obtain necessary attributes.
out_a_attr = flip_flop_no_usd.get_attribute("outputs:a")
out_b_attr = flip_flop_no_usd.get_attribute("outputs:b")
out_isa_attr = flip_flop_no_usd.get_attribute("outputs:isA")
on_tick_no_usd.get_attribute("inputs:onlyPlayback").set(False)
# Make sure that the node attribute paths are prefaced with the graph
# path that they reside in (so that each instanced node attribute can
# be uniquely processed)!
og.cmds.ConnectAttrs(
src_attr=f"{graph_path}/OnTickNoUSD.outputs:tick",
dest_attr=f"{graph_path}/FlipFlopNoUSD.inputs:execIn",
modify_usd=False,
)
# First eval, 'a'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.D)
self.assertTrue(out_isa_attr.get())
# Second eval 'b'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.D)
self.assertEqual(out_b_attr.get(), self.E)
self.assertFalse(out_isa_attr.get())
# Third eval 'a'.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_a_attr.get(), self.E)
self.assertEqual(out_b_attr.get(), self.D)
self.assertTrue(out_isa_attr.get())
# ----------------------------------------------------------------------
# The ForEach node has a built-in test construct in its .ogn file located at ../../nodes/OgnForEach.ogn
# (relative to the source location of the currently-opened testing script), so we skip adding extra
# node-specific tests for it here.
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_forloop_node(self, test_instance_id: int = 0):
"""Test ForLoop node"""
context = omni.usd.get_context()
stage = context.get_stage()
# Since we want to use the same prim across all graph instances in the
# thread-safety test, we add it to the threading cache like so:
prim = ThreadsafetyTestUtils.add_to_threading_cache(test_instance_id, stage.DefinePrim("/World/TestPrim"))
ThreadsafetyTestUtils.add_to_threading_cache(
test_instance_id,
prim.CreateAttribute("val1", Sdf.ValueTypeNames.Int2, False).Set(Gf.Vec2i(1, 1)),
)
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (_, _, _, _, _, _, write_node, finish_counter), _, _) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Const", "omni.graph.nodes.ConstantInt2"),
("StopNum", "omni.graph.nodes.ConstantInt"),
("Add", "omni.graph.nodes.Add"),
("Branch", "omni.graph.action.Branch"),
("For", "omni.graph.action.ForLoop"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
("FinishCounter", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Const.inputs:value", [1, 2]),
("StopNum.inputs:value", 3),
("Write1.inputs:name", "val1"),
("Write1.inputs:primPath", "/World/TestPrim"),
("Write1.inputs:usePath", True),
("Branch.inputs:condition", True),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "For.inputs:execIn"),
("StopNum.inputs:value", "For.inputs:stop"),
("For.outputs:loopBody", "Branch.inputs:execIn"),
("For.outputs:finished", "FinishCounter.inputs:execIn"),
("Branch.outputs:execTrue", "Write1.inputs:execIn"),
("For.outputs:value", "Add.inputs:a"),
("Const.inputs:value", "Add.inputs:b"),
("Add.outputs:sum", "Write1.inputs:value"),
],
},
)
# Evaluate the graph(s).
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertListEqual([3, 4], list(stage.GetAttributeAtPath("/World/TestPrim.val1").Get()))
self.assertEqual(3, write_node.get_compute_count())
self.assertEqual(1, finish_counter.get_compute_count())
# This tests make sure that a for loop writing arrays to diferent prims
# work as expected (OM-84129)
async def test_foreach_node_write_multiple_prim(self, test_instance_id: int = 0):
"""Test the foreach node writing arrays to output prims"""
og.Controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, _, (prim1, prim2), _) = og.Controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_PRIMS: [
("/World/Prim1", {"graph_output": ("Int[]", [])}),
("/World/Prim2", {"graph_output": ("Int[]", [])}),
],
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("For", "omni.graph.action.ForEach"),
("Write", "omni.graph.nodes.WritePrimAttribute"),
("MakeArray", "omni.graph.nodes.ConstructArray"),
],
self.keys.SET_VALUES: [
("For.inputs:arrayIn", {"type": "token[]", "value": ["/World/Prim1", "/World/Prim2"]}),
("OnTick.inputs:onlyPlayback", False),
("Write.inputs:name", "graph_output"),
("Write.inputs:usePath", True),
("Write.inputs:usdWriteBack", True),
("MakeArray.inputs:arraySize", 1),
],
self.keys.CONNECT: [
("OnTick.outputs:tick", "For.inputs:execIn"),
("For.outputs:loopBody", "Write.inputs:execIn"),
("For.outputs:element", "Write.inputs:primPath"),
("For.outputs:arrayIndex", "MakeArray.inputs:input0"),
("MakeArray.outputs:array", "Write.inputs:value"),
],
},
)
await omni.kit.app.get_app().next_update_async()
prim1_out = prim1.GetAttribute("graph_output")
prim2_out = prim2.GetAttribute("graph_output")
self.assertEqual(prim1_out.Get(), Vt.IntArray([0]))
self.assertEqual(prim2_out.Get(), Vt.IntArray([1]))
# ----------------------------------------------------------------------
# The Gate node has a built-in test construct in its .ogn file located at ../../nodes/OgnGate.ogn
# (relative to the source location of the currently-opened testing script) AND is used in other
# testing methods, so we skip adding extra node-specific tests for it here.
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_multigate_node(self, test_instance_id: int = 0):
"""Test Multigate node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
(_, (_, multigate_node), _, _) = og.Controller.edit(
{"graph_path": graph_path, "evaluator_name": "execution"},
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Multigate", "omni.graph.action.Multigate"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Multigate.inputs:execIn"),
],
},
)
# Add 5 extra outputs to the Multigate node.
for i in range(1, 6):
og.Controller.create_attribute(
multigate_node,
f"outputs:output{i}",
og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
# Obtain necessary attributes.
out_attr_0 = multigate_node.get_attribute("outputs:output0")
out_attr_1 = multigate_node.get_attribute("outputs:output1")
out_attr_2 = multigate_node.get_attribute("outputs:output2")
out_attr_3 = multigate_node.get_attribute("outputs:output3")
out_attr_4 = multigate_node.get_attribute("outputs:output4")
out_attr_5 = multigate_node.get_attribute("outputs:output5")
# Check that the Multigate node correctly cycles through each of its outputs.
# Note that we trigger an execution through the Multigate node via the OnTick node,
# whose onlyPlayback input we've set to False in order to trigger an execution each
# time we evaluate the graph(s).
for i in range(0, 6):
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 0) % 6}").get(), self.E)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 1) % 6}").get(), self.D)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 2) % 6}").get(), self.D)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 3) % 6}").get(), self.D)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 4) % 6}").get(), self.D)
self.assertEqual(multigate_node.get_attribute(f"outputs:output{(i + 5) % 6}").get(), self.D)
# Next try removing some output attributes during evaluation and test if the
# Multigate node correctly cycles through.
for _ in range(4):
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.D)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.E)
self.assertEqual(out_attr_4.get(), self.D)
self.assertEqual(out_attr_5.get(), self.D)
multigate_node.remove_attribute("outputs:output4")
# The Multigate node cycles back to 0 instead of going to 5 since it thinks that it's
# reached the end of its outputs list (i.e. it expects to jump from pin 3 to 4, but b/c
# there is no such pin it goes back to 0 rather than 5).
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_attr_0.get(), self.E)
self.assertEqual(out_attr_1.get(), self.D)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.D)
self.assertEqual(out_attr_5.get(), self.D)
# Further showing that executing 4 times brings us back to pin 0 rather than pin 5.
for _ in range(4):
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_attr_0.get(), self.E)
self.assertEqual(out_attr_1.get(), self.D)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.D)
self.assertEqual(out_attr_5.get(), self.D)
# Execute the graph(s) once, then remove the currently-enabled output pin. The Multigate node will think
# that it's reached the end of the outputs list, and cycle back. Because we removed pin 1, it'll go
# back to pin 0 and never cycle through the other outputs since it cannot make the jump from
# pin 0 to 2 (as mentioned previously).
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
multigate_node.remove_attribute("outputs:output1")
for _ in range(3):
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_attr_0.get(), self.E)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.D)
self.assertEqual(out_attr_5.get(), self.D)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_multisequence_node(self, test_instance_id: int = 0):
"""Test Multisequence node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(
_,
(on_tick_node, multisequence_node, counter0_node, counter1_node, counter2_node),
_,
_,
) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Multisequence", "omni.graph.action.Multisequence"),
("Counter0", "omni.graph.action.Counter"),
("Counter1", "omni.graph.action.Counter"),
("Counter2", "omni.graph.action.Counter"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: [
("OnTick.outputs:tick", "Multisequence.inputs:execIn"),
],
},
)
# Add 3 extra outputs to the Multisequence node.
for j in range(1, 4):
og.Controller.create_attribute(
multisequence_node,
f"outputs:output{j}",
og.Type(og.BaseDataType.UINT, 1, 0, og.AttributeRole.EXECUTION),
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT,
)
# Obtain necessary attributes.
out_attr_0 = multisequence_node.get_attribute("outputs:output0")
out_attr_1 = multisequence_node.get_attribute("outputs:output1")
out_attr_2 = multisequence_node.get_attribute("outputs:output2")
out_attr_3 = multisequence_node.get_attribute("outputs:output3")
in_exec_attr_0 = counter0_node.get_attribute("inputs:execIn")
in_exec_attr_1 = counter1_node.get_attribute("inputs:execIn")
in_exec_attr_2 = counter2_node.get_attribute("inputs:execIn")
out_cnt_attr_0 = counter0_node.get_attribute("outputs:count")
out_cnt_attr_1 = counter1_node.get_attribute("outputs:count")
out_cnt_attr_2 = counter2_node.get_attribute("outputs:count")
in_onlyplayback_attr = on_tick_node.get_attribute("inputs:onlyPlayback")
# Connect Multisequence node output attributes to the counter nodes.
og.Controller.connect(out_attr_0, in_exec_attr_0)
og.Controller.connect(out_attr_2, in_exec_attr_1)
og.Controller.connect(out_attr_1, in_exec_attr_2)
# Check that the Multisequence node correctly executes through its outputs when input
# execution is enabled via the OnTick node. This is done by checking whether
# each counter has been incremented by 1, and if the last output pin on the
# Multisequence node remains enabled (regardless of the fact that it's not connected
# downstream).
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 1)
self.assertEqual(out_cnt_attr_1.get(), 1)
self.assertEqual(out_cnt_attr_2.get(), 1)
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.D)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.E)
# Connect the Counter2 node to another Multisequence output pin.
og.Controller.connect(out_attr_3, in_exec_attr_2)
# Once again evaluate the graph(s). In this situation the Counter2 node should be incremented twice
# (since it's connected to 2 separate Multisequence output pins). Also Multisequence output pins
# 1 AND 3 should both be enabled by the end of the execution; this is because pin 3 would
# typically be the last output that gets enabled, but because pin 3 shares a downstream
# node with pin 1 (that node being Counter2), both outputs need to be enabled by the end.
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 2)
self.assertEqual(out_cnt_attr_1.get(), 2)
self.assertEqual(out_cnt_attr_2.get(), 3)
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.E)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.E)
# Set the OnTick node to only trigger downstream execution when playback is enabled; check
# that in this situation the Multisequence node correctly skips executing through its outputs
# (i.e. that the Counter nodes don't get incremented). The state of the Multisequence's output
# pins should not have changed since the last graph evaluation.
in_onlyplayback_attr.set(True)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 2)
self.assertEqual(out_cnt_attr_1.get(), 2)
self.assertEqual(out_cnt_attr_2.get(), 3)
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.E)
self.assertEqual(out_attr_2.get(), self.D)
self.assertEqual(out_attr_3.get(), self.E)
# Try removing an output attribute from the Multisequence node, check that all other
# outputs that come before in the list get triggered. In this example we remove outputs2,
# which means that outputs3 won't get triggered at all (as evidenced by the fact that the
# Counter2 node only gets incremented once by output1).
og.Controller.disconnect(out_attr_2, in_exec_attr_1)
multisequence_node.remove_attribute("outputs:output2")
in_onlyplayback_attr.set(False)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_cnt_attr_0.get(), 3)
self.assertEqual(out_cnt_attr_1.get(), 2)
self.assertEqual(out_cnt_attr_2.get(), 4)
self.assertEqual(out_attr_0.get(), self.D)
self.assertEqual(out_attr_1.get(), self.E)
self.assertEqual(out_attr_3.get(), self.D)
# ----------------------------------------------------------------------
@ThreadsafetyTestUtils.make_threading_test
def test_once_node(self, test_instance_id: int = 0):
"""Test Once node"""
# Instance a test graph setup. Note that we append the graph path with the test_instance_id
# so that the graph can be uniquely identified in the thread-safety test!
graph_path = self.TEST_GRAPH_PATH + str(test_instance_id)
og.Controller.create_graph({"graph_path": graph_path, "evaluator_name": "execution"})
(_, (ontick_node, once_node), _, _,) = og.Controller.edit(
graph_path,
{
self.keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Once", "omni.graph.action.Once"),
],
self.keys.SET_VALUES: [("OnTick.inputs:onlyPlayback", False)],
self.keys.CONNECT: ("OnTick.outputs:tick", "Once.inputs:execIn"),
},
)
# Obtain necessary attributes.
in_exec_attr = once_node.get_attribute("inputs:execIn")
in_reset_attr = once_node.get_attribute("inputs:reset")
out_once_attr = once_node.get_attribute("outputs:once")
out_after_attr = once_node.get_attribute("outputs:after")
out_tick_attr = ontick_node.get_attribute("outputs:tick")
# Check that the Once node controls flow of execution by passing flow
# differently the first time it's executed compared to all subsequent
# executions.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.E)
self.assertEqual(out_after_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.E)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.E)
# Check that the reset flag works correctly when inputs:execIn is set to 0 (i.e. when
# the Once node is NOT supposed to be executing).
og.Controller.disconnect(out_tick_attr, in_exec_attr)
og.Controller.connect(out_tick_attr, in_reset_attr)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.D)
og.Controller.disconnect(out_tick_attr, in_reset_attr)
og.Controller.connect(out_tick_attr, in_exec_attr)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.E)
self.assertEqual(out_after_attr.get(), self.D)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
self.assertEqual(out_once_attr.get(), self.D)
self.assertEqual(out_after_attr.get(), self.E)
# Check that when both the execIn and reset input attributes get triggered, the latter
# overrides the former and execution flow does not pass through outputs:after.
# FIXME: Something about the 2nd connection here is messing up the data model such
# that inputs:reset is being read as 0 inside the node
og.Controller.connect(out_tick_attr, in_reset_attr)
yield # Yielding to wait for compute to happen across all graph instances before continuing the test.
# self.assertEqual(out_once_attr.get(), self.D)
# self.assertEqual(out_after_attr.get(), self.D)
# ----------------------------------------------------------------------
# NOTE: Even though the OnClosing node is threadsafe (its compute method is very simple),
# we don't adapt the below test to check for thread-safety conditions because it relies
# on other nodes (omni.graph.action.SendCustomEvent and omni.graph.nodes.GraphTarget)
# which are NOT threadsafe.
async def test_onclosing_node(self):
"""Test OnClosing node"""
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# Testing OnClosing is tricky because OG is being destroyed when it happens -
# so test by sending a custom event when the network is triggered
# and then checking if we got that event.
def registered_event_name(event_name):
"""Returns the internal name used for the given custom event name"""
name = "omni.graph.action." + event_name
return carb.events.type_from_string(name)
got_event = [0]
def on_event(_):
got_event[0] = got_event[0] + 1
reg_event_name = registered_event_name("foo")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_push_by_type(reg_event_name, on_event)
self.assertIsNotNone(sub)
async def set_up_graph():
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnClosing", "omni.graph.action.OnClosing"),
("Send", "omni.graph.action.SendCustomEvent"),
("GraphTarget", "omni.graph.nodes.GraphTarget"),
],
keys.CONNECT: [
("OnClosing.outputs:execOut", "Send.inputs:execIn"),
("GraphTarget.outputs:primPath", "Send.inputs:path"),
],
keys.SET_VALUES: [("Send.inputs:eventName", "foo")],
},
)
await set_up_graph()
# Evaluate once so that the standalone graph is in steady state.
await omni.kit.app.get_app().next_update_async()
self.assertEqual(got_event[0], 0)
# Close the stage.
usd_context = omni.usd.get_context()
(result, _) = await usd_context.close_stage_async()
self.assertTrue(result)
# Check our handler was called.
self.assertEqual(got_event[0], 1)
# Reset the counter.
got_event[0] = 0
# Now check that the same works with instanced graphs.
await usd_context.new_stage_async()
await set_up_graph()
og.cmds.SetEvaluationMode(
graph=og.get_graph_by_path(self.TEST_GRAPH_PATH),
new_evaluation_mode=og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED,
)
stage = usd_context.get_stage()
prims = [stage.DefinePrim(f"/prim_{i}") for i in range(0, 100)]
for prim in prims:
OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim.GetPath(), self.TEST_GRAPH_PATH)
# Wait an update for the graphs to get set up.
await omni.kit.app.get_app().next_update_async()
# Close the stage.
(result, _) = await usd_context.close_stage_async()
self.assertTrue(result)
# Check that our handler was called.
self.assertEqual(got_event[0], len(prims))
# ----------------------------------------------------------------------
async def test_oncustomevent_and_sendcustomevent_nodes(self):
"""Test OnCustomEvent and SendCustomEvent nodes"""
controller = og.Controller()
controller.create_graph({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
(_, (_, _, event1_node, counter1_node, event2_node, counter2_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Send", "omni.graph.action.SendCustomEvent"),
("OnCustomEvent1", "omni.graph.action.OnCustomEvent"),
("Counter1", "omni.graph.action.Counter"),
("OnCustomEvent2", "omni.graph.action.OnCustomEvent"),
("Counter2", "omni.graph.action.Counter"),
],
self.keys.CONNECT: [
("OnImpulse.outputs:execOut", "Send.inputs:execIn"),
("OnCustomEvent1.outputs:execOut", "Counter1.inputs:execIn"),
("OnCustomEvent2.outputs:execOut", "Counter2.inputs:execIn"),
],
self.keys.SET_VALUES: [
("OnCustomEvent1.inputs:onlyPlayback", False),
("OnCustomEvent2.inputs:onlyPlayback", False),
("OnImpulse.inputs:onlyPlayback", False),
("Send.inputs:eventName", "foo"),
("Send.inputs:path", "Test Path"),
("OnCustomEvent1.inputs:eventName", "foo"),
("OnCustomEvent2.inputs:eventName", "foo"),
],
},
)
counter1_controller = og.Controller(og.Controller.attribute("outputs:count", counter1_node))
counter2_controller = og.Controller(og.Controller.attribute("outputs:count", counter2_node))
event1_controller = og.Controller(og.Controller.attribute("outputs:path", event1_node))
event2_controller = og.Controller(og.Controller.attribute("outputs:path", event2_node))
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 0)
# Trigger graph once, this will queue up the event for the next evaluation.
controller.edit(self.TEST_GRAPH_PATH, {self.keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
# Note that if this is a push subscription, the receivers will run this frame instead of next.
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 0)
# This evaluation should trigger the receivers.
await omni.kit.app.get_app().next_update_async()
# Verify that events were received.
self.assertEqual(counter1_controller.get(), 1)
self.assertEqual(event1_controller.get(), "Test Path")
self.assertEqual(counter2_controller.get(), 1)
self.assertEqual(event2_controller.get(), "Test Path")
# Verify the contents of the associated bundle.
# FIXME: Authored bundle is always empty?
# bundle_contents = og.BundleContents(graph.get_default_graph_context(), event1_node, "outputs:bundle", True)
# self.assertEqual(1, bundle_contents.size)
# Modify the event name one receiver and sender and ensure it still works.
controller.edit(
self.TEST_GRAPH_PATH,
{
self.keys.SET_VALUES: [("Send.inputs:eventName", "bar"), ("OnImpulse.state:enableImpulse", True)],
},
)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# We changed the sender event name, so counter should NOT have triggered again.
self.assertEqual(counter1_controller.get(), 1)
# Change the receiver name to match.
controller.edit(self.TEST_GRAPH_PATH, {self.keys.SET_VALUES: ("OnCustomEvent1.inputs:eventName", "bar")})
await omni.kit.app.get_app().next_update_async()
# Trigger send again and verify we get it (1 frame lag for pop).
controller.edit(self.TEST_GRAPH_PATH, {self.keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(counter1_controller.get(), 2)
| 42,965 | Python | 50.089179 | 117 | 0.59218 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_action_graph_evaluation_01.py | """Action Graph Evaluation Tests, Part 1"""
import asyncio
import json
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
# ======================================================================
class TestActionGraphEvaluation(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_active_latent(self):
"""Exercise a latent node that executes downstream nodes while latent"""
# +--------+ +----------+finished+-------------+
# | OnTick+-->| Countdown+-------->FinishCounter|
# +--------+ | | +-------------+
# | +-+
# +----------+ | +------------+ +------------+ +------------+
# +-----> TickCounter+----->TickCounter2+---->TickCounter3|
# tick +------------+ +------------+ +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Countdown", "omni.graph.action.Countdown"),
("FinishCounter", "omni.graph.action.Counter"),
("TickCounter", "omni.graph.action.Counter"),
("TickCounter2", "omni.graph.action.Counter"),
("TickCounter3", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Countdown.inputs:execIn"),
("Countdown.outputs:finished", "FinishCounter.inputs:execIn"),
("Countdown.outputs:tick", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickCounter2.inputs:execIn"),
("TickCounter2.outputs:execOut", "TickCounter3.inputs:execIn"),
],
keys.SET_VALUES: [("Countdown.inputs:duration", 3), ("OnTick.inputs:onlyPlayback", False)],
},
)
(_, _, finish_counter, tick_counter, _, tick_counter_3) = nodes
finish_counter_controller = og.Controller(og.Controller.attribute("outputs:count", finish_counter))
tick_counter_controller = og.Controller(og.Controller.attribute("outputs:count", tick_counter))
tick_counter_3_controller = og.Controller(og.Controller.attribute("outputs:count", tick_counter_3))
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
await controller.evaluate(graph)
self.assertEqual(tick_counter_controller.get(), 1)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
self.assertEqual(tick_counter_controller.get(), 2)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
self.assertEqual(tick_counter_3_controller.get(), 3)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 1)
self.assertEqual(tick_counter_3_controller.get(), 3)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 1)
self.assertEqual(tick_counter_3_controller.get(), 3)
# ----------------------------------------------------------------------
async def test_async_nodes(self):
"""Test asynchronous action nodes"""
# Check that a nested loop state is maintained when executing a latent delay.
#
# +---------+ +----------+ +----------+ +-------+ +--------+
# | IMPULSE +-->| FOR-LOOP +--->| FOR-LOOP +--->| DELAY +--->| COUNTER|
# +---------+ +----------+ +----------+ +-------+ +--------+
#
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, _, counter_node, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ForLoop1", "omni.graph.action.ForLoop"),
("ForLoop2", "omni.graph.action.ForLoop"),
("Delay", "omni.graph.action.Delay"),
("Counter", "omni.graph.action.Counter"),
("OnTick", "omni.graph.action.OnTick"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "ForLoop2.inputs:execIn"),
("ForLoop2.outputs:loopBody", "Delay.inputs:execIn"),
("Delay.outputs:finished", "Counter.inputs:execIn"),
("OnTick.outputs:tick", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("OnImpulse.inputs:onlyPlayback", False),
("Delay.inputs:duration", 0.1),
("ForLoop1.inputs:stop", 2),
("ForLoop2.inputs:stop", 5),
],
},
)
await controller.evaluate(graph)
# Trigger graph once.
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# In delay now, no count.
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
self.assertEqual(counter_controller.get(), 0)
# Wait to ensure the first 5 delays compute.
for _ in range(5):
await asyncio.sleep(0.2)
await controller.evaluate(graph)
count_val = counter_controller.get()
self.assertGreater(count_val, 4)
# Wait and verify the remainder go through.
for _ in range(5):
await asyncio.sleep(0.1)
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 10)
# ----------------------------------------------------------------------
async def test_chained_stateful_nodes(self):
"""Test that chaining loop nodes works"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("ForLoop1", "omni.graph.action.ForLoop"),
("ForLoop2", "omni.graph.action.ForLoop"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "ForLoop2.inputs:execIn"),
("ForLoop2.outputs:loopBody", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("ForLoop1.inputs:stop", 5),
("ForLoop2.inputs:stop", 5),
],
},
)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_node)), 5 * 5)
# ----------------------------------------------------------------------
async def test_cycle_break(self):
"""Test that an illegal cycle issues a warning"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (on_impulse, count_a, count_b), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("A", "omni.graph.action.Counter"),
("B", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "A.inputs:execIn"),
("A.outputs:execOut", "B.inputs:execIn"),
("B.outputs:execOut", "A.inputs:execIn"),
],
keys.SET_VALUES: [
("OnImpulse.state:enableImpulse", True),
("OnImpulse.inputs:onlyPlayback", False),
],
},
)
with ogts.ExpectedError():
await controller.evaluate(graph)
og.Controller.set(controller.attribute("state:enableImpulse", on_impulse), True)
with ogts.ExpectedError():
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", count_a)), 2)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", count_b)), 2)
# ----------------------------------------------------------------------
async def test_dep_sort_fan_out(self):
"""Test that dependency sort works when there is data fan-out"""
# +-------------+
# +-------->| |
# | | SwitchTokenA|
# | +--->+-------------+
# +----------+ |
# |OnImpulse +----|------+ +--------------+
# +----------+ | +---------->| SwitchTokenB |
# | +^-------------+
# +------+-+ +--------+ |
# | ConstA +--->AppendB +---+
# +--------+ +--------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, _, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ConstA", "omni.graph.nodes.ConstantToken"),
("AppendB", "omni.graph.nodes.AppendString"),
("SwitchTokenA", "omni.graph.action.SwitchToken"),
("SwitchTokenB", "omni.graph.action.SwitchToken"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "SwitchTokenA.inputs:execIn"),
("OnImpulse.outputs:execOut", "SwitchTokenB.inputs:execIn"),
("ConstA.inputs:value", "SwitchTokenA.inputs:value"),
("ConstA.inputs:value", "AppendB.inputs:value"),
("AppendB.outputs:value", "SwitchTokenB.inputs:value"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("AppendB.inputs:suffix", {"value": "Foo", "type": "token"}),
],
},
)
await controller.evaluate(graph)
graph_state = og.OmniGraphInspector().as_json(graph, flags=["evaluation"])
graph_state_obj = json.loads(graph_state)
trace = graph_state_obj["Evaluator"]["Instances"][0]["LastNonEmptyEvaluation"]["Trace"]
# The switches can run in any order
self.assertTrue(
trace in (["SwitchTokenA", "AppendB", "SwitchTokenB"], ["AppendB", "SwitchTokenB", "SwitchTokenA"])
)
# ----------------------------------------------------------------------
async def test_diamond_fan(self):
"""Test latent nodes in parallel fan-out which fan-in to a downstream node"""
# +--------++ +----------+
# +--> TickA +--->|FinishedA |---+
# | +---------+ +----------+ |
# +---------+ +-----------+ | | +------------+
# |OnImpulse+-->|TickCounter+-+ +-->|MergeCounter|
# +---------+ +-----------+ | | +------------+
# | +---------+ +----------+ |
# +-->| TickB +--->|FinishedB |--+
# +--------++ +----------+
# | +---------+
# +-->| TickC |
# +--------++
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickCounter", "omni.graph.action.Counter"),
("TickA", "omni.graph.action.Countdown"),
("TickB", "omni.graph.action.Countdown"),
("TickC", "omni.graph.action.Countdown"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
("MergeCounter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickA.inputs:execIn"),
("TickCounter.outputs:execOut", "TickB.inputs:execIn"),
("TickCounter.outputs:execOut", "TickC.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
("FinishCounterA.outputs:execOut", "MergeCounter.inputs:execIn"),
("FinishCounterB.outputs:execOut", "MergeCounter.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 1),
("TickB.inputs:duration", 1),
("TickC.inputs:duration", 1),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, tick_counter, _, _, tick_c, finish_counter_a, finish_counter_b, merge_counter) = nodes
def check_counts(t_c, f_a, f_b, m_c, tick_c_count):
for node, expected in (
(tick_counter, t_c),
(finish_counter_a, f_a),
(finish_counter_b, f_b),
(merge_counter, m_c),
):
count = og.Controller.get(controller.attribute("outputs:count", node))
self.assertEqual(count, expected, node.get_prim_path())
self.assertEqual(tick_c.get_compute_count(), tick_c_count)
self.assertEqual(tick_c.get_compute_count(), 0)
# Set up latent tickers.
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 1)
# Latent ticks.
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 2)
# Both branches complete.
await controller.evaluate(graph)
check_counts(1, 1, 1, 2, 3)
# No count changes + no additional computes of tickC.
await controller.evaluate(graph)
check_counts(1, 1, 1, 2, 3)
# ----------------------------------------------------------------------
async def test_diamond_latent_fan(self):
"""Test latent nodes in parallel fan-out which fan-in to a latent downstream node"""
# +--------++
# +--> TickA +--+
# | +---------+ |
# +---------+ | | +-------+ +-------+
# |OnImpulse+-->+ +-->|TickD +-+--->|CountF |
# +---------+ | | +-------+ | +-------+
# | +--------+ | +--->+-------+
# +-->| TickB +--+ |TickE |
# | +--------+ +--->+-------+
# | +--------+ |
# +-->| TickC +----------------+
# +--------+
# Note that when TickA triggers TickD into latent state, then TickB hits TickD subsequently. This subsequent
# evaluation is _transient_. Meaning that TickB will not block on a new copy of TickD.
# This is because there is only one TickD so there can be only one state (latent or not).
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.Countdown"),
("TickB", "omni.graph.action.Countdown"),
("TickC", "omni.graph.action.Countdown"),
("TickD", "omni.graph.action.Countdown"),
("TickE", "omni.graph.action.Countdown"),
("CountF", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("OnImpulse.outputs:execOut", "TickB.inputs:execIn"),
("OnImpulse.outputs:execOut", "TickC.inputs:execIn"),
("TickA.outputs:finished", "TickD.inputs:execIn"),
("TickB.outputs:finished", "TickD.inputs:execIn"),
("TickC.outputs:finished", "TickE.inputs:execIn"),
("TickD.outputs:finished", "TickE.inputs:execIn"),
("TickD.outputs:finished", "CountF.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 1),
("TickB.inputs:duration", 1),
("TickC.inputs:duration", 2),
("TickD.inputs:duration", 1),
("TickE.inputs:duration", 1),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, tick_a, tick_b, tick_c, tick_d, tick_e, count_f) = nodes
def check_counts(i, t_a, t_b, t_c, t_d, t_e):
for node, expected in ((tick_a, t_a), (tick_b, t_b), (tick_c, t_c), (tick_d, t_d), (tick_e, t_e)):
self.assertEqual(node.get_compute_count(), expected, f"Check {i} for {node.get_prim_path()}")
# A, B, C, D, E
compute_counts = [
(1, 1, 1, 0, 0), # 0. fan out to trigger A, B, C into latent state
(2, 2, 2, 0, 0), # 1. A, B, C tick
(3, 3, 3, 2, 0), # 2. A, B end latent, D into latent via A or B, D ticks via A or B, C ticks
(3, 3, 4, 3, 2), # 3.
(3, 3, 4, 3, 3), # 4.
(3, 3, 4, 3, 3), # 5.
(3, 3, 4, 3, 3), # 6.
]
for i, c_c in enumerate(compute_counts):
await controller.evaluate(graph)
check_counts(i, *c_c)
# Verify that CountF has computed 1x due to the fan-in at TickD NOT acting like separate threads.
self.assertEqual(count_f.get_compute_count(), 1)
# ----------------------------------------------------------------------
async def test_dynamic_exec_pins(self):
"""Test that adding execution pins to a non-action node works"""
controller = og.Controller()
keys = og.Controller.Keys
(_, (on_tick, to_string), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("ToString", "omni.graph.nodes.ToString"),
],
keys.SET_VALUES: [
("ToString.inputs:value", 42, "double"),
("OnTick.inputs:onlyPlayback", False),
],
},
)
# Verify to_string has not been computed.
await controller.evaluate()
self.assertEqual(0, to_string.get_compute_count())
self.assertEqual(1, on_tick.get_compute_count())
# Add execution attribs and verify it still doesn't get computed.
attrib = og.Controller.create_attribute(
to_string,
"inputs:execIn",
"execution",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT,
)
self.assertIsNotNone(attrib)
await controller.evaluate()
self.assertEqual(0, to_string.get_compute_count())
self.assertEqual(2, on_tick.get_compute_count())
# Hook up to OnTick and verify it is now computing.
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CONNECT: [
("OnTick.outputs:tick", "ToString.inputs:execIn"),
]
},
)
for i in range(10):
await controller.evaluate()
self.assertEqual(i + 1, to_string.get_compute_count())
self.assertEqual(i + 3, on_tick.get_compute_count())
# ----------------------------------------------------------------------
async def test_exec_fan_out(self):
"""Test that fanning out from an exec port works"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FF1", "omni.graph.action.FlipFlop"),
("FF2", "omni.graph.action.FlipFlop"),
("FF11", "omni.graph.action.FlipFlop"),
("FF12", "omni.graph.action.FlipFlop"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
keys.CONNECT: [
("OnTick.outputs:tick", "FF1.inputs:execIn"),
("OnTick.outputs:tick", "FF2.inputs:execIn"),
("FF1.outputs:a", "FF11.inputs:execIn"),
("FF1.outputs:a", "FF12.inputs:execIn"),
],
},
)
# 1. OnTick triggers FF1 which triggers FF11 and FF12, then FF2.
# 2. OnTick triggers FF1 and FF2.
# 3. OnTick triggers FF1 which triggers FF11 and FF12, then FF2.
await controller.evaluate(graph)
flip_flops = nodes[1:]
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [True, True, True, True])
await controller.evaluate(graph)
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [False, False, True, True])
await controller.evaluate(graph)
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [True, True, False, False])
# ----------------------------------------------------------------------
async def test_exec_fan_out_shared_deps(self):
"""Test that dependency sort works when there is shared data in exec fan-out"""
# +---------+
# +---------->| Write1 |
# | +----^----+
# | |
# | +----------+
# | |
# +-----------+ | |
# | OnImpulse +-----+-----+----> +---------+
# +-----------+ | | | Write2 |
# | +----->+---------+
# | |
# | | +---------+
# +-----+----->| Write3 |
# | +---------+
# | ^
# +-------+ +---+----+---+
# | Const +----->| Inc |
# +-------+ +--------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, _, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Const", "omni.graph.nodes.ConstantDouble"),
("Inc", "omni.graph.nodes.Increment"),
("Write1", "omni.graph.nodes.WritePrimAttribute"),
("Write2", "omni.graph.nodes.WritePrimAttribute"),
("Write3", "omni.graph.nodes.WritePrimAttribute"),
],
keys.CREATE_PRIMS: [
("/World/TestPrim1", {"val": ("double", 1.0)}),
("/World/TestPrim2", {"val": ("double", 2.0)}),
("/World/TestPrim3", {"val": ("double", 3.0)}),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Write1.inputs:execIn"),
("OnImpulse.outputs:execOut", "Write2.inputs:execIn"),
("OnImpulse.outputs:execOut", "Write3.inputs:execIn"),
("Const.inputs:value", "Inc.inputs:value"),
("Inc.outputs:result", "Write1.inputs:value"),
("Inc.outputs:result", "Write2.inputs:value"),
("Inc.outputs:result", "Write3.inputs:value"),
],
keys.SET_VALUES: [
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
("Const.inputs:value", 41.0),
("Inc.inputs:increment", 1.0),
("Write1.inputs:primPath", "/World/TestPrim1"),
("Write1.inputs:usePath", True),
("Write1.inputs:name", "val"),
("Write2.inputs:primPath", "/World/TestPrim2"),
("Write2.inputs:usePath", True),
("Write2.inputs:name", "val"),
("Write3.inputs:primPath", "/World/TestPrim3"),
("Write3.inputs:usePath", True),
("Write3.inputs:name", "val"),
],
},
)
await controller.evaluate(graph)
stage = omni.usd.get_context().get_stage()
for i in (1, 2, 3):
self.assertEqual(stage.GetAttributeAtPath(f"/World/TestPrim{i}.val").Get(), 42.0)
# ----------------------------------------------------------------------
async def test_exec_sort_failure(self):
"""Test that sorting dependencies with non-trivial authored graph"""
# Our global sort excludes exec nodes, so a global topo (Kahn) sort will fail such that Inc3 doesn't get
# computed until after Add2, so instead we sort each dep network independently. This test verifies the case
# where that matters.
#
# +-----------------------------> Write1(var) +----------------------------------------+
# | ^ | |
# | | | v
# OnTick --------------------+ | +-----------Inc------------+ Write2(var2)
# | | | ^
# v | | |
# Read1(var)------------> Add1 --Inc2--+ v |
# Inc3 --------------> Add2 ---------------+
controller = og.Controller()
keys = og.Controller.Keys
(_, (on_tick, a_1, a_2, _, _, _, _, _, _), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("A1", "omni.graph.nodes.Add"),
("A2", "omni.graph.nodes.Add"),
("Write1", "omni.graph.core.WriteVariable"),
("Write2", "omni.graph.core.WriteVariable"),
("Read1", "omni.graph.core.ReadVariable"),
("Inc", "omni.graph.nodes.Increment"),
("Inc2", "omni.graph.nodes.Increment"),
("Inc3", "omni.graph.nodes.Increment"),
],
keys.CREATE_VARIABLES: [
("var", og.Type(og.BaseDataType.DOUBLE)),
("var2", og.Type(og.BaseDataType.DOUBLE)),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Inc3.inputs:value", {"type": "double", "value": 42.0}),
("Write1.inputs:variableName", "var"),
("Write2.inputs:variableName", "var2"),
("Read1.inputs:variableName", "var"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Write1.inputs:execIn"),
("OnTick.outputs:timeSinceStart", "A1.inputs:a"),
("Read1.outputs:value", "A1.inputs:b"),
("A1.outputs:sum", "Inc2.inputs:value"),
("Inc2.outputs:result", "Write1.inputs:value"),
("Write1.outputs:execOut", "Write2.inputs:execIn"),
("Write1.outputs:value", "Inc.inputs:value"),
("Inc.outputs:result", "A2.inputs:a"),
("Inc3.outputs:result", "A2.inputs:b"),
("A2.outputs:sum", "Write2.inputs:value"),
],
},
)
await omni.kit.app.get_app().next_update_async()
a_1_v = og.Controller.get(controller.attribute("outputs:sum", a_1))
a_2_v = og.Controller.get(controller.attribute("outputs:sum", a_2))
on_tick_dt = og.Controller.get(controller.attribute("outputs:timeSinceStart", on_tick))
a_1_expected = 0 + on_tick_dt
a_2_expected = (a_1_expected + 1.0 + 1.0) + (42.0 + 1.0)
self.assertAlmostEqual(a_1_v, a_1_expected, places=3)
self.assertAlmostEqual(a_2_v, a_2_expected, places=3)
# ----------------------------------------------------------------------
async def test_fan_in(self):
"""Test that fan-in of execution connections works as expected (from a loaded test .usda file)"""
(result, error) = await ogts.load_test_file("TestActionFanIn.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
graph_path = "/World/ActionGraph"
controller = og.Controller()
graph = controller.graph(graph_path)
# Trigger the loop.
og.Controller.set(controller.attribute(f"{graph_path}/on_impulse_event.state:enableImpulse"), True)
await controller.evaluate(graph)
graph_state = og.OmniGraphInspector().as_json(controller.graph(graph_path), flags=["evaluation"])
graph_state_obj = json.loads(graph_state)
trace = graph_state_obj["Evaluator"]["Instances"][0]["LastNonEmptyEvaluation"]["Trace"]
# Verify the first loop iteration.
self.assertEqual("for_loop", trace[0])
# These nodes can compute in any order
self.assertEqual(["counter", "counter_01"], sorted(trace[1:3]))
expected_trace = [
"to_uint64",
"sync_gate",
"to_uint64",
"sync_gate",
]
self.assertListEqual(expected_trace, trace[3:7])
trace[0:7] = []
# Verify downstream from sync gate.
expected_trace = [
"counter_02",
]
self.assertListEqual(expected_trace, trace[0:1])
trace[0 : len(expected_trace)] = []
# Verify second iteration.
self.assertEqual("for_loop", trace[0])
# These nodes can compute in any order
self.assertEqual(["counter", "counter_01"], sorted(trace[1:3]))
expected_trace = [
"to_uint64",
"sync_gate",
"to_uint64",
"sync_gate",
]
self.assertListEqual(expected_trace, trace[3:7])
# ----------------------------------------------------------------------
async def test_loading_type_resol(self):
"""Test that loading a file with weird type resolution pattern works"""
(result, error) = await ogts.load_test_file("load_with_type_resol.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
graph_path = "/World/ActionGraph"
controller = og.Controller()
graph = controller.graph(graph_path)
# eval
await controller.evaluate(graph)
# check result
var = graph.find_variable("Result")
val = var.get_array(graph.get_default_graph_context(), False, 0)
self.assertTrue((val == [(-50, -50, -50), (50, 50, 50)]).all())
# ----------------------------------------------------------------------
async def test_fan_in_exec(self):
"""Test that execution fan-in is handled correctly"""
# The evaluator has to consider the case that gate.enter will have contradicting upstream values.
# Gate needs to know which input is active, it needs the value of enter to be ENABLED when it
# is triggered by OnTick, even though OnTickDisabled has set it's output to the same attrib as DISABLED.
#
# +--------------+
# |OnImpulseEvent+---+ +-----------+
# +--------------+ | |Gate |
# +--->toggle |
# +--------------+ | |
# |OnTick +------>|enter |
# +--------------+ +^-----exit-+
# |
# +--------------+ |
# |OnTickDisabled+--------+
# +--------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, gate, on_impulse_event), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("OnTickDisabled", "omni.graph.action.OnTick"),
("Gate", "omni.graph.action.Gate"),
("OnImpulseEvent", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Gate.inputs:enter"),
("OnTickDisabled.outputs:tick", "Gate.inputs:enter"),
("OnImpulseEvent.outputs:execOut", "Gate.inputs:toggle"),
],
keys.SET_VALUES: [
("Gate.inputs:startClosed", True),
("OnTick.inputs:onlyPlayback", False),
("OnImpulseEvent.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
gate_exit = controller.attribute("outputs:exit", gate)
# Verify the Gate has not triggered.
self.assertFalse(gate_exit.get())
await controller.evaluate(graph)
self.assertFalse(gate_exit.get())
# Toggle the gate and verify that the tick goes through. The first evaluate it isn't known if the Gate will
# trigger because the order that entry points are executed is not defined... FIXME.
controller.attribute("state:enableImpulse", on_impulse_event).set(True)
await controller.evaluate(graph)
await controller.evaluate(graph)
self.assertTrue(gate_exit.get())
# ----------------------------------------------------------------------
async def test_fan_out_exec(self):
"""Test that execution fan-out is handled correctly"""
# We want to reset the execution attribute states before the node compute() to avoid bugs
# that arise when authors forget to fully specify the output states. However we can't
# do this in the middle of traversal, because fan-out from a connection requires that the state
# be preserved for every downstream node which may read from it (like Gate).
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, gate, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Gate", "omni.graph.action.Gate"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Counter.inputs:execIn"),
("OnTick.outputs:tick", "Gate.inputs:enter"),
],
keys.SET_VALUES: [
("Gate.inputs:startClosed", False),
("OnTick.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
gate_exit = controller.attribute("outputs:exit", gate)
# Verify the Gate has triggered.
self.assertTrue(gate_exit.get())
await controller.evaluate(graph)
self.assertTrue(gate_exit.get())
# ----------------------------------------------------------------------
async def test_latent_and_push(self):
"""Exercise latent nodes in combination with stateful loop node"""
#
# +---------+ +-------+ tick +--------+ loopBody +-------+ +------------+
# |OnImpulse+-->|TickA +----------->ForLoop1++--------->|TickB +-+->|TickCounterB|
# +---------+ +----+--+ +--------++ +-------+ | +------------+
# | finish | |
# | | |
# | +--------------+ +v----------------+ +-v------------+
# +----->|FinishCounterA| |FinishLoopCounter| |FinishCounterB|
# +--------------+ +-----------------+ +--------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.Countdown"),
("ForLoop1", "omni.graph.action.ForLoop"),
("TickB", "omni.graph.action.Countdown"),
("FinishLoopCounter", "omni.graph.action.Counter"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("TickA.outputs:tick", "ForLoop1.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("ForLoop1.outputs:loopBody", "TickB.inputs:execIn"),
("ForLoop1.outputs:finished", "FinishLoopCounter.inputs:execIn"),
("TickB.outputs:tick", "TickCounterB.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
],
keys.SET_VALUES: [
("ForLoop1.inputs:start", 0),
("ForLoop1.inputs:stop", 3),
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("OnImpulse.state:enableImpulse", True),
("OnImpulse.inputs:onlyPlayback", False),
],
},
)
(_, _, _, _, finish_loop_counter, finish_counter_a, finish_counter_b, tick_counter_b) = nodes
for _ in range(20):
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_counter_a)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_b)), 12)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_counter_b)), 6)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_loop_counter)), 2)
# ----------------------------------------------------------------------
async def test_latent_chain(self):
"""Exercise a chain of latent nodes"""
# +---------+ +-------+ tick +-------+ tick +-------+
# |OnImpulse+-->TickA +-------->TickB +-------->|LatentC|
# +---------+ +-----+-+ +------++ +-------+-----+
# | finish | finish |
# finish | +-------------+ | +-------------+ +-v----------+
# +->TickCounterA | +-->| TickCounterB| |TickCounterC|
# +-------------+ +-------------+ +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.Countdown"),
("TickB", "omni.graph.action.Countdown"),
("LatentC", "omni.graph.action.Countdown"),
("TickCounterA", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
("TickCounterC", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("TickA.outputs:tick", "TickB.inputs:execIn"),
("TickA.outputs:finished", "TickCounterA.inputs:execIn"),
("TickB.outputs:tick", "LatentC.inputs:execIn"),
("TickB.outputs:finished", "TickCounterB.inputs:execIn"),
("LatentC.outputs:finished", "TickCounterC.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("LatentC.inputs:duration", 2),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, _, _, _, tick_counter_a, tick_counter_b, tick_counter_c) = nodes
for _ in range(16):
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_a)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_b)), 2)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_c)), 4)
| 44,222 | Python | 47.225736 | 116 | 0.453349 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_on_stage_event_node.py | """Basic tests of the OnStageEvent node"""
import omni.client
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.graph.tools.ogn as ogn
import omni.kit.app
import omni.kit.test
import omni.usd
from pxr import Sdf
# ======================================================================
class TestOnStageEventNode(ogts.OmniGraphTestCase):
"""Tests OnStageEvent node functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
async def test_backward_compatibility_v3(self):
"""Validate backward compatibility for legacy versions of OnStageEvent node."""
# load the test scene which contains a OnStageEvent V2 node
(result, error) = await ogts.load_test_file("TestOnStageEventNode_v2.usda", use_caller_subdirectory=True)
self.assertTrue(result, error)
action_graph_path = "/World/ActionGraph"
action_graph = og.get_graph_by_path(action_graph_path)
on_stage_event_node = action_graph.get_node(action_graph_path + "/on_stage_event")
self.assertTrue(on_stage_event_node.is_valid())
# The "Hierarchy Changed" event has been introduced since V3. Validate that it is
# automatically included by the list of allowed tokens after loading V2.
attr = on_stage_event_node.get_attribute("inputs:eventName")
allowed_tokens = attr.get_metadata(ogn.MetadataKeys.ALLOWED_TOKENS)
self.assertTrue(isinstance(allowed_tokens, str))
self.assertTrue("Hierarchy Changed" in allowed_tokens.split(","))
async def test_stage_events(self):
"""Test OnStageEvent"""
controller = og.Controller()
keys = og.Controller.Keys
(_, (on_stage_node, _, _, counter_sel_node, counter_stop_node, counter_start_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnStageEvent", "omni.graph.action.OnStageEvent"),
("OnStageEvent2", "omni.graph.action.OnStageEvent"),
("OnStageEvent3", "omni.graph.action.OnStageEvent"),
("Counter", "omni.graph.action.Counter"),
("Counter2", "omni.graph.action.Counter"),
("Counter3", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnStageEvent.outputs:execOut", "Counter.inputs:execIn"),
("OnStageEvent2.outputs:execOut", "Counter2.inputs:execIn"),
("OnStageEvent3.outputs:execOut", "Counter3.inputs:execIn"),
],
keys.SET_VALUES: [
("OnStageEvent.inputs:eventName", "Selection Changed"),
("OnStageEvent.inputs:onlyPlayback", False),
("OnStageEvent2.inputs:eventName", "Animation Stop Play"),
("OnStageEvent2.inputs:onlyPlayback", True),
("OnStageEvent3.inputs:eventName", "Animation Start Play"),
("OnStageEvent3.inputs:onlyPlayback", True),
],
},
)
async def wait_2():
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
def get_start_count():
return og.Controller.get(controller.attribute("outputs:count", counter_start_node))
def get_stop_count():
return og.Controller.get(controller.attribute("outputs:count", counter_stop_node))
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 0)
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 0)
selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([self.TEST_GRAPH_PATH + "/OnStageEvent"], False)
# 1 frame delay on the pop, 1 frame delay on the compute
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 1)
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 0)
# change the tracked event, verify selection doesn't fire
og.Controller.set(controller.attribute("inputs:eventName", on_stage_node), "Saved")
selection.set_selected_prim_paths([self.TEST_GRAPH_PATH + "/OnStageEvent2"], False)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 1)
await omni.kit.app.get_app().next_update_async()
# change it back, verify it does fire when selection changes again
og.Controller.set(controller.attribute("inputs:eventName", on_stage_node), "Selection Changed")
await omni.kit.app.get_app().next_update_async()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 1)
selection.set_selected_prim_paths([self.TEST_GRAPH_PATH + "/OnStageEvent"], False)
await wait_2()
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_sel_node)), 2)
# Verify that start/stop events work when only-playback is true
timeline = omni.timeline.get_timeline_interface()
timeline.set_start_time(1.0)
timeline.set_end_time(10.0)
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
timeline.play()
await wait_2()
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 1)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 1)
# Check that pausing / resuming does not trigger
timeline.pause()
await wait_2()
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 1)
timeline.play()
await wait_2()
self.assertEqual(get_stop_count(), 0)
self.assertEqual(get_start_count(), 1)
timeline.stop()
await wait_2()
self.assertEqual(get_stop_count(), 1)
self.assertEqual(get_start_count(), 1)
await controller.evaluate()
self.assertEqual(get_stop_count(), 1)
self.assertEqual(get_start_count(), 1)
# Verify that stopping while paused triggers the event
timeline.play()
await wait_2()
self.assertEqual(get_stop_count(), 1)
self.assertEqual(get_start_count(), 2)
timeline.pause()
await wait_2()
self.assertEqual(get_stop_count(), 1)
self.assertEqual(get_start_count(), 2)
timeline.stop()
await wait_2()
self.assertEqual(get_stop_count(), 2)
self.assertEqual(get_start_count(), 2)
# ----------------------------------------------------------------------
async def test_stage_hierarchy_changed_event(self):
"""Test the Hierarchy Changed event"""
app = omni.kit.app.get_app()
controller = og.Controller()
keys = og.Controller.Keys
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
root_path = Sdf.Path.absoluteRootPath
# Create Xform
omni.kit.commands.execute("CreatePrim", prim_type="Xform")
xform_path = root_path.AppendChild("Xform")
xform = stage.GetPrimAtPath(xform_path)
self.assertTrue(xform)
# Create Material
omni.kit.commands.execute("CreatePrim", prim_type="Material")
material_path = root_path.AppendChild("Material")
material = stage.GetPrimAtPath(material_path)
self.assertTrue(material)
# Create action graph
(_, (on_stage_node, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnStageEvent", "omni.graph.action.OnStageEvent"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnStageEvent.outputs:execOut", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("OnStageEvent.inputs:eventName", "Hierarchy Changed"),
("OnStageEvent.inputs:onlyPlayback", False),
],
},
)
outputs_count_attr = controller.attribute("outputs:count", counter_node)
expected_hierarchy_changed_event_count = 0
await app.next_update_async()
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Create cube
omni.kit.commands.execute("CreatePrim", prim_type="Cube")
cube_path = root_path.AppendChild("Cube")
cube = stage.GetPrimAtPath(cube_path)
self.assertTrue(cube)
# 1 frame delay on the pop, 1 frame delay on the compute
await app.next_update_async()
await app.next_update_async()
expected_hierarchy_changed_event_count += 1
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Reparent cube
cube_path_reparented = xform_path.AppendChild("Cube")
omni.kit.commands.execute("MovePrim", path_from=cube_path, path_to=cube_path_reparented)
await app.next_update_async()
await app.next_update_async()
expected_hierarchy_changed_event_count += 1
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Rename cube to lowercase
cube_path_lowercase = xform_path.AppendChild("cube")
omni.kit.commands.execute("MovePrim", path_from=cube_path_reparented, path_to=cube_path_lowercase)
await app.next_update_async()
await app.next_update_async()
expected_hierarchy_changed_event_count += 1
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Modify size attribute.
cube = stage.GetPrimAtPath(cube_path_lowercase)
self.assertTrue(cube)
cube.GetAttribute("size").Set(1.0)
await app.next_update_async()
await app.next_update_async()
# The "Hierarchy Changed" event is not expected for attribute change.
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Modify material binding.
rel = cube.CreateRelationship("material:binding", False)
rel.SetTargets([material_path])
await app.next_update_async()
await app.next_update_async()
# The "Hierarchy Changed" event is not expected for relationship change.
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Change the tracked event
og.Controller.set(controller.attribute("inputs:eventName", on_stage_node), "Saved")
await og.Controller.evaluate()
omni.kit.commands.execute("MovePrim", path_from=cube_path_lowercase, path_to=cube_path)
await app.next_update_async()
await app.next_update_async()
# verify hierarchy changed event doesn't fire
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
###########################################################
# Change it back, verify it does fire when hierarchy changes again
og.Controller.set(controller.attribute("inputs:eventName", on_stage_node), "Hierarchy Changed")
await og.Controller.evaluate()
# Remove cube
omni.kit.commands.execute("DeletePrims", paths=[cube_path])
await app.next_update_async()
await app.next_update_async()
expected_hierarchy_changed_event_count += 1
self.assertEqual(og.Controller.get(outputs_count_attr), expected_hierarchy_changed_event_count)
| 12,775 | Python | 42.016835 | 117 | 0.599687 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/tests/test_evaluation.py | """Action Graph Evaluation Tests"""
import asyncio
import carb.events
import omni.client
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.kit.test
import omni.usd
# ======================================================================
class TestActionGraphEvaluation(ogts.OmniGraphTestCase):
"""Tests action graph evaluator functionality"""
TEST_GRAPH_PATH = "/World/TestGraph"
async def setUp(self):
"""Set up test environment, to be torn down when done"""
await super().setUp()
og.Controller.edit({"graph_path": self.TEST_GRAPH_PATH, "evaluator_name": "execution"})
# ----------------------------------------------------------------------
async def test_exec_fan_out(self):
"""Test that fanning out from an exec port works"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("FF1", "omni.graph.action.FlipFlop"),
("FF2", "omni.graph.action.FlipFlop"),
("FF11", "omni.graph.action.FlipFlop"),
("FF12", "omni.graph.action.FlipFlop"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
],
keys.CONNECT: [
("OnTick.outputs:tick", "FF1.inputs:execIn"),
("OnTick.outputs:tick", "FF2.inputs:execIn"),
("FF1.outputs:a", "FF11.inputs:execIn"),
("FF1.outputs:a", "FF12.inputs:execIn"),
],
},
)
# 1. OnTick triggers FF1 which triggers FF11 and FF12, then FF2
# 2. OnTick triggers FF1 and FF2
# 3. OnTick triggers FF1 which triggers FF11 and FF12, then FF2
await controller.evaluate(graph)
flip_flops = nodes[1:]
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [True, True, True, True])
await controller.evaluate(graph)
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [False, False, True, True])
await controller.evaluate(graph)
ff_state = [og.Controller.get(controller.attribute("outputs:isA", node)) for node in flip_flops]
self.assertEqual(ff_state, [True, True, False, False])
# ----------------------------------------------------------------------
async def test_chained_stateful_nodes(self):
"""Test that chaining loop nodes works"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("ForLoop1", "omni.graph.action.ForLoop"),
("ForLoop2", "omni.graph.action.ForLoop"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "ForLoop2.inputs:execIn"),
("ForLoop2.outputs:loopBody", "Counter.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("ForLoop1.inputs:stop", 5),
("ForLoop2.inputs:stop", 5),
],
},
)
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter_node)), 5 * 5)
# ----------------------------------------------------------------------
async def test_async_nodes(self):
"""Test asynchronous action nodes"""
# Check that a nested loop state is maintained when executing a latent delay
#
# +---------+ +----------+ +----------+ +-------+ +--------+
# | IMPULSE +-->| FOR-LOOP +--->| FOR-LOOP +--->| DELAY +--->| COUNTER|
# +---------+ +----------+ +----------+ +-------+ +--------+
#
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, _, _, counter_node, _, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("ForLoop1", "omni.graph.action.ForLoop"),
("ForLoop2", "omni.graph.action.ForLoop"),
("Delay", "omni.graph.action.Delay"),
("Counter", "omni.graph.action.Counter"),
("OnTick", "omni.graph.action.OnTick"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:loopBody", "ForLoop2.inputs:execIn"),
("ForLoop2.outputs:loopBody", "Delay.inputs:execIn"),
("Delay.outputs:finished", "Counter.inputs:execIn"),
("OnTick.outputs:tick", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("OnImpulse.inputs:onlyPlayback", False),
("Delay.inputs:duration", 0.1),
("ForLoop1.inputs:stop", 2),
("ForLoop2.inputs:stop", 5),
],
},
)
await controller.evaluate(graph)
# trigger graph once
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# in delay now, no count
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
self.assertEqual(counter_controller.get(), 0)
# wait to ensure the first 5 delays compute
for _ in range(5):
await asyncio.sleep(0.2)
await controller.evaluate(graph)
count_val = counter_controller.get()
self.assertGreater(count_val, 4)
# wait and verify the remainder go through
for _ in range(5):
await asyncio.sleep(0.1)
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 10)
# ----------------------------------------------------------------------
async def test_stateful_flowcontrol_evaluation(self):
"""Test that stateful flow control nodes are fully evaluated"""
# b
# +----------+ +---------+
# +--->| Sequence +-->|Counter1 |
# | +----------+ +---------+
# +-----------+ |
# | OnImpulse +-+
# +-----------+ |
# | +----------+ +----------+
# +--->| ForLoop1 +-->| Counter2 |
# +----------+ +----------+
# finished
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, counter1_node, _, counter2_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Sequence", "omni.graph.action.Sequence"),
("Counter1", "omni.graph.action.Counter"),
("ForLoop1", "omni.graph.action.ForLoop"),
("Counter2", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "Sequence.inputs:execIn"),
("Sequence.outputs:b", "Counter1.inputs:execIn"),
("OnImpulse.outputs:execOut", "ForLoop1.inputs:execIn"),
("ForLoop1.outputs:finished", "Counter2.inputs:execIn"),
],
keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False), ("ForLoop1.inputs:stop", 10)],
},
)
await controller.evaluate(graph)
# trigger graph once
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
# verify that counter was called in spite of sequence 'a' being disconnected
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter1_node)), 1)
# verify that counter was called in spite of there being no loopBody - execution evaluator has to still trigger
# the loop 11 times despite there being no downstream connection
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", counter2_node)), 1)
# ----------------------------------------------------------------------
async def test_request_driven_node(self):
"""Test that RequestDriven nodes are computed as expected"""
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, counter_node), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("Counter", "omni.graph.action.Counter"),
],
keys.SET_VALUES: [("OnImpulse.inputs:onlyPlayback", False)],
keys.CONNECT: ("OnImpulse.outputs:execOut", "Counter.inputs:execIn"),
},
)
# After several updates, there should have been no compute calls
await controller.evaluate(graph)
await controller.evaluate(graph)
await controller.evaluate(graph)
counter_controller = og.Controller(og.Controller.attribute("outputs:count", counter_node))
self.assertEqual(counter_controller.get(), 0)
# change OnImpulse state attrib. The node should now request compute
controller.edit(self.TEST_GRAPH_PATH, {keys.SET_VALUES: ("OnImpulse.state:enableImpulse", True)})
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 1)
# more updates should not result in more computes
await controller.evaluate(graph)
await controller.evaluate(graph)
await controller.evaluate(graph)
self.assertEqual(counter_controller.get(), 1)
# ----------------------------------------------------------------------
async def test_fan_in_exec(self):
"""Test that execution fan-in is handled correctly."""
# The evaluator has to consider the case that gate.enter will have contradicting upstream values.
# Gate needs to know which input is active, it needs the value of enter to be ENABLED when it
# is triggered by OnTick, even though OnTickDisabled has set it's output to the same attrib as DISABLED.
#
# +--------------+
# |OnImpulseEvent+---+ +-----------+
# +--------------+ | |Gate |
# +--->toggle |
# +--------------+ | |
# |OnTick +------>|enter |
# +--------------+ +^-----exit-+
# |
# +--------------+ |
# |OnTickDisabled+--------+
# +--------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, _, gate, on_impulse_event), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("OnTickDisabled", "omni.graph.action.OnTick"),
("Gate", "omni.graph.action.Gate"),
("OnImpulseEvent", "omni.graph.action.OnImpulseEvent"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Gate.inputs:enter"),
("OnTickDisabled.outputs:tick", "Gate.inputs:enter"),
("OnImpulseEvent.outputs:execOut", "Gate.inputs:toggle"),
],
keys.SET_VALUES: [
("Gate.inputs:startClosed", True),
("OnTick.inputs:onlyPlayback", False),
("OnImpulseEvent.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
gate_exit = controller.attribute("outputs:exit", gate)
# Verify the Gate has not triggered
self.assertFalse(gate_exit.get())
await controller.evaluate(graph)
self.assertFalse(gate_exit.get())
# toggle the gate and verify that the tick goes through. The first evaluate it isn't known if the Gate will
# trigger because the order that entry points are executed is not defined... FIXME
controller.attribute("state:enableImpulse", on_impulse_event).set(True)
await controller.evaluate(graph)
await controller.evaluate(graph)
self.assertTrue(gate_exit.get())
# ----------------------------------------------------------------------
async def test_fan_out_exec(self):
"""Test that execution fan-out is handled correctly."""
# We want to reset the execution attribute states before the node compute() to avoid bugs
# that arise when authors forget to fully specify the output states. However we can't
# do this in the middle of traversal, because fan-out from a connection requires that the state
# be preserved for every downstream node which may read from it (like Gate).
controller = og.Controller()
keys = og.Controller.Keys
(graph, (_, gate, _), _, _,) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("Gate", "omni.graph.action.Gate"),
("Counter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "Counter.inputs:execIn"),
("OnTick.outputs:tick", "Gate.inputs:enter"),
],
keys.SET_VALUES: [
("Gate.inputs:startClosed", False),
("OnTick.inputs:onlyPlayback", False),
],
},
)
await controller.evaluate(graph)
gate_exit = controller.attribute("outputs:exit", gate)
# Verify the Gate has triggered
self.assertTrue(gate_exit.get())
await controller.evaluate(graph)
self.assertTrue(gate_exit.get())
# ----------------------------------------------------------------------
async def test_onclosing(self):
"""Test OnClosing node"""
# Test OnClosing is tricky because OG is being destroyed when it happens -
# so test by sending a custom event when the network is triggered
# and then checking if we got that event
def registered_event_name(event_name):
"""Returns the internal name used for the given custom event name"""
n = "omni.graph.action." + event_name
return carb.events.type_from_string(n)
got_event = [False]
def on_event(_):
got_event[0] = True
reg_event_name = registered_event_name("foo")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_push_by_type(reg_event_name, on_event)
self.assertIsNotNone(sub)
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnClosing", "omni.graph.action.OnClosing"),
("Send", "omni.graph.action.SendCustomEvent"),
],
keys.CONNECT: [("OnClosing.outputs:execOut", "Send.inputs:execIn")],
keys.SET_VALUES: [("Send.inputs:eventName", "foo"), ("Send.inputs:path", "Test Path")],
},
)
# evaluate once so that graph is in steady state
await controller.evaluate()
# close the stage
usd_context = omni.usd.get_context()
(result, _) = await usd_context.close_stage_async()
self.assertTrue(result)
# Check our handler was called
self.assertTrue(got_event[0])
async def test_onloaded(self):
"""Test OnLoaded node"""
def registered_event_name(event_name):
"""Returns the internal name used for the given custom event name"""
n = "omni.graph.action." + event_name
return carb.events.type_from_string(n)
events = []
def on_event(e):
events.append(e.payload["!path"])
reg_event_name = registered_event_name("foo")
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
sub = message_bus.create_subscription_to_push_by_type(reg_event_name, on_event)
self.assertIsNotNone(sub)
controller = og.Controller()
keys = og.Controller.Keys
controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("OnLoaded", "omni.graph.action.OnLoaded"),
("Send1", "omni.graph.action.SendCustomEvent"),
("Send2", "omni.graph.action.SendCustomEvent"),
],
keys.CONNECT: [
("OnLoaded.outputs:execOut", "Send1.inputs:execIn"),
("OnTick.outputs:tick", "Send2.inputs:execIn"),
],
keys.SET_VALUES: [
("OnTick.inputs:onlyPlayback", False),
("Send1.inputs:eventName", "foo"),
("Send2.inputs:eventName", "foo"),
("Send1.inputs:path", "Loaded"),
("Send2.inputs:path", "Tick"),
],
},
)
# evaluate once so that graph is in steady state
await controller.evaluate()
# Verify Loaded came before OnTick
self.assertListEqual(events, ["Loaded", "Tick"])
# ----------------------------------------------------------------------
async def test_active_latent(self):
"""exercise a latent node that executes downstream nodes while latent"""
# +--------+ +----------+finished+-------------+
# | OnTick+-->| TickN +-------->FinishCounter|
# +--------+ | | +-------------+
# | +-+
# +----------+ | +------------+ +------------+ +------------+
# +-----> TickCounter+----->TickCounter2+---->TickCounter3|
# tick +------------+ +------------+ +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnTick", "omni.graph.action.OnTick"),
("TickN", "omni.graph.action.TickN"),
("FinishCounter", "omni.graph.action.Counter"),
("TickCounter", "omni.graph.action.Counter"),
("TickCounter2", "omni.graph.action.Counter"),
("TickCounter3", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnTick.outputs:tick", "TickN.inputs:execIn"),
("TickN.outputs:finished", "FinishCounter.inputs:execIn"),
("TickN.outputs:tick", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickCounter2.inputs:execIn"),
("TickCounter2.outputs:execOut", "TickCounter3.inputs:execIn"),
],
keys.SET_VALUES: [("TickN.inputs:duration", 3), ("OnTick.inputs:onlyPlayback", False)],
},
)
(_, _, finish_counter, tick_counter, _, tick_counter_3) = nodes
finish_counter_controller = og.Controller(og.Controller.attribute("outputs:count", finish_counter))
tick_counter_controller = og.Controller(og.Controller.attribute("outputs:count", tick_counter))
tick_counter_3_controller = og.Controller(og.Controller.attribute("outputs:count", tick_counter_3))
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
await controller.evaluate(graph)
self.assertEqual(tick_counter_controller.get(), 1)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
self.assertEqual(tick_counter_controller.get(), 2)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 0)
self.assertEqual(tick_counter_3_controller.get(), 3)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 1)
self.assertEqual(tick_counter_3_controller.get(), 3)
await controller.evaluate(graph)
self.assertEqual(finish_counter_controller.get(), 1)
self.assertEqual(tick_counter_3_controller.get(), 3)
# ----------------------------------------------------------------------
async def test_latent_chain(self):
"""exercise a chain of latent nodes"""
# +---------+ +-------+ tick +-------+ tick +-------+
# |OnImpulse+-->TickA +-------->TickB +-------->|LatentC|
# +---------+ +-----+-+ +------++ +-------+-----+
# | finish | finish |
# finish | +-------------+ | +-------------+ +-v----------+
# +->TickCounterA | +-->| TickCounterB| |TickCounterC|
# +-------------+ +-------------+ +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.TickN"),
("TickB", "omni.graph.action.TickN"),
("LatentC", "omni.graph.action.TickN"),
("TickCounterA", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
("TickCounterC", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("TickA.outputs:tick", "TickB.inputs:execIn"),
("TickA.outputs:finished", "TickCounterA.inputs:execIn"),
("TickB.outputs:tick", "LatentC.inputs:execIn"),
("TickB.outputs:finished", "TickCounterB.inputs:execIn"),
("LatentC.outputs:finished", "TickCounterC.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("LatentC.inputs:duration", 2),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, _, _, _, tick_counter_a, tick_counter_b, tick_counter_c) = nodes
for _ in range(16):
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_a)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_b)), 2)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_c)), 4)
# ----------------------------------------------------------------------
async def test_latent_and_push(self):
"""exercise latent nodes in combination with stateful loop node"""
#
# +---------+ +-------+ tick +--------+ loopBody +-------+ +------------+
# |OnImpulse+-->|TickA +----------->ForLoop1++--------->|TickB +-+->|TickCounterB|
# +---------+ +----+--+ +--------++ +-------+ | +------------+
# | finish | |
# | | |
# | +--------------+ +v----------------+ +-v------------+
# +----->|FinishCounterA| |FinishLoopCounter| |FinishCounterB|
# +--------------+ +-----------------+ +--------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.TickN"),
("ForLoop1", "omni.graph.action.ForLoop"),
("TickB", "omni.graph.action.TickN"),
("FinishLoopCounter", "omni.graph.action.Counter"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("TickA.outputs:tick", "ForLoop1.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("ForLoop1.outputs:loopBody", "TickB.inputs:execIn"),
("ForLoop1.outputs:finished", "FinishLoopCounter.inputs:execIn"),
("TickB.outputs:tick", "TickCounterB.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
],
keys.SET_VALUES: [
("ForLoop1.inputs:start", 0),
("ForLoop1.inputs:stop", 3),
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("OnImpulse.state:enableImpulse", True),
("OnImpulse.inputs:onlyPlayback", False),
],
},
)
(_, _, _, _, finish_loop_counter, finish_counter_a, finish_counter_b, tick_counter_b) = nodes
for _ in range(20):
await controller.evaluate(graph)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_counter_a)), 1)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", tick_counter_b)), 12)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_counter_b)), 6)
self.assertEqual(og.Controller.get(controller.attribute("outputs:count", finish_loop_counter)), 2)
# ----------------------------------------------------------------------
async def test_latent_fan_out(self):
"""Test latent nodes when part of parallel evaluation"""
# +------------+
# +---->|TickCounterA|
# | +------------+
# |
# +--------++ +----------+
# +-> TickA +--->|FinishedA |
# | +---------+ +----------+
# +---------+ +-----------+ |
# |OnImpulse+-->|TickCounter+-+
# +---------+ +-----------+ |
# | +---------+ +----------+
# +>| TickB +--->|FinishedB |
# +--------++ +----------+
# |
# | +------------+
# +---->|TickCounterB|
# +------------+
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.TickN"),
("TickB", "omni.graph.action.TickN"),
("TickCounter", "omni.graph.action.Counter"),
("TickCounterA", "omni.graph.action.Counter"),
("TickCounterB", "omni.graph.action.Counter"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickA.inputs:execIn"),
("TickCounter.outputs:execOut", "TickB.inputs:execIn"),
("TickA.outputs:tick", "TickCounterA.inputs:execIn"),
("TickB.outputs:tick", "TickCounterB.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 2),
("TickB.inputs:duration", 2),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, _, _, tick_counter, tick_counter_a, tick_counter_b, finish_counter_a, finish_counter_b) = nodes
def check_counts(c, a, b, f_a, f_b):
for node, expected in (
(tick_counter, c),
(tick_counter_a, a),
(tick_counter_b, b),
(finish_counter_a, f_a),
(finish_counter_b, f_b),
):
count = og.Controller.get(controller.attribute("outputs:count", node))
self.assertEqual(count, expected, node.get_prim_path())
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 0)
await controller.evaluate(graph)
check_counts(1, 1, 1, 0, 0)
await controller.evaluate(graph)
check_counts(1, 2, 2, 0, 0)
await controller.evaluate(graph)
check_counts(1, 2, 2, 1, 1)
# ----------------------------------------------------------------------
async def test_diamond_fan(self):
"""Test latent nodes in parallel fan-out which fan-in to a downstream node"""
# +--------++ +----------+
# +--> TickA +--->|FinishedA |---+
# | +---------+ +----------+ |
# +---------+ +-----------+ | | +------------+
# |OnImpulse+-->|TickCounter+-+ +-->|MergeCounter|
# +---------+ +-----------+ | | +------------+
# | +---------+ +----------+ |
# +-->| TickB +--->|FinishedB |--+
# +--------++ +----------+
# | +---------+
# +-->| TickC |
# +--------++
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickCounter", "omni.graph.action.Counter"),
("TickA", "omni.graph.action.TickN"),
("TickB", "omni.graph.action.TickN"),
("TickC", "omni.graph.action.TickN"),
("FinishCounterA", "omni.graph.action.Counter"),
("FinishCounterB", "omni.graph.action.Counter"),
("MergeCounter", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickCounter.inputs:execIn"),
("TickCounter.outputs:execOut", "TickA.inputs:execIn"),
("TickCounter.outputs:execOut", "TickB.inputs:execIn"),
("TickCounter.outputs:execOut", "TickC.inputs:execIn"),
("TickA.outputs:finished", "FinishCounterA.inputs:execIn"),
("TickB.outputs:finished", "FinishCounterB.inputs:execIn"),
("FinishCounterA.outputs:execOut", "MergeCounter.inputs:execIn"),
("FinishCounterB.outputs:execOut", "MergeCounter.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 1),
("TickB.inputs:duration", 1),
("TickC.inputs:duration", 1),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, tick_counter, _, _, tick_c, finish_counter_a, finish_counter_b, merge_counter) = nodes
def check_counts(tc, f_a, f_b, mc, tick_c_count):
for node, expected in (
(tick_counter, tc),
(finish_counter_a, f_a),
(finish_counter_b, f_b),
(merge_counter, mc),
):
count = og.Controller.get(controller.attribute("outputs:count", node))
self.assertEqual(count, expected, node.get_prim_path())
self.assertEqual(tick_c.get_compute_count(), tick_c_count)
self.assertEqual(tick_c.get_compute_count(), 0)
# set up latent tickers
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 1)
# latent ticks
await controller.evaluate(graph)
check_counts(1, 0, 0, 0, 2)
# both branches complete
await controller.evaluate(graph)
check_counts(1, 1, 1, 2, 3)
# no count changes + no additional computes of tickC
await controller.evaluate(graph)
check_counts(1, 1, 1, 2, 3)
# ----------------------------------------------------------------------
async def test_diamond_latent_fan(self):
"""Test latent nodes in parallel fan-out which fan-in to a latent downstream node"""
# +--------++
# +--> TickA +--+
# | +---------+ |
# +---------+ | | +-------+ +-------+
# |OnImpulse+-->+ +-->|TickD +-+--->|CountF |
# +---------+ | | +-------+ | +-------+
# | +--------+ | +--->+-------+
# +-->| TickB +--+ |TickE |
# | +--------+ +--->+-------+
# | +--------+ |
# +-->| TickC +----------------+
# +--------+
# Note that when TickA triggers TickD into latent state, then TickB hits TickD subsequently. This subsequent
# evaluation is _transient_. Meaning that TickB will not block on a new copy of TickD.
# This is because there is only one TickD so there can be only one state (latent or not).
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes, _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("OnImpulse", "omni.graph.action.OnImpulseEvent"),
("TickA", "omni.graph.action.TickN"),
("TickB", "omni.graph.action.TickN"),
("TickC", "omni.graph.action.TickN"),
("TickD", "omni.graph.action.TickN"),
("TickE", "omni.graph.action.TickN"),
("CountF", "omni.graph.action.Counter"),
],
keys.CONNECT: [
("OnImpulse.outputs:execOut", "TickA.inputs:execIn"),
("OnImpulse.outputs:execOut", "TickB.inputs:execIn"),
("OnImpulse.outputs:execOut", "TickC.inputs:execIn"),
("TickA.outputs:finished", "TickD.inputs:execIn"),
("TickB.outputs:finished", "TickD.inputs:execIn"),
("TickC.outputs:finished", "TickE.inputs:execIn"),
("TickD.outputs:finished", "TickE.inputs:execIn"),
("TickD.outputs:finished", "CountF.inputs:execIn"),
],
keys.SET_VALUES: [
("TickA.inputs:duration", 1),
("TickB.inputs:duration", 1),
("TickC.inputs:duration", 2),
("TickD.inputs:duration", 1),
("TickE.inputs:duration", 1),
("OnImpulse.inputs:onlyPlayback", False),
("OnImpulse.state:enableImpulse", True),
],
},
)
(_, tick_a, tick_b, tick_c, tick_d, tick_e, count_f) = nodes
def check_counts(i, ta, tb, tc, td, te):
# print(f"{[node.get_compute_count() for node, expected in ((tick_a, ta), (tick_b, tb), (tick_c, tc), (tick_d, td), (tick_e, te))]}")
for node, expected in ((tick_a, ta), (tick_b, tb), (tick_c, tc), (tick_d, td), (tick_e, te)):
self.assertEqual(node.get_compute_count(), expected, f"Check {i} for {node.get_prim_path()}")
# A, B, C, D, E
compute_counts = [
(1, 1, 1, 0, 0), # 0. fan out to trigger A, B, C into latent state
(2, 2, 2, 0, 0), # 1. A, B, C tick
(3, 3, 3, 2, 0), # 2. A, B end latent, D into latent via A or B, D ticks via A or B, C ticks
(3, 3, 4, 3, 2), # 3.
(3, 3, 4, 3, 3), # 4.
(3, 3, 4, 3, 3), # 5.
(3, 3, 4, 3, 3), # 6.
]
for i, cc in enumerate(compute_counts):
await controller.evaluate(graph)
check_counts(i, *cc)
# Verify that CountF has computed 1x due to the fan-in at TickD NOT acting like separate threads
self.assertEqual(count_f.get_compute_count(), 1)
async def test_om_63924(self):
"""Test OM-63924 bug is fixed"""
# The problem here was that if there was fan in to a node which was
# computed once and then totally unwound before the other history was
# processed, there would never be a deferred activation and so the 2nd
# compute would never happen. Instead we want to only unwind one history
# at a time to ensure each one is fully evaluated.
i = 2
class OnForEachEventPy:
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
nonlocal i
go = node.get_attribute("inputs:go")
go_val = og.Controller.get(go)
if not go_val:
return True
if i > 0:
og.Controller.set(
node.get_attribute("outputs:execOut"), og.ExecutionAttributeState.ENABLED_AND_PUSH
)
og.Controller.set(node.get_attribute("outputs:syncValue"), i)
i -= 1
return True
@staticmethod
def get_node_type() -> str:
return "omni.graph.test.OnForEachEventPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
node_type.add_input(
"inputs:go",
"bool",
False,
)
node_type.add_output("outputs:execOut", "execution", True)
node_type.add_output("outputs:syncValue", "uint64", True)
return True
og.register_node_type(OnForEachEventPy, 1)
class NoOpPy:
@staticmethod
def compute(context: og.GraphContext, node: og.Node):
og.Controller.set(node.get_attribute("outputs:execOut"), og.ExecutionAttributeState.ENABLED)
return True
@staticmethod
def get_node_type() -> str:
return "omni.graph.test.NoOpPy"
@staticmethod
def initialize_type(node_type: og.NodeType):
node_type.add_input(
"inputs:execIn",
"execution",
True,
)
node_type.add_output("outputs:execOut", "execution", True)
return True
og.register_node_type(NoOpPy, 1)
controller = og.Controller()
keys = og.Controller.Keys
(graph, (for_each, _, _, _, _, no_op_2), _, _) = controller.edit(
self.TEST_GRAPH_PATH,
{
keys.CREATE_NODES: [
("PostProcessDispatcher", "omni.graph.test.OnForEachEventPy"),
("TSA1", "omni.graph.action.SyncGate"),
("TSA0", "omni.graph.action.SyncGate"),
("TestSyncAccum", "omni.graph.action.SyncGate"),
("TestPrimBbox", "omni.graph.test.NoOpPy"),
("NoOpPy2", "omni.graph.test.NoOpPy"),
],
keys.CONNECT: [
("PostProcessDispatcher.outputs:execOut", "TSA0.inputs:execIn"),
("PostProcessDispatcher.outputs:execOut", "TSA1.inputs:execIn"),
("TSA1.outputs:execOut", "TestSyncAccum.inputs:execIn"),
("TSA0.outputs:execOut", "TestPrimBbox.inputs:execIn"),
("TestPrimBbox.outputs:execOut", "TestSyncAccum.inputs:execIn"),
("TestSyncAccum.outputs:execOut", "NoOpPy2.inputs:execIn"),
("PostProcessDispatcher.outputs:syncValue", "TSA1.inputs:syncValue"),
("PostProcessDispatcher.outputs:syncValue", "TSA0.inputs:syncValue"),
("PostProcessDispatcher.outputs:syncValue", "TestSyncAccum.inputs:syncValue"),
],
},
)
og.Controller.set(controller.attribute("inputs:go", for_each), True)
await controller.evaluate(graph)
# Verify the final sync gate triggered due to being computed 2x
exec_out = og.Controller.get(controller.attribute("outputs:execOut", no_op_2))
self.assertEqual(exec_out, og.ExecutionAttributeState.ENABLED)
| 44,048 | Python | 46.364516 | 145 | 0.4706 |
omniverse-code/kit/exts/omni.kit.renderer.cuda_interop/omni/kit/renderer/cuda_interop_test/__init__.py | from ._renderer_cuda_interop_test import *
# Cached interface instance pointer
def get_renderer_cuda_interop_test_interface() -> IRendererCudaInteropTest:
if not hasattr(get_renderer_cuda_interop_test_interface, "renderer_cuda_interop_test"):
get_renderer_cuda_interop_test_interface.renderer_cuda_interop_test = acquire_renderer_cuda_interop_test_interface()
return get_renderer_cuda_interop_test_interface.renderer_cuda_interop_test
| 453 | Python | 49.444439 | 124 | 0.785872 |
omniverse-code/kit/exts/omni.kit.renderer.cuda_interop/omni/kit/renderer/cuda_interop/__init__.py | from ._renderer_cuda_interop import *
# Cached interface instance pointer
def get_renderer_cuda_interop_interface() -> IRendererCudaInterop:
"""Returns cached :class:`omni.kit.renderer.IRendererCudaInterop` interface"""
if not hasattr(get_renderer_cuda_interop_interface, "renderer_cuda_interop"):
get_renderer_cuda_interop_interface.renderer = acquire_renderer_cuda_interop_interface()
return get_renderer_cuda_interop_interface.renderer_cuda_interop
| 475 | Python | 42.272723 | 96 | 0.772632 |
omniverse-code/kit/exts/omni.kit.renderer.cuda_interop/omni/kit/renderer/cuda_interop/tests/__init__.py | from .test_renderer_cuda_interop import *
| 42 | Python | 20.49999 | 41 | 0.785714 |
omniverse-code/kit/exts/omni.kit.renderer.cuda_interop/omni/kit/renderer/cuda_interop/tests/test_renderer_cuda_interop.py | import inspect
import pathlib
import carb
import carb.settings
import carb.tokens
import omni.kit.app
import omni.kit.test
import omni.kit.renderer.cuda_interop_test
class RendererCudaInteropTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.acquire_settings_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
self._renderer_cuda_interop_test = omni.kit.renderer.cuda_interop_test.acquire_renderer_cuda_interop_test_interface()
self._renderer.startup()
self._renderer_cuda_interop_test.startup()
def __test_name(self) -> str:
return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}"
async def tearDown(self):
self._renderer_cuda_interop_test.shutdown()
self._renderer.shutdown()
self._renderer_cuda_interop_test = None
self._renderer = None
self._app_window_factory = None
self._settings = None
async def test_1_render_cuda_interop_test(self):
app_window = self._app_window_factory.create_window_from_settings()
app_window.startup_with_desc(
title="Renderer test OS window",
width=16,
height=16,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._renderer.attach_app_window(app_window)
self._app_window_factory.set_default_window(app_window)
TEST_COLOR = (1, 2, 3, 255)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_cuda_interop_test.startup_resources_for_app_window(app_window)
self._renderer_cuda_interop_test.setup_simple_comparison_for_app_window(app_window, TEST_COLOR[0], TEST_COLOR[1], TEST_COLOR[2], TEST_COLOR[3])
test_name = self.__test_name()
for _ in range(3):
await omni.kit.app.get_app().next_update_async()
self._renderer_cuda_interop_test.shutdown_resources_for_app_window(app_window)
self._app_window_factory.set_default_window(None)
self._renderer.detach_app_window(app_window)
app_window.shutdown()
app_window = None
| 2,522 | Python | 35.042857 | 151 | 0.647898 |
omniverse-code/kit/exts/omni.kit.window.audioplayer/omni/kit/window/audioplayer/__init__.py | from .audio_player_window import *
| 35 | Python | 16.999992 | 34 | 0.771429 |
omniverse-code/kit/exts/omni.kit.window.audioplayer/omni/kit/window/audioplayer/audio_player_window.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 carb.settings
import carb.dictionary
import omni.audioplayer
import omni.kit.ui
import omni.ui
import threading
import time
import re
import asyncio
import enum
from typing import Callable
from omni.kit.window.filepicker import FilePickerDialog
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class EndReason(enum.Enum):
# sound finished naturally
FINISHED = 0,
# sound was explicitly stopped
STOPPED = 1,
# seeked to a new location in the sound (causes an end callback)
SEEK = 2,
# the previous sound ended because another one is being played
QUEUED_NEW_SOUND = 3,
class AudioPlayerWindowExtension(omni.ext.IExt):
"""Audio Player Window Extension"""
class FieldModel(omni.ui.AbstractValueModel):
def __init__(self, end_edit_callback):
super(AudioPlayerWindowExtension.FieldModel, self).__init__()
self._end_edit_callback = end_edit_callback
self._value = ""
def get_value_as_string(self):
return self._value
def begin_edit(self):
pass
def set_value(self, value):
self._value = value
self._value_changed()
def end_edit(self):
self._end_edit_callback(self._value)
class SliderModel(omni.ui.AbstractValueModel):
def __init__(self, update_callback, end_edit_callback):
super(AudioPlayerWindowExtension.SliderModel, self).__init__()
self._update_callback = update_callback
self._end_edit_callback = end_edit_callback
self._value = 0
def get_value_as_int(self): # pragma: no cover
return int(self._value)
def get_value_as_float(self): # pragma: no cover
return float(self._value)
def begin_edit(self): # pragma: no cover
pass
def set_value(self, value): # pragma: no cover
self._value = value
self._value_changed()
self._update_callback(self._value)
def end_edit(self): # pragma: no cover
self._end_edit_callback(self._value)
def _on_file_pick(self, dialog: FilePickerDialog, filename: str, dirname: str): # pragma: no cover
path = ""
if dirname:
path = f"{dirname}/{filename}"
elif filename:
path = filename
dialog.hide()
self._file_field.model.set_value(path)
# this has to be called manually because set_value doesn't do it
self._file_field_end_edit(path)
def _choose_file_clicked(self): # pragma: no cover
dialog = FilePickerDialog(
"Select File",
apply_button_label="Select",
click_apply_handler=lambda filename, dirname: self._on_file_pick(dialog, filename, dirname),
)
dialog.show()
def _set_pause_button(self): # pragma: no cover
self._play_button.set_style({"image_url": "resources/glyphs/timeline_pause.svg"})
def _set_play_button(self): # pragma: no cover
self._play_button.set_style({"image_url": "resources/glyphs/timeline_play.svg"})
def _timeline_str(self, time): # pragma: no cover
sec = ":{:02.0f}".format(time % 60)
if time > 60.0 * 60.0:
return "{:1.0f}".format(time // (60 * 60)) + ":{:02.0f}".format((time // 60) % 60) + sec
else:
return "{:1.0f}".format(time // 60) + sec
def _timeline_ticker(self): # pragma: no cover
if not self._playing:
return
time = self._player.get_play_cursor()
self._timeline_cursor_label.text = self._timeline_str(time)
self._timeline_slider.model.set_value(time * self._timeline_slider_scale)
# if the window was closed, stop the player
if not self._window.visible:
self._end_reason = EndReason.STOPPED
self._player.stop_sound()
self._ticker = threading.Timer(0.25, self._timeline_ticker).start()
def _loading_ticker(self):
labels = {0: "Loading", 1: "Loading.", 2: "Loading..", 3: "Loading..."}
if not self._loading:
self._loading_label.text = ""
return
self._loading_label.text = labels[self._loading_counter % 4]
self._loading_counter += 1
self._loading_timer = threading.Timer(0.25, self._loading_ticker).start()
def _play_sound(self, time):
self._loading = True
self._player.play_sound(
self._file_field.model.get_value_as_string(), time
)
def _close_error_window(self): # pragma: no cover
self._error_window.visible = False
def _set_play_cursor(self, time): # pragma: no cover
self._end_reason = EndReason.SEEK
self._player.set_play_cursor(time)
def _file_loaded(self, success): # pragma: no cover
self._loading = False
if not success:
self._playing = False
self._set_play_button()
error_text = "Loading failed"
file_name = self._file_field.model.get_value_as_string()
if re.search("^.*.(m4a|aac)$", file_name):
error_text = (
f"Failed to load file '{file_name}' codec not supported - only Vorbis, FLAC and WAVE are supported"
)
else:
error_text = f"Failed to load file '{file_name}' codec not supported (only Vorbis, FLAC, MP3 and WAVE are supported), file does not exist or the file is corrupted"
self._error_window = omni.ui.Window(
"Audio Player Error", width=400, height=0, flags=omni.ui.WINDOW_FLAGS_NO_DOCKING
)
with self._error_window.frame:
with omni.ui.VStack():
with omni.ui.HStack():
omni.ui.Spacer()
self._error_window_label = omni.ui.Label(
error_text, word_wrap=True, width=380, alignment=omni.ui.Alignment.CENTER
)
omni.ui.Spacer()
with omni.ui.HStack():
omni.ui.Spacer()
self._error_window_ok_button = omni.ui.Button(
width=64, height=32, clicked_fn=self._close_error_window, text="ok"
)
omni.ui.Spacer()
self._waveform_image_provider.set_bytes_data([0, 0, 0, 0], [1, 1])
return
if self._new_file:
width = 2048
height = 64
raw_image = self._player.draw_waveform(width, height, [0.89, 0.54, 0.14, 1.0], [0.0, 0.0, 0.0, 0.0])
self._waveform_image_provider.set_bytes_data(raw_image, [width, height])
self._new_file = False
self._timeline_end_label.text = self._timeline_str(self._player.get_sound_length())
self._sound_length = self._player.get_sound_length()
self._timeline_slider_scale = 1.0 / self._sound_length
# set the timeline ticker going
self._timeline_ticker()
# set this back to default
self._end_reason = EndReason.FINISHED
def _play_finished(self): # pragma: no cover
if self._end_reason != EndReason.SEEK and self._end_reason != EndReason.QUEUED_NEW_SOUND:
self._playing = False
# set the slider to finished
self._timeline_cursor_label.text = self._timeline_str(0)
self._timeline_slider.model.set_value(0.0)
if self._end_reason == EndReason.FINISHED or self._end_reason == EndReason.STOPPED:
self._set_play_button()
if self._end_reason == EndReason.FINISHED and self._settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop"):
self._window.visible = False
def _play_clicked(self): # pragma: no cover
if self._loading:
return
if self._playing:
if self._paused:
self._player.unpause_sound()
self._set_pause_button()
self._paused = False
else:
self._player.pause_sound()
self._set_play_button()
self._paused = True
return
self._playing = True
self._paused = False
self._load_result_label.text = ""
self._loading_ticker()
self._set_pause_button()
self._play_sound(self._timeline_slider.model.get_value_as_float() * self._sound_length)
def _file_field_end_edit(self, value):
self._loading = True
self._new_file = True
self._load_result_label.text = ""
self._loading_ticker()
self._stop_clicked()
self._player.load_sound(self._file_field.model.get_value_as_string())
def _stop_clicked(self): # pragma: no cover
if self._loading:
return
self._end_reason = EndReason.STOPPED
self._player.stop_sound()
self._playing = False
self._paused = False
def _slider_end_edit(self, value): # pragma: no cover
if self._loading:
return
if not self._playing:
return
self._set_play_cursor(value * self._sound_length)
def _slider_changed(self, value): # pragma: no cover
if not self._playing and not self._loading:
self._timeline_cursor_label.text = self._timeline_str(value * self._sound_length)
def open_window(self):
"""
Make the window become visible
Args:
No arguments
Returns:
No return value
"""
self._window.visible = True
def open_window_and_play(self, path): # pragma: no cover
"""
Make the window become visible then begin playing a file
Args:
path: The file to begin playing
Returns:
No return value
"""
self._playing = True
self._loading = True;
self._paused = False
self._new_file = True
self._window.visible = True
self._load_result_label.text = ""
self._loading_ticker()
self._set_pause_button()
self._end_reason = EndReason.QUEUED_NEW_SOUND
self._file_field.model.set_value(path)
self._play_sound(0.0)
def _menu_callback(self, a, b):
self._window.visible = not self._window.visible
def _on_menu_click(self, menu, value): # pragma: no cover
if self._content_window is None:
return
protocol = self._content_window.get_selected_icon_protocol()
path = self._content_window.get_selected_icon_path()
if not path.startswith(protocol):
path = protocol + path
self.open_window_and_play(path)
def _on_menu_check(self, url):
return not not re.search("^.*\\.(wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus|adpcm)$", url)
def _on_browser_click(self, menu, value): # pragma: no cover
if self._content_browser is None:
return
# protocol = self._content_browser.get_selected_icon_protocol()
# path = self._content_browser.get_selected_icon_path()
# if not path.startswith(protocol):
# path = protocol + path
self.open_window_and_play(value)
def _on_content_browser_load(self): # pragma: no cover
import omni.kit.window.content_browser
self._content_browser = omni.kit.window.content_browser.get_content_window()
if self._content_browser is not None:
self._content_browser_entry = self._content_browser.add_context_menu(
"Play Audio", "audio_play.svg", self._on_browser_click, self._on_menu_check
)
def _on_content_browser_unload(self): # pragma: no cover
if self._content_browser is not None:
self._content_browser.delete_context_menu("Play Audio")
self._content_browser_entry = None
self._content_browser = None
def _on_player_event(self, event):
if event.type == int(omni.audioplayer.CallbackType.LOADED):
success = event.payload["success"]
self._file_loaded(success)
elif event.type == int(omni.audioplayer.CallbackType.ENDED):
self._play_finished()
else:
print("unrecognized type " + str(event.type))
def on_startup(self):
self._content_browser = None
self._hooks = []
manager = omni.kit.app.get_app().get_extension_manager()
# current content window
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._on_content_browser_load(),
on_disable_fn=lambda _: self._on_content_browser_unload(),
ext_name="omni.kit.window.content_browser",
hook_name="omni.kit.window.audioplayer omni.kit.window.content_browser listener",
)
)
self._loading_counter = 0
self._ticker = None
self._loading = False
self._end_reason = EndReason.FINISHED
self._new_file = True
self._sound_length = 0
self._timeline_slider_scale = 0
self._file = ""
self._playing = False
self._paused = False
self._player = omni.audioplayer.create_audio_player()
self._sub = self._player.get_event_stream().create_subscription_to_pop(self._on_player_event)
self._window = omni.ui.Window("Audio Player", width=600, height=200)
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop", False)
with self._window.frame:
with omni.ui.VStack(height=0, spacing=8):
# file dialogue
with omni.ui.HStack():
omni.ui.Button(
width=32,
height=32,
clicked_fn=self._choose_file_clicked,
style={"image_url": "resources/glyphs/folder.svg"},
)
self._file_field_model = AudioPlayerWindowExtension.FieldModel(self._file_field_end_edit)
self._file_field = omni.ui.StringField(self._file_field_model, height=32)
# timeline slider
with omni.ui.HStack(height=64):
self._timeline_cursor_label = omni.ui.Label("0:00", width=25)
omni.ui.Label(" / ", width=10)
self._timeline_end_label = omni.ui.Label("0:00", width=25)
self._timeline_slider_model = AudioPlayerWindowExtension.SliderModel(
self._slider_changed, self._slider_end_edit
)
with omni.ui.ZStack():
self._waveform_image_provider = omni.ui.ByteImageProvider()
self._waveform_image = omni.ui.ImageWithProvider(
self._waveform_image_provider,
width=omni.ui.Percent(100),
height=omni.ui.Percent(100),
fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH,
)
with omni.ui.VStack():
omni.ui.Spacer()
self._timeline_slider = omni.ui.FloatSlider(
self._timeline_slider_model,
height=0,
style={
"color": 0x00FFFFFF,
"background_color": 0x00000000,
"draw_mode": omni.ui.SliderDrawMode.HANDLE,
"font_size": 22,
},
)
omni.ui.Spacer()
# buttons
with omni.ui.HStack():
with omni.ui.ZStack():
omni.ui.Spacer()
self._load_result_label = omni.ui.Label(
"", alignment=omni.ui.Alignment.CENTER, style={"color": 0xFF0000FF}
)
self._play_button = omni.ui.Button(
width=32,
height=32,
clicked_fn=self._play_clicked,
style={"image_url": "resources/glyphs/timeline_play.svg"},
)
omni.ui.Button(
width=32,
height=32,
clicked_fn=self._stop_clicked,
style={"image_url": "resources/glyphs/timeline_stop.svg"},
)
with omni.ui.ZStack():
omni.ui.Spacer()
self._loading_label = omni.ui.Label("", alignment=omni.ui.Alignment.CENTER)
with omni.ui.HStack(alignment=omni.ui.Alignment.LEFT, width=100):
omni.ui.Label("Close on Stop", alignment=omni.ui.Alignment.LEFT)
omni.ui.Spacer()
self._auto_close_on_stop = omni.ui.CheckBox(alignment=omni.ui.Alignment.LEFT)
omni.ui.Spacer()
self._auto_close_on_stop.model.set_value(
self._settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop")
)
self._dict = carb.dictionary.get_dictionary()
self._auto_close_on_stop.model.add_value_changed_fn(
lambda a, b=self._settings: b.set_bool(
PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop", a.get_value_as_bool()
)
)
def on_change(item, event_type): # pragma: no cover
self._auto_close_on_stop.model.set_value(self._dict.get(item))
self._subscription = self._settings.subscribe_to_node_change_events(
PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop", on_change
)
# add a callback to open the window
# FIXME: disabled until the bugs are worked out
self._menuEntry = omni.kit.ui.get_editor_menu().add_item("Window/Audio Player", self._menu_callback)
self._window.visible = False
def on_shutdown(self): # pragma: no cover
self._end_reason = EndReason.STOPPED
self._player.stop_sound()
if self._ticker != None:
self._ticker.cancel()
self._settings.unsubscribe_to_change_events(self._subscription)
self._subscription = None
# run the unload function to avoid breaking the extension when it reloads
self._on_content_browser_unload()
# remove the subscription before the player to avoid events with a dead player
self._sub = None
self._player = None
self._window = None
self._menuEntry = None
self._content_window_entry = None
| 19,473 | Python | 37.259332 | 179 | 0.559185 |
omniverse-code/kit/exts/omni.kit.window.audioplayer/omni/kit/window/audioplayer/tests/test_audio_player.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.test
import omni.kit.ui_test
import omni.ui as ui
import omni.usd
import omni.timeline
import carb.tokens
import omni.usd.audio
from omni.ui.tests.test_base import OmniUiTest
import pathlib
import asyncio;
class TestAudioPlayerWindow(OmniUiTest): # pragma: no cover
async def _dock_window(self):
await self.docked_test_window(
window=self._win.window,
width=600,
height=200)
def _dump_ui_tree(self, root):
print("DUMP UI TREE START")
#windows = omni.ui.Workspace.get_windows()
#children = [windows[0].frame]
children = [root.frame]
print(str(dir(root.frame)))
def recurse(children, path=""):
for c in children:
name = path + "/" + type(c).__name__
print(name)
if isinstance(c, omni.ui.ComboBox):
print(str(dir(c)))
recurse(omni.ui.Inspector.get_children(c), name)
recurse(children)
print("DUMP UI TREE END")
async def setUp(self):
await super().setUp()
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.window.audioplayer}")
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
self._golden_img_dir = self._test_path.joinpath("golden")
# open the dropdown
window_menu = omni.kit.ui_test.get_menubar().find_menu("Window")
self.assertIsNotNone(window_menu)
await window_menu.click()
# click the audioplayer option to open it
player_menu = omni.kit.ui_test.get_menubar().find_menu("Audio Player")
self.assertIsNotNone(player_menu)
await player_menu.click()
self._win = omni.kit.ui_test.find("Audio Player")
self.assertIsNotNone(self._win)
self._file_name_textbox = self._win.find("**/StringField[*]")
self.assertIsNotNone(self._file_name_textbox)
async def _test_just_opened(self):
await self._dock_window()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_just_opened.png")
async def _test_load_file(self):
await self._file_name_textbox.click()
await self._file_name_textbox.input(str(self._test_path / "1hz.oga"))
await asyncio.sleep(1.0)
# delete the text in the textbox so we'll have something constant
# for the image comparison
await self._file_name_textbox.double_click()
await omni.kit.ui_test.emulate_keyboard_press(carb.input.KeyboardInput.DEL)
await self._dock_window()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_open_file.png")
async def test_all(self):
await self._test_just_opened()
await self._test_load_file()
self._dump_ui_tree(self._win.window)
| 3,359 | Python | 34.368421 | 109 | 0.649598 |
omniverse-code/kit/exts/omni.kit.property.geometry/omni/kit/property/geometry/scripts/geometry_properties.py | import os
import carb
import omni.ext
from functools import partial
from pathlib import Path
from pxr import Sdf, Usd, UsdGeom, UsdUI
from typing import Any, Callable
from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload
_extension_instance = None
TEST_DATA_PATH = ""
def get_instance():
global _extension_instance
return _extension_instance
class GeometryPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
self._button_menu_entry = []
self._visual_property_widget = None
super().__init__()
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
# +add menu item(s)
from omni.kit.property.usd import PrimPathWidget
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None:
carb.log_error("context_menu is disabled!") # pragma: no cover
return None # pragma: no cover
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Instanceable",
show_fn=context_menu.is_prim_selected,
onclick_fn=self._click_toggle_instanceable,
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Wireframe Mode",
name_fn=partial(self._get_primvar_state, prim_name="wireframe", text_name=" Wireframe Mode"),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="wireframe"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Do Not Cast Shadows",
name_fn=partial(
self._get_primvar_state, prim_name="doNotCastShadows", text_name=" Do Not Cast Shadows"
),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="doNotCastShadows"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Enable Shadow Terminator Fix",
name_fn=partial(
self._get_primvar_state, prim_name="enableShadowTerminatorFix", text_name=" Enable Shadow Terminator Fix"
),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="enableShadowTerminatorFix"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Enable Fast Refraction Shadow",
name_fn=partial(
self._get_primvar_state, prim_name="enableFastRefractionShadow", text_name=" Enable Fast Refraction Shadow"
),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="enableFastRefractionShadow"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Disable RT SSS Transmission",
name_fn=partial(
self._get_primvar_state, prim_name="disableRtSssTransmission", text_name=" Disable RT SSS Transmission"
),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="disableRtSssTransmission"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Multimatted ID:",
name_fn=partial(
self._get_primvar_state, prim_name="multimatte_id", text_name=" ID for multimatte"
),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="multimatte_id"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Enable Holdout Object",
name_fn=partial(
self._get_primvar_state, prim_name="holdoutObject", text_name=" Enable Holdout Object"
),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="holdoutObject"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Invisible To Secondary Rays",
name_fn=partial(
self._get_primvar_state, prim_name="invisibleToSecondaryRays", text_name=" Invisible To Secondary Rays"
),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="invisibleToSecondaryRays"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Is Procedural Volume",
name_fn=partial(
self._get_primvar_state, prim_name="isVolume", text_name=" Is Volume"
),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="isVolume"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Matte Object",
name_fn=partial(self._get_primvar_state, prim_name="isMatteObject", text_name=" Matte Object"),
show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Boundable),
onclick_fn=partial(self._click_set_primvar, prim_name="isMatteObject"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Hide From Camera",
name_fn=partial(
self._get_primvar_state, prim_name="hideForCamera", text_name=" Hide From Camera"
),
show_fn=[partial(context_menu.prim_is_type, type=UsdGeom.Boundable)],
onclick_fn=partial(self._click_set_primvar, prim_name="hideForCamera"),
)
)
self._button_menu_entry.append(
PrimPathWidget.add_button_menu_entry(
"Rendering/Toggle Is Light",
name_fn=partial(self._get_primvar_state, prim_name="isLight", text_name=" Is Light"),
show_fn=[partial(context_menu.prim_is_type, type=UsdGeom.Boundable)],
onclick_fn=partial(self._click_set_primvar, prim_name="isLight"),
)
)
def on_shutdown(self): # pragma: no cover
if self._registered:
self._unregister_widget()
# release menu item(s)
from omni.kit.property.usd import PrimPathWidget
for item in self._button_menu_entry:
PrimPathWidget.remove_button_menu_entry(item)
global _extension_instance
_extension_instance = None
def register_custom_visual_attribute(self,
attribute_name: str,
display_name: str,
type_name: str,
default_value: Any,
predicate: Callable[[Any], bool] = None):
"""
Add custom attribute with placeholder.
"""
if self._visual_property_widget:
self._visual_property_widget.add_custom_attribute(
attribute_name,
display_name,
type_name,
default_value,
predicate
)
def deregister_custom_visual_attribute(self, attribute_name: str):
if self._visual_property_widget:
self._visual_property_widget.remove_custom_attribute(attribute_name)
def _register_widget(self):
import omni.kit.window.property as p
from .prim_kind_widget import PrimKindWidget
from .prim_geometry_widget import GeometrySchemaAttributesWidget, ImageableSchemaAttributesWidget
w = p.get_window()
if w:
w.register_widget(
"prim",
"geometry",
GeometrySchemaAttributesWidget(
"Geometry",
UsdGeom.Xformable,
[
UsdGeom.BasisCurves,
UsdGeom.Capsule,
UsdGeom.Cone,
UsdGeom.Cube,
UsdGeom.Cylinder,
UsdGeom.HermiteCurves,
UsdGeom.Mesh,
UsdGeom.NurbsCurves,
UsdGeom.NurbsPatch,
UsdGeom.PointInstancer,
UsdGeom.Points,
UsdGeom.Subset,
UsdGeom.Sphere,
UsdGeom.Xform,
UsdGeom.Gprim,
UsdGeom.PointBased,
UsdGeom.Boundable,
UsdGeom.Curves,
UsdGeom.Imageable,
UsdGeom.PointBased,
UsdGeom.Subset,
UsdGeom.ModelAPI,
UsdGeom.MotionAPI,
UsdGeom.PrimvarsAPI,
UsdGeom.XformCommonAPI,
UsdGeom.ModelAPI,
UsdUI.Backdrop,
UsdUI.NodeGraphNodeAPI,
UsdUI.SceneGraphPrimAPI,
],
[
"proceduralMesh:parameterCheck",
"outputs:parameterCheck",
"refinementEnableOverride",
"refinementLevel",
"primvars:doNotCastShadows",
"primvars:enableShadowTerminatorFix",
"primvars:enableFastRefractionShadow",
"primvars:disableRtSssTransmission",
"primvars:holdoutObject",
"primvars:invisibleToSecondaryRays",
"primvars:isMatteObject",
"primvars:isVolume",
"primvars:multimatte_id",
"primvars:numSplits",
"primvars:endcaps",
UsdGeom.Tokens.proxyPrim,
],
[
"primvars:displayColor",
"primvars:displayOpacity",
"doubleSided",
"purpose",
"visibility",
"xformOpOrder",
],
),
)
self._visual_property_widget = ImageableSchemaAttributesWidget(
"Visual",
UsdGeom.Imageable,
[],
["primvars:displayColor", "primvars:displayOpacity", "doubleSided", "singleSided"],
[]
)
w.register_widget(
"prim",
"geometry_imageable",
self._visual_property_widget,
)
w.register_widget("prim", "kind", PrimKindWidget())
self._registered = True
def _unregister_widget(self): # pragma: no cover
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "geometry")
w.unregister_widget("prim", "geometry_imageable")
w.unregister_widget("prim", "kind")
self._registered = False
def _click_set_primvar(self, payload: PrimSelectionPayload, prim_name: str):
stage = payload.get_stage()
if not stage:
return
omni.kit.commands.execute("TogglePrimVarCommand", prim_path=payload.get_paths(), prim_name=prim_name)
def _get_primvar_state(self, objects: dict, prim_name: str, text_prefix: str = "", text_name: str = "") -> str:
if not "stage" in objects or not "prim_list" in objects or not objects["stage"]:
return None
stage = objects["stage"]
primvar_state = []
for path in objects["prim_list"]:
prim = stage.GetPrimAtPath(path) if isinstance(path, Sdf.Path) else path
if prim:
primvars_api = UsdGeom.PrimvarsAPI(prim)
is_primvar = primvars_api.GetPrimvar(prim_name)
if is_primvar:
primvar_state.append(is_primvar.Get())
else:
primvar_state.append(False)
if primvar_state == [False] * len(primvar_state):
return f"{text_prefix}Set{text_name}"
elif primvar_state == [True] * len(primvar_state):
return f"{text_prefix}Clear{text_name}"
return f"{text_prefix}Toggle{text_name}"
def _click_toggle_instanceable(self, payload: PrimSelectionPayload):
omni.kit.commands.execute("ToggleInstanceableCommand", prim_path=payload.get_paths())
| 14,059 | Python | 41.477341 | 127 | 0.532968 |
omniverse-code/kit/exts/omni.kit.property.geometry/omni/kit/property/geometry/scripts/prim_geometry_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import omni.usd
from dataclasses import dataclass, field
from typing import Any, Callable, OrderedDict, List
from omni.kit.property.usd.usd_property_widget import MultiSchemaPropertiesWidget, UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import create_primspec_bool, create_primspec_int
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from pxr import Kind, Sdf, Usd, UsdGeom
class GeometrySchemaAttributesWidget(MultiSchemaPropertiesWidget):
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
# custom attributes
self.add_custom_schema_attribute("primvars:enableFastRefractionShadow", lambda p: p.IsA(UsdGeom.Gprim), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("primvars:doNotCastShadows", lambda p: p.IsA(UsdGeom.Gprim), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("primvars:enableShadowTerminatorFix", lambda p: p.IsA(UsdGeom.Gprim), None, "", create_primspec_bool(True))
self.add_custom_schema_attribute("primvars:holdoutObject", lambda p: p.IsA(UsdGeom.Gprim), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("primvars:invisibleToSecondaryRays", lambda p: p.IsA(UsdGeom.Gprim), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("primvars:isMatteObject", lambda p: p.IsA(UsdGeom.Gprim), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("primvars:isVolume", lambda p: p.IsA(UsdGeom.Gprim), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("primvars:multimatte_id", lambda p: p.IsA(UsdGeom.Gprim), None, "", create_primspec_int(-1))
self.add_custom_schema_attribute("primvars:disableRtSssTransmission", lambda p: p.IsA(UsdGeom.Gprim), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("primvars:numSplitsOverride", lambda p: p.IsA(UsdGeom.BasisCurves), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("primvars:numSplits", lambda p: p.IsA(UsdGeom.BasisCurves), None, "", create_primspec_int(2))
self.add_custom_schema_attribute("primvars:endcaps", lambda p: p.IsA(UsdGeom.BasisCurves), None, "", create_primspec_int(1))
self.add_custom_schema_attribute("refinementEnableOverride", self._is_prim_refinement_level_supported, None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("refinementLevel", self._is_prim_refinement_level_supported, None, "", create_primspec_int(0))
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
self._add_curves = False
self._add_points = False
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim or not prim.IsA(self._schema):
return False
used += [attr for attr in prim.GetProperties() if attr.GetName() in self._schema_attr_names and not attr.IsHidden()]
if (prim.IsA(UsdGeom.BasisCurves)):
self._add_curves = True
if (prim.IsA(UsdGeom.Points)):
self._add_points = True
if self.is_custom_schema_attribute_used(prim):
used.append(None)
return used
def _is_prim_refinement_level_supported(self, prim):
return (
prim.IsA(UsdGeom.Mesh)
or prim.IsA(UsdGeom.Cylinder)
or prim.IsA(UsdGeom.Capsule)
or prim.IsA(UsdGeom.Cone)
or prim.IsA(UsdGeom.Sphere)
or prim.IsA(UsdGeom.Cube)
)
def _is_prim_single_sided_supported(self, prim):
return (
prim.IsA(UsdGeom.Mesh)
or prim.IsA(UsdGeom.Cylinder)
or prim.IsA(UsdGeom.Capsule)
or prim.IsA(UsdGeom.Cone)
or prim.IsA(UsdGeom.Sphere)
or prim.IsA(UsdGeom.Cube)
)
def _customize_props_layout(self, attrs):
self.add_custom_schema_attributes_to_props(attrs)
frame = CustomLayoutFrame(hide_extra=False)
with frame:
def update_bounds(stage, prim_paths):
timeline = omni.timeline.get_timeline_interface()
current_time = timeline.get_current_time()
current_time_code = Usd.TimeCode(
omni.usd.get_frame_time_code(current_time, stage.GetTimeCodesPerSecond())
)
for path in prim_paths:
prim = stage.GetPrimAtPath(path)
attr = prim.GetAttribute("extent") if prim else None
if prim and attr:
bounds = UsdGeom.Boundable.ComputeExtentFromPlugins(UsdGeom.Boundable(prim), current_time_code)
attr.Set(bounds)
def build_extent_func(
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs={},
additional_widget_kwargs={},
):
from omni.kit.window.property.templates import HORIZONTAL_SPACING
from omni.kit.property.usd.usd_attribute_model import UsdAttributeModel
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.property.usd.widgets import ICON_PATH
if not attr_name or not property_type:
return
def value_changed_func(model, widget):
val = model.get_value_as_string()
widget.set_tooltip(val)
with ui.HStack(spacing=HORIZONTAL_SPACING):
model = UsdAttributeModel(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata)
UsdPropertiesWidgetBuilder._create_label(attr_name, metadata, additional_label_kwargs)
kwargs = {
"name": "models_readonly",
"model": model,
"enabled": False,
"tooltip": model.get_value_as_string(),
}
if additional_widget_kwargs:
kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.StringField(**kwargs)
mixed_overlay = UsdPropertiesWidgetBuilder._create_mixed_text_overlay()
ui.Spacer(width=0)
with ui.VStack(width=8):
ui.Spacer()
ui.Image(
f"{ICON_PATH}/Default value.svg",
width=5.5,
height=5.5,
)
ui.Spacer()
model.add_value_changed_fn(lambda m, w=value_widget: value_changed_func(m,w))
return model
def build_size_func(
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs={},
additional_widget_kwargs={},
):
from omni.kit.window.property.templates import HORIZONTAL_SPACING
from omni.kit.property.usd.usd_attribute_model import UsdAttributeModel
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.property.usd.widgets import ICON_PATH
if not attr_name or not property_type:
return
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = UsdPropertiesWidgetBuilder._get_attr_value_range_kwargs(metadata)
model = UsdAttributeModel(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs
)
UsdPropertiesWidgetBuilder._create_label(attr_name, metadata, additional_label_kwargs)
widget_kwargs = {"model": model}
widget_kwargs.update(UsdPropertiesWidgetBuilder._get_attr_value_soft_range_kwargs(metadata))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = UsdPropertiesWidgetBuilder._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs)
mixed_overlay = UsdPropertiesWidgetBuilder._create_mixed_text_overlay()
UsdPropertiesWidgetBuilder._create_control_state(value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs)
model.add_value_changed_fn(lambda m, s=stage, p=prim_paths: update_bounds(s, p))
return model
def build_axis_func(
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs={},
additional_widget_kwargs={},
):
from omni.kit.window.property.templates import HORIZONTAL_SPACING
from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.property.usd.widgets import ICON_PATH
if not attr_name or not property_type:
return
with ui.HStack(spacing=HORIZONTAL_SPACING):
model = None
UsdPropertiesWidgetBuilder._create_label(attr_name, metadata, additional_label_kwargs)
tokens = metadata.get("allowedTokens")
if tokens is not None and len(tokens) > 0:
model = TfTokenAttributeModel(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata
)
widget_kwargs = {"name": "choices"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.ComboBox(model, **widget_kwargs)
mixed_overlay = UsdPropertiesWidgetBuilder._create_mixed_text_overlay()
else:
model = UsdAttributeModel(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata
)
widget_kwargs = {"name": "models"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.StringField(model, **widget_kwargs)
mixed_overlay = UsdPropertiesWidgetBuilder._create_mixed_text_overlay()
UsdPropertiesWidgetBuilder._create_control_state(
model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs
)
model.add_item_changed_fn(lambda m, i, s=stage, p=prim_paths: update_bounds(s, p))
return model
def build_endcaps_func(
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs={},
additional_widget_kwargs={},
):
from omni.kit.window.property.templates import HORIZONTAL_SPACING
from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
from omni.kit.property.usd.widgets import ICON_PATH
if not attr_name or not property_type:
return
with ui.HStack(spacing=HORIZONTAL_SPACING):
model = None
UsdPropertiesWidgetBuilder._create_label(attr_name, metadata, additional_label_kwargs)
class MyTfTokenAttributeModel(TfTokenAttributeModel):
allowed_tokens = ["open", "flat", "round"]
def _get_allowed_tokens(self, attr):
return self.allowed_tokens
def _get_value_from_index(self, value):
return value
def _update_value(self, force=False):
was_updating_value = self._updating_value
self._updating_value = True
if super(TfTokenAttributeModel, self)._update_value(force):
# TODO don't have to do this every time. Just needed when "allowedTokens" actually changed
self._update_allowed_token()
index = self._value if self._value < len(self._allowed_tokens) else -1
if index != -1 and self._current_index.as_int != index:
self._current_index.set_value(index)
self._item_changed(None)
self._updating_value = was_updating_value
model = MyTfTokenAttributeModel(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata
)
widget_kwargs = {"name": "choices"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.ComboBox(model, **widget_kwargs)
mixed_overlay = UsdPropertiesWidgetBuilder._create_mixed_text_overlay()
UsdPropertiesWidgetBuilder._create_control_state(
model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs
)
return model
if self._add_curves:
with CustomLayoutGroup("Curve"):
CustomLayoutProperty("curveVertexCounts", "Per curve points")
CustomLayoutProperty("points", "Points")
CustomLayoutProperty("normals", "Normals")
CustomLayoutProperty("widths", "Widths")
CustomLayoutProperty("type", "Type")
CustomLayoutProperty("basis", "Basis")
CustomLayoutProperty("wrap", "Wrap")
CustomLayoutProperty("primvars:numSplitsOverride", "Number of BVH splits Override")
CustomLayoutProperty("primvars:numSplits", "Number of BVH splits")
CustomLayoutProperty("primvars:endcaps", "Endcaps", build_fn=build_endcaps_func)
if self._add_points:
with CustomLayoutGroup("Points"):
CustomLayoutProperty("points", "Points")
CustomLayoutProperty("normals", "Normals")
CustomLayoutProperty("widths", "Widths")
commonSectionName = "Mesh"
if self._add_curves or self._add_points:
commonSectionName = "Common"
with CustomLayoutGroup(commonSectionName):
CustomLayoutProperty("normals", "Normals")
CustomLayoutProperty("orientation", "Orientation")
CustomLayoutProperty("points", "Points")
CustomLayoutProperty("velocities", "Velocities")
CustomLayoutProperty("accelerations", "Accelerations")
CustomLayoutProperty("extent", "Extent", build_fn=build_extent_func)
CustomLayoutProperty("size", "Size", build_fn=build_size_func)
CustomLayoutProperty("radius", "Radius", build_fn=build_size_func)
CustomLayoutProperty("axis", "Axis", build_fn=build_axis_func)
CustomLayoutProperty("height", "Height", build_fn=build_size_func)
CustomLayoutProperty("polymesh:parameterCheck", "Parameter Check")
CustomLayoutProperty("primvars:doNotCastShadows", "Cast Shadows", build_fn=self._inverse_bool_builder)
CustomLayoutProperty("primvars:enableShadowTerminatorFix", "Shadow Terminator Fix")
CustomLayoutProperty("primvars:enableFastRefractionShadow", "Fast Refraction Shadow")
CustomLayoutProperty("primvars:disableRtSssTransmission", "Enable Rt SSS Transmission", build_fn=self._inverse_bool_builder)
CustomLayoutProperty("primvars:holdoutObject", "Holdout Object")
CustomLayoutProperty("primvars:invisibleToSecondaryRays", "Invisible To Secondary Rays")
CustomLayoutProperty("primvars:isMatteObject", "Matte Object")
CustomLayoutProperty("primvars:isVolme", "Is Volume")
CustomLayoutProperty("primvars:multimatte_id", "Multimatte ID")
with CustomLayoutGroup("Face"):
CustomLayoutProperty("faceVertexIndices", "Indices")
CustomLayoutProperty("faceVertexCounts", "Counts")
CustomLayoutProperty("faceVaryingLinearInterpolation", "Linear Interpolation")
CustomLayoutProperty("holeIndices", "Hole Indices")
with CustomLayoutGroup("Refinement"):
CustomLayoutProperty("refinementEnableOverride", "Refinement Override")
CustomLayoutProperty("refinementLevel", "Refinement Level")
CustomLayoutProperty("interpolateBoundary", "Interpolate Boundary")
CustomLayoutProperty("subdivisionScheme", "Subdivision Scheme")
CustomLayoutProperty("triangleSubdivisionRule", "Triangle SubdivisionRule")
with CustomLayoutGroup("Corner"):
CustomLayoutProperty("cornerIndices", "Indices")
CustomLayoutProperty("cornerSharpnesses", "Sharpnesses")
with CustomLayoutGroup("Crease"):
CustomLayoutProperty("creaseIndices", "Indices")
CustomLayoutProperty("creaseLengths", "Lengths")
CustomLayoutProperty("creaseSharpnesses", "Sharpnesses")
return frame.apply(attrs)
def get_additional_kwargs(self, ui_prop: UsdPropertyUiEntry):
"""
Override this function if you want to supply additional arguments when building the label or ui widget.
"""
additional_widget_kwargs = None
if ui_prop.prop_name == "refinementLevel":
additional_widget_kwargs = {"min": 0, "max": 5}
return None, additional_widget_kwargs
def _inverse_bool_builder(self,
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs={},
additional_widget_kwargs={}
):
import carb.settings
from omni.kit.window.property.templates import HORIZONTAL_SPACING
from omni.kit.property.usd.usd_attribute_model import UsdAttributeInvertedModel
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
if not attr_name or not property_type:
return
with ui.HStack(spacing=HORIZONTAL_SPACING):
model = UsdAttributeInvertedModel(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata)
settings = carb.settings.get_settings()
left_aligned = settings.get("ext/omni.kit.window.property/checkboxAlignment") == "left"
if not left_aligned:
if not additional_label_kwargs:
additional_label_kwargs = {}
additional_label_kwargs["width"] = 0
UsdPropertiesWidgetBuilder._create_label(attr_name, metadata, additional_label_kwargs)
if not left_aligned:
ui.Spacer(width=10)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
ui.Spacer(width=5)
with ui.VStack(width=10):
ui.Spacer()
widget_kwargs = {"width": 10, "height": 0, "name": "greenCheck", "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
with ui.Placer(offset_x=0, offset_y=-2):
value_widget = ui.CheckBox(**widget_kwargs)
with ui.Placer(offset_x=1, offset_y=-1):
mixed_overlay = ui.Rectangle(
height=8, width=8, name="mixed_overlay", alignment=ui.Alignment.CENTER, visible=False
)
ui.Spacer()
if left_aligned:
ui.Spacer(width=5)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
UsdPropertiesWidgetBuilder._create_control_state(value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs)
return model
@dataclass(frozen=True)
class CustomAttributeInfo:
schema_name: str
display_name: str
type_name: str
default_value: Any
predicate: Callable[[Any], bool] = None
def is_supported(self, prim):
return self.predicate is None or self.predicate(prim)
def get_metadata(self):
return {Sdf.PrimSpec.TypeNameKey: self.type_name, "customData": {"default": self.default_value}}
class ImageableSchemaAttributesWidget(MultiSchemaPropertiesWidget):
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
self._custom_attributes: OrderedDict[str, CustomAttributeInfo] = OrderedDict()
self._custom_placeholders: List[str] = []
# custom attributes
self.add_custom_schema_attribute("singleSided", self._is_prim_single_sided_supported, None, "", create_primspec_bool(False))
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
self._custom_placeholders.clear()
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim or not prim.IsA(self._schema):
return False
used += [attr for attr in prim.GetProperties() if attr.GetName() in self._schema_attr_names and not attr.IsHidden()]
for schema_name, attr_info in self._custom_attributes.items():
if attr_info.is_supported(prim) and not prim.GetAttribute(schema_name):
self._custom_placeholders.append(schema_name)
used.append(None)
if self.is_custom_schema_attribute_used(prim):
used.append(None)
return used
def add_custom_attribute(self,
attribute_name,
display_name,
type_name="bool",
default_value=False,
predicate: Callable[[Any], bool] = None):
"""
Add custom attribute with placeholder.
"""
self._schema_attr_base.add(attribute_name)
self._custom_attributes.update(
{attribute_name: CustomAttributeInfo(attribute_name, display_name, type_name, default_value, predicate)}
)
self.request_rebuild()
def remove_custom_attribute(self, attribute_name):
self._schema_attr_base.remove(attribute_name)
del self._custom_attributes[attribute_name]
self.request_rebuild()
def _is_prim_single_sided_supported(self, prim):
return (
prim.IsA(UsdGeom.Mesh)
or prim.IsA(UsdGeom.Cylinder)
or prim.IsA(UsdGeom.Capsule)
or prim.IsA(UsdGeom.Cone)
or prim.IsA(UsdGeom.Sphere)
or prim.IsA(UsdGeom.Cube)
)
def _customize_props_layout(self, attrs):
self.add_custom_schema_attributes_to_props(attrs)
for schema_name, attr_info in self._custom_attributes.items():
if schema_name in self._custom_placeholders:
attrs.append(
UsdPropertyUiEntry(
schema_name,
"",
attr_info.get_metadata(),
Usd.Attribute,
)
)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
for schema_name, attr_info in self._custom_attributes.items():
CustomLayoutProperty(schema_name, attr_info.display_name)
# OMFP-1917: Most Visual settings under the Property tab don't work
# Hiding doubleSided, singleSided, primvars:displayColor, primvars:displayOpacity
CustomLayoutProperty("doubleSided", "Double Sided", hide_if_true=True)
CustomLayoutProperty("singleSided", "Single Sided", hide_if_true=True)
CustomLayoutProperty("purpose", "Purpose")
CustomLayoutProperty("visibility", "Visibility")
CustomLayoutProperty("primvars:displayColor", "Display Color")
CustomLayoutProperty("primvars:displayOpacity", "Display Opacity")
return frame.apply(attrs)
| 28,148 | Python | 49.627698 | 160 | 0.574996 |
omniverse-code/kit/exts/omni.kit.property.geometry/omni/kit/property/geometry/scripts/__init__.py | from .geometry_properties import *
from .geometry_commands import *
| 68 | Python | 21.999993 | 34 | 0.794118 |
omniverse-code/kit/exts/omni.kit.property.geometry/omni/kit/property/geometry/scripts/geometry_commands.py | import carb
import omni.kit.commands
from typing import List, Optional, Any
from pxr import Usd, Sdf, UsdGeom
class PrimVarCommand(omni.kit.commands.Command):
"""
Set primvar undoable **Command**.
Args:
prim_path (list): List of paths of prims.
prim_name (str): Primvar name.
prim_type (): Primvar variable type (EG. Sdf.ValueTypeNames.Bool)
value (any): New primvar value. If primvar doesn't exist, it will be created
"""
def __init__(
self,
prim_path: List[str],
prim_name: str,
prim_type: str,
value: Any,
usd_context_name: Optional[str] = "",
):
self._prim_path = prim_path
self._prim_name = prim_name
self._prim_type = prim_type
self._value = value
self._usd_context = omni.usd.get_context(usd_context_name)
self._undo_values = {}
def do(self):
stage = self._usd_context.get_stage()
for path in self._prim_path:
if path:
primvars_api = UsdGeom.PrimvarsAPI(stage.GetPrimAtPath(path))
value = primvars_api.GetPrimvar(self._prim_name)
if value:
if value.GetTypeName() != self._prim_type:
carb.log_error(f"PrimVarCommand: cannot set value as {path}.{self._prim_name} is type {value.GetTypeName()} and expected type is {self._prim_type}")
else:
self._undo_values[str(path)] = value.Get()
value.Set(self._value)
else:
self._undo_values[str(path)] = None
primvars_api.CreatePrimvar(self._prim_name, self._prim_type).Set(self._value)
def undo(self):
stage = self._usd_context.get_stage()
for path in self._undo_values.keys():
primvars_api = UsdGeom.PrimvarsAPI(stage.GetPrimAtPath(path))
value = primvars_api.GetPrimvar(self._prim_name)
orig_value = self._undo_values[path]
if orig_value:
value.Set(orig_value)
else:
primvars_api.RemovePrimvar(self._prim_name)
self._undo_values = {}
class TogglePrimVarCommand(omni.kit.commands.Command):
"""
Toggle primvar undoable **Command**.
Args:
prim_path (list): List of paths of prims.
prim_name (str): Primvar name.
"""
def __init__(
self,
prim_path: List[str],
prim_name: str,
usd_context_name: Optional[str] = "",
):
self._prim_path = prim_path
self._prim_name = prim_name
self._usd_context = omni.usd.get_context(usd_context_name)
self._undo_values = {}
def do(self):
stage = self._usd_context.get_stage()
for path in self._prim_path:
if path:
primvars_api = UsdGeom.PrimvarsAPI(stage.GetPrimAtPath(path))
value = primvars_api.GetPrimvar(self._prim_name)
if value:
if value.GetTypeName() != Sdf.ValueTypeNames.Bool:
carb.log_error(f"TogglePrimVarCommand: cannot set value as {value.GetTypeName()} isn't a {self._prim_type}")
else:
self._undo_values[str(path)] = value.Get()
value.Set(not value.Get())
else:
self._undo_values[path] = None
primvars_api.CreatePrimvar(self._prim_name, Sdf.ValueTypeNames.Bool).Set(True)
def undo(self):
stage = self._usd_context.get_stage()
for path in self._undo_values.keys():
primvars_api = UsdGeom.PrimvarsAPI(stage.GetPrimAtPath(path))
value = primvars_api.GetPrimvar(self._prim_name)
orig_value = self._undo_values[path]
if orig_value:
value.Set(orig_value)
else:
primvars_api.RemovePrimvar(self._prim_name)
self._undo_values = {}
class ToggleInstanceableCommand(omni.kit.commands.Command):
"""
Toggle instanceable undoable **Command**.
Args:
prim_path (list): List of paths of prims.
"""
def __init__(
self,
prim_path: List[str],
usd_context_name: Optional[str] = "",
):
self._prim_path = prim_path
self._usd_context = omni.usd.get_context(usd_context_name)
self._undo_values = {}
def do(self):
stage = self._usd_context.get_stage()
for path in self._prim_path:
if path:
prim = stage.GetPrimAtPath(path)
value = prim.IsInstanceable()
self._undo_values[str(path)] = value
prim.SetInstanceable(not value)
def undo(self):
stage = self._usd_context.get_stage()
for path in self._undo_values.keys():
prim = stage.GetPrimAtPath(path)
value = self._undo_values[path]
prim.SetInstanceable(value)
self._undo_values = {}
| 5,046 | Python | 33.101351 | 173 | 0.550139 |
omniverse-code/kit/exts/omni.kit.property.geometry/omni/kit/property/geometry/scripts/prim_kind_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ui as ui
import omni.usd
import carb
from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT, HORIZONTAL_SPACING
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder, UsdPropertiesWidget
from omni.kit.property.usd.usd_object_model import MetadataObjectModel
from pxr import Kind, Usd, UsdGeom
class Constant:
def __setattr__(self, name, value):
raise Exception(f"Can't change Constant.{name}") # pragma: no cover
FONT_SIZE = 14.0
MIXED = "Mixed"
MIXED_COLOR = 0xFFCC9E61
class PrimKindWidget(UsdPropertiesWidget):
def __init__(self):
super().__init__(title="Kind", collapsed=False)
self._metadata_model = None
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload): # pragma: no cover
return False # pragma: no cover
if len(self._payload) == 0:
return False
for prim_path in self._payload: # pragma: no cover
prim = self._get_prim(prim_path) # pragma: no cover
if not prim or not prim.IsA(UsdGeom.Imageable): # pragma: no cover
return False
return True
def reset(self):
super().reset()
if self._metadata_model:
self._metadata_model.clean()
self._metadata_model = None
def build_items(self):
super().build_items()
# get Kinds
all_kinds = Kind.Registry.GetAllKinds()
all_kinds.insert(0, "")
# http://graphics.pixar.com/usd/docs/USD-Glossary.html#USDGlossary-Kind
# "model" is considered an abstract type and should not be assigned as any prim's kind.
all_kinds.remove(Kind.Tokens.model)
kind = None
ambiguous = False
stage = self._payload.get_stage()
for path in self._payload:
prim = stage.GetPrimAtPath(path)
if prim:
prim_kind = Usd.ModelAPI(prim).GetKind()
if kind == None:
kind = prim_kind
elif kind != prim_kind:
kind = "mixed"
if prim_kind not in all_kinds: # pragma: no cover
all_kinds.append(prim_kind) # pragma: no cover
carb.log_verbose(f"{path} has invalid Kind:{prim_kind}") # pragma: no cover
if kind == None: # pragma: no cover
return # pragma: no cover
if self._filter.matches("Kind"):
self._any_item_visible = True
highlight = self._filter.name
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._create_label("Kind", {}, {"highlight": highlight})
with ui.ZStack():
self._metadata_model = MetadataObjectModel(
stage, [path for path in self._payload], False, {}, key="kind", default="", options=all_kinds
)
value_widget = ui.ComboBox(self._metadata_model, name="choices")
mixed_overlay = UsdPropertiesWidgetBuilder._create_mixed_text_overlay()
UsdPropertiesWidgetBuilder._create_control_state(self._metadata_model, value_widget, mixed_overlay)
def _get_shared_properties_from_selected_prims(self, anchor_prim):
return None
def _get_prim(self, prim_path):
if prim_path:
stage = self._payload.get_stage()
if stage:
return stage.GetPrimAtPath(prim_path)
return None # pragma: no cover
| 4,198 | Python | 37.172727 | 117 | 0.596951 |
omniverse-code/kit/exts/omni.kit.property.geometry/omni/kit/property/geometry/tests/test_path_toggle.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
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Gf
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class PropertyPathAddMenu(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "geometry_test.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_property_path_rendering(self):
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# select cube
await select_prims(["/World/Cube"])
await ui_test.human_delay()
# verify not set
prim = stage.GetPrimAtPath("/World/Cube")
attr = prim.GetAttribute("primvars:wireframe")
self.assertFalse(attr.IsValid())
# click "Add"
add_widget = [w for w in ui_test.find_all("Property//Frame/**/Button[*].identifier==''") if w.widget.text.endswith("Add")][0]
await add_widget.click()
# select wireframe
await ui_test.select_context_menu("Rendering/Set Wireframe Mode")
# verify set
self.assertTrue(attr.IsValid())
self.assertTrue(attr.Get())
# undo
omni.kit.undo.undo()
# verify not set
self.assertFalse(attr.IsValid())
| 2,006 | Python | 33.016949 | 133 | 0.678465 |
omniverse-code/kit/exts/omni.kit.property.geometry/omni/kit/property/geometry/tests/__init__.py | from .test_geometry import *
from .test_commands import *
from .test_path_toggle import *
| 90 | Python | 21.749995 | 31 | 0.755556 |
omniverse-code/kit/exts/omni.kit.property.geometry/omni/kit/property/geometry/tests/test_commands.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import pathlib
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test_suite.helpers import open_stage, get_test_data_path
from omni.kit import ui_test
from pxr import Sdf
class TestCommandWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
await open_stage(get_test_data_path(__name__, "geometry_test.usda"))
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_command_prim_var(self):
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath("/World/Cube")
attr = prim.GetAttribute('primvars:test_int')
self.assertFalse(attr.IsValid())
# create primvar as int
omni.kit.commands.execute("PrimVarCommand", prim_path=["/World/Cube"], prim_name="test_int", prim_type=Sdf.ValueTypeNames.Int, value=123456)
attr = prim.GetAttribute('primvars:test_int')
self.assertTrue(attr.IsValid())
self.assertEqual(attr.Get(), 123456)
# try and change using bool
omni.kit.commands.execute("PrimVarCommand", prim_path=["/World/Cube"], prim_name="test_int", prim_type=Sdf.ValueTypeNames.Bool, value=True)
attr = prim.GetAttribute('primvars:test_int')
self.assertTrue(attr.IsValid())
self.assertEqual(attr.Get(), 123456)
# change primvar
omni.kit.commands.execute("PrimVarCommand", prim_path=["/World/Cube"], prim_name="test_int", prim_type=Sdf.ValueTypeNames.Int, value=654321)
attr = prim.GetAttribute('primvars:test_int')
self.assertTrue(attr.IsValid())
self.assertEqual(attr.Get(), 654321)
# undo
omni.kit.undo.undo()
omni.kit.undo.undo()
omni.kit.undo.undo()
# verify undo removed primvar
attr = prim.GetAttribute('primvars:test_int')
self.assertFalse(attr.IsValid())
# create primvar as bool
omni.kit.commands.execute("PrimVarCommand", prim_path=["/World/Cube"], prim_name="test_bool", prim_type=Sdf.ValueTypeNames.Bool, value=True)
attr = prim.GetAttribute('primvars:test_bool')
self.assertTrue(attr.IsValid())
self.assertEqual(attr.Get(), True)
# try and change using int
omni.kit.commands.execute("PrimVarCommand", prim_path=["/World/Cube"], prim_name="test_bool", prim_type=Sdf.ValueTypeNames.Int, value=123456)
attr = prim.GetAttribute('primvars:test_bool')
self.assertTrue(attr.IsValid())
self.assertEqual(attr.Get(), True)
# change primvar
omni.kit.commands.execute("PrimVarCommand", prim_path=["/World/Cube"], prim_name="test_bool", prim_type=Sdf.ValueTypeNames.Bool, value=False)
attr = prim.GetAttribute('primvars:test_bool')
self.assertTrue(attr.IsValid())
self.assertEqual(attr.Get(), False)
# undo
omni.kit.undo.undo()
omni.kit.undo.undo()
omni.kit.undo.undo()
# verify undo removed primvar
attr = prim.GetAttribute('primvars:test_bool')
self.assertFalse(attr.IsValid())
async def test_command_toggle_prim_var(self):
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath("/World/Cube")
attr = prim.GetAttribute('primvars:test_bool')
self.assertFalse(attr.IsValid())
# create primvar as bool
omni.kit.commands.execute("TogglePrimVarCommand", prim_path=["/World/Cube"], prim_name="test_bool")
attr = prim.GetAttribute('primvars:test_bool')
self.assertTrue(attr.IsValid())
self.assertEqual(attr.Get(), True)
# try and change using int
omni.kit.commands.execute("PrimVarCommand", prim_path=["/World/Cube"], prim_name="test_bool", prim_type=Sdf.ValueTypeNames.Int, value=123456)
attr = prim.GetAttribute('primvars:test_bool')
self.assertTrue(attr.IsValid())
self.assertEqual(attr.Get(), True)
# change primvar
omni.kit.commands.execute("TogglePrimVarCommand", prim_path=["/World/Cube"], prim_name="test_bool")
attr = prim.GetAttribute('primvars:test_bool')
self.assertTrue(attr.IsValid())
self.assertEqual(attr.Get(), False)
# undo
omni.kit.undo.undo()
omni.kit.undo.undo()
omni.kit.undo.undo()
# verify undo removed primvar
attr = prim.GetAttribute('primvars:test_bool')
self.assertFalse(attr.IsValid())
async def test_command_toggle_instanceable(self):
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath("/World/Cube")
self.assertFalse(prim.IsInstanceable())
# toggle instanceable
omni.kit.commands.execute("ToggleInstanceableCommand", prim_path=["/World/Cube"])
self.assertTrue(prim.IsInstanceable())
# toggle instanceable
omni.kit.commands.execute("ToggleInstanceableCommand", prim_path=["/World/Cube"])
self.assertFalse(prim.IsInstanceable())
# undo
omni.kit.undo.undo()
omni.kit.undo.undo()
omni.kit.undo.undo()
# verify undo
self.assertFalse(prim.IsInstanceable())
| 5,718 | Python | 38.171233 | 149 | 0.659671 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.display/omni/kit/viewport/menubar/display/style.py | from pathlib import Path
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("icons")
UI_STYLE = {"Menu.Item.Icon::Display": {"image_url": f"{ICON_PATH}/viewport_visibility.svg"}}
| 253 | Python | 35.285709 | 94 | 0.727273 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.display/omni/kit/viewport/menubar/display/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__ = ["ViewportDisplayMenuBarExtension", "get_instance"]
from typing import Union
from omni.kit.viewport.menubar.core import BaseCategoryItem
from .display_menu_container import DEFAULT_SECTION, DisplayMenuContainer
import omni.ext
_extension_instance = None
def get_instance():
global _extension_instance
return _extension_instance
class ViewportDisplayMenuBarExtension(omni.ext.IExt):
"""The Entry Point for the Display Settings in Viewport Menu Bar"""
def on_startup(self, ext_id):
self._display_menu = DisplayMenuContainer()
global _extension_instance
_extension_instance = self
def on_shutdown(self):
self._display_menu.destroy()
self._display_menu = None
global _extension_instance
_extension_instance = None
def register_custom_setting(self, text: str, setting_path: str):
"""
Register custom display setting.
Args:
text (str): Text shown in menu item.
setting_path (str): Setting path for custom display setting (bool value).
"""
if self._display_menu:
self._display_menu.register_custom_setting(text, setting_path)
def deregister_custom_setting(self, text: str):
"""
Deregister custom display setting.
Args:
text (str): Text shown in menu item.
"""
if self._display_menu:
self._display_menu.deregister_custom_setting(text)
def register_custom_category_item(self, category: str, item: BaseCategoryItem, section: str = DEFAULT_SECTION):
"""
Register custom display setting in category.
Args:
category (str): Category to add menu item. Can be an existing category e.g. "Heads Up Display" or a new one.
item (item: BaseCategoryItem): Item to append.
section (str): Optional section to organise category, default no section.
"""
if self._display_menu:
self._display_menu.register_custom_category_item(category, item, section)
def deregister_custom_category_item(self, category: str, item: BaseCategoryItem):
"""
Deregister custom display setting in category.
Args:
category (str): Category to remove menu item. Can be an existing category e.g. "Heads Up Display" or a new one.
item (item: BaseCategoryItem): Item to remove.
"""
if self._display_menu:
self._display_menu.deregister_custom_category_item(category, item)
| 2,971 | Python | 36.15 | 123 | 0.672164 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.display/omni/kit/viewport/menubar/display/model.py | import omni.ui as ui
class DisplayLayerModel(ui.SimpleBoolModel):
def __init__(self, layer) -> None:
self._layer = layer
super().__init__()
def get_value_as_bool(self) -> bool:
return self._layer.visible
def set_value(self, visible: bool):
if visible != self._layer.visible:
self._layer.visible = visible
self._value_changed()
def begin_edit(self) -> None:
pass
def end_edit(self) -> None:
pass
| 493 | Python | 21.454544 | 44 | 0.56998 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.display/omni/kit/viewport/menubar/display/display_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__ = ["DisplayMenuContainer"]
from omni.kit.viewport.menubar.core import (
IconMenuDelegate,
SettingModel,
ViewportMenuContainer,
CategoryMenuContainer,
SelectableMenuItem,
SimpleCategoryModel,
CategoryStateItem,
BaseCategoryItem,
CategoryCustomItem,
CategoryCollectionItem
)
from .style import UI_STYLE
import carb
import carb.settings
import omni.ui as ui
import omni.kit.app
import omni.usd
from functools import partial
from typing import Dict, List, Optional
SHOW_BY_TYPE_EXCLUDE_LIST = "/exts/omni.kit.viewport.menubar.display/showByType/exclude_list"
HEADS_UP_CATEGORY_NAME = "Heads Up Display"
SHOW_BY_TYPE_CATEGORY_NAME = "Show By Type"
SHOW_BY_PURPOSE_CATEGORY_NAME = "Show By Purpose"
DEFAULT_CATEGORIES = [HEADS_UP_CATEGORY_NAME, SHOW_BY_TYPE_CATEGORY_NAME, SHOW_BY_PURPOSE_CATEGORY_NAME]
DEFAULT_SECTION = "default"
def _make_viewport_setting(viewport_api_id: str, setting: str):
return f"/persistent/app/viewport/{viewport_api_id}/{setting}/visible"
class DisplayMenuContainer(ViewportMenuContainer):
"""The menu with the visibility settings"""
def __init__(self):
super().__init__(
name="Display",
delegate=IconMenuDelegate("Display"),
visible_setting_path="/exts/omni.kit.viewport.menubar.display/visible",
order_setting_path="/exts/omni.kit.viewport.menubar.display/order",
style=UI_STYLE
)
self._root_menu: Optional[ui.Menu] = None
self._category_models: Dict[str, SimpleCategoryModel] = {}
self._custom_settings: List[List[str, str]] = []
self._custom_category_items: Dict[str, List[BaseCategoryItem]] = {}
self._section_categories: Dict[str, List[str]] = {}
self._section_categories[DEFAULT_SECTION] = DEFAULT_CATEGORIES[:] # Copy the default categories list
def destroy(self):
super().destroy()
def register_custom_setting(self, text: str, setting_path: str):
self._custom_settings.append((text, setting_path))
if self._root_menu:
self._root_menu.invalidate()
def deregister_custom_setting(self, text: str):
found = [item for item in self._custom_settings if item[0] == text]
if found:
for item in found:
self._custom_settings.remove(item)
if self._root_menu:
self._root_menu.invalidate()
def register_custom_category_item(self, category: str, item: BaseCategoryItem, section: str):
is_top_category = False
if category not in DEFAULT_CATEGORIES and category not in self._category_models:
if item.text == category and isinstance(item, CategoryCollectionItem):
self._category_models[category] = SimpleCategoryModel(category, root=item)
is_top_category = True
else:
self._category_models[category] = SimpleCategoryModel(category)
if category not in self._custom_category_items:
self._custom_category_items[category] = []
if section not in self._section_categories:
self._section_categories[section] = []
if not is_top_category:
self._custom_category_items[category].append(item)
if category not in self._section_categories[section]:
self._section_categories[section].append(category)
if self._root_menu:
self._root_menu.invalidate()
def deregister_custom_category_item(self, category: str, item: BaseCategoryItem):
if category in self._custom_category_items:
if item in self._custom_category_items[category]:
self._custom_category_items[category].remove(item)
if category not in DEFAULT_CATEGORIES:
if (item.text == category and isinstance(item, CategoryCollectionItem)) or len(self._custom_category_items[category]) == 0:
del self._category_models[category]
# Now clean up section
sections = list(self._section_categories.keys())
for section in sections:
if category in self._section_categories[section]:
self._section_categories[section].remove(category)
if len(self._section_categories[section]) == 0:
del self._section_categories[section]
if self._root_menu:
self._root_menu.invalidate()
def build_fn(self, viewport_context: dict):
self._root_menu = ui.Menu(self.name, delegate=self._delegate,
on_build_fn=partial(self._build_menu_items, viewport_context),
style=self._style)
def _build_menu_items(self, viewport_context: dict, *args, **kwargs):
viewport = viewport_context.get("viewport_api")
viewport_api_id: str = str(viewport.id)
settings = carb.settings.get_settings()
show_by_type_items: list[BaseCategoryItem] = [
CategoryStateItem("Cameras", setting_path=_make_viewport_setting(viewport_api_id, "scene/cameras")),
CategoryStateItem("Lights", setting_path=_make_viewport_setting(viewport_api_id, "scene/lights")),
CategoryStateItem("Skeletons", setting_path=_make_viewport_setting(viewport_api_id, "scene/skeletons")),
CategoryStateItem("Audio", setting_path=_make_viewport_setting(viewport_api_id, "scene/audio")),
]
if (exclude_list := settings.get(SHOW_BY_TYPE_EXCLUDE_LIST)):
show_by_type_items = [item for item in show_by_type_items if item.text not in exclude_list]
# 105.1: Support alternate label of memory (i.e. "Host Memory", "Process Memory", "Memory")
# Defaults to pre 105.1 label (Host Memory) when not specified
mem_label = settings.get("/exts/omni.kit.viewport.window/hud/hostMemory/label")
if mem_label is None:
mem_label = "Host"
default_category_models = {
HEADS_UP_CATEGORY_NAME: SimpleCategoryModel(
HEADS_UP_CATEGORY_NAME,
[
CategoryStateItem("FPS", setting_path=_make_viewport_setting(viewport_api_id, "hud/renderFPS")),
CategoryStateItem("Device Memory", setting_path=_make_viewport_setting(viewport_api_id, "hud/deviceMemory")),
CategoryStateItem(f"{mem_label} Memory", setting_path=_make_viewport_setting(viewport_api_id, "hud/hostMemory")),
CategoryStateItem("Resolution", setting_path=_make_viewport_setting(viewport_api_id, "hud/renderResolution")),
CategoryStateItem("Progress", setting_path=_make_viewport_setting(viewport_api_id, "hud/renderProgress")),
]
),
SHOW_BY_TYPE_CATEGORY_NAME: SimpleCategoryModel(
SHOW_BY_TYPE_CATEGORY_NAME,
show_by_type_items
),
SHOW_BY_PURPOSE_CATEGORY_NAME: SimpleCategoryModel(
SHOW_BY_PURPOSE_CATEGORY_NAME,
[
CategoryStateItem("Guide", setting_path="/persistent/app/hydra/displayPurpose/guide"),
CategoryStateItem("Proxy", setting_path="/persistent/app/hydra/displayPurpose/proxy"),
CategoryStateItem("Render", setting_path="/persistent/app/hydra/displayPurpose/render"),
]
)
}
self._category_models.update(default_category_models)
# XXX: These add_item calls currently must occur to add the separator!
self._category_models[SHOW_BY_TYPE_CATEGORY_NAME].add_item(CategoryCustomItem(
"Meshes",
lambda: SelectableMenuItem("Meshes",
SettingModel(setting_path=_make_viewport_setting(viewport_api_id, "scene/meshes")))
))
self._category_models[HEADS_UP_CATEGORY_NAME].add_item(CategoryCustomItem(
"Camera Speed",
lambda: SelectableMenuItem("Camera Speed",
SettingModel(_make_viewport_setting(viewport_api_id, "hud/cameraSpeed")))
))
identifier = "omni.kit.viewport.menubar.display"
# Create default section categories first
for name in self._section_categories[DEFAULT_SECTION]:
model = self._category_models[name]
if name in self._custom_category_items:
for item in self._custom_category_items[name]:
model.add_item(item)
# XXX: Workaround nested creation of these items not being able to trigger an action!
trigger_fns = None
if name == SHOW_BY_TYPE_CATEGORY_NAME:
icon_click_id = f"{identifier}.{name}.{name}" # Left-most check/mixed icon was toggled
trigger_fns = {
"Cameras": partial(self.__trigger_action, "toggle_camera_visibility", viewport_api=viewport),
"Lights": partial(self.__trigger_action, "toggle_light_visibility", viewport_api=viewport),
"Skeletons": partial(self.__trigger_action, "toggle_skeleton_visibility", viewport_api=viewport),
"Audio": partial(self.__trigger_action, "toggle_audio_visibility", viewport_api=viewport),
"Meshes": partial(self.__trigger_action, "toggle_mesh_visibility", viewport_api=viewport),
icon_click_id: partial(self.__trigger_action, "toggle_show_by_type_visibility", viewport_api=viewport),
}
CategoryMenuContainer(model, identifier=f"{identifier}.{name}", trigger_fns=trigger_fns)
# Now iterate named sections, with a separator for each.
for section, categories in self._section_categories.items():
if section is DEFAULT_SECTION:
continue
ui.Separator(text=section)
for name in categories:
model = self._category_models[name]
if name in self._custom_category_items:
for item in self._custom_category_items[name]:
model.add_item(item)
CategoryMenuContainer(model, identifier=f"{identifier}.{name}")
ui.Separator()
# This currently is just easier tied to legacy global setting
SelectableMenuItem("Selection Outline", SettingModel(_make_viewport_setting(viewport_api_id, "guide/selection")),
triggered_fn=partial(self.__trigger_action, "toggle_selection_hilight_visibility", viewport_api=viewport),
trigger_will_set_model=True
)
SelectableMenuItem("Axis", SettingModel(_make_viewport_setting(viewport_api_id, "guide/axis")),
triggered_fn=partial(self.__trigger_action, "toggle_axis_visibility", viewport_api=viewport),
trigger_will_set_model=True
)
SelectableMenuItem("Grid", SettingModel(_make_viewport_setting(viewport_api_id, "guide/grid")),
triggered_fn=partial(self.__trigger_action, "toggle_grid_visibility", viewport_api=viewport),
trigger_will_set_model=True
)
# Custom display settings
if self._custom_settings:
ui.Separator()
for (text, setting_path) in self._custom_settings:
SelectableMenuItem(text, SettingModel(setting_path))
def __trigger_action(self, action: str, *args, **kwargs):
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
if action_registry:
exc_action = action_registry.get_action("omni.kit.viewport.actions", action)
if exc_action:
exc_action.execute(*args, **kwargs)
else:
carb.log_error(f"Could not find action to run: '{action}'")
else:
carb.log_error(f"Could not get action_registry to run '{action}")
| 12,371 | Python | 47.140078 | 135 | 0.629941 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.display/omni/kit/viewport/menubar/display/tests/test_ui.py | import omni.kit.test
from re import I
from omni.ui.tests.test_base import OmniUiTest
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 asyncio
import omni.ui as ui
from omni.kit.viewport.menubar.core import CategoryCollectionItem, CategoryStateItem, CategoryCustomItem, ViewportMenuDelegate, SelectableMenuItem
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
TEST_SETTING_TRUE = "/exts/test/setting/true"
TEST_SETTING_FALSE = "/exts/test/setting/false"
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)
await omni.kit.app.get_app().next_update_async()
async def test_general(self):
await self._show_display_menu("menubar_display.png", None)
async def test_heads_up(self):
await self._show_display_menu("menubar_display_headsup.png", 86)
async def test_show_by_type(self):
await self._show_display_menu("menubar_display_show_type.png", 106)
async def test_show_by_purpose(self):
await self._show_display_menu("menubar_display_show_purpose.png", 126)
async def test_show_custom_menu_item(self):
inst = omni.kit.viewport.menubar.display.get_instance()
custom_collection_item = CategoryCollectionItem(
"Custom catetory",
[
CategoryStateItem("Custom Item", ui.SimpleBoolModel(True)),
]
)
inst.register_custom_category_item("Show By Type", custom_collection_item)
def _build_menu():
with ui.Menu("Physics", delegate=ViewportMenuDelegate()):
SelectableMenuItem("Joints", ui.SimpleBoolModel(True))
with ui.Menu("Colliders", delegate=ViewportMenuDelegate()):
SelectableMenuItem("None", ui.SimpleBoolModel(True))
SelectableMenuItem("Selected", ui.SimpleBoolModel(False))
SelectableMenuItem("All", ui.SimpleBoolModel(False))
ui.Separator()
SelectableMenuItem("Normals", ui.SimpleBoolModel(False))
physics_item = CategoryCustomItem("Physics", _build_menu)
inst.register_custom_category_item("Show By Type", physics_item)
settings = carb.settings.get_settings()
settings.set(TEST_SETTING_FALSE, False)
settings.set(TEST_SETTING_TRUE, True)
inst.register_custom_setting("test new setting (True)", TEST_SETTING_TRUE)
inst.register_custom_setting("test new setting (False)", TEST_SETTING_FALSE)
await omni.kit.app.get_app().next_update_async()
await self._show_display_menu("menubar_display_custom.png", 106)
inst.deregister_custom_category_item("Show By Type", custom_collection_item)
inst.deregister_custom_category_item("Show By Type", physics_item)
inst.deregister_custom_setting("test new setting (True)")
inst.deregister_custom_setting("test new setting (False)")
await omni.kit.app.get_app().next_update_async()
async def test_show_custom_category_and_section(self):
inst = omni.kit.viewport.menubar.display.get_instance()
category = "Draw Overlay"
section = "Selection Display"
did_shown_changed_callback = False
def on_shown(s):
print("on_shown: {s}")
nonlocal did_shown_changed_callback
did_shown_changed_callback = True
overlay_item = CategoryCollectionItem(
category,
[
CategoryCustomItem("Points", lambda: SelectableMenuItem("Points", model=ui.SimpleBoolModel())),
CategoryCustomItem("Normals", lambda: SelectableMenuItem("Normals", model=ui.SimpleBoolModel()))
],
shown_changed_fn=on_shown
)
inst.register_custom_category_item(category, overlay_item, section)
await omni.kit.app.get_app().next_update_async()
await self._show_display_menu("menubar_display_custom_category_and_section.png", 166)
self.assertTrue(did_shown_changed_callback)
inst.deregister_custom_category_item(category, overlay_item)
await omni.kit.app.get_app().next_update_async()
async def _show_display_menu(self, golden_img_name: str, y: int = None) -> 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)
try:
await ui_test.emulate_mouse_move(Vec2(20, 46), human_delay_speed=4)
await ui_test.emulate_mouse_click()
if y is not None:
await ui_test.emulate_mouse_move(Vec2(20, y))
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name)
finally:
for i in range(3):
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(Vec2(300, 26))
await ui_test.emulate_mouse_click()
for i in range(3):
await omni.kit.app.get_app().next_update_async()
| 5,475 | Python | 39.865671 | 146 | 0.652603 |
omniverse-code/kit/exts/omni.kit.usdz_export/omni/kit/usdz_export/extension_usdz.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 .layers_menu import layers_available
from .layers_menu import LayersMenu
import omni.ext
import omni.kit.app
class UsdzExportExtension(omni.ext.IExt):
def on_startup(self, ext_id):
# Setup a callback for the event
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
self.__extensions_subscription = ext_manager.get_change_event_stream().create_subscription_to_pop(
self._on_event, name="omni.kit.usdz_export"
)
self.__layers_menu = None
self._on_event(None)
def _on_event(self, event):
# Create/destroy the menu in the Layers window
if self.__layers_menu:
if not layers_available():
self.__layers_menu.destroy()
self.__layers_menu = None
else:
if layers_available():
self.__layers_menu = LayersMenu()
def on_shutdown(self):
self.__extensions_subscription = None
if self.__layers_menu:
self.__layers_menu.destroy()
self.__layers_menu = None
| 1,530 | Python | 33.795454 | 106 | 0.65817 |
omniverse-code/kit/exts/omni.kit.usdz_export/omni/kit/usdz_export/layers_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .utils import is_extension_loaded, copy, list_folder_async
from pxr import Sdf, Usd
from pathlib import Path
from zipfile import ZipFile
from functools import partial
from typing import Callable, List
from omni.kit.window.file_exporter import get_file_exporter
from omni.kit.widget.prompt import PromptManager
import carb
import omni.kit.tool.collect as collect
import omni.usd
import asyncio
import tempfile
import os
import shutil
import omni.kit.app
import omni.kit.notification_manager as nm
def layers_available() -> bool:
"""Returns True if the extension "omni.kit.widget.layers" is loaded"""
return is_extension_loaded("omni.kit.widget.layers")
async def usdz_export(identifier, export_path):
try:
target_out = export_path
carb.log_info(f"Starting to export layer '{identifier}' to '{target_out}'")
prompt = PromptManager.post_simple_prompt("Please Wait", "Exporting to USDZ...", ok_button_info=None, modal=True)
# Waits for prompt to be shown
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
layer = Sdf.Layer.FindOrOpen(identifier)
if not layer:
message = f"Failed to export layer {identifier} as it does not exist."
carb.log_error(message)
nm.post_notification(message, status=nm.NotificationStatus.WARNING)
return
with tempfile.TemporaryDirectory() as tmp_path:
tmp_path = Path(tmp_path)
collect_path = tmp_path.joinpath("collected")
split_ext = os.path.splitext(identifier)
# Can't collect USDZ files because MDLs can't be resolved
if (split_ext[1] == '.usdz'):
input_usdz_temp_path = str(tmp_path.joinpath('temp_copy.usdz'))
await copy(identifier, str(input_usdz_temp_path))
with ZipFile(input_usdz_temp_path, 'r') as zip_ref:
zip_ref.extractall(str(tmp_path))
tmp_file_path = str(tmp_path.joinpath("main.usdc"))
layer.Export(tmp_file_path)
entry_layer_to_collect = tmp_file_path
elif not omni.usd.is_usd_writable_filetype(identifier) or identifier.startswith('anon'):
tmp_file_path = str(tmp_path.joinpath("main.usdc"))
layer.Export(tmp_file_path)
entry_layer_to_collect = tmp_file_path
else:
entry_layer_to_collect = identifier
collector = collect.Collector(entry_layer_to_collect, str(collect_path), flat_collection=True)
await collector.collect(None, None)
# must create USDZ locally because the UsdUtils package cannot handle omniverse:// URIs
absolute_paths, relative_paths = await list_folder_async(str(collect_path))
local_out_path = collect_path.joinpath("local_out.usdz")
# Create usdz package manually without using USD API as it cannot handle UDIM textures.
zip_writer = Usd.ZipFileWriter.CreateNew(str(local_out_path))
with zip_writer:
for absolute_path, relative_path in zip(absolute_paths, relative_paths):
url = omni.client.break_url(absolute_path)
absolute_path = url.path
# FIXME: omni.client will return windows path prefixed with '/'
if os.name == "nt" and absolute_path[0] == '/':
absolute_path = absolute_path[1:]
zip_writer.AddFile(absolute_path, relative_path)
await copy(str(local_out_path), target_out)
layer = None
zip_writer = None
finally:
prompt.visible = False
prompt = None
carb.log_info(f"Finished exporting layer '{identifier}' to '{target_out}'")
def export(objects):
"""Export the target layer to USDZ"""
def on_export(callback: Callable, flatten: bool, filename: str, dirname: str, extension: str = '', selections: List[str] = []):
nonlocal objects
path = f"{dirname}/{filename}{extension}"
item = objects["item"]
identifier = item().identifier
asyncio.ensure_future(usdz_export(identifier, path))
file_picker = get_file_exporter()
file_picker.show_window(
title="Export To USDZ",
export_button_label="Export",
export_handler=partial(on_export, None, False),
file_extension_types=[(".usdz", "Zipped package")]
)
class LayersMenu:
"""
When this object is alive, Layers 2.0 has an additional action
for exporting the layer to USDZ.
"""
def __init__(self):
import omni.kit.widget.layers as layers
self.__menu_subscription = layers.ContextMenu.add_menu(
[
{"name": ""},
{
"name": "Export USDZ",
"glyph": "menu_rename.svg",
"show_fn": [
layers.ContextMenu.is_layer_item,
layers.ContextMenu.is_not_missing_layer,
layers.ContextMenu.is_layer_not_locked_by_other,
layers.ContextMenu.is_layer_and_parent_unmuted
],
"onclick_fn": export,
}
]
)
def destroy(self):
"""Remove the menu from Layers 2.0"""
self.__menu_subscription = None
| 5,903 | Python | 38.891892 | 131 | 0.614942 |
omniverse-code/kit/exts/omni.kit.usdz_export/omni/kit/usdz_export/utils.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import omni.kit.app
import traceback
import carb
import omni.client
import omni.client.utils as clientutils
def is_extension_loaded(extansion_name: str) -> bool:
"""
Returns True if the extension with the given name is loaded.
"""
def is_ext(id: str, extension_name: str) -> bool:
id_name = id.split("-")[0]
return id_name == extension_name
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
extensions = ext_manager.get_extensions()
loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None)
return not not loaded
async def copy(src_path: str, dest_path: str):
carb.log_info(f"Copying from {src_path} to {dest_path}...")
try:
result = await omni.client.copy_async(src_path, dest_path, omni.client.CopyBehavior.OVERWRITE)
if result != omni.client.Result.OK:
carb.log_error(f"Cannot copy from {src_path} to {dest_path}, error code: {result}.")
return False
else:
return True
except Exception as e:
traceback.print_exc()
carb.log_error(str(e))
return False
async def list_folder_async(folder_path):
def compute_absolute_path(base_path, is_base_path_folder, path, is_path_folder):
if is_base_path_folder and not base_path.endswith("/"):
base_path += "/"
if is_path_folder and not path.endswith("/"):
path += "/"
return clientutils.make_absolute_url_if_possible(base_path, path)
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix) :]
return text
absolute_paths = []
relative_paths = []
result, entry = await omni.client.stat_async(folder_path)
if result == omni.client.Result.OK and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
is_folder = True
else:
is_folder = False
folder_path = clientutils.make_file_url_if_possible(folder_path)
if not is_folder:
absolute_paths = [folder_path]
relative_paths = [os.path.basename(folder_path)]
else:
if not folder_path.endswith("/"):
folder_path += "/"
folder_queue = [folder_path]
while len(folder_queue) > 0:
folder = folder_queue.pop(0)
(result, entries) = await omni.client.list_async(folder)
if result != omni.client.Result.OK:
break
folders = set((e.relative_path for e in entries if e.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN))
for f in folders:
folder_queue.append(compute_absolute_path(folder, True, f, False))
files = set((e.relative_path for e in entries if not e.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN))
for file in files:
absolute_path = compute_absolute_path(folder, True, file, False)
absolute_paths.append(absolute_path)
relative_path = remove_prefix(absolute_path, folder_path[:-1])
relative_path = relative_path.replace("\\", "/")
if relative_path != "/" and relative_path.startswith("/"):
relative_path = relative_path[1:]
if len(relative_path) > 0:
relative_paths.append(relative_path)
return absolute_paths, relative_paths
| 3,859 | Python | 36.115384 | 116 | 0.63177 |
omniverse-code/kit/exts/omni.kit.usdz_export/omni/kit/usdz_export/tests/usdz_export_test.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 omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from pxr import Usd
from pxr import UsdGeom
import carb
import omni.client
import omni.kit
import omni.usd
import os
import time
import unittest
from omni.kit.usdz_export import usdz_export
OMNI_SERVER = "omniverse://ov-test"
class TestUsdzExport(OmniUiTest):
def get_test_dir(self):
token = carb.tokens.get_tokens_interface()
data_dir = token.resolve("${data}")
return f"{data_dir}"
async def test_export_usdz_file(self):
usdz_size = 2600000
usdz_size_tc = 2675966
current_path = Path(__file__)
test_data_path = current_path.parent.parent.parent.parent.parent.joinpath("data")
test_stage_path = str(test_data_path.joinpath("test_stage").joinpath("scene.usd"))
test_dir = self.get_test_dir()
export_file_path = Path(test_dir).joinpath("out.usdz").resolve()
await usdz_export(test_stage_path, export_file_path.__str__())
self.assertTrue(os.path.isfile(export_file_path.__str__()), 'out.usdz does not exist')
size = os.stat(export_file_path).st_size
self.assertTrue(size >= usdz_size and size <= usdz_size_tc, f'File size mismatch, expected {usdz_size} but got {size}')
| 1,702 | Python | 36.844444 | 127 | 0.706228 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/gol.py | """Build global dictionary"""
from .sunpath_data import SunpathData
def _init():
global _global_dict
_global_dict = {}
# Pathmodel For draw sphere
_global_dict["pathmodel"] = SunpathData(230, 12, 30, 112.94, 28.12)
# For distant light to determine whether to change the attribute
_global_dict["dome_angle"] = None
# Parameter for DrawSunpath
_global_dict["origin"] = [0, 0, 0]
_global_dict["scale"] = 50
_global_dict["color"] = [255, 255, 255]
_global_dict["length"] = 3.5
# Flag for show sun
_global_dict["sun_state"] = False
# Flag for show info
_global_dict["show_info"] = False
def set_value(key, value):
_global_dict[key] = value
def set_item(key, i, value):
_global_dict[key][i] = value
def get_value(key):
try:
return _global_dict[key]
except:
print("get" + key + "fail\r\n")
| 888 | Python | 20.682926 | 71 | 0.608108 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/gesture.py | from omni.ui import scene as sc
from omni.ui import color as cl
from . import gol
class _ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
window.disable_selection_rect(True)
except Exception:
pass
class MoveGesture(sc.DragGesture):
"""Define the action of gesture"""
def __init__(self, transform: sc.Transform):
super().__init__()
self.__transform = transform
self._previous_ray_point = None
self._pre_origin = None
def on_began(self):
self.sender.color = cl.beige
self.sender.width = gol.get_value("length")
self.disable_selection = _ViewportLegacyDisableSelection()
self._previous_ray_point = self.gesture_payload.ray_closest_point
self._pre_origin = gol.get_value("origin")
def on_changed(self):
translate = self.sender.gesture_payload.moved
current = sc.Matrix44.get_translation_matrix(*translate)
self.__transform.transform *= current
object_ray_point = self.gesture_payload.ray_closest_point
# Compute translation vector(point)
moved = [a - b for a, b in zip(object_ray_point, self._previous_ray_point)]
# Compute new origin and save it to dictionary
origin = [a + b for a, b in zip(self._pre_origin, moved)]
gol.set_value("origin", origin)
def on_ended(self):
self.sender.color = cl.documentation_nvidia
self.sender.width = gol.get_value("length") / 2
self.disable_selection = None
| 2,129 | Python | 32.281249 | 83 | 0.608736 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/sunlight_manipulator.py | __all__ = ["SunlightManipulator"]
from .sunpath_data import SunpathData
from pxr import Gf, Sdf
import omni.kit.commands
from . import gol
class SunlightManipulator:
def __init__(self, pathmodel: SunpathData):
self.path = None
# Get origin value from global dictionary
self.origin = gol.get_value("origin")
self.pathmodel = pathmodel
def add_sun(self):
"""
Add distant light to present sunlight
"""
omni.kit.commands.execute("CreatePrim", prim_type="DistantLight", attributes={"angle": 1.0, "intensity": 3000})
self.path = "/World/DistantLight"
def change_sun(self):
"""
Change distant light property(rotation)
"""
xr, yr = self.pathmodel.dome_rotate_angle()
if [xr, yr] != gol.get_value("dome_angle"):
omni.kit.commands.execute(
"TransformPrimSRT",
path=Sdf.Path("/World/DistantLight"),
new_rotation_euler=Gf.Vec3d(xr, yr, 0),
)
x, y, z = self.pathmodel.cur_sun_position()
if y < 0:
omni.kit.commands.execute(
"ChangeProperty", prop_path=Sdf.Path("/World/DistantLight.visibility"), value="invisible", prev=None
)
else:
omni.kit.commands.execute(
"ChangeProperty", prop_path=Sdf.Path("/World/DistantLight.visibility"), value="inherited", prev=None
)
gol.set_value("dome_angle", [xr, yr])
def show_sun(self):
"""
The method to add light and change it's property
"""
if self.path is None:
self.add_sun()
self.change_sun()
def del_sun(self):
"""
the method to delete exisit distant light
"""
if self.path is not None:
omni.kit.commands.execute("DeletePrims", paths=["/World/DistantLight"])
self.path = None
| 1,974 | Python | 30.349206 | 120 | 0.556231 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/style.py | __all__ = ["sunpath_window_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
# Pre-defined constants. It's possible to change them runtime.
cl.slider_bg_color = cl(0.28, 0.28, 0.28, 0.0)
cl.window_bg_color = cl(0.2, 0.2, 0.2, 1.0)
cl.sunpath_window_attribute_bg = cl(0, 0, 0)
cl.sunpath_window_attribute_fg = cl(1.0, 1.0, 1.0, 0.3)
cl.sunpath_window_hovered = cl(0.95, 0.95, 0.95, 1.0)
cl.sunpath_window_item = cl(0.65, 0.65, 0.65, 1.0)
fl.sunpath_window_attr_hspacing = 15
fl.sunpath_window_attr_spacing = 1
fl.sunpath_window_group_spacing = 2
fl.border_radius = 3
fl.outer_frame_padding = 8
url.sunpath_window_icon_closed = f"{EXTENSION_FOLDER_PATH}/icons/closed.svg"
url.sunpath_window_icon_opened = f"{EXTENSION_FOLDER_PATH}/icons/opened.svg"
url.diag_bg_lines_texture = f"{EXTENSION_FOLDER_PATH}/icons/diagonal_texture.png"
url.button_update = f"{EXTENSION_FOLDER_PATH}/icons/update.png"
url.extension_tittle = f"{EXTENSION_FOLDER_PATH}/icons/window_tittle.png"
extension_tittle = f"{EXTENSION_FOLDER_PATH}/icons/test.png"
# The main style dict
sunpath_window_style = {
"CheckBox": {
"background_color": cl.sunpath_window_item,
"selected_color": cl.beige,
},
"CheckBox:hovered": {"background_color": cl.beige},
"Button": {
"background_color": cl.sunpath_window_attribute_fg,
"border_radius": 4,
"margin_height": 2,
"margin_width": 10,
"padding": 2,
},
"Button:hovered": {"background_color": cl.beige},
"Button:pressed": {"background_color": cl.sunpath_window_item},
"Button.Label": {"alignment": ui.Alignment.CENTER_BOTTOM},
"Button.Image::attribute_set": {
"image_url": url.button_update,
},
"Label::attribute_name": {
"font_size": 14,
"color": cl.sunpath_window_item,
"alignment": ui.Alignment.RIGHT_CENTER,
"margin_height": fl.sunpath_window_attr_spacing,
"margin_width": fl.sunpath_window_attr_hspacing,
},
"CollapsableFrame::group": {
"margin_height": 5,
"background_color": cl.slider_bg_color,
},
"ScrollingFrame::window_bg": {
"background_color": cl.window_bg_color,
"padding": fl.outer_frame_padding,
"border_radius": 20,
},
"Label::attribute_name:hovered": {"color": cl.sunpath_window_hovered},
"Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER},
"HeaderLine": {"color": cl(0.5, 0.5, 0.5, 0.5)},
"Slider": {
"background_color": cl.slider_bg_color,
"secondary_color": cl.beige,
"secondary_selected_color": cl.sunpath_window_item,
"color": 0x00000000,
"draw_mode": ui.SliderDrawMode.HANDLE,
"border_radius": fl.border_radius,
"corner_flag": ui.CornerFlag.LEFT,
"margin_height": 4,
},
"Image::slider_bg_texture": {
"image_url": url.diag_bg_lines_texture,
"border_radius": fl.border_radius,
"margin_height": 13,
},
"Field": {
"background_color": 0x00000000,
"color": cl.sunpath_window_item,
"margin_height": 4,
"margin_width": 5,
"border_radius": fl.border_radius,
},
"Image::extension_tittle": {"image_url": url.extension_tittle, "margin": 10},
"Image::collapsable_opened": {"color": cl.sunpath_window_item, "image_url": url.sunpath_window_icon_opened},
"Image::collapsable_closed": {"color": cl.sunpath_window_item, "image_url": url.sunpath_window_icon_closed},
}
| 3,718 | Python | 35.821782 | 112 | 0.640129 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/sunpath_data.py | __all__ = ["SunpathData"]
import omni
# Use this method to import pyephem-sunpath packages
omni.kit.pipapi.install("pyephem-sunpath", None, False, False, None, True, True, None)
import math
from datetime import datetime
from pyephem_sunpath.sunpath import sunpos, sunrise, sunset
class SunpathData:
"""Generate sunpath data"""
def __init__(self, datevalue, hour, min, lon, lat):
self.datevalue = datevalue
self.year = datetime.now().year
self.hour = hour
self.lat = lat
self.lon = lon
self.min = min
# Compute the timezone
self.tz = round(self.lon / 15)
def set_date(self, value):
"""
The method to reset date parameter
"""
self.datevalue = value
def set_hour(self, value):
"""
The method to reset hour parameter
"""
self.hour = value
def set_min(self, value):
"""
The method to reset minite parameter
"""
self.min = value
def set_longitude(self, value):
"""
The method to reset longitude parameter
"""
self.lon = value
def set_latitude(self, value):
"""
The method to reset latitude parameter
"""
self.lat = value
@staticmethod
def calc_xyz(alt, azm):
"""
Convert spherical coordinates to Cartesian coordinates
"""
x_val = math.sin((azm - 180) * math.pi / 180)
y_val = math.cos((azm - 180) * math.pi / 180)
z_val = math.tan(alt * math.pi / 180)
length = (x_val**2 + y_val**2 + z_val**2) ** 0.5
return [-x_val / length, z_val / length, y_val / length]
def dome_rotate_angle(self):
"""
Compute dome rotate angle
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
alt, azm = sunpos(thetime, self.lat, self.lon, self.tz, dst=False)
return -alt, 180 - azm
def get_sun_position(self, thetime, lat, lon, tz):
"""
Get sun position of exact time
"""
alt, azm = sunpos(thetime, lat, lon, tz, dst=False)
position = self.calc_xyz(alt, azm)
return position
def cur_sun_position(self):
"""
Get sun position of current time(input)
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
return self.get_sun_position(thetime, self.lat, self.lon, self.tz)
def all_day_position(self, datevalue):
"""
Get sun posion of all day(exact date)
"""
points = []
month, day = self.slider_to_datetime(datevalue)
for t in range(24):
for m in range(0, 60, 5):
thetime = datetime(self.year, month, day, t, m)
pos = self.get_sun_position(thetime, self.lat, self.lon, self.tz)
if pos[1] >= 0:
points.append(pos)
return points
def all_year_sametime_position(self, hour):
"""
Get all year sametime position
"""
points = []
for d in range(1, 366, 2):
month, day = self.slider_to_datetime(d)
thetime = datetime(self.year, month, day, hour)
pos = self.get_sun_position(thetime, self.lat, self.lon, self.tz)
if pos[1] >= 0:
points.append(pos)
if len(points) > 0:
points.append(points[0])
return points
def get_cur_time(self):
"""
Get current datetime(input)
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
return thetime
def get_sunrise_time(self):
"""
Get sunrise time of exact date
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
return sunrise(thetime, self.lat, self.lon, self.tz, dst=False).time()
def get_sunset_time(self):
"""
Get sunset time of exact date
"""
month, day = self.slider_to_datetime(self.datevalue)
thetime = datetime(self.year, month, day, self.hour, self.min)
return sunset(thetime, self.lat, self.lon, self.tz, dst=False).time()
@staticmethod
def slider_to_datetime(datevalue):
"""
Convert slider value to datetime
"""
if datevalue <= 31:
return [1, datevalue]
if datevalue > 31 and datevalue <= 59:
return [2, datevalue - 31]
if datevalue > 59 and datevalue <= 90:
return [3, datevalue - 59]
if datevalue > 90 and datevalue <= 120:
return [4, datevalue - 90]
if datevalue > 120 and datevalue <= 151:
return [5, datevalue - 120]
if datevalue > 151 and datevalue <= 181:
return [6, datevalue - 151]
if datevalue > 181 and datevalue <= 212:
return [7, datevalue - 181]
if datevalue > 212 and datevalue <= 243:
return [8, datevalue - 212]
if datevalue > 243 and datevalue <= 273:
return [9, datevalue - 243]
if datevalue > 273 and datevalue <= 304:
return [10, datevalue - 273]
if datevalue > 304 and datevalue <= 334:
return [11, datevalue - 304]
if datevalue > 334 and datevalue <= 365:
return [12, datevalue - 334]
| 5,595 | Python | 30.795454 | 86 | 0.55353 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/extension.py | __all__ = ["SunpathExtension"]
from .window import SunpathWindow
from functools import partial
import asyncio
import omni.ext
import omni.kit.ui
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportScene
from .sunlight_manipulator import SunlightManipulator
# Import global dictionary
from . import gol
# Initialize dictionary
gol._init()
class SunpathExtension(omni.ext.IExt):
WINDOW_NAME = "sunpath extension".upper()
MENU_PATH = f"Window/{WINDOW_NAME}"
def __init__(self):
self._window = None
# Get acive viewport window
self.viewport_window = get_active_viewport_window()
self._viewport_scene = None
# Preset display toggle
self._show_path = False
self._show_sun = False
# Preset path model and sunlight model
self.pathmodel = gol.get_value("pathmodel")
self.sunlightmodel = SunlightManipulator(self.pathmodel)
def on_startup(self, ext_id):
# Add ext_id key value
self.ext_id = ext_id
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(SunpathExtension.WINDOW_NAME, partial(self.show_window, None))
# Put the new menu
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(SunpathExtension.MENU_PATH, self.show_window, toggle=True, value=True)
# Show the window. It will call `self.show_window`
ui.Workspace.show_window(SunpathExtension.WINDOW_NAME)
def on_shutdown(self):
"""
Destroy viewport scene and window
"""
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
self._menu = None
if self._window:
self._window.destroy()
self._window = None
# Deregister the function that shows the window from omni.ui
ui.Workspace.set_show_window_fn(SunpathExtension.WINDOW_NAME, None)
def sunpath_toggle(self, value):
"""
The method to change the toggle, this dropped into the window
"""
if value:
self._show_path = value
self._viewport_scene = ViewportScene(self.viewport_window, self.ext_id, self.pathmodel)
else:
self._show_path = value
self._viewport_scene.destroy()
self._viewport_scene = None
def sunlight_toggle(self, value):
"""
The method to change the toggle, this dropped into the window file
"""
if value:
self._show_sun = value
self.sunlightmodel.show_sun()
else:
self._show_sun = value
self.sunlightmodel.del_sun()
gol.set_value("sun_state", value)
def update_viewport_scene(self):
"""
The method to upadate viewport scene
"""
if self._show_sun:
self.sunlightmodel = SunlightManipulator(self.pathmodel)
self.sunlightmodel.path = "/World/DistantLight"
self.sunlightmodel.show_sun()
if self._show_path:
if self._viewport_scene is not None:
self._viewport_scene.destroy()
self._viewport_scene = ViewportScene(self.viewport_window, self.ext_id, self.pathmodel)
def update_parameter(self, valtype, val):
"""
The method to change parameters and update viewport scene, this dropped into window file
"""
if valtype is None:
pass
if valtype == "show_info":
gol.set_value("show_info", val)
if valtype == 0:
gol.set_value("color_r", val * 255)
if valtype == 1:
gol.set_value("color_g", val * 255)
if valtype == 2:
gol.set_value("color_b", val * 255)
if valtype == "scale":
gol.set_value("scale", val)
if valtype == "longitude":
self.pathmodel.set_longitude(val)
if valtype == "latitude":
self.pathmodel.set_latitude(val)
if valtype == "date":
self.pathmodel.set_date(val)
if valtype == "hour":
self.pathmodel.set_hour(val)
# Save pathmodel to dictionary
gol.set_value("pathmodel", self.pathmodel)
if valtype == "minite":
self.pathmodel.set_min(val)
self.update_viewport_scene()
def _set_menu(self, value):
"""
Set the menu to create this window on and off
"""
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(SunpathExtension.MENU_PATH, value)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def _visiblity_changed_fn(self, visible):
# Called when the user pressed "X"
self._set_menu(visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, menu, value):
"""
Show window and deliver some method to it
"""
if value:
self._window = SunpathWindow(
SunpathExtension.WINDOW_NAME,
delegate_1=self.update_parameter,
delegate_2=self.sunpath_toggle,
delegate_3=self.sunlight_toggle,
delegate_4=self.update_viewport_scene,
width=360,
height=590,
)
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
| 6,004 | Python | 32.547486 | 116 | 0.590273 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/viewport_scene.py | __all__ = ["ViewportScene"]
from omni.ui import scene as sc
import omni.ui as ui
from .sunpath_data import SunpathData
from .draw_sunpath import DrawSunpath
from .draw_sphere import draw_movable_sphere
from .gesture import MoveGesture
from . import gol
class ViewportScene:
def __init__(self, viewport_window: ui.Window, ext_id: str, pathmodel: SunpathData) -> None:
self._scene_view = None
self._viewport_window = viewport_window
with self._viewport_window.get_frame(ext_id):
self._scene_view = sc.SceneView()
with self._scene_view.scene:
transform = sc.Transform()
move_ges = MoveGesture(transform)
with transform:
DrawSunpath(pathmodel, move_ges)
if gol.get_value("sun_state"):
draw_movable_sphere()
self._viewport_window.viewport_api.add_scene_view(self._scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self._scene_view:
self._scene_view.scene.clear()
if self._viewport_window:
self._viewport_window.viewport_api.remove_scene_view(self._scene_view)
self._viewport_window = None
self._scene_view = None
| 1,289 | Python | 32.076922 | 96 | 0.60512 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/draw_sphere.py | import math
from math import sin, cos
import numpy as np
from omni.ui import scene as sc
from omni.ui import color as cl
from . import gol
def rotate_matrix_z(angle):
"""
Build Z-axis rotation matrix
"""
sep = 2 * math.pi / 360
Rz = [
[cos(sep * angle), -sin(sep * angle), 0],
[sin(sep * angle), cos(sep * angle), 0],
[0, 0, 1],
]
return np.array(Rz)
def rotate_points(points, angle):
"""
rotate a point list
"""
rotated_pts = []
for pt in points:
pt_arr = np.array(pt)
Rz = rotate_matrix_z(angle)
rotated_pt = list(np.dot(Rz, pt_arr))
rotated_pts.append(rotated_pt)
return rotated_pts
def generate_circle_pts(offset, step, scale):
"""
Generate the points that make up the circle
"""
points = []
sep = 2 * math.pi / 360
for angle in range(0, 361, step):
x = scale * math.cos(sep * angle) * offset
z = scale * math.sin(sep * angle) * offset
points.append([round(x, 3), 0, round(z, 3)])
return points
def draw_base_sphere():
"""
Draw a shpere base on [0,0,0]
"""
scale = gol.get_value("scale") * 200
points = generate_circle_pts(0.1, 5, scale)
sc.Curve(points, thicknesses=[1], colors=[cl.beige], curve_type=sc.Curve.CurveType.LINEAR)
for angle in range(0, 361, 4):
r_pts = rotate_points(points, angle)
sc.Curve(r_pts, thicknesses=[1], colors=[cl.beige], curve_type=sc.Curve.CurveType.LINEAR)
def points_modify(points):
"""
Change the coordinates of the point based on the origin and scale
"""
scale = gol.get_value("scale") * 200
origin = gol.get_value("origin")
s_points = []
for pt in points:
x = pt[0] * scale + origin[0]
y = pt[1] * scale + origin[1]
z = pt[2] * scale + origin[2]
newpt = [x, y, z]
s_points.append(newpt)
return s_points
def draw_movable_sphere():
"""
According parametes to move sphere positon
"""
pathmodel = gol.get_value("pathmodel")
sun_pos = pathmodel.cur_sun_position()
x, y, z = points_modify([sun_pos])[0]
if y > 0:
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(x, y, z)):
draw_base_sphere()
| 2,278 | Python | 24.322222 | 97 | 0.579017 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/draw_sunpath.py | __all__ = ["DrawSunpath"]
import math
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
from .sunpath_data import SunpathData
from . import gol
class DrawSunpath:
def __init__(self, pathmodel: SunpathData, move_ges):
self.move_ges = move_ges
self.pathmodel = pathmodel
self.origin = gol.get_value("origin")
self.scale = gol.get_value("scale") * 200
self.color = cl(*gol.get_value("color"))
# Draw sunpath
self.draw_anydate_path(self.pathmodel, self.pathmodel.datevalue, cl.documentation_nvidia, 1.5)
self.draw_paths()
self.draw_compass()
if gol.get_value("show_info"):
self.show_info()
def sort_points(self, points):
"""
Resort the points to make sure they connect to a reasonable curve
"""
x_points = list(filter(lambda p: p[0] < 0, points))
if len(x_points) != 0:
y_min = min(x_points, key=lambda p: p[1])
id = points.index(y_min) + 1
return points[id:] + points[:id]
return points
def points_modify(self, points):
"""
Change the coordinates of the point based on the origin
"""
s_points = []
for pt in points:
x = pt[0] * self.scale + self.origin[0]
y = pt[1] * self.scale + self.origin[1]
z = pt[2] * self.scale + self.origin[2]
newpt = [x, y, z]
s_points.append(newpt)
return s_points
def generate_circle_pts(self, offset, step):
"""
Generate the points that make up the circle or present anchor point
"""
points = []
sep = 2 * math.pi / 360
for angle in range(0, 361, step):
x = self.origin[0] + self.scale * math.cos(sep * angle) * offset
z = self.origin[2] + self.scale * math.sin(sep * angle) * offset
points.append([round(x, 3), 0, round(z, 3)])
return points
def draw_circle(self, offset, step, color, thickness):
"""
Connet points to draw a circle
"""
points = self.generate_circle_pts(offset, step)
sc.Curve(points, thicknesses=[thickness], colors=[color], curve_type=sc.Curve.CurveType.LINEAR)
def draw_drections(self):
"""
Draw cross line and mark main directions
"""
# Generate anchor point
points_a = self.generate_circle_pts(1.15, 90)
points_b = self.generate_circle_pts(1.25, 90)
points_c = self.generate_circle_pts(1.15, 2)
points_t = self.generate_circle_pts(1.33, 90)
for pt in points_b:
sc.Curve([pt, self.origin], thicknesses=[1.0], colors=[cl.gray], curve_type=sc.Curve.CurveType.LINEAR)
arrow = []
for i in range(1, 181, 45):
arrow.append(points_c[i])
# Draw arrow
for p_a, p_b, p_c in zip(points_a, points_b, arrow):
sc.Curve(
[p_b, p_c, p_a, p_b],
thicknesses=[1.5],
colors=[cl.documentation_nvidia],
curve_type=sc.Curve.CurveType.LINEAR,
)
# Draw diretions label
text = ["E", "S", "W", "N"]
for i in range(4):
x, y, z = points_t[i]
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(x, y, z)):
sc.Label(text[i], alignment=ui.Alignment.CENTER, color=cl.documentation_nvidia, size=20)
def draw_drection_mark(self):
"""
Draw degrees directions and add a move gesture
"""
points_a = self.generate_circle_pts(1, 30)
points_b = self.generate_circle_pts(1.06, 30)
points_g = self.generate_circle_pts(1.03, 90)
points_t = self.generate_circle_pts(1.1, 30)
# Compute length of tick-mark line
length = points_b[3][2] - points_a[3][2]
gol.set_value("length", length)
# Add move gesture block
x, y, z = points_g[3]
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(x, y, z)):
sc.Rectangle(
axis=ui.Axis.X,
color=cl.documentation_nvidia,
width=length / 2,
height=length,
gesture=self.move_ges,
)
# Add tick-mark line
for p1, p2 in zip(points_a, points_b):
sc.Curve(
[p1, p2], thicknesses=[1.5], colors=[cl.documentation_nvidia], curve_type=sc.Curve.CurveType.LINEAR
)
# Add degree label
text = [f"{d}" for d in list(range(0, 361, 30))]
text = text[3:12] + text[:3]
for i in range(12):
x, y, z = points_t[i]
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(x, y, z)):
sc.Label(text[i], alignment=ui.Alignment.CENTER, color=cl.documentation_nvidia, size=12)
def draw_anydate_path(self, pathmodel: SunpathData, datevalue: int, color, thickness):
"""
The method to draw the path of sun on exact date
"""
points = pathmodel.all_day_position(datevalue)
sort_pts = self.sort_points(points)
scale_pts = self.points_modify(sort_pts)
if len(scale_pts) > 0:
sc.Curve(scale_pts, thicknesses=[thickness], colors=[color], curve_type=sc.Curve.CurveType.LINEAR)
def draw_sametime_position(self, pathmodel: SunpathData, hour, color, thickness):
"""
The method to draw the path of sun on diffrent date but in same time,'8' shape curve
"""
points = pathmodel.all_year_sametime_position(hour)
sort_pts = self.sort_points(points)
scale_pts = self.points_modify(sort_pts)
if len(scale_pts) > 0:
sc.Curve(scale_pts, thicknesses=[thickness], colors=[color], curve_type=sc.Curve.CurveType.LINEAR)
def draw_multi_sametime_position(self, pathmodel: SunpathData, color, thickness):
"""
Draw twenty four '8' shape curves
"""
for h in range(0, 24, 1):
self.draw_sametime_position(pathmodel, h, color, thickness)
def draw_paths(self):
"""
Draw diffrent path
"""
self.draw_anydate_path(self.pathmodel, 172, self.color, 1.3)
self.draw_anydate_path(self.pathmodel, 355, self.color, 1.3)
self.draw_anydate_path(self.pathmodel, 80, self.color, 1.3)
self.draw_anydate_path(self.pathmodel, 110, cl.grey, 1.0)
self.draw_anydate_path(self.pathmodel, 295, cl.grey, 1.0)
self.draw_multi_sametime_position(self.pathmodel, self.color, 0.5)
def draw_compass(self):
"""
Draw entire compass
"""
self.draw_circle(1, 1, self.color, 1.1)
self.draw_circle(1.04, 1, self.color, 1.1)
self.draw_drections()
self.draw_drection_mark()
def show_info(self):
"""
Draw information label
"""
anchor = self.generate_circle_pts(1.5, 90)
anchor_e = anchor[0]
anchor_w = anchor[2]
anchor_n = anchor[3]
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*anchor_e)):
sc.Label(
f"sunrise: {self.pathmodel.get_sunrise_time()}".upper(),
alignment=ui.Alignment.RIGHT_CENTER,
color=cl.beige,
size=16,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*anchor_w)):
sc.Label(
f"sunset: {self.pathmodel.get_sunset_time()}".upper(),
alignment=ui.Alignment.LEFT_CENTER,
color=cl.beige,
size=16,
)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*anchor_n)):
sc.Label(
f"datetime: {self.pathmodel.get_cur_time()}".upper(),
alignment=ui.Alignment.LEFT_CENTER,
color=cl.beige,
size=16,
)
| 7,998 | Python | 36.55399 | 115 | 0.56064 |
WuPingFan/omniverse-exts-sunpath/exts/hnadi.tools.sunpath/hnadi/tools/sunpath/window.py | __all__ = ["SunpathWindow"]
import omni.ui as ui
from functools import partial
from .style import sunpath_window_style
from . import gol
LABEL_WIDTH = 120
SPACING = 4
class SunpathWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate_1=None, delegate_2=None, delegate_3=None, delegate_4=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = sunpath_window_style
# Set the function that is called to build widgets when the window is visible
self.frame.set_build_fn(self._build_fn)
# Methods to change parameters and update viewport secene
self.update = delegate_1
self.show_path = delegate_2
self.show_sun = delegate_3
self.update_scene = delegate_4
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def _build_collapsable_header(self, collapsed, title):
"""Build a custom title of CollapsableFrame"""
with ui.VStack():
ui.Spacer(height=8)
with ui.HStack():
ui.Label(title, name="collapsable_name")
if collapsed:
image_name = "collapsable_opened"
else:
image_name = "collapsable_closed"
ui.Image(name=image_name, width=10, height=10)
ui.Spacer(height=8)
ui.Line(style_type_name_override="HeaderLine")
def _build_display(self):
"""Build the widgets of the "display" group"""
with ui.CollapsableFrame("display".upper(), name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=8)
with ui.HStack():
with ui.VStack():
with ui.HStack():
ui.Label("Show Path", name="attribute_name", width=self.label_width)
sp = ui.CheckBox(name="attribute_bool").model
sp.add_value_changed_fn(lambda m: self.show_path(m.get_value_as_bool()))
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Show Sun", name="attribute_name", width=self.label_width)
ss = ui.CheckBox(name="attribute_bool").model
ss.add_value_changed_fn(lambda m: self.show_sun(m.get_value_as_bool()))
ss.add_value_changed_fn(lambda m: self.update_scene())
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Show Info", name="attribute_name", width=self.label_width)
si = ui.CheckBox(name="attribute_bool").model
si.add_value_changed_fn(lambda m: self.update("show_info", m.get_value_as_bool()))
with ui.ZStack():
ui.Image(
name="extension_tittle",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
width=ui.Percent(100),
)
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Path Color", name="attribute_name", width=self.label_width)
color_model = ui.ColorWidget(1, 1, 1, width=0, height=0).model
r_model = color_model.get_item_children()[0]
r_component = color_model.get_item_value_model(r_model)
r_component.add_value_changed_fn(lambda m: gol.set_item("color", 0, m.get_value_as_float()))
g_model = color_model.get_item_children()[1]
g_component = color_model.get_item_value_model(g_model)
g_component.add_value_changed_fn(lambda m: gol.set_item("color", 1, m.get_value_as_float()))
b_model = color_model.get_item_children()[2]
b_component = color_model.get_item_value_model(b_model)
b_component.add_value_changed_fn(lambda m: gol.set_item("color", 2, m.get_value_as_float()))
ui.Spacer()
ui.Button(
name="attribute_set",
tooltip="update color or update scene",
width=60,
clicked_fn=partial(self.update, None, None),
)
ui.Spacer(height=4)
with ui.HStack():
ui.Label("Path Scale", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(name="slider_bg_texture", fill_policy=ui.FillPolicy.STRETCH, width=ui.Percent(100))
ps_slider = ui.FloatSlider(name="attribute_slider", min=1, max=100, setp=1).model
ps_slider.set_value(50)
ps_slider.add_value_changed_fn(lambda m: self.update("scale", m.get_value_as_float()))
ui.FloatField(model=ps_slider, width=60)
def _build_location(self):
"""Build the widgets of the "location" group"""
with ui.CollapsableFrame("location".upper(), name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Longitude", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(name="slider_bg_texture", fill_policy=ui.FillPolicy.STRETCH, width=ui.Percent(100))
lon_slider = ui.FloatSlider(name="attribute_slider", min=-180, max=180, setp=0.01).model
lon_slider.set_value(112.22)
lon_slider.add_value_changed_fn(lambda m: self.update("longitude", m.get_value_as_float()))
ui.FloatField(model=lon_slider, width=60)
ui.Spacer(height=2)
with ui.HStack():
ui.Label("Latitude", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(
name="slider_bg_texture",
fill_policy=ui.FillPolicy.STRETCH,
width=ui.Percent(100),
)
lat_slider = ui.FloatSlider(name="attribute_slider", min=-90, max=90, step=0.01).model
lat_slider.set_value(22.22)
lat_slider.add_value_changed_fn(lambda m: self.update("latitude", m.get_value_as_float()))
ui.FloatField(model=lat_slider, width=60)
def _build_datetime(self):
"""Build the widgets of the "datetime" group"""
with ui.CollapsableFrame("datetime".upper(), name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=8)
with ui.HStack():
ui.Label("Date", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(
name="slider_bg_texture",
fill_policy=ui.FillPolicy.STRETCH,
width=ui.Percent(100),
)
dt_slider = ui.IntSlider(
name="attribute_slider",
min=1,
max=365,
).model
dt_slider.set_value(175)
dt_slider.add_value_changed_fn(lambda m: self.update("date", m.get_value_as_int()))
ui.IntField(model=dt_slider, width=60)
ui.Spacer(height=2)
with ui.HStack():
ui.Label("Hour", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(
name="slider_bg_texture",
fill_policy=ui.FillPolicy.STRETCH,
width=ui.Percent(100),
)
hr_slider = ui.IntSlider(name="attribute_slider", min=0, max=23).model
hr_slider.set_value(12)
hr_slider.add_value_changed_fn(lambda m: self.update("hour", m.get_value_as_int()))
ui.IntField(model=hr_slider, width=60)
ui.Spacer(height=2)
with ui.HStack():
ui.Label("Minite", name="attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(
name="slider_bg_texture",
fill_policy=ui.FillPolicy.STRETCH,
width=ui.Percent(100),
)
mt_slider = ui.IntSlider(name="attribute_slider", min=0, max=59).model
mt_slider.set_value(30)
mt_slider.add_value_changed_fn(lambda m: self.update("minite", m.get_value_as_int()))
ui.IntField(model=mt_slider, width=60)
def _build_fn(self):
"""
The method that is called to build all the UI once the window is visible.
"""
with ui.ScrollingFrame(name="window_bg", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF):
with ui.ScrollingFrame():
with ui.VStack(height=0):
self._build_display()
self._build_location()
self._build_datetime()
| 10,277 | Python | 48.893204 | 118 | 0.504427 |
USwampertor/OmniverseJS/ov/bindings-python/omni/client/__init__.py | # fmt: off
import os
import platform
import sys
import asyncio
import concurrent.futures
from typing import Tuple, List, Callable
if hasattr(os, "add_dll_directory"):
scriptdir = os.path.dirname(os.path.realpath(__file__))
dlldir = os.path.abspath(os.path.join(scriptdir, "../../.."))
with os.add_dll_directory(dlldir):
from ._omniclient import *
else:
from ._omniclient import *
def get_server_info(url: str) -> Tuple[Result, ServerInfo]:
"""Deprecated: Use :py:func:`omni.client.get_server_info_async` or :py:func:`omni.client.get_server_info_with_callback` instead.
"""
ret = None
def get_server_info_cb(result, info):
nonlocal ret
ret = (result, info)
get_server_info_with_callback(url=url, callback=get_server_info_cb).wait()
return ret
async def get_server_info_async(url: str) -> Tuple[Result, ServerInfo]:
"""Asynchronously Get Server Info
See: :py:func:`omni.client.get_server_info_with_callback`
"""
f = concurrent.futures.Future()
def get_server_info_cb(result, info):
if not f.done():
f.set_result((result, info))
get_server_info_with_callback(url=url, callback=get_server_info_cb)
return await asyncio.wrap_future(f)
def list(url: str) -> Tuple[Result, Tuple[ListEntry]]:
"""Deprecated: Use :py:func:`omni.client.list_async` or :py:func:`omni.client.list_with_callback` instead.
"""
ret = None
def list_cb(result, entries):
nonlocal ret
ret = (result, entries)
list_with_callback(url=url, callback=list_cb).wait()
return ret
async def list_async(url: str) -> Tuple[Result, Tuple[ListEntry]]:
"""Asynchronously List contents of a folder
See: :py:func:`omni.client.list_with_callback`
"""
f = concurrent.futures.Future()
def list_cb(result, entries):
if not f.done():
f.set_result((result, entries))
list_with_callback(url=url, callback=list_cb)
return await asyncio.wrap_future(f)
def stat(url: str) -> Tuple[Result, ListEntry]:
"""Deprecated: Use :py:func:`omni.client.stat_async` or :py:func:`omni.client.stat_with_callback` instead.
"""
ret = None
def stat_cb(result, entry):
nonlocal ret
ret = (result, entry)
stat_with_callback(url=url, callback=stat_cb).wait()
return ret
async def stat_async(url: str) -> Tuple[Result, ListEntry]:
"""Asynchronously Retrieve information about a single item
See: :py:func:`omni.client.stat_with_callback`
"""
f = concurrent.futures.Future()
def stat_cb(result, entry):
if not f.done():
f.set_result((result, entry))
stat_with_callback(url=url, callback=stat_cb)
return await asyncio.wrap_future(f)
def delete(url: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.delete_async` or :py:func:`omni.client.delete_with_callback` instead.
"""
ret = None
def delete_cb(result):
nonlocal ret
ret = result
delete_with_callback(url=url, callback=delete_cb).wait()
return ret
async def delete_async(url: str) -> Result:
"""Asynchronously Delete an item
See: :py:func:`omni.client.delete_with_callback`
"""
f = concurrent.futures.Future()
def delete_cb(result):
if not f.done():
f.set_result(result)
delete_with_callback(url=url, callback=delete_cb)
return await asyncio.wrap_future(f)
def create_folder(url: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.create_folder_async` or :py:func:`omni.client.create_folder_with_callback` instead.
"""
ret = None
def create_folder_cb(result):
nonlocal ret
ret = result
create_folder_with_callback(url=url, callback=create_folder_cb).wait()
return ret
async def create_folder_async(url: str) -> Result:
"""Asynchronously Create a folder
See: :py:func:`omni.client.create_folder_with_callback`
"""
f = concurrent.futures.Future()
def create_folder_cb(result):
if not f.done():
f.set_result(result)
create_folder_with_callback(url=url, callback=create_folder_cb)
return await asyncio.wrap_future(f)
def copy(src_url: str, dst_url: str, behavior: CopyBehavior = CopyBehavior.ERROR_IF_EXISTS, message: str = "") -> Result:
"""Deprecated: Use :py:func:`omni.client.copy_async` or :py:func:`omni.client.copy_with_callback` instead.
"""
ret = None
def copy_cb(result):
nonlocal ret
ret = result
copy_with_callback(src_url=src_url, dst_url=dst_url, behavior=behavior, message=message, callback=copy_cb).wait()
return ret
async def copy_async(src_url: str, dst_url: str, behavior: CopyBehavior = CopyBehavior.ERROR_IF_EXISTS, message: str = "") -> Result:
"""Asynchronously Copy an item from ``src_url`` to ``dst_url``
See: :py:func:`omni.client.copy_with_callback`
"""
f = concurrent.futures.Future()
def copy_cb(result):
if not f.done():
f.set_result(result)
copy_with_callback(src_url=src_url, dst_url=dst_url, behavior=behavior, message=message, callback=copy_cb)
return await asyncio.wrap_future(f)
def move(src_url: str, dst_url: str, behavior: CopyBehavior = CopyBehavior.ERROR_IF_EXISTS, message: str = "") -> Tuple[Result, bool]:
"""Deprecated: Use :py:func:`omni.client.move_async` or :py:func:`omni.client.move_with_callback` instead.
"""
ret = None
def move_cb(result, copied):
nonlocal ret
ret = (result, copied)
move_with_callback(src_url=src_url, dst_url=dst_url, behavior=behavior, message=message, callback=move_cb).wait()
return ret
async def move_async(src_url: str, dst_url: str, behavior: CopyBehavior = CopyBehavior.ERROR_IF_EXISTS, message: str = "") -> Tuple[Result, bool]:
"""Asynchronously Move an item from ``src_url`` to ``dst_url``
See: :py:func:`omni.client.move_with_callback`
"""
f = concurrent.futures.Future()
def move_cb(result, copied):
if not f.done():
f.set_result((result, copied))
move_with_callback(src_url=src_url, dst_url=dst_url, behavior=behavior, message=message, callback=move_cb)
return await asyncio.wrap_future(f)
def get_local_file(url: str) -> Tuple[Result, str]:
"""Deprecated: Use :py:func:`omni.client.get_local_file_async` or :py:func:`omni.client.get_local_file_with_callback` instead.
"""
ret = None
def get_local_file_cb(result, local_file_path):
nonlocal ret
ret = (result, local_file_path)
get_local_file_with_callback(url=url, callback=get_local_file_cb).wait()
return ret
async def get_local_file_async(url: str) -> Tuple[Result, str]:
"""Asynchronously Get local file path from a URL
See: :py:func:`omni.client.get_local_file_with_callback`
"""
f = concurrent.futures.Future()
def get_local_file_cb(result, local_file_path):
if not f.done():
f.set_result((result, local_file_path))
get_local_file_with_callback(url=url, callback=get_local_file_cb)
return await asyncio.wrap_future(f)
def read_file(url: str) -> Tuple[Result, str, Content]:
"""Deprecated: Use :py:func:`omni.client.read_file_async` or :py:func:`omni.client.read_file_with_callback` instead.
"""
ret = None
def read_file_cb(result, version, content):
nonlocal ret
ret = (result, version, content)
read_file_with_callback(url=url, callback=read_file_cb).wait()
return ret
async def read_file_async(url: str) -> Tuple[Result, str, Content]:
"""Asynchronously Read a file
See: :py:func:`omni.client.read_file_with_callback`
"""
f = concurrent.futures.Future()
def read_file_cb(result, version, content):
if not f.done():
f.set_result((result, version, content))
read_file_with_callback(url=url, callback=read_file_cb)
return await asyncio.wrap_future(f)
def write_file(url: str, content: bytes, message: str = "") -> Result:
"""Deprecated: Use :py:func:`omni.client.write_file_async` or :py:func:`omni.client.write_file_with_callback` instead.
"""
ret = None
def write_file_cb(result):
nonlocal ret
ret = result
write_file_with_callback(url=url, content=content, message=message, callback=write_file_cb).wait()
return ret
async def write_file_async(url: str, content: bytes, message: str = "") -> Result:
"""Asynchronously Write a file
See: :py:func:`omni.client.write_file_with_callback`
"""
f = concurrent.futures.Future()
def write_file_cb(result):
if not f.done():
f.set_result(result)
write_file_with_callback(url=url, content=content, message=message, callback=write_file_cb)
return await asyncio.wrap_future(f)
def get_acls(url: str) -> Tuple[Result, List[AclEntry]]:
"""Deprecated: Use :py:func:`omni.client.get_acls_async` or :py:func:`omni.client.get_acls_with_callback` instead.
"""
ret = None
def get_acls_cb(result, acls):
nonlocal ret
ret = (result, acls)
get_acls_with_callback(url=url, callback=get_acls_cb).wait()
return ret
async def get_acls_async(url: str) -> Tuple[Result, List[AclEntry]]:
"""Asynchronously Get the ACLs for an item
See: :py:func:`omni.client.get_acls_with_callback`
"""
f = concurrent.futures.Future()
def get_acls_cb(result, acls):
if not f.done():
f.set_result((result, acls))
get_acls_with_callback(url=url, callback=get_acls_cb)
return await asyncio.wrap_future(f)
def set_acls(url: str, acls: List[AclEntry]) -> Result:
"""Deprecated: Use :py:func:`omni.client.set_acls_async` or :py:func:`omni.client.set_acls_with_callback` instead.
"""
ret = None
def set_acls_cb(result):
nonlocal ret
ret = result
set_acls_with_callback(url=url, acls=acls, callback=set_acls_cb).wait()
return ret
async def set_acls_async(url: str, acls: List[AclEntry]) -> Result:
"""Asynchronously Set the ACLs for an item
See: :py:func:`omni.client.set_acls_with_callback`
"""
f = concurrent.futures.Future()
def set_acls_cb(result):
if not f.done():
f.set_result(result)
set_acls_with_callback(url=url, acls=acls, callback=set_acls_cb)
return await asyncio.wrap_future(f)
def send_message(join_request_id: int, content: bytes) -> Result:
"""Deprecated: Use :py:func:`omni.client.send_message_async` or :py:func:`omni.client.send_message_with_callback` instead.
"""
ret = None
def send_message_cb(result):
nonlocal ret
ret = result
send_message_with_callback(join_request_id=join_request_id, content=content, callback=send_message_cb).wait()
return ret
async def send_message_async(join_request_id: int, content: bytes) -> Result:
"""Asynchronously Send a message to a channel
See: :py:func:`omni.client.send_message_with_callback`
"""
f = concurrent.futures.Future()
def send_message_cb(result):
if not f.done():
f.set_result(result)
send_message_with_callback(join_request_id=join_request_id, content=content, callback=send_message_cb)
return await asyncio.wrap_future(f)
def list_checkpoints(url: str) -> Tuple[Result, Tuple[ListEntry]]:
"""Deprecated: Use :py:func:`omni.client.list_checkpoints_async` or :py:func:`omni.client.list_checkpoints_with_callback` instead.
"""
ret = None
def list_checkpoints_cb(result, entries):
nonlocal ret
ret = (result, entries)
list_checkpoints_with_callback(url=url, callback=list_checkpoints_cb).wait()
return ret
async def list_checkpoints_async(url: str) -> Tuple[Result, Tuple[ListEntry]]:
"""Asynchronously List the checkpoints of an item
See: :py:func:`omni.client.list_checkpoints_with_callback`
"""
f = concurrent.futures.Future()
def list_checkpoints_cb(result, entries):
if not f.done():
f.set_result((result, entries))
list_checkpoints_with_callback(url=url, callback=list_checkpoints_cb)
return await asyncio.wrap_future(f)
def create_checkpoint(url: str, comment: str, force: bool = False) -> Tuple[Result, str]:
"""Deprecated: Use :py:func:`omni.client.create_checkpoint_async` or :py:func:`omni.client.create_checkpoint_with_callback` instead.
"""
ret = None
def create_checkpoint_cb(result, query):
nonlocal ret
ret = (result, query)
create_checkpoint_with_callback(url=url, comment=comment, force=force, callback=create_checkpoint_cb).wait()
return ret
async def create_checkpoint_async(url: str, comment: str, force: bool = False) -> Tuple[Result, str]:
"""Asynchronously Create a checkpoint of an item
See: :py:func:`omni.client.create_checkpoint_with_callback`
"""
f = concurrent.futures.Future()
def create_checkpoint_cb(result, query):
if not f.done():
f.set_result((result, query))
create_checkpoint_with_callback(url=url, comment=comment, force=force, callback=create_checkpoint_cb)
return await asyncio.wrap_future(f)
def get_groups(url: str) -> Tuple[Result, List[str]]:
"""Deprecated: Use :py:func:`omni.client.get_groups_async` or :py:func:`omni.client.get_groups_with_callback` instead.
"""
ret = None
def get_groups_cb(result, groups):
nonlocal ret
ret = (result, groups)
get_groups_with_callback(url=url, callback=get_groups_cb).wait()
return ret
async def get_groups_async(url: str) -> Tuple[Result, List[str]]:
"""Asynchronously Get a list of all groups
See: :py:func:`omni.client.get_groups_with_callback`
"""
f = concurrent.futures.Future()
def get_groups_cb(result, groups):
if not f.done():
f.set_result((result, groups))
get_groups_with_callback(url=url, callback=get_groups_cb)
return await asyncio.wrap_future(f)
def get_group_users(url: str, group: str) -> Tuple[Result, List[str]]:
"""Deprecated: Use :py:func:`omni.client.get_group_users_async` or :py:func:`omni.client.get_group_users_with_callback` instead.
"""
ret = None
def get_group_users_cb(result, users):
nonlocal ret
ret = (result, users)
get_group_users_with_callback(url=url, group=group, callback=get_group_users_cb).wait()
return ret
async def get_group_users_async(url: str, group: str) -> Tuple[Result, List[str]]:
"""Asynchronously Get a list of all users in a group
See: :py:func:`omni.client.get_group_users_with_callback`
"""
f = concurrent.futures.Future()
def get_group_users_cb(result, users):
if not f.done():
f.set_result((result, users))
get_group_users_with_callback(url=url, group=group, callback=get_group_users_cb)
return await asyncio.wrap_future(f)
def create_group(url: str, group: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.create_group_async` or :py:func:`omni.client.create_group_with_callback` instead.
"""
ret = None
def create_group_cb(result):
nonlocal ret
ret = result
create_group_with_callback(url=url, group=group, callback=create_group_cb).wait()
return ret
async def create_group_async(url: str, group: str) -> Result:
"""Asynchronously Create a group
See: :py:func:`omni.client.create_group_with_callback`
"""
f = concurrent.futures.Future()
def create_group_cb(result):
if not f.done():
f.set_result(result)
create_group_with_callback(url=url, group=group, callback=create_group_cb)
return await asyncio.wrap_future(f)
def rename_group(url: str, group: str, new_group: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.rename_group_async` or :py:func:`omni.client.rename_group_with_callback` instead.
"""
ret = None
def rename_group_cb(result):
nonlocal ret
ret = result
rename_group_with_callback(url=url, group=group, new_group=new_group, callback=rename_group_cb).wait()
return ret
async def rename_group_async(url: str, group: str, new_group: str) -> Result:
"""Asynchronously Rename a group
See: :py:func:`omni.client.rename_group_with_callback`
"""
f = concurrent.futures.Future()
def rename_group_cb(result):
if not f.done():
f.set_result(result)
rename_group_with_callback(url=url, group=group, new_group=new_group, callback=rename_group_cb)
return await asyncio.wrap_future(f)
def remove_group(url: str, group: str) -> Tuple[Result, int]:
"""Deprecated: Use :py:func:`omni.client.remove_group_async` or :py:func:`omni.client.remove_group_with_callback` instead.
"""
ret = None
def remove_group_cb(result, change_count):
nonlocal ret
ret = (result, change_count)
remove_group_with_callback(url=url, group=group, callback=remove_group_cb).wait()
return ret
async def remove_group_async(url: str, group: str) -> Tuple[Result, int]:
"""Asynchronously Remove a group
See: :py:func:`omni.client.remove_group_with_callback`
"""
f = concurrent.futures.Future()
def remove_group_cb(result, change_count):
if not f.done():
f.set_result((result, change_count))
remove_group_with_callback(url=url, group=group, callback=remove_group_cb)
return await asyncio.wrap_future(f)
def get_users(url: str) -> Tuple[Result, List[str]]:
"""Deprecated: Use :py:func:`omni.client.get_users_async` or :py:func:`omni.client.get_users_with_callback` instead.
"""
ret = None
def get_users_cb(result, users):
nonlocal ret
ret = (result, users)
get_users_with_callback(url=url, callback=get_users_cb).wait()
return ret
async def get_users_async(url: str) -> Tuple[Result, List[str]]:
"""Asynchronously Get a list of all users
See: :py:func:`omni.client.get_users_with_callback`
"""
f = concurrent.futures.Future()
def get_users_cb(result, users):
if not f.done():
f.set_result((result, users))
get_users_with_callback(url=url, callback=get_users_cb)
return await asyncio.wrap_future(f)
def get_user_groups(url: str, user: str) -> Tuple[Result, List[str]]:
"""Deprecated: Use :py:func:`omni.client.get_user_groups_async` or :py:func:`omni.client.get_user_groups_with_callback` instead.
"""
ret = None
def get_user_groups_cb(result, groups):
nonlocal ret
ret = (result, groups)
get_user_groups_with_callback(url=url, user=user, callback=get_user_groups_cb).wait()
return ret
async def get_user_groups_async(url: str, user: str) -> Tuple[Result, List[str]]:
"""Asynchronously Get a list of groups the user is in
See: :py:func:`omni.client.get_user_groups_with_callback`
"""
f = concurrent.futures.Future()
def get_user_groups_cb(result, groups):
if not f.done():
f.set_result((result, groups))
get_user_groups_with_callback(url=url, user=user, callback=get_user_groups_cb)
return await asyncio.wrap_future(f)
def add_user_to_group(url: str, user: str, group: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.add_user_to_group_async` or :py:func:`omni.client.add_user_to_group_with_callback` instead.
"""
ret = None
def add_user_to_group_cb(result):
nonlocal ret
ret = result
add_user_to_group_with_callback(url=url, user=user, group=group, callback=add_user_to_group_cb).wait()
return ret
async def add_user_to_group_async(url: str, user: str, group: str) -> Result:
"""Asynchronously Add a user to a group
See: :py:func:`omni.client.add_user_to_group_with_callback`
"""
f = concurrent.futures.Future()
def add_user_to_group_cb(result):
if not f.done():
f.set_result(result)
add_user_to_group_with_callback(url=url, user=user, group=group, callback=add_user_to_group_cb)
return await asyncio.wrap_future(f)
def remove_user_from_group(url: str, user: str, group: str) -> Result:
"""Deprecated: Use :py:func:`omni.client.remove_user_from_group_async` or :py:func:`omni.client.remove_user_from_group_with_callback` instead.
"""
ret = None
def remove_user_from_group_cb(result):
nonlocal ret
ret = result
remove_user_from_group_with_callback(url=url, user=user, group=group, callback=remove_user_from_group_cb).wait()
return ret
async def remove_user_from_group_async(url: str, user: str, group: str) -> Result:
"""Asynchronously Remove a user from a group
See: :py:func:`omni.client.remove_user_from_group_with_callback`
"""
f = concurrent.futures.Future()
def remove_user_from_group_cb(result):
if not f.done():
f.set_result(result)
remove_user_from_group_with_callback(url=url, user=user, group=group, callback=remove_user_from_group_cb)
return await asyncio.wrap_future(f)
| 21,138 | Python | 25.96301 | 146 | 0.652805 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/common.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from .qt import QtCore, QtGui, QtWidgets
import os, time, sys, platform, math
from pxr import Ar, Tf, Sdf, Kind, Usd, UsdGeom, UsdShade
from .customAttributes import CustomAttribute
from .constantGroup import ConstantGroup
DEBUG_CLIPPING = "USDVIEWQ_DEBUG_CLIPPING"
class ClearColors(ConstantGroup):
"""Names of available background colors."""
BLACK = "Black"
DARK_GREY = "Grey (Dark)"
LIGHT_GREY = "Grey (Light)"
WHITE = "White"
class HighlightColors(ConstantGroup):
"""Names of available highlight colors for selected objects."""
WHITE = "White"
YELLOW = "Yellow"
CYAN = "Cyan"
class UIBaseColors(ConstantGroup):
RED = QtGui.QBrush(QtGui.QColor(230, 132, 131))
LIGHT_SKY_BLUE = QtGui.QBrush(QtGui.QColor(135, 206, 250))
DARK_YELLOW = QtGui.QBrush(QtGui.QColor(222, 158, 46))
class UIPrimTypeColors(ConstantGroup):
HAS_ARCS = UIBaseColors.DARK_YELLOW
NORMAL = QtGui.QBrush(QtGui.QColor(227, 227, 227))
INSTANCE = UIBaseColors.LIGHT_SKY_BLUE
MASTER = QtGui.QBrush(QtGui.QColor(118, 136, 217))
class UIPrimTreeColors(ConstantGroup):
SELECTED = QtGui.QBrush(QtGui.QColor(189, 155, 84))
SELECTED_HOVER = QtGui.QBrush(QtGui.QColor(227, 186, 101))
ANCESTOR_OF_SELECTED = QtGui.QBrush(QtGui.QColor(189, 155, 84, 50))
ANCESTOR_OF_SELECTED_HOVER = QtGui.QBrush(QtGui.QColor(189, 155, 84, 100))
UNSELECTED_HOVER = QtGui.QBrush(QtGui.QColor(70, 70, 70))
class UIPropertyValueSourceColors(ConstantGroup):
FALLBACK = UIBaseColors.DARK_YELLOW
TIME_SAMPLE = QtGui.QBrush(QtGui.QColor(177, 207, 153))
DEFAULT = UIBaseColors.LIGHT_SKY_BLUE
NONE = QtGui.QBrush(QtGui.QColor(140, 140, 140))
VALUE_CLIPS = QtGui.QBrush(QtGui.QColor(230, 150, 230))
class UIFonts(ConstantGroup):
# Font constants. We use font in the prim browser to distinguish
# "resolved" prim specifier
# XXX - the use of weight here may need to be revised depending on font family
BASE_POINT_SIZE = 10
ITALIC = QtGui.QFont()
ITALIC.setWeight(QtGui.QFont.Light)
ITALIC.setItalic(True)
NORMAL = QtGui.QFont()
NORMAL.setWeight(QtGui.QFont.Normal)
BOLD = QtGui.QFont()
BOLD.setWeight(QtGui.QFont.Bold)
BOLD_ITALIC = QtGui.QFont()
BOLD_ITALIC.setWeight(QtGui.QFont.Bold)
BOLD_ITALIC.setItalic(True)
OVER_PRIM = ITALIC
DEFINED_PRIM = BOLD
ABSTRACT_PRIM = NORMAL
INHERITED = QtGui.QFont()
INHERITED.setPointSize(BASE_POINT_SIZE * 0.8)
INHERITED.setWeight(QtGui.QFont.Normal)
INHERITED.setItalic(True)
class KeyboardShortcuts(ConstantGroup):
FramingKey = QtCore.Qt.Key_F
class PropertyViewIndex(ConstantGroup):
TYPE, NAME, VALUE = range(3)
ICON_DIR_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'icons')
# We use deferred loading because icons can't be constructed before
# application initialization time.
_icons = {}
def _DeferredIconLoad(path):
fullPath = os.path.join(ICON_DIR_ROOT, path)
try:
icon = _icons[fullPath]
except KeyError:
icon = QtGui.QIcon(fullPath)
_icons[fullPath] = icon
return icon
class PropertyViewIcons(ConstantGroup):
ATTRIBUTE = lambda: _DeferredIconLoad('usd-attr-plain-icon.png')
ATTRIBUTE_WITH_CONNECTIONS = lambda: _DeferredIconLoad('usd-attr-with-conn-icon.png')
RELATIONSHIP = lambda: _DeferredIconLoad('usd-rel-plain-icon.png')
RELATIONSHIP_WITH_TARGETS = lambda: _DeferredIconLoad('usd-rel-with-target-icon.png')
TARGET = lambda: _DeferredIconLoad('usd-target-icon.png')
CONNECTION = lambda: _DeferredIconLoad('usd-conn-icon.png')
COMPOSED = lambda: _DeferredIconLoad('usd-cmp-icon.png')
class PropertyViewDataRoles(ConstantGroup):
ATTRIBUTE = "Attr"
RELATIONSHIP = "Rel"
ATTRIBUTE_WITH_CONNNECTIONS = "Attr_"
RELATIONSHIP_WITH_TARGETS = "Rel_"
TARGET = "Tgt"
CONNECTION = "Conn"
COMPOSED = "Cmp"
class RenderModes(ConstantGroup):
# Render modes
WIREFRAME = "Wireframe"
WIREFRAME_ON_SURFACE = "WireframeOnSurface"
SMOOTH_SHADED = "Smooth Shaded"
FLAT_SHADED = "Flat Shaded"
POINTS = "Points"
GEOM_ONLY = "Geom Only"
GEOM_FLAT = "Geom Flat"
GEOM_SMOOTH = "Geom Smooth"
HIDDEN_SURFACE_WIREFRAME = "Hidden Surface Wireframe"
class ShadedRenderModes(ConstantGroup):
# Render modes which use shading
SMOOTH_SHADED = RenderModes.SMOOTH_SHADED
FLAT_SHADED = RenderModes.FLAT_SHADED
WIREFRAME_ON_SURFACE = RenderModes.WIREFRAME_ON_SURFACE
GEOM_FLAT = RenderModes.GEOM_FLAT
GEOM_SMOOTH = RenderModes.GEOM_SMOOTH
class ColorCorrectionModes(ConstantGroup):
# Color correction used when render is presented to screen
# These strings should match HdxColorCorrectionTokens
DISABLED = "disabled"
SRGB = "sRGB"
OPENCOLORIO = "openColorIO"
class PickModes(ConstantGroup):
# Pick modes
PRIMS = "Prims"
MODELS = "Models"
INSTANCES = "Instances"
PROTOTYPES = "Prototypes"
class SelectionHighlightModes(ConstantGroup):
# Selection highlight modes
NEVER = "Never"
ONLY_WHEN_PAUSED = "Only when paused"
ALWAYS = "Always"
class CameraMaskModes(ConstantGroup):
NONE = "none"
PARTIAL = "partial"
FULL = "full"
class IncludedPurposes(ConstantGroup):
DEFAULT = UsdGeom.Tokens.default_
PROXY = UsdGeom.Tokens.proxy
GUIDE = UsdGeom.Tokens.guide
RENDER = UsdGeom.Tokens.render
def _PropTreeWidgetGetRole(tw):
return tw.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
def PropTreeWidgetTypeIsRel(tw):
role = _PropTreeWidgetGetRole(tw)
return role in (PropertyViewDataRoles.RELATIONSHIP,
PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS)
def _UpdateLabelText(text, substring, mode):
return text.replace(substring, '<'+mode+'>'+substring+'</'+mode+'>')
def ItalicizeLabelText(text, substring):
return _UpdateLabelText(text, substring, 'i')
def BoldenLabelText(text, substring):
return _UpdateLabelText(text, substring, 'b')
def ColorizeLabelText(text, substring, r, g, b):
return _UpdateLabelText(text, substring,
"span style=\"color:rgb(%d, %d, %d);\"" % (r, g, b))
def PrintWarning(title, description):
msg = sys.stderr
print("------------------------------------------------------------", file=msg)
print("WARNING: %s" % title, file=msg)
print(description, file=msg)
print("------------------------------------------------------------", file=msg)
def GetValueAndDisplayString(prop, time):
"""If `prop` is a timeSampled Sdf.AttributeSpec, compute a string specifying
how many timeSamples it possesses. Otherwise, compute the single default
value, or targets for a relationship, or value at 'time' for a
Usd.Attribute. Return a tuple of a parameterless function that returns the
resolved value at 'time', and the computed brief string for display. We
return a value-producing function rather than the value itself because for
an Sdf.AttributeSpec with multiple timeSamples, the resolved value is
*all* of the timeSamples, which can be expensive to compute, and is
rarely needed.
"""
def _ValAndStr(val):
return (lambda: val, GetShortStringForValue(prop, val))
if isinstance(prop, Usd.Relationship):
return _ValAndStr(prop.GetTargets())
elif isinstance(prop, (Usd.Attribute, CustomAttribute)):
return _ValAndStr(prop.Get(time))
elif isinstance(prop, Sdf.AttributeSpec):
if time == Usd.TimeCode.Default():
return _ValAndStr(prop.default)
else:
numTimeSamples = prop.layer.GetNumTimeSamplesForPath(prop.path)
if numTimeSamples == 0:
return _ValAndStr(prop.default)
else:
def _GetAllTimeSamples(attrSpec):
l = attrSpec.layer
p = attrSpec.path
ordinates = l.ListTimeSamplesForPath(p)
return [(o, l.QueryTimeSample(p, o)) for o in ordinates]
if numTimeSamples == 1:
valStr = "1 time sample"
else:
valStr = str(numTimeSamples) + " time samples"
return (lambda prop=prop: _GetAllTimeSamples(prop), valStr)
elif isinstance(prop, Sdf.RelationshipSpec):
return _ValAndStr(prop.targetPathList)
return (lambda: None, "unrecognized property type")
def GetShortStringForValue(prop, val):
if isinstance(prop, Usd.Relationship):
val = ", ".join(str(p) for p in val)
elif isinstance(prop, Sdf.RelationshipSpec):
return str(prop.targetPathList)
# If there is no value opinion, we do not want to display anything,
# since python 'None' has a different meaning than usda-authored None,
# which is how we encode attribute value blocks (which evaluate to
# Sdf.ValueBlock)
if val is None:
return ''
from .scalarTypes import GetScalarTypeFromAttr
scalarType, isArray = GetScalarTypeFromAttr(prop)
result = ''
if isArray and not isinstance(val, Sdf.ValueBlock):
def arrayToStr(a):
from itertools import chain
elems = a if len(a) <= 6 else chain(a[:3], ['...'], a[-3:])
return '[' + ', '.join(map(str, elems)) + ']'
if val is not None and len(val):
result = "%s[%d]: %s" % (scalarType, len(val), arrayToStr(val))
else:
result = "%s[]" % scalarType
else:
result = str(val)
return result[:500]
# Return a string that reports size in metric units (units of 1000, not 1024).
def ReportMetricSize(sizeInBytes):
if sizeInBytes == 0:
return "0 B"
sizeSuffixes = ("B", "KB", "MB", "GB", "TB", "PB", "EB")
i = int(math.floor(math.log(sizeInBytes, 1000)))
if i >= len(sizeSuffixes):
i = len(sizeSuffixes) - 1
p = math.pow(1000, i)
s = round(sizeInBytes / p, 2)
return "%s %s" % (s, sizeSuffixes[i])
# Return attribute status at a certian frame (is it using the default, or the
# fallback? Is it authored at this frame? etc.
def _GetAttributeStatus(attribute, frame):
return attribute.GetResolveInfo(frame).GetSource()
# Return a Font corresponding to certain attribute properties.
# Currently this only applies italicization on interpolated time samples.
def GetPropertyTextFont(prop, frame):
if not isinstance(prop, Usd.Attribute):
# Early-out for non-attribute properties.
return None
frameVal = frame.GetValue()
bracketing = prop.GetBracketingTimeSamples(frameVal)
# Note that some attributes return an empty tuple, some None, from
# GetBracketingTimeSamples(), but all will be fed into this function.
if bracketing and (len(bracketing) == 2) and (bracketing[0] != frameVal):
return UIFonts.ITALIC
return None
# Helper function that takes attribute status and returns the display color
def GetPropertyColor(prop, frame, hasValue=None, hasAuthoredValue=None,
valueIsDefault=None):
if not isinstance(prop, Usd.Attribute):
# Early-out for non-attribute properties.
return UIBaseColors.RED.color()
statusToColor = {Usd.ResolveInfoSourceFallback : UIPropertyValueSourceColors.FALLBACK,
Usd.ResolveInfoSourceDefault : UIPropertyValueSourceColors.DEFAULT,
Usd.ResolveInfoSourceValueClips : UIPropertyValueSourceColors.VALUE_CLIPS,
Usd.ResolveInfoSourceTimeSamples: UIPropertyValueSourceColors.TIME_SAMPLE,
Usd.ResolveInfoSourceNone : UIPropertyValueSourceColors.NONE}
valueSource = _GetAttributeStatus(prop, frame)
return statusToColor[valueSource].color()
# Gathers information about a layer used as a subLayer, including its
# position in the layerStack hierarchy.
class SubLayerInfo(object):
def __init__(self, sublayer, offset, containingLayer, prefix):
self.layer = sublayer
self.offset = offset
self.parentLayer = containingLayer
self._prefix = prefix
def GetOffsetString(self):
o = self.offset.offset
s = self.offset.scale
if o == 0:
if s == 1:
return ""
else:
return str.format("(scale = {})", s)
elif s == 1:
return str.format("(offset = {})", o)
else:
return str.format("(offset = {0}; scale = {1})", o, s)
def GetHierarchicalDisplayString(self):
return self._prefix + self.layer.GetDisplayName()
def _AddSubLayers(layer, layerOffset, prefix, parentLayer, layers):
offsets = layer.subLayerOffsets
layers.append(SubLayerInfo(layer, layerOffset, parentLayer, prefix))
for i, l in enumerate(layer.subLayerPaths):
offset = offsets[i] if offsets is not None and len(offsets) > i else Sdf.LayerOffset()
subLayer = Sdf.Layer.FindRelativeToLayer(layer, l)
# Due to an unfortunate behavior of the Pixar studio resolver,
# FindRelativeToLayer() may fail to resolve certain paths. We will
# remove this extra Find() call as soon as we can retire the behavior;
# in the meantime, the extra call does not hurt (but should not, in
# general, be necessary)
if not subLayer:
subLayer = Sdf.Layer.Find(l)
if subLayer:
# This gives a 'tree'-ish presentation, but it looks sad in
# a QTableWidget. Just use spaces for now
# addedPrefix = "|-- " if parentLayer is None else "| "
addedPrefix = " "
_AddSubLayers(subLayer, offset, addedPrefix + prefix, layer, layers)
else:
print("Could not find layer " + l)
def GetRootLayerStackInfo(layer):
layers = []
_AddSubLayers(layer, Sdf.LayerOffset(), "", None, layers)
return layers
def PrettyFormatSize(sz):
k = 1024
meg = k * 1024
gig = meg * 1024
ter = gig * 1024
sz = float(sz)
if sz > ter:
return "%.1fT" % (sz/float(ter))
elif sz > gig:
return "%.1fG" % (sz/float(gig))
elif sz > meg:
return "%.1fM" % (sz/float(meg))
elif sz > k:
return "%.1fK" % (sz/float(k))
else:
return "%db" % sz
class Timer(object):
"""Use as a context object with python's "with" statement, like so:
with Timer() as t:
doSomeStuff()
t.PrintTime("did some stuff")
"""
def __enter__(self):
self._start = time.time()
self.interval = 0
return self
def __exit__(self, *args):
self._end = time.time()
self.interval = self._end - self._start
def PrintTime(self, action):
print("Time to %s: %2.3fs" % (action, self.interval))
class BusyContext(object):
"""When used as a context object with python's "with" statement,
will set Qt's busy cursor upon entry and pop it on exit.
"""
def __enter__(self):
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
def __exit__(self, *args):
QtWidgets.QApplication.restoreOverrideCursor()
def InvisRootPrims(stage):
"""Make all defined root prims of stage be invisible,
at Usd.TimeCode.Default()"""
for p in stage.GetPseudoRoot().GetChildren():
UsdGeom.Imageable(p).MakeInvisible()
def _RemoveVisibilityRecursive(primSpec):
try:
primSpec.RemoveProperty(primSpec.attributes[UsdGeom.Tokens.visibility])
except IndexError:
pass
for child in primSpec.nameChildren:
_RemoveVisibilityRecursive(child)
def ResetSessionVisibility(stage):
session = stage.GetSessionLayer()
with Sdf.ChangeBlock():
_RemoveVisibilityRecursive(session.pseudoRoot)
# This is unfortunate.. but until UsdAttribute will return you a ResolveInfo,
# we have little alternative, other than manually walking prim's PcpPrimIndex
def HasSessionVis(prim):
"""Is there a session-layer override for visibility for 'prim'?"""
session = prim.GetStage().GetSessionLayer()
primSpec = session.GetPrimAtPath(prim.GetPath())
return bool(primSpec and UsdGeom.Tokens.visibility in primSpec.attributes)
# This should be codified on UsdModelAPI, but maybe after 117137 is addressed...
def GetEnclosingModelPrim(prim):
"""If 'prim' is inside/under a model of any kind, return the closest
such ancestor prim - If 'prim' has no model ancestor, return None"""
if prim:
prim = prim.GetParent()
while prim:
# We use Kind here instead of prim.IsModel because point instancer
# prototypes currently don't register as models in IsModel. See
# bug: http://bugzilla.pixar.com/show_bug.cgi?id=117137
if Kind.Registry.IsA(Usd.ModelAPI(prim).GetKind(), Kind.Tokens.model):
break
prim = prim.GetParent()
return prim
def GetPrimLoadability(prim):
"""Return a tuple of (isLoadable, isLoaded) for 'prim', according to
the following rules:
A prim is loadable if it is active, and either of the following are true:
* prim has a payload
* prim is a model group
The latter is useful because loading is recursive on a UsdStage, and it
is convenient to be able to (e.g.) load everything loadable in a set.
A prim 'isLoaded' only if there are no unloaded prims beneath it, i.e.
it is stating whether the prim is "fully loaded". This
is a debatable definition, but seems useful for usdview's purposes."""
if not (prim.IsActive() and (prim.IsGroup() or prim.HasAuthoredPayloads())):
return (False, True)
# XXX Note that we are potentially traversing the entire stage here.
# If this becomes a performance issue, we can cast this query into C++,
# cache results, etc.
for p in Usd.PrimRange(prim, Usd.PrimIsActive):
if not p.IsLoaded():
return (True, False)
return (True, True)
def GetPrimsLoadability(prims):
"""Follow the logic of GetPrimLoadability for each prim, combining
results so that isLoadable is the disjunction of all prims, and
isLoaded is the conjunction."""
isLoadable = False
isLoaded = True
for prim in prims:
loadable, loaded = GetPrimLoadability(prim)
isLoadable = isLoadable or loadable
isLoaded = isLoaded and loaded
return (isLoadable, isLoaded)
def GetFileOwner(path):
try:
if platform.system() == 'Windows':
# This only works if pywin32 is installed.
# Try "pip install pypiwin32".
import win32security as w32s
fs = w32s.GetFileSecurity(path, w32s.OWNER_SECURITY_INFORMATION)
sdo = fs.GetSecurityDescriptorOwner()
name, domain, use = w32.LookupAccountSid(None, sdo)
return "%s\\%s" % (domain, name)
else:
import pwd
return pwd.getpwuid(os.stat(path).st_uid).pw_name
except:
return "<unknown>"
# In future when we have better introspection abilities in Usd core API,
# we will change this function to accept a prim rather than a primStack.
def GetAssetCreationTime(primStack, assetIdentifier):
"""Finds the weakest layer in which assetInfo.identifier is set to
'assetIdentifier', and considers that an "asset-defining layer". We then
retrieve the creation time for the asset by stat'ing the layer's
real path.
Returns a triple of strings: (fileDisplayName, creationTime, owner)"""
definingLayer = None
for spec in reversed(primStack):
if spec.HasInfo('assetInfo'):
identifier = spec.GetInfo('assetInfo')['identifier']
if identifier.path == assetIdentifier.path:
definingLayer = spec.layer
break
if definingLayer:
definingFile = definingLayer.realPath
else:
definingFile = primStack[-1].layer.realPath
print("Warning: Could not find expected asset-defining layer for %s" %
assetIdentifier)
if Ar.IsPackageRelativePath(definingFile):
definingFile = Ar.SplitPackageRelativePathOuter(definingFile)[0]
if not definingFile:
displayName = (definingLayer.GetDisplayName()
if definingLayer and definingLayer.anonymous else
"<in-memory layer>")
creationTime = "<unknown>"
owner = "<unknown>"
else:
displayName = definingFile.split('/')[-1]
try:
creationTime = time.ctime(os.stat(definingFile).st_ctime)
except:
creationTime = "<unknown>"
owner = GetFileOwner(definingFile)
return (displayName, creationTime, owner)
def DumpMallocTags(stage, contextStr):
if Tf.MallocTag.IsInitialized():
callTree = Tf.MallocTag.GetCallTree()
memInMb = Tf.MallocTag.GetTotalBytes() / (1024.0 * 1024.0)
import os.path as path
import tempfile
layerName = path.basename(stage.GetRootLayer().identifier)
# CallTree.Report() gives us the most informative (and processable)
# form of output, but it only accepts a fileName argument. So we
# use NamedTemporaryFile just to get a filename.
statsFile = tempfile.NamedTemporaryFile(prefix=layerName+'.',
suffix='.mallocTag',
delete=False)
statsFile.close()
reportName = statsFile.name
callTree.Report(reportName)
print("Memory consumption of %s for %s is %d Mb" % (contextStr,
layerName,
memInMb))
print("For detailed analysis, see " + reportName)
else:
print("Unable to accumulate memory usage since the Pxr MallocTag system was not initialized")
def GetInstanceIdForIndex(prim, instanceIndex, time):
'''Attempt to find an authored Id value for the instance at index
'instanceIndex' at time 'time', on the given prim 'prim', which we access
as a UsdGeom.PointInstancer (whether it actually is or not, to provide
some dynamic duck-typing for custom instancer types that support Ids.
Returns 'None' if no ids attribute was found, or if instanceIndex is
outside the bounds of the ids array.'''
if not prim or instanceIndex < 0:
return None
ids = UsdGeom.PointInstancer(prim).GetIdsAttr().Get(time)
if not ids or instanceIndex >= len(ids):
return None
return ids[instanceIndex]
def GetInstanceIndicesForIds(prim, instanceIds, time):
'''Attempt to find the instance indices of a list of authored instance IDs
for prim 'prim' at time 'time'. If the prim is not a PointInstancer or does
not have authored IDs, returns None. If any ID from 'instanceIds' does not
exist at the given time, its index is not added to the list (because it does
not have an index).'''
ids = UsdGeom.PointInstancer(prim).GetIdsAttr().Get(time)
if ids:
return [instanceIndex for instanceIndex, instanceId in enumerate(ids)
if instanceId in instanceIds]
else:
return None
def Drange(start, stop, step):
'''Return a list whose first element is 'start' and the following elements
(if any) are 'start' plus increasing whole multiples of 'step', up to but
not greater than 'stop'. For example:
Drange(1, 3, 0.3) -> [1, 1.3, 1.6, 1.9, 2.2, 2.5, 2.8]'''
lst = [start]
n = 1
while start + n * step <= stop:
lst.append(start + n * step)
n += 1
return lst
class PrimNotFoundException(Exception):
"""Raised when a prim does not exist at a valid path."""
def __init__(self, path):
super(PrimNotFoundException, self).__init__(
"Prim not found at path in stage: %s" % str(path))
class PropertyNotFoundException(Exception):
"""Raised when a property does not exist at a valid path."""
def __init__(self, path):
super(PropertyNotFoundException, self).__init__(
"Property not found at path in stage: %s" % str(path))
class FixableDoubleValidator(QtGui.QDoubleValidator):
"""This class implements a fixup() method for QDoubleValidator
(see method for specific behavior). To work around the brokenness
of Pyside's fixup() wrapping, we allow the validator to directly
update its parent if it is a QLineEdit, from within fixup(). Thus
every QLineEdit must possess its own unique FixableDoubleValidator.
The fixup method we supply (which can be usefully called directly)
applies clamping and rounding to enforce the QDoubleValidator's
range and decimals settings."""
def __init__(self, parent):
super(FixableDoubleValidator, self).__init__(parent)
self._lineEdit = parent if isinstance(parent, QtWidgets.QLineEdit) else None
def fixup(self, valStr):
# We implement this to fulfill the virtual for internal QLineEdit
# behavior, hoping that PySide will do the right thing, but it is
# useless to call from Python directly due to string immutability
try:
val = float(valStr)
val = max(val, self.bottom())
val = min(val, self.top())
val = round(val)
valStr = str(val)
if self._lineEdit:
self._lineEdit.setText(valStr)
except ValueError:
pass
| 26,669 | Python | 37.708273 | 101 | 0.656718 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/attributeViewContextMenu.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtGui, QtWidgets, QtCore
from pxr import Sdf
from .usdviewContextMenuItem import UsdviewContextMenuItem
from .common import (PropertyViewIndex, PropertyViewDataRoles,
PrimNotFoundException, PropertyNotFoundException)
#
# Specialized context menu for running commands in the attribute viewer.
#
class AttributeViewContextMenu(QtWidgets.QMenu):
def __init__(self, parent, item, dataModel):
QtWidgets.QMenu.__init__(self, parent)
self._menuItems = _GetContextMenuItems(item, dataModel)
for menuItem in self._menuItems:
# create menu actions
if menuItem.isValid() and menuItem.ShouldDisplay():
action = self.addAction(menuItem.GetText(), menuItem.RunCommand)
# set enabled
if not menuItem.IsEnabled():
action.setEnabled(False)
def _GetContextMenuItems(item, dataModel):
return [ # Root selection methods
CopyAttributeNameMenuItem(dataModel, item),
CopyAttributeValueMenuItem(dataModel, item),
CopyAllTargetPathsMenuItem(dataModel, item),
SelectAllTargetPathsMenuItem(dataModel, item),
# Individual/multi target selection menus
CopyTargetPathMenuItem(dataModel, item),
SelectTargetPathMenuItem(dataModel, item)]
def _selectPrimsAndProps(dataModel, paths):
prims = []
props = []
for path in paths:
primPath = path.GetAbsoluteRootOrPrimPath()
prim = dataModel.stage.GetPrimAtPath(primPath)
if not prim:
raise PrimNotFoundException(primPath)
prims.append(prim)
if path.IsPropertyPath():
prop = prim.GetProperty(path.name)
if not prop:
raise PropertyNotFoundException(path)
props.append(prop)
with dataModel.selection.batchPrimChanges:
dataModel.selection.clearPrims()
for prim in prims:
dataModel.selection.addPrim(prim)
with dataModel.selection.batchPropChanges:
dataModel.selection.clearProps()
for prop in props:
dataModel.selection.addProp(prop)
dataModel.selection.clearComputedProps()
#
# The base class for propertyview context menu items.
#
class AttributeViewContextMenuItem(UsdviewContextMenuItem):
def __init__(self, dataModel, item):
self._dataModel = dataModel
self._item = item
self._role = self._item.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
self._name = self._item.text(PropertyViewIndex.NAME) if self._item else ""
self._value = self._item.text(PropertyViewIndex.VALUE) if self._item else ""
def IsEnabled(self):
return True
def ShouldDisplay(self):
return True
def GetText(self):
return ""
def RunCommand(self):
pass
#
# Copy the attribute's name to clipboard.
#
class CopyAttributeNameMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return self._role not in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)
def GetText(self):
return "Copy Property Name"
def RunCommand(self):
if self._name == "":
return
cb = QtWidgets.QApplication.clipboard()
cb.setText(self._name, QtGui.QClipboard.Selection)
cb.setText(self._name, QtGui.QClipboard.Clipboard)
#
# Copy the attribute's value to clipboard.
#
class CopyAttributeValueMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return self._role not in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)
def GetText(self):
return "Copy Property Value"
def RunCommand(self):
# We display relationships targets as:
# /f, /g/a ...
# But when we ask to copy the value, we'd like to get back:
# [Sdf.Path('/f'), Sdf.Path('/g/a')]
# Which is useful for pasting into a python interpreter.
if self._role == PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS:
valueStr = str([Sdf.Path("".join(p.split())) \
for p in self._value.split(",")])
else:
valueStr = self._value
if self._item:
rawVal = self._item.rawValue
if rawVal is not None:
valueStr = str(rawVal)
cb = QtWidgets.QApplication.clipboard()
cb.setText(valueStr, QtGui.QClipboard.Selection)
cb.setText(valueStr, QtGui.QClipboard.Clipboard)
# --------------------------------------------------------------------
# Individual target selection menus
# --------------------------------------------------------------------
#
# Copy the target path to clipboard.
#
class CopyTargetPathMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return self._role in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)
def GetText(self):
return "Copy Target Path As Text"
def GetSelectedOfType(self):
getRole = lambda s: s.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
return [s for s in self._item.treeWidget().selectedItems() \
if getRole(s) in (PropertyViewDataRoles.TARGET, PropertyViewDataRoles.CONNECTION)]
def RunCommand(self):
if not self._item:
return
value = ", ".join([s.text(PropertyViewIndex.NAME) for s in self.GetSelectedOfType()])
cb = QtWidgets.QApplication.clipboard()
cb.setText(value, QtGui.QClipboard.Selection)
cb.setText(value, QtGui.QClipboard.Clipboard)
#
# Jump to the target path in the prim browser
# This will include all other highlighted paths of this type, if any.
#
class SelectTargetPathMenuItem(CopyTargetPathMenuItem):
def GetText(self):
return "Select Target Path"
def RunCommand(self):
paths = [Sdf.Path(s.text(PropertyViewIndex.NAME))
for s in self.GetSelectedOfType()]
_selectPrimsAndProps(self._dataModel, paths)
# --------------------------------------------------------------------
# Target owning property selection menus
# --------------------------------------------------------------------
def _GetTargetPathsForItem(item):
paths = [Sdf.Path(item.child(i).text(PropertyViewIndex.NAME)) for
i in range (0, item.childCount())]
# If there are no children, the value column must hold a valid path
# (since the command is enabled).
if len(paths) == 0:
itemText = item.text(PropertyViewIndex.VALUE)
if len(itemText) > 0:
paths.append(Sdf.Path(itemText))
return paths
#
# Select all target paths under the selected attribute
#
class SelectAllTargetPathsMenuItem(AttributeViewContextMenuItem):
def ShouldDisplay(self):
return (self._role == PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS
or self._role == PropertyViewDataRoles.ATTRIBUTE_WITH_CONNNECTIONS)
def IsEnabled(self):
if not self._item:
return False
# Enable the menu item if there are one or more targets for this
# rel/attribute connection
if self._item.childCount() > 0:
return True
# Enable the menu if the item holds a valid SdfPath.
itemText = self._item.text(2)
return Sdf.Path.IsValidPathString(itemText)
def GetText(self):
return "Select Target Path(s)"
def RunCommand(self):
if not self._item:
return
_selectPrimsAndProps(self._dataModel,
_GetTargetPathsForItem(self._item))
#
# Copy all target paths under the currently selected relationship to the clipboard
#
class CopyAllTargetPathsMenuItem(SelectAllTargetPathsMenuItem):
def GetText(self):
return "Copy Target Path(s) As Text"
def RunCommand(self):
if not self._item:
return
value = ", ".join(_GetTargetPathsForItem(self._item))
cb = QtWidgets.QApplication.clipboard()
cb.setText(value, QtGui.QClipboard.Selection)
cb.setText(value, QtGui.QClipboard.Clipboard)
| 9,265 | Python | 33.966038 | 102 | 0.649217 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/usdviewApi.py | #!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to # it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) # of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY
# KIND, either express or implied. See the Apache License for the # specific
# language governing permissions and limitations under the Apache # License.
import types
from pxr import Gf
from .qt import QtCore
class UsdviewApi(object):
"""This class is an interface that provides access to Usdview context for
Usdview plugins and other clients. It abstracts away the implementation of
Usdview so that the core can change without affecting clients.
"""
def __init__(self, appController):
self.__appController = appController
@property
def dataModel(self):
"""Usdview's active data model object."""
return self.__appController._dataModel
@property
def stage(self):
"""The current Usd.Stage."""
return self.__appController._dataModel.stage
@property
def frame(self):
"""The current frame."""
return self.__appController._dataModel.currentFrame
@property
def prim(self):
"""The focus prim from the prim selection."""
return self.__appController._dataModel.selection.getFocusPrim()
@property
def selectedPoint(self):
"""The currently selected world space point."""
return self.__appController._dataModel.selection.getPoint()
@property
def selectedPrims(self):
"""A list of all currently selected prims."""
return self.__appController._dataModel.selection.getPrims()
@property
def selectedPaths(self):
"""A list of the paths of all currently selected prims."""
return self.__appController._dataModel.selection.getPrimPaths()
@property
def selectedInstances(self):
"""The current prim instance selection. This is a dictionary where each
key is a prim and each value is a set of instance ids selected from that
prim.
"""
return self.__appController._dataModel.selection.getPrimInstances()
@property
def spec(self):
"""The currently selected Sdf.Spec from the Composition tab."""
return self.__appController._currentSpec
@property
def layer(self):
"""The currently selected Sdf.Layer in the Composition tab."""
return self.__appController._currentLayer
@property
def cameraPrim(self):
"""The current camera prim."""
return self.__appController._dataModel.viewSettings.cameraPrim
@property
def currentGfCamera(self):
"""A copy of the last computed Gf Camera."""
if self.__appController._stageView:
return Gf.Camera(self.__appController._stageView.gfCamera)
else:
return None
@property
def viewportSize(self):
"""The width and height of the viewport in pixels."""
stageView = self.__appController._stageView
if stageView is not None:
return stageView.width(), stageView.height()
else:
return 0, 0
@property
def configDir(self):
"""The config dir, typically ~/.usdview/."""
return self.__appController._outputBaseDirectory()
@property
def stageIdentifier(self):
"""The identifier of the open Usd.Stage's root layer."""
return self.__appController._dataModel.stage.GetRootLayer().identifier
@property
def qMainWindow(self):
"""A QWidget object that other widgets can use as a parent."""
return self.__appController._mainWindow
# This needs to be the last property added because otherwise the @property
# decorator will call this method rather than the actual property decorator.
@property
def property(self):
"""The focus property from the property selection."""
return self.__appController._dataModel.selection.getFocusProp()
def ComputeModelsFromSelection(self):
"""Returns selected models. this will walk up to find the nearest model.
Note, this may return "group"'s if they are selected.
"""
models = []
items = self.__appController.getSelectedItems()
for item in items:
currItem = item
while currItem and not currItem.prim.IsModel():
currItem = currItem.parent()
if currItem:
models.append(currItem.prim)
return models
def ComputeSelectedPrimsOfType(self, schemaType):
"""Returns selected prims of the provided schemaType (TfType)."""
prims = []
items = self.__appController.getSelectedItems()
for item in items:
if item.prim.IsA(schemaType):
prims.append(item.prim)
return prims
def UpdateGUI(self):
"""Updates the main UI views"""
self.__appController.updateGUI()
def PrintStatus(self, msg):
"""Prints a status message."""
self.__appController.statusMessage(msg)
def GetSettings(self):
"""DEPRECATED Returns the old settings object."""
return self.__appController._settings
def ClearPrimSelection(self):
self.__appController._dataModel.selection.clearPrims()
def AddPrimToSelection(self, prim):
self.__appController._dataModel.selection.addPrim(prim)
# Screen capture functionality.
def GrabWindowShot(self):
"""Returns a QImage of the full usdview window."""
return self.__appController.GrabWindowShot()
def GrabViewportShot(self):
"""Returns a QImage of the current stage view in usdview."""
return self.__appController.GrabViewportShot()
def _ExportSession(self, stagePath, defcamName='usdviewCam', imgWidth=None,
imgHeight=None):
"""Export the free camera (if currently active) and session layer to a
USD file at the specified stagePath that references the current-viewed
stage.
"""
stageView = self.__appController._stageView
if stageView is not None:
stageView.ExportSession(stagePath, defcamName='usdviewCam',
imgWidth=None, imgHeight=None)
| 6,994 | Python | 30.367713 | 81 | 0.660709 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/overridableLineEdit.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets
# simple class to have a "clear" button on a line edit when the line edit
# contains an override. Clicking the clear button returns to the default value.
class OverridableLineEdit(QtWidgets.QLineEdit):
def __init__(self, parent):
QtWidgets.QLineEdit.__init__(self, parent)
# create the clear button.
self._clearButton = QtWidgets.QToolButton(self)
self._clearButton.setText('x')
self._clearButton.setCursor(QtCore.Qt.ArrowCursor)
self._clearButton.setFixedSize(16, 16)
self._clearButton.hide()
self._defaultText = '' # default value holder
self._clearButton.clicked.connect(self._resetDefault)
self.textEdited.connect(self._overrideSet)
# properly place the button
def resizeEvent(self, event):
sz = QtCore.QSize(self._clearButton.size())
frameWidth = self.style().pixelMetric(QtWidgets.QStyle.PM_DefaultFrameWidth)
self._clearButton.move(self.rect().right() - frameWidth - sz.width(),
(self.rect().bottom() + 1 - sz.height())/2)
# called when the user types an override
def _overrideSet(self, text):
self._clearButton.setVisible(True)
# called programatically to reset the default text
def setText(self, text):
QtWidgets.QLineEdit.setText(self, text)
self._defaultText = text
self._clearButton.setVisible(False)
# called when the clear button is clicked
def _resetDefault(self):
self.setText(self._defaultText)
| 2,628 | Python | 38.238805 | 84 | 0.705099 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/attributeValueEditorUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'attributeValueEditorUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_AttributeValueEditor(object):
def setupUi(self, AttributeValueEditor):
if not AttributeValueEditor.objectName():
AttributeValueEditor.setObjectName(u"AttributeValueEditor")
AttributeValueEditor.resize(400, 300)
self.verticalLayout = QVBoxLayout(AttributeValueEditor)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName(u"verticalLayout")
self.stackedWidget = QStackedWidget(AttributeValueEditor)
self.stackedWidget.setObjectName(u"stackedWidget")
self.stackedWidget.setLineWidth(0)
self.valueViewer = QTextBrowser()
self.valueViewer.setObjectName(u"valueViewer")
self.stackedWidget.addWidget(self.valueViewer)
self.verticalLayout.addWidget(self.stackedWidget)
self.retranslateUi(AttributeValueEditor)
self.stackedWidget.setCurrentIndex(0)
QMetaObject.connectSlotsByName(AttributeValueEditor)
# setupUi
def retranslateUi(self, AttributeValueEditor):
AttributeValueEditor.setWindowTitle(QCoreApplication.translate("AttributeValueEditor", u"Form", None))
AttributeValueEditor.setProperty("comment", QCoreApplication.translate("AttributeValueEditor", u"\n"
" Copyright 2016 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
# retranslateUi
| 3,830 | Python | 53.728571 | 110 | 0.529243 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/prettyPrint.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
'''
Hopefully we can deprecate this since most of the array stuff is handled by the
arrayAttributeView
'''
from .qt import QtWidgets
def progressDialog(title, value):
dialog = QtWidgets.QProgressDialog(title, "Cancel", 0, value)
dialog.setModal(True)
dialog.setMinimumDuration(500)
return dialog
def prettyPrint(v):
"""Returns a string representing a "detailed view" of the value v.
This string is used in the watch window"""
# Pretty-print a dictionary
if isinstance(v, dict):
result = "Dictionary contents:\n"
for pair in v.items():
keystring = str(pair[0])
valstring = prettyPrint(pair[1])
result += "------\n%s:\n%s\n" % (keystring, valstring)
# Pretty-print list
elif isinstance(v, list):
dialog = progressDialog("Pretty-printing list...", len(v))
result = "[\n"
for i in range(len(v)):
dialog.setValue(i)
result += str(i) + ": " + prettyPrint(v[i]) + "\n"
if (dialog.wasCanceled()):
return "Pretty-printing canceled"
result += "]\n"
dialog.done(0)
# Pretty-print tuple
elif isinstance(v, tuple):
dialog = progressDialog("Pretty-printing tuple...", len(v))
result = "(\n"
for i in range(len(v)):
dialog.setValue(i)
result += str(i) + ": " + prettyPrint(v[i]) + "\n"
if (dialog.wasCanceled()):
return "Pretty-printing canceled"
result += ")\n"
dialog.done(0)
else:
from .scalarTypes import ToString
result = ToString(v)
return result
| 2,714 | Python | 33.367088 | 79 | 0.648121 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/selectionDataModel.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from collections import OrderedDict
from pxr import Sdf, Gf
from .qt import QtCore
from .customAttributes import (ComputedPropertyNames, BoundingBoxAttribute,
LocalToWorldXformAttribute, ComputedPropertyFactory)
# Indicates that all instances of a prim are selected.
ALL_INSTANCES = -1
class Blocker:
"""Object which can be used to temporarily block the execution of a body of
code. This object is a context manager, and enters a 'blocked' state when
used in a 'with' statement. The 'blocked()' method can be used to find if
the Blocker is in this 'blocked' state.
"""
def __init__(self, exitCallback=lambda: None):
# A count is used rather than a 'blocked' flag to allow for nested
# blocking.
self._count = 0
# Fired when the Blocker's context is exited.
self._exitCallback = exitCallback
def __enter__(self):
"""Enter the 'blocked' state until the context is exited."""
self._count += 1
def __exit__(self, *args):
"""Exit the 'blocked' state."""
self._count -= 1
if not self.blocked():
self._exitCallback()
def blocked(self):
"""Returns True if in the 'blocked' state, and False otherwise."""
return self._count > 0
class _PrimSelection(object):
"""This class keeps track of the core data for prim selection: paths and
instances. The methods here can be called in any order required without
corrupting the path selection state.
"""
def __init__(self):
# The order of paths selected needs to be maintained so we can track the
# focus path. An OrderedDict is more efficient than a list here since it
# supports efficient removal of arbitrary paths but still maintains the
# path order. Sdf.Path objects are the keys in the OrderedDict, and a
# set of selected instances are the values. If all instances are
# selected, None is the value rather than a set.
self._selection = OrderedDict()
self._added = set()
self._removed = set()
def _clearPrimPath(self, path):
"""Clears a path from the selection and updates the diff."""
if path in self._added:
# Path was added in this diff, but we are removing it again. Since
# there is no net change, it shouldn't be in _added or _removed.
self._added.discard(path)
else:
self._removed.add(path)
del self._selection[path]
def _discardInstance(self, path, instance):
"""Discards an instance from the selection, then deletes the path from
the selection if it has no more instances.
"""
instances = self._selection[path]
instances.discard(instance)
if len(instances) == 0:
# Last instance deselected, so path should be deselected.
self._clearPrimPath(path)
def _allInstancesSelected(self, path):
"""Returns True if all instances of a specified path are selected and
False otherwise.
"""
if path in self._selection:
return self._selection[path] == ALL_INSTANCES
else:
return False
def _noInstancesSelected(self, path):
"""Returns True if all instances of a specified path are selected and
False otherwise.
"""
return path not in self._selection
def clear(self):
"""Clear the path selection."""
# _clearPrimPath modifies self._selection, so make a copy of keys
# before mutating it.
for path in list(self._selection.keys()):
self._clearPrimPath(path)
def removeMatchingPaths(self, matches):
"""Remove any paths that pass the given predicate"""
# _clearPrimPath modifies self._selection, so make a copy of keys
# before mutating it.
for path in list(self._selection.keys()):
if matches(path):
self._clearPrimPath(path)
def addPrimPath(self, path, instance=ALL_INSTANCES):
"""Add a path to the selection. If an instance is given, then only add
that instance. If all instances are selected when this happens then the
single instance will become the only selected one.
"""
# If the path is not already in the selection, update the diff.
if path not in self._selection:
if path in self._removed:
# Path was removed in this diff, but is back now. Since there is
# no net change, it shouldn't be in _added or _removed.
self._removed.discard(path)
else:
self._added.add(path)
if instance == ALL_INSTANCES:
# Trying to add all instances, make sure all instances are selected.
self._selection[path] = ALL_INSTANCES
else:
# Trying to add a single instance.
if self._allInstancesSelected(path) or self._noInstancesSelected(path):
# Either all instances selected or none selected. Create an
# empty set of instances then add the target instance.
self._selection[path] = set()
self._selection[path].add(instance)
def removePrimPath(self, path, instance=ALL_INSTANCES):
"""Remove a path from the selection. If an instance is given, then only
remove that instance. If all instances are selected when this happens,
deselect all instances. If the target does not exist in the selection,
do nothing.
"""
if path in self._selection:
if instance == ALL_INSTANCES or self._allInstancesSelected(path):
# Want to deselect all instances or all instances are selected.
# Either way, deselect all.
self._clearPrimPath(path)
else:
# Some instances selected and want to deselect one of them.
self._discardInstance(path, instance)
def togglePrimPath(self, path, instance=ALL_INSTANCES):
"""Toggle the selection of a path. If an instance is given, only toggle
that instance's selection.
"""
if path not in self._selection:
self.addPrimPath(path, instance)
return
# Path is at least partially selected.
if instance == ALL_INSTANCES:
# Trying to toggle all instances.
if self._allInstancesSelected(path):
# All instances are already selected, so deselect the path.
self._clearPrimPath(path)
else:
# Only some instances are selected, select all all of them.
self._selection[path] = ALL_INSTANCES
else:
# Trying to toggle a single instance.
if self._allInstancesSelected(path):
# Currently all instances are selected. Switch selection to
# only the new instance.
self._selection[path] = set([instance])
else:
# Some instances already selected. Toggle the new instance
# in the selection.
instances = self._selection[path]
if instance in instances:
self._discardInstance(path, instance)
else:
instances.add(instance)
def getPrimPaths(self):
"""Get a list of paths that are at least partially selected."""
return list(self._selection.keys())
def getPrimPathInstances(self):
"""Get the full selection of paths and their corresponding selected
instances.
"""
return OrderedDict(
(path, set(instances)) if isinstance(instances, set) else (path, instances)
for path, instances in self._selection.items())
def getDiff(self):
"""Get the prims added to or removed from the selection since the last
time getDiff() was called.
"""
diff = (self._added, self._removed)
self._added = set()
self._removed = set()
return diff
class _PropSelection(object):
"""This class keeps track of the state of property selection."""
def __init__(self):
self._selection = OrderedDict()
def clear(self):
"""Clears the property selection."""
self._selection = OrderedDict()
def addPropPath(self, primPath, propName):
"""Add a property to the selection."""
propTuple = (primPath, propName)
# If this property is already selected, remove it from the selection and
# re-add it so it becomes the focus property.
if propTuple in self._selection:
targets = self._selection[propTuple]
del self._selection[propTuple]
self._selection[propTuple] = targets
else:
self._selection[propTuple] = set()
def removePropPath(self, primPath, propName):
"""Remove a property from the selection."""
propTuple = (primPath, propName)
if propTuple in self._selection:
del self._selection[propTuple]
def addTarget(self, primPath, propName, target):
"""Add a target to the selection. Also add the target's property if it
is not already in the selection.
"""
propTuple = (primPath, propName)
# If this property is already selected, remove it from the selection and
# re-add it so it becomes the focus property.
if propTuple in self._selection:
targets = self._selection[propTuple]
del self._selection[propTuple]
self._selection[propTuple] = targets
else:
targets = self._selection.setdefault(propTuple, set())
targets.add(target)
def removeTarget(self, primPath, propName, target):
"""Remove a target from the selection. If the target or its property are
not already in the selection, nothing is changed.
"""
propTuple = (primPath, propName)
if propTuple in self._selection:
self._selection[propTuple].discard(target)
def getPropPaths(self):
"""Get the list of properties."""
return list(self._selection.keys())
def getTargets(self):
"""Get a dictionary which maps selected properties to a set of their
selected targets or connections.
"""
propTargets = OrderedDict()
for propTuple, targets in self._selection.items():
propTargets[propTuple] = set(targets)
return propTargets
class SelectionDataModel(QtCore.QObject):
"""Data model managing the current selection of prims and properties.
Please note that the owner of an instance of this class is
responsible for calling SelectionDataModel.removeUnpopulatedPrims() when
appropriate, lest methods like getPrims() return invalid prims."""
# Signals must be declared in the class, but each instance of the selection
# data model has its own unique signal instances.
# When emitted, includes two sets: one of newly selected prims, and one of
# newly deselected prims.
signalPrimSelectionChanged = QtCore.Signal(set, set)
signalPropSelectionChanged = QtCore.Signal()
signalComputedPropSelectionChanged = QtCore.Signal()
def __init__(self, rootDataModel, _computedPropFactory=None):
QtCore.QObject.__init__(self)
self._rootDataModel = rootDataModel
# _computedPropFactory may be passed explicitly for unit testing.
if _computedPropFactory is None:
self._computedPropFactory = ComputedPropertyFactory(
self._rootDataModel)
else:
self._computedPropFactory = _computedPropFactory
self.batchPrimChanges = Blocker(
exitCallback=self._primSelectionChanged)
self.batchPropChanges = Blocker(
exitCallback=self._propSelectionChanged)
self.batchComputedPropChanges = Blocker(
exitCallback=self._computedPropSelectionChanged)
self._pointSelection = Gf.Vec3f(0.0, 0.0, 0.0)
self._primSelection = _PrimSelection()
# The path selection should never be empty. If it ever is, we
# immediately add the root path before returning to user control (see
# _primSelectionChanged).
self._primSelection.addPrimPath(Sdf.Path.absoluteRootPath)
# Clear the prim selection diff so we don't get the absolute root in the
# first signal from signalPrimSelectionChanged.
self._primSelection.getDiff()
self._lcdPathSelection = [Sdf.Path.absoluteRootPath]
self._propSelection = _PropSelection()
self._computedPropSelection = _PropSelection()
### Internal Operations ###
def _primSelectionChanged(self, emitSelChangedSignal=True):
"""Should be called whenever a change is made to _primSelection. Some
final work is done then the prim selection changed signal is emitted.
"""
# If updates are suppressed, do not emit a signal or do any
# pre-processing.
if self.batchPrimChanges.blocked():
return
# Make sure there is always at least one path selected.
if len(self.getPrimPaths()) == 0:
self._primSelection.addPrimPath(Sdf.Path.absoluteRootPath)
# Recalculate the LCD prims whenever the path selection changes.
paths = self._primSelection.getPrimPaths()
if len(paths) > 1:
paths = [path for path in paths
if path != Sdf.Path.absoluteRootPath]
self._lcdPathSelection = Sdf.Path.RemoveDescendentPaths(paths)
# Finally, emit the changed signal.
added, removed = self._primSelection.getDiff()
if emitSelChangedSignal:
self.signalPrimSelectionChanged.emit(added, removed)
def _propSelectionChanged(self):
"""Should be called whenever a change is made to _propSelection."""
# If updates are suppressed, do not emit a signal or do any
# pre-processing.
if self.batchPropChanges.blocked():
return
self.signalPropSelectionChanged.emit()
def _computedPropSelectionChanged(self):
"""Should be called whenever a change is made to _computedPropSelection.
"""
# If updates are suppressed, do not emit a signal or do any
# pre-processing.
if self.batchComputedPropChanges.blocked():
return
self.signalComputedPropSelectionChanged.emit()
def _ensureValidPrimPath(self, path):
"""Validate an input path. If it is a string path, convert it to an
Sdf.Path object.
"""
sdfPath = Sdf.Path(str(path))
if not sdfPath.IsAbsoluteRootOrPrimPath():
raise ValueError("Path must be a prim path, got: {}".format(
repr(sdfPath)))
return sdfPath
def _validateInstanceIndexParameter(self, instance):
"""Validate an instance used as a parameter. This can be any positive
int or ALL_INSTANCES."""
validIndex = False
if isinstance(instance, int):
if instance >= 0 or instance == ALL_INSTANCES:
validIndex = True
if not validIndex:
raise ValueError(
"Instance must be a positive int or ALL_INSTANCES"
", got: {}".format(repr(instance)))
def _ensureValidPropPath(self, prop):
"""Validate a property."""
sdfPath = Sdf.Path(str(prop))
if not sdfPath.IsPropertyPath():
raise ValueError("Path must be a property path, got: {}".format(
repr(sdfPath)))
return sdfPath
def _ensureValidTargetPath(self, target):
"""Validate a property target or connection."""
return Sdf.Path(str(target))
def _getPropFromPath(self, path):
"""Get a Usd property object from a property path."""
prim = self._rootDataModel.stage.GetPrimAtPath(path.GetPrimPath())
return prim.GetProperty(path.name)
def _getTargetFromPath(self, path):
"""Get the Usd object from a target path. It can be either a Usd prim or
Usd property.
"""
if path.IsPropertyPath():
return self._getPropFromPath(path)
else:
return self._rootDataModel.stage.GetPrimAtPath(path)
def _requireNotBatchingPrims(self):
"""Raise an error if we are currently batching prim selection changes.
We don't want to allow reading prim selection state in the middle of a
batch.
"""
if self.batchPrimChanges.blocked():
raise RuntimeError(
"Cannot get prim selection state while batching changes.")
def _requireNotBatchingProps(self):
"""Raise an error if we are currently batching prop selection changes.
We don't want to allow reading prop selection state in the middle of a
batch.
"""
if self.batchPropChanges.blocked():
raise RuntimeError(
"Cannot get property selection state while batching changes.")
def _getComputedPropFromPath(self, primPath, propName):
"""Get a CustomAttribute object from a prim path and property name.
Raise an error if the property name does not match any known
CustomAttribute.
"""
prim = self._rootDataModel.stage.GetPrimAtPath(primPath)
return self._computedPropFactory.getComputedProperty(prim, propName)
def _requireNotBatchingComputedProps(self):
"""Raise an error if we are currently batching prop selection changes.
We don't want to allow reading prop selection state in the middle of a
batch.
"""
if self.batchComputedPropChanges.blocked():
raise RuntimeError("Cannot get computed property selection state "
"while batching changes.")
def _buildPropPath(self, primPath, propName):
"""Build a new property path from a prim path and a property name."""
return Sdf.Path(str(primPath) + "." + propName)
def _validateComputedPropName(self, propName):
"""Validate a computed property name."""
if propName not in ComputedPropertyNames:
raise ValueError("Invalid computed property name: {}".format(
repr(propName)))
def _switchProps(self, fromPrimPath, toPrimPath):
"""Switch all selected properties from one prim to another. Only do this
if all properties currently belong to the "from" prim.
"""
propTargets = self.getPropTargetPaths()
computedProps = self.getComputedPropPaths()
# Check that all properties belong to the "from" prim.
for propPath in propTargets:
if propPath.GetPrimPath() != fromPrimPath:
return
for propPrimPath, propName in computedProps:
if propPrimPath != fromPrimPath:
return
# Switch all properties to the "to" prim.
with self.batchPropChanges:
self.clearProps()
# Root prim cannot have non-computed properties. The property paths
# in this case are invalid.
if str(toPrimPath) != "/":
for propPath, targets in propTargets.items():
newPropPath = self._buildPropPath(toPrimPath, propPath.name)
self.addPropPath(newPropPath)
for target in targets:
self.addPropTargetPath(newPropPath, target)
with self.batchComputedPropChanges:
self.clearComputedProps()
for primPath, propName in computedProps:
self.addComputedPropPath(toPrimPath, propName)
### General Operations ###
def clear(self):
"""Clear all selections."""
self.clearPoint()
self.clearPrims()
self.clearProps()
def clearPoint(self):
self.setPoint(Gf.Vec3f(0.0, 0.0, 0.0))
def setPoint(self, point):
self._pointSelection = point
def getPoint(self):
return self._pointSelection
### Prim Path Operations ###
def clearPrims(self):
"""Clear the prim selection (same as path selection)."""
self._primSelection.clear()
self._primSelectionChanged()
def addPrimPath(self, path, instance=ALL_INSTANCES):
"""Add a path to the path selection. If an instance is given, only add
that instance.
"""
path = self._ensureValidPrimPath(path)
self._validateInstanceIndexParameter(instance)
self._primSelection.addPrimPath(path, instance)
self._primSelectionChanged()
def removePrimPath(self, path, instance=ALL_INSTANCES):
"""Remove a path from the path selection. If an instance is given, only
remove that instance. If the target does not exist in the selection, do
nothing.
"""
path = self._ensureValidPrimPath(path)
self._validateInstanceIndexParameter(instance)
self._primSelection.removePrimPath(path, instance)
self._primSelectionChanged()
def togglePrimPath(self, path, instance=ALL_INSTANCES):
"""Toggle a path in the path selection. If an instance is given, only
that instance is toggled.
"""
path = self._ensureValidPrimPath(path)
self._validateInstanceIndexParameter(instance)
self._primSelection.togglePrimPath(path, instance)
self._primSelectionChanged()
def setPrimPath(self, path, instance=ALL_INSTANCES):
"""Clear the prim selection then add a single prim path back to the
selection. If an instance is given, only add that instance.
"""
with self.batchPrimChanges:
self.clearPrims()
self.addPrimPath(path, instance)
def getFocusPrimPath(self):
"""Get the path currently in focus."""
self._requireNotBatchingPrims()
return self._primSelection.getPrimPaths()[0]
def getPrimPaths(self):
"""Get a list of all selected paths."""
self._requireNotBatchingPrims()
return self._primSelection.getPrimPaths()
def getLCDPaths(self):
"""Get a list of paths from the selection who do not have an ancestor
that is also in the selection. The "Least Common Denominator" paths.
"""
self._requireNotBatchingPrims()
return list(self._lcdPathSelection)
def getPrimPathInstances(self):
"""Get a dictionary which maps each selected prim to a set of its
selected instances. If all of a path's instances are selected, the value
is ALL_INSTANCES rather than a set.
"""
self._requireNotBatchingPrims()
return self._primSelection.getPrimPathInstances()
def switchToPrimPath(self, path, instance=ALL_INSTANCES):
"""Select only the given prim path. If only a single prim was selected
before and all selected properties belong to this prim, select the
corresponding properties on the new prim instead. If an instance is
given, only select that instance.
"""
path = self._ensureValidPrimPath(path)
oldPrimPaths = self.getPrimPaths()
with self.batchPrimChanges:
self.clearPrims()
self.addPrimPath(path, instance)
if len(oldPrimPaths) == 1:
self._switchProps(oldPrimPaths[0], path)
### Prim Operations ###
# These are all convenience methods which just call their respective path
# operations.
def addPrim(self, prim, instance=ALL_INSTANCES):
"""Add a prim's path to the path selection. If an instance is given,
only add that instance.
"""
self.addPrimPath(prim.GetPath(), instance)
def removePrim(self, prim, instance=ALL_INSTANCES):
"""Remove a prim from the prim selection. If an instance is given, only
remove that instance. If the target does not exist in the selection, do
nothing.
"""
self.removePrimPath(prim.GetPath(), instance)
def togglePrim(self, prim, instance=ALL_INSTANCES):
"""Toggle a prim's path in the path selection. If an instance is given,
only that instance is toggled.
"""
self.togglePrimPath(prim.GetPath(), instance)
def setPrim(self, prim, instance=ALL_INSTANCES):
"""Clear the prim selection then add a single prim back to the
selection. If an instance is given, only add that instance.
"""
self.setPrimPath(prim.GetPath(), instance)
def getFocusPrim(self):
"""Get the prim whose path is currently in focus."""
return self._rootDataModel.stage.GetPrimAtPath(self.getFocusPrimPath())
def getPrims(self):
"""Get a list of all prims whose paths are selected."""
return [self._rootDataModel.stage.GetPrimAtPath(path)
for path in self.getPrimPaths()]
def getLCDPrims(self):
"""Get a list of prims whose paths are both selected and do not have an
ancestor that is also in the selection. The "Least Common Denominator"
prims.
"""
return [self._rootDataModel.stage.GetPrimAtPath(path)
for path in self.getLCDPaths()]
def getPrimInstances(self):
"""Get a dictionary which maps each prim whose path is selected to a set
of its selected instances. If all of a path's instances are selected,
the value is ALL_INSTANCES rather than a set.
"""
return OrderedDict(
(self._rootDataModel.stage.GetPrimAtPath(path), instance)
for path, instance in self.getPrimPathInstances().items())
def switchToPrim(self, prim, instance=ALL_INSTANCES):
"""Select only the given prim. If only a single prim was selected before
and all selected properties belong to this prim, select the
corresponding properties on the new prim instead.
"""
self.switchToPrimPath(prim.GetPath(), instance)
### Prim Group Removal Operations ###
# Convenience methods for removing groups of prims
def removeInactivePrims(self):
"""Remove all inactive prims"""
for prim in self.getPrims():
if not prim.IsActive():
self.removePrim(prim)
def removeMasterPrims(self):
"""Remove all master prims"""
for prim in self.getPrims():
if prim.IsMaster() or prim.IsInMaster():
self.removePrim(prim)
def removeAbstractPrims(self):
"""Remove all abstract prims"""
for prim in self.getPrims():
if prim.IsAbstract():
self.removePrim(prim)
def removeUndefinedPrims(self):
"""Remove all undefined prims"""
for prim in self.getPrims():
if not prim.IsDefined():
self.removePrim(prim)
def removeUnpopulatedPrims(self):
"""Remove all prim paths whose corresponding prims do not currently
exist on the stage. It is the application's responsibility to
call this method while it is processing changes to the stage,
*before* querying this object for selections. Because this is a
synchronization operation rather than an expression of GUI state
change, it does *not* perform any notifications/signals, which could
cause reentrant application change processing."""
stage = self._rootDataModel.stage
self._primSelection.removeMatchingPaths(lambda path: not stage.GetPrimAtPath(path))
self._primSelectionChanged(emitSelChangedSignal=False)
### Property Path Operations ###
def clearProps(self):
"""Clear the property selection."""
self._propSelection.clear()
self._propSelectionChanged()
def addPropPath(self, path):
"""Add a property to the selection."""
path = self._ensureValidPropPath(path)
primPath = path.GetPrimPath()
propName = path.name
self._propSelection.addPropPath(primPath, propName)
self._propSelectionChanged()
def removePropPath(self, path):
"""Remove a property from the selection."""
path = self._ensureValidPropPath(path)
primPath = path.GetPrimPath()
propName = path.name
self._propSelection.removePropPath(primPath, propName)
self._propSelectionChanged()
def setPropPath(self, path):
"""Clear the property selection, then add a single property path back to
the selection.
"""
path = self._ensureValidPropPath(path)
with self.batchPropChanges:
self.clearProps()
self.addPropPath(path)
def addPropTargetPath(self, path, targetPath):
"""Select a property's target or connection."""
path = self._ensureValidPropPath(path)
targetPath = self._ensureValidTargetPath(targetPath)
primPath = path.GetPrimPath()
propName = path.name
self._propSelection.addTarget(primPath, propName, targetPath)
self._propSelectionChanged()
def removePropTargetPath(self, path, targetPath):
"""Deselect a property's target or connection."""
path = self._ensureValidPropPath(path)
targetPath = self._ensureValidTargetPath(targetPath)
primPath = path.GetPrimPath()
propName = path.name
self._propSelection.removeTarget(primPath, propName, targetPath)
self._propSelectionChanged()
def setPropTargetPath(self, path, targetPath):
"""Clear the property selection, then add a single property path back to
the selection with a target.
"""
with self.batchPropChanges:
self.clearProps()
self.addPropTargetPath(path, targetPath)
def getFocusPropPath(self):
"""Get the focus property from the property selection."""
self._requireNotBatchingProps()
propPaths = [self._buildPropPath(*propTuple)
for propTuple in self._propSelection.getPropPaths()]
if len(propPaths) > 0:
return propPaths[-1]
else:
return None
def getPropPaths(self):
"""Get a list of all selected properties."""
self._requireNotBatchingProps()
propPaths = [self._buildPropPath(*propTuple)
for propTuple in self._propSelection.getPropPaths()]
return propPaths
def getPropTargetPaths(self):
"""Get a dictionary which maps selected properties to a set of their
selected targets or connections.
"""
self._requireNotBatchingProps()
return OrderedDict((self._buildPropPath(*propTuple), set(targets))
for propTuple, targets in self._propSelection.getTargets().items())
### Property Operations ###
def addProp(self, prop):
"""Add a property to the selection."""
self.addPropPath(prop.GetPath())
def removeProp(self, prop):
"""Remove a property from the selection."""
self.removePropPath(prop.GetPath())
def setProp(self, prop):
"""Clear the property selection, then add a single property back to the
selection.
"""
self.setPropPath(prop.GetPath())
def addPropTarget(self, prop, target):
"""Select a property's target or connection."""
self.addPropTargetPath(prop.GetPath(), target.GetPath())
def removePropTarget(self, prop, target):
"""Deselect a property's target or connection."""
self.removePropTargetPath(prop.GetPath(), target.GetPath())
def setPropTarget(self, prop, target):
"""Clear the property selection, then add a single property back to the
selection with a target.
"""
self.removePropTargetPath(prop.GetPath(), target.GetPath())
def getFocusProp(self):
"""Get the focus property from the property selection."""
focusPath = self.getFocusPropPath()
if focusPath is None:
return None
return self._getPropFromPath(focusPath)
def getProps(self):
"""Get a list of all selected properties."""
return [self._getPropFromPath(path)
for path in self.getPropPaths()]
def getPropTargets(self):
"""Get a dictionary which maps selected properties to a set of their
selected targets or connections.
"""
propTargets = OrderedDict()
for propPath, targetPaths in self.getPropTargetPaths().items():
prop = self._getPropFromPath(propPath)
targets = {self._getTargetFromPath(target)
for target in targetPaths}
propTargets[prop] = targets
return propTargets
### Computed Property Path Operations ###
def clearComputedProps(self):
"""Clear the computed property selection."""
self._computedPropSelection.clear()
self._computedPropSelectionChanged()
def addComputedPropPath(self, primPath, propName):
"""Add a computed property to the selection."""
primPath = self._ensureValidPrimPath(primPath)
self._validateComputedPropName(propName)
self._computedPropSelection.addPropPath(primPath, propName)
self._computedPropSelectionChanged()
def removeComputedPropPath(self, primPath, propName):
"""Remove a computed property from the selection."""
primPath = self._ensureValidPrimPath(primPath)
self._validateComputedPropName(propName)
self._computedPropSelection.removePropPath(primPath, propName)
self._computedPropSelectionChanged()
def setComputedPropPath(self, primPath, propName):
"""Clear the computed property selection, then add a single computed
property path back to the selection.
"""
primPath = self._ensureValidPrimPath(primPath)
self._validateComputedPropName(propName)
with self.batchComputedPropChanges:
self.clearComputedProps()
self.addComputedPropPath(primPath, propName)
def getFocusComputedPropPath(self):
"""Get the focus computed property from the property selection."""
self._requireNotBatchingComputedProps()
propPaths = self._computedPropSelection.getPropPaths()
if len(propPaths) > 0:
return propPaths[-1]
else:
return (None, None)
def getComputedPropPaths(self):
"""Get a list of all selected computed properties."""
self._requireNotBatchingComputedProps()
return self._computedPropSelection.getPropPaths()
### Computed Property Operations ###
def addComputedProp(self, prop):
"""Add a computed property to the selection."""
self.addComputedPropPath(prop.GetPrimPath(), prop.GetName())
def removeComputedProp(self, prop):
"""Remove a computed property from the selection."""
self.removeComputedPropPath(prop.GetPrimPath(), prop.GetName())
def setComputedProp(self, prop):
"""Clear the computed property selection, then add a single computed
property back to the selection.
"""
self.setComputedPropPath(prop.GetPrimPath(), prop.GetName())
def getFocusComputedProp(self):
"""Get the focus computed property from the property selection."""
focusPath = self.getFocusComputedPropPath()
if focusPath == (None, None):
return None
return self._getComputedPropFromPath(*focusPath)
def getComputedProps(self):
"""Get a list of all selected computed properties."""
return [self._getComputedPropFromPath(*path)
for path in self.getComputedPropPaths()]
| 36,931 | Python | 34.039848 | 91 | 0.638461 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/propertyLegendUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'propertyLegendUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_PropertyLegend(object):
def setupUi(self, PropertyLegend):
if not PropertyLegend.objectName():
PropertyLegend.setObjectName(u"PropertyLegend")
PropertyLegend.setWindowModality(Qt.NonModal)
PropertyLegend.resize(654, 151)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(PropertyLegend.sizePolicy().hasHeightForWidth())
PropertyLegend.setSizePolicy(sizePolicy)
self.gridLayout = QGridLayout(PropertyLegend)
self.gridLayout.setObjectName(u"gridLayout")
self.gridLayout_2 = QGridLayout()
self.gridLayout_2.setSpacing(3)
self.gridLayout_2.setObjectName(u"gridLayout_2")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.propertyLegendColorNoValue = QGraphicsView(PropertyLegend)
self.propertyLegendColorNoValue.setObjectName(u"propertyLegendColorNoValue")
self.propertyLegendColorNoValue.setMaximumSize(QSize(20, 15))
self.horizontalLayout.addWidget(self.propertyLegendColorNoValue)
self.propertyLegendLabelNoValue = QLabel(PropertyLegend)
self.propertyLegendLabelNoValue.setObjectName(u"propertyLegendLabelNoValue")
font = QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.propertyLegendLabelNoValue.setFont(font)
self.horizontalLayout.addWidget(self.propertyLegendLabelNoValue)
self.horizontalSpacer_8 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(self.horizontalSpacer_8)
self.gridLayout_2.addLayout(self.horizontalLayout, 0, 0, 1, 1)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.propertyLegendColorDefault = QGraphicsView(PropertyLegend)
self.propertyLegendColorDefault.setObjectName(u"propertyLegendColorDefault")
self.propertyLegendColorDefault.setMaximumSize(QSize(20, 15))
self.horizontalLayout_2.addWidget(self.propertyLegendColorDefault)
self.propertyLegendLabelDefault = QLabel(PropertyLegend)
self.propertyLegendLabelDefault.setObjectName(u"propertyLegendLabelDefault")
self.propertyLegendLabelDefault.setFont(font)
self.horizontalLayout_2.addWidget(self.propertyLegendLabelDefault)
self.horizontalSpacer_10 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer_10)
self.gridLayout_2.addLayout(self.horizontalLayout_2, 0, 1, 1, 1)
self.horizontalLayout_5 = QHBoxLayout()
self.horizontalLayout_5.setObjectName(u"horizontalLayout_5")
self.propertyLegendColorTimeSample = QGraphicsView(PropertyLegend)
self.propertyLegendColorTimeSample.setObjectName(u"propertyLegendColorTimeSample")
self.propertyLegendColorTimeSample.setMaximumSize(QSize(20, 15))
self.horizontalLayout_5.addWidget(self.propertyLegendColorTimeSample)
self.propertyLegendLabelTimeSample = QLabel(PropertyLegend)
self.propertyLegendLabelTimeSample.setObjectName(u"propertyLegendLabelTimeSample")
self.propertyLegendLabelTimeSample.setFont(font)
self.horizontalLayout_5.addWidget(self.propertyLegendLabelTimeSample)
self.horizontalSpacer_12 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_5.addItem(self.horizontalSpacer_12)
self.gridLayout_2.addLayout(self.horizontalLayout_5, 0, 2, 1, 1)
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.propertyLegendColorFallback = QGraphicsView(PropertyLegend)
self.propertyLegendColorFallback.setObjectName(u"propertyLegendColorFallback")
self.propertyLegendColorFallback.setMaximumSize(QSize(20, 15))
self.horizontalLayout_3.addWidget(self.propertyLegendColorFallback)
self.propertyLegendLabelFallback = QLabel(PropertyLegend)
self.propertyLegendLabelFallback.setObjectName(u"propertyLegendLabelFallback")
self.propertyLegendLabelFallback.setFont(font)
self.horizontalLayout_3.addWidget(self.propertyLegendLabelFallback)
self.horizontalSpacer_9 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(self.horizontalSpacer_9)
self.gridLayout_2.addLayout(self.horizontalLayout_3, 1, 0, 1, 1)
self.horizontalLayout_4 = QHBoxLayout()
self.horizontalLayout_4.setObjectName(u"horizontalLayout_4")
self.propertyLegendColorCustom = QGraphicsView(PropertyLegend)
self.propertyLegendColorCustom.setObjectName(u"propertyLegendColorCustom")
self.propertyLegendColorCustom.setMaximumSize(QSize(20, 15))
self.horizontalLayout_4.addWidget(self.propertyLegendColorCustom)
self.propertyLegendLabelCustom = QLabel(PropertyLegend)
self.propertyLegendLabelCustom.setObjectName(u"propertyLegendLabelCustom")
self.horizontalLayout_4.addWidget(self.propertyLegendLabelCustom)
self.horizontalSpacer_11 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(self.horizontalSpacer_11)
self.gridLayout_2.addLayout(self.horizontalLayout_4, 1, 1, 1, 1)
self.horizontalLayout_6 = QHBoxLayout()
self.horizontalLayout_6.setObjectName(u"horizontalLayout_6")
self.propertyLegendColorValueClips = QGraphicsView(PropertyLegend)
self.propertyLegendColorValueClips.setObjectName(u"propertyLegendColorValueClips")
self.propertyLegendColorValueClips.setMaximumSize(QSize(20, 15))
self.horizontalLayout_6.addWidget(self.propertyLegendColorValueClips)
self.propertyLegendLabelValueClips = QLabel(PropertyLegend)
self.propertyLegendLabelValueClips.setObjectName(u"propertyLegendLabelValueClips")
self.propertyLegendLabelValueClips.setFont(font)
self.horizontalLayout_6.addWidget(self.propertyLegendLabelValueClips)
self.horizontalSpacer_13 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_6.addItem(self.horizontalSpacer_13)
self.gridLayout_2.addLayout(self.horizontalLayout_6, 1, 2, 1, 1)
self.gridLayout.addLayout(self.gridLayout_2, 0, 0, 1, 3)
self.verticalLayout = QVBoxLayout()
self.verticalLayout.setSpacing(3)
self.verticalLayout.setObjectName(u"verticalLayout")
self.horizontalLayout_9 = QHBoxLayout()
self.horizontalLayout_9.setSpacing(3)
self.horizontalLayout_9.setObjectName(u"horizontalLayout_9")
self.propertyLegendAttrPlainIcon = QLabel(PropertyLegend)
self.propertyLegendAttrPlainIcon.setObjectName(u"propertyLegendAttrPlainIcon")
self.horizontalLayout_9.addWidget(self.propertyLegendAttrPlainIcon)
self.propertyLegendAttrPlainDesc = QLabel(PropertyLegend)
self.propertyLegendAttrPlainDesc.setObjectName(u"propertyLegendAttrPlainDesc")
self.propertyLegendAttrPlainDesc.setFont(font)
self.horizontalLayout_9.addWidget(self.propertyLegendAttrPlainDesc)
self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(self.horizontalSpacer)
self.verticalLayout.addLayout(self.horizontalLayout_9)
self.horizontalLayout_10 = QHBoxLayout()
self.horizontalLayout_10.setSpacing(3)
self.horizontalLayout_10.setObjectName(u"horizontalLayout_10")
self.propertyLegendRelPlainIcon = QLabel(PropertyLegend)
self.propertyLegendRelPlainIcon.setObjectName(u"propertyLegendRelPlainIcon")
self.horizontalLayout_10.addWidget(self.propertyLegendRelPlainIcon)
self.propertyLegendRelPlainDesc = QLabel(PropertyLegend)
self.propertyLegendRelPlainDesc.setObjectName(u"propertyLegendRelPlainDesc")
self.propertyLegendRelPlainDesc.setFont(font)
self.horizontalLayout_10.addWidget(self.propertyLegendRelPlainDesc)
self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_10.addItem(self.horizontalSpacer_2)
self.verticalLayout.addLayout(self.horizontalLayout_10)
self.horizontalLayout_11 = QHBoxLayout()
self.horizontalLayout_11.setSpacing(3)
self.horizontalLayout_11.setObjectName(u"horizontalLayout_11")
self.propertyLegendCompIcon = QLabel(PropertyLegend)
self.propertyLegendCompIcon.setObjectName(u"propertyLegendCompIcon")
self.horizontalLayout_11.addWidget(self.propertyLegendCompIcon)
self.propertyLegendCompDesc = QLabel(PropertyLegend)
self.propertyLegendCompDesc.setObjectName(u"propertyLegendCompDesc")
self.propertyLegendCompDesc.setFont(font)
self.horizontalLayout_11.addWidget(self.propertyLegendCompDesc)
self.horizontalSpacer_3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_11.addItem(self.horizontalSpacer_3)
self.verticalLayout.addLayout(self.horizontalLayout_11)
self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1)
self.verticalLayout_2 = QVBoxLayout()
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
self.horizontalLayout_12 = QHBoxLayout()
self.horizontalLayout_12.setSpacing(3)
self.horizontalLayout_12.setObjectName(u"horizontalLayout_12")
self.propertyLegendConnIcon = QLabel(PropertyLegend)
self.propertyLegendConnIcon.setObjectName(u"propertyLegendConnIcon")
self.horizontalLayout_12.addWidget(self.propertyLegendConnIcon)
self.propertyLegendConnDesc = QLabel(PropertyLegend)
self.propertyLegendConnDesc.setObjectName(u"propertyLegendConnDesc")
self.propertyLegendConnDesc.setFont(font)
self.horizontalLayout_12.addWidget(self.propertyLegendConnDesc)
self.horizontalSpacer_4 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_12.addItem(self.horizontalSpacer_4)
self.verticalLayout_2.addLayout(self.horizontalLayout_12)
self.horizontalLayout_13 = QHBoxLayout()
self.horizontalLayout_13.setSpacing(3)
self.horizontalLayout_13.setObjectName(u"horizontalLayout_13")
self.propertyLegendTargetIcon = QLabel(PropertyLegend)
self.propertyLegendTargetIcon.setObjectName(u"propertyLegendTargetIcon")
self.horizontalLayout_13.addWidget(self.propertyLegendTargetIcon)
self.propertyLegendTargetDesc = QLabel(PropertyLegend)
self.propertyLegendTargetDesc.setObjectName(u"propertyLegendTargetDesc")
self.propertyLegendTargetDesc.setMinimumSize(QSize(20, 20))
self.propertyLegendTargetDesc.setFont(font)
self.horizontalLayout_13.addWidget(self.propertyLegendTargetDesc)
self.horizontalSpacer_5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_13.addItem(self.horizontalSpacer_5)
self.verticalLayout_2.addLayout(self.horizontalLayout_13)
self.horizontalLayout_14 = QHBoxLayout()
self.horizontalLayout_14.setObjectName(u"horizontalLayout_14")
self.inheritedPropertyIcon = QLabel(PropertyLegend)
self.inheritedPropertyIcon.setObjectName(u"inheritedPropertyIcon")
self.inheritedPropertyIcon.setTextFormat(Qt.RichText)
self.horizontalLayout_14.addWidget(self.inheritedPropertyIcon)
self.inheritedPropertyText = QLabel(PropertyLegend)
self.inheritedPropertyText.setObjectName(u"inheritedPropertyText")
font1 = QFont()
font1.setItalic(False)
self.inheritedPropertyText.setFont(font1)
self.inheritedPropertyText.setFrameShape(QFrame.NoFrame)
self.inheritedPropertyText.setTextFormat(Qt.RichText)
self.inheritedPropertyText.setAlignment(Qt.AlignCenter)
self.inheritedPropertyText.setWordWrap(False)
self.horizontalLayout_14.addWidget(self.inheritedPropertyText)
self.horizontalSpacer_14 = QSpacerItem(13, 13, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_14.addItem(self.horizontalSpacer_14)
self.verticalLayout_2.addLayout(self.horizontalLayout_14)
self.gridLayout.addLayout(self.verticalLayout_2, 1, 1, 1, 1)
self.verticalLayout_3 = QVBoxLayout()
self.verticalLayout_3.setObjectName(u"verticalLayout_3")
self.horizontalLayout_8 = QHBoxLayout()
self.horizontalLayout_8.setSpacing(3)
self.horizontalLayout_8.setObjectName(u"horizontalLayout_8")
self.propertyLegendAttrWithConnIcon = QLabel(PropertyLegend)
self.propertyLegendAttrWithConnIcon.setObjectName(u"propertyLegendAttrWithConnIcon")
self.horizontalLayout_8.addWidget(self.propertyLegendAttrWithConnIcon)
self.propertyLegendAttrWithConnDesc = QLabel(PropertyLegend)
self.propertyLegendAttrWithConnDesc.setObjectName(u"propertyLegendAttrWithConnDesc")
self.propertyLegendAttrWithConnDesc.setFont(font)
self.horizontalLayout_8.addWidget(self.propertyLegendAttrWithConnDesc)
self.horizontalSpacer_6 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_8.addItem(self.horizontalSpacer_6)
self.verticalLayout_3.addLayout(self.horizontalLayout_8)
self.horizontalLayout_7 = QHBoxLayout()
self.horizontalLayout_7.setSpacing(3)
self.horizontalLayout_7.setObjectName(u"horizontalLayout_7")
self.propertyLegendRelWithTargetIcon = QLabel(PropertyLegend)
self.propertyLegendRelWithTargetIcon.setObjectName(u"propertyLegendRelWithTargetIcon")
self.horizontalLayout_7.addWidget(self.propertyLegendRelWithTargetIcon)
self.propertyLegendRelWithTargetDesc = QLabel(PropertyLegend)
self.propertyLegendRelWithTargetDesc.setObjectName(u"propertyLegendRelWithTargetDesc")
self.propertyLegendRelWithTargetDesc.setFont(font)
self.horizontalLayout_7.addWidget(self.propertyLegendRelWithTargetDesc)
self.horizontalSpacer_7 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_7.addItem(self.horizontalSpacer_7)
self.verticalLayout_3.addLayout(self.horizontalLayout_7)
self.horizontalSpacer_15 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.verticalLayout_3.addItem(self.horizontalSpacer_15)
self.gridLayout.addLayout(self.verticalLayout_3, 1, 2, 1, 1)
self.retranslateUi(PropertyLegend)
QMetaObject.connectSlotsByName(PropertyLegend)
# setupUi
def retranslateUi(self, PropertyLegend):
PropertyLegend.setProperty("comment", QCoreApplication.translate("PropertyLegend", u"\n"
" Copyright 2017 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
self.propertyLegendLabelNoValue.setText(QCoreApplication.translate("PropertyLegend", u"No Value", None))
self.propertyLegendLabelDefault.setText(QCoreApplication.translate("PropertyLegend", u"Default", None))
self.propertyLegendLabelTimeSample.setText(QCoreApplication.translate("PropertyLegend", u"Time Samples (Interpolated) ", None))
self.propertyLegendLabelFallback.setText(QCoreApplication.translate("PropertyLegend", u"Fallback", None))
self.propertyLegendLabelCustom.setText(QCoreApplication.translate("PropertyLegend", u"Custom", None))
self.propertyLegendLabelValueClips.setText(QCoreApplication.translate("PropertyLegend", u"Value Clips (Interpolated)", None))
self.propertyLegendAttrPlainDesc.setText(QCoreApplication.translate("PropertyLegend", u"Attribute", None))
self.propertyLegendRelPlainDesc.setText(QCoreApplication.translate("PropertyLegend", u"Relationship", None))
self.propertyLegendCompDesc.setText(QCoreApplication.translate("PropertyLegend", u"Computed Value", None))
self.propertyLegendConnDesc.setText(QCoreApplication.translate("PropertyLegend", u"Connection", None))
self.propertyLegendTargetDesc.setText(QCoreApplication.translate("PropertyLegend", u"Target", None))
self.inheritedPropertyIcon.setText(QCoreApplication.translate("PropertyLegend", u"<small><i>(i)</i></small>", None))
self.inheritedPropertyText.setText(QCoreApplication.translate("PropertyLegend", u"Inherited Property", None))
self.propertyLegendAttrWithConnDesc.setText(QCoreApplication.translate("PropertyLegend", u"Attribute w/Connection(s)", None))
self.propertyLegendRelWithTargetDesc.setText(QCoreApplication.translate("PropertyLegend", u"Relationship w/Target(s)", None))
# retranslateUi
| 19,598 | Python | 47.154791 | 135 | 0.714155 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primTreeWidget.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .constantGroup import ConstantGroup
from pxr import Sdf, Usd, UsdGeom
from .primViewItem import PrimViewItem
from .common import PrintWarning, Timer, UIPrimTreeColors, KeyboardShortcuts
def _GetPropertySpecInSessionLayer(usdAttribute):
propertyStack = usdAttribute.GetPropertyStack(Usd.TimeCode.Default())
if len(propertyStack) > 0:
stageSessionLayer = usdAttribute.GetStage().GetSessionLayer()
return stageSessionLayer.GetPropertyAtPath(usdAttribute.GetPath())
return None
# Function for getting the background color of the item for the delegates.
# Returns none if we only want the default paint method.
def _GetBackgroundColor(item, option):
mouseOver = option.state & QtWidgets.QStyle.State_MouseOver
selected = option.state & QtWidgets.QStyle.State_Selected
pressed = option.state & QtWidgets.QStyle.State_Sunken
background = None
if item.ancestorOfSelected:
background = UIPrimTreeColors.ANCESTOR_OF_SELECTED
if mouseOver:
background = UIPrimTreeColors.ANCESTOR_OF_SELECTED_HOVER
if selected:
background = UIPrimTreeColors.SELECTED
if mouseOver:
background = UIPrimTreeColors.SELECTED_HOVER
else:
if not selected and not pressed and mouseOver:
background = UIPrimTreeColors.UNSELECTED_HOVER
if selected:
background = UIPrimTreeColors.SELECTED
if mouseOver:
background = UIPrimTreeColors.SELECTED_HOVER
return background
class PrimViewColumnIndex(ConstantGroup):
NAME, TYPE, VIS, DRAWMODE = range(4)
class DrawModes(ConstantGroup):
DEFAULT = "default"
CARDS = "cards"
BOUNDS = "bounds"
ORIGIN = "origin"
class DrawModeComboBox(QtWidgets.QComboBox):
""" Specialize from QComboBox, so that we can send a signal when the pop-up
is hidden.
"""
signalPopupHidden = QtCore.Signal()
def __init__(self, parent=None):
QtWidgets.QComboBox.__init__(self, parent)
def hidePopup(self):
QtWidgets.QComboBox.hidePopup(self)
self.signalPopupHidden.emit()
class DrawModeWidget(QtWidgets.QWidget):
""" This widget contains a combobox for selecting the draw mode and a
clear ('x') button for clearing an authored drawMode override in the
session layer.
"""
def __init__(self, primViewItem, refreshFunc, printTiming=False,
parent=None):
QtWidgets.QWidget.__init__(self, parent)
self._primViewItem = primViewItem
self._layout = QtWidgets.QHBoxLayout()
self._layout.setSpacing(0)
self._layout.setContentsMargins(0,0,0,0)
self.setLayout(self._layout)
self._comboBox = DrawModeComboBox(self)
self._modelAPI = UsdGeom.ModelAPI(self._primViewItem.prim)
# Reducing the width further causes the pop-up dialog to be trimmed
# and option text to be pruned.
self._comboBox.setFixedWidth(100)
self._comboBox.addItem(DrawModes.DEFAULT)
self._comboBox.addItem(DrawModes.CARDS)
self._comboBox.addItem(DrawModes.BOUNDS)
self._comboBox.addItem(DrawModes.ORIGIN)
self._layout.addWidget(self._comboBox)
self._clearButton = QtWidgets.QToolButton(self)
self._clearButton.setText('X')
self._clearButton.setFixedSize(16, 16)
retainSizePolicy = self._clearButton.sizePolicy()
retainSizePolicy.setRetainSizeWhenHidden(True)
self._clearButton.setSizePolicy(retainSizePolicy)
self._layout.addWidget(self._clearButton)
self._currentDrawMode = None
self.RefreshDrawMode()
self._firstPaint = True
self._refreshFunc = refreshFunc
self._printTiming = printTiming
self._comboBox.signalPopupHidden.connect(self._PopupHidden)
self._comboBox.activated.connect(self._UpdateDrawMode)
self._clearButton.clicked.connect(self._ClearDrawMode)
def paintEvent(self, event):
# Virtual override of the paintEvent method on QWidget.
# Popup the combo box the first time the widget is drawn, since
# mouse-down in the column makes the widget appear.
#
# An alternative approach would be to set a timer in a constructor to
# pop open the combo box at the end of the event loop, but it causes a
# noticeable flicker in the UI.
if self._firstPaint:
self._comboBox.showPopup()
self._firstPaint = False
# Invoke paintEvent on super class to do the actual painting of the
# widget.
super(DrawModeWidget, self).paintEvent(event)
def _ShouldHideClearButton(self):
# Check if there's an authored value in the session layer.
drawModeAttr = self._modelAPI.GetModelDrawModeAttr()
if drawModeAttr:
sessionSpec = _GetPropertySpecInSessionLayer(drawModeAttr)
if sessionSpec and sessionSpec.HasDefaultValue():
return False
return True
def RefreshDrawMode(self, currentDrawMode=None):
self._currentDrawMode = currentDrawMode if currentDrawMode else \
self._modelAPI.ComputeModelDrawMode()
self._comboBox.setCurrentText(self._currentDrawMode)
clearButtonIsHidden = self._clearButton.isHidden()
if self._ShouldHideClearButton():
if not clearButtonIsHidden:
self._clearButton.hide()
self.update()
else:
if clearButtonIsHidden:
self._clearButton.show()
self.update()
def _UpdateDrawMode(self):
newDrawModeSelection = str(self._comboBox.currentText())
currentDrawMode = self._modelAPI.ComputeModelDrawMode()
if currentDrawMode != newDrawModeSelection:
with Timer() as t:
self._modelAPI.CreateModelDrawModeAttr().Set(
newDrawModeSelection)
self.RefreshDrawMode(currentDrawMode=newDrawModeSelection)
# We need to redraw the scene to pick up updates to draw mode.
self._refreshFunc(self._primViewItem)
if self._printTiming:
t.PrintTime("change model:drawMode on <%s> to %s" %
(self._modelAPI.GetPath(), newDrawModeSelection))
self._CloseEditorIfNoEdit()
def _ClearDrawMode(self):
with Timer() as t:
drawModeAttr = self._modelAPI.GetModelDrawModeAttr()
if drawModeAttr:
sessionSpec = _GetPropertySpecInSessionLayer(drawModeAttr)
if sessionSpec:
self._primViewItem.drawModeWidget = None
self._primViewItem.treeWidget().closePersistentEditor(
self._primViewItem, PrimViewColumnIndex.DRAWMODE)
sessionSpec.ClearDefaultValue()
sessionSpec.layer.ScheduleRemoveIfInert(sessionSpec)
self._refreshFunc(self._primViewItem)
else:
PrintWarning(self._modelAPI.GetPath(), "Failed to get "
"session layer spec for the model:drawMode attribute")
return
else:
PrintWarning(self._modelAPI.GetPath(), "Failed to get "
"model:drawMode attribute")
return
if self._printTiming:
t.PrintTime("clear model:drawMode on <%s> to %s" %
(self._modelAPI.GetPath(),
self._comboBox.currentText()))
def _CloseEditorIfNoEdit(self):
# If the clear button isn't present, then there's no edit.
if self._clearButton.isHidden():
self._primViewItem.drawModeWidget = None
self._primViewItem.treeWidget().closePersistentEditor(
self._primViewItem, PrimViewColumnIndex.DRAWMODE)
def _PopupHidden(self):
# Schedule closing the editor if no edit was made.
QtCore.QTimer.singleShot(0, self._CloseEditorIfNoEdit)
class DrawModeItemDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, printTiming, parent=None):
QtWidgets.QStyledItemDelegate.__init__(self, parent=parent)
self._treeWidget = parent
self._printTiming = printTiming
# We need to override paint in this delegate as well so that the
# Draw Mode column will match with the behavior of the other
# items in the treeview.
def paint(self, painter, option, index):
primViewItem = self._treeWidget.itemFromIndex(index)
background = _GetBackgroundColor(primViewItem, option)
if background:
painter.fillRect(option.rect, background)
super(DrawModeItemDelegate, self).paint(painter, option, index)
def createEditor(self, parent, option, index):
primViewItem = self._treeWidget.itemFromIndex(index)
if not primViewItem.supportsDrawMode:
return None
drawModeWidget = DrawModeWidget(primViewItem,
refreshFunc=self._treeWidget.UpdatePrimViewDrawMode,
printTiming=self._printTiming,
parent=parent)
# Store a copy of the widget in the primViewItem, for use when
# propagating changes to draw mode down a prim hierarchy.
primViewItem.drawModeWidget = drawModeWidget
return drawModeWidget
class SelectedAncestorItemDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, parent=None):
QtWidgets.QStyledItemDelegate.__init__(self, parent=parent)
self._treeWidget = parent
# In order to highlight the ancestors of selected prims, we require
# a new delegate to be created to override the paint function.
# Because the stylesheet will override styling when items are hovered
# over, the hovering styling logic is moved to this delegate, and
# primTreeWidget is excluded from the selectors for hovering
# in the stylesheet.
def paint(self, painter, option, index):
primViewItem = self._treeWidget.itemFromIndex(index)
originalPosition = option.rect.left()
offsetPosition = self._treeWidget.header().offset()
# In order to fill in the entire cell for Prim Name, we must update the
# dimensions of the rectangle painted. If the column is for Prim Name,
# we set the left side of the rectangle to be equal to the offset of the
# tree widget's header.
background = _GetBackgroundColor(primViewItem, option)
if primViewItem.ancestorOfSelected:
if index.column() == PrimViewColumnIndex.NAME:
option.rect.setLeft(offsetPosition)
if background:
painter.fillRect(option.rect, background)
# resetting the dimensions of the rectangle so that we paint the correct
# content in the cells on top of the colors we previously painted.
option.rect.setLeft(originalPosition)
super(SelectedAncestorItemDelegate, self).paint(painter, option, index)
class PrimItemSelectionModel(QtCore.QItemSelectionModel):
"""Standard QItemSelectionModel does not allow one to have full-item
selection while exlcuding some columns in the view from activating
selection. Since that's exactly the behavior we want, we derive our
own class that we can force to ignore selection requests except when we
really want it to."""
def __init__(self, model):
super(PrimItemSelectionModel, self).__init__(model)
self._processSelections = True
@property
def processSelections(self):
"""If True, calls to clear(), reset(), and select() will function
as normal. If False, such calls will be ignored."""
return self._processSelections
@processSelections.setter
def processSelections(self, doProcess):
self._processSelections = doProcess
def clear(self):
if self.processSelections:
super(PrimItemSelectionModel, self).clear()
def reset(self):
if self.processSelections:
super(PrimItemSelectionModel, self).reset()
def select(self, indexOrSelection, command):
if self.processSelections:
super(PrimItemSelectionModel, self).select(indexOrSelection, command)
class SelectionEnabler(object):
def __init__(self, selectionModel):
self._selectionModel = selectionModel
self._selectionWasEnabled = False
def __enter__(self):
self._selectionWasEnabled = self._selectionModel.processSelections
self._selectionModel.processSelections = True
return self
def __exit__(self, *args):
self._selectionModel.processSelections = self._selectionWasEnabled
# This class extends QTreeWidget and is used to draw the prim tree view in
# usdview.
# More of the prim browser specific behavior needs to be migrated from
# appController into this class.
class PrimTreeWidget(QtWidgets.QTreeWidget):
def __init__(self, parent):
super(PrimTreeWidget, self).__init__(parent=parent)
self._appController = None
self._selectionModel = PrimItemSelectionModel(self.model())
self.setSelectionModel(self._selectionModel)
# The list of ancestors of currently selected items
self._ancestorsOfSelected = []
def InitControllers(self, appController):
self._appController = appController
selectedAncestorItemDelegate = SelectedAncestorItemDelegate(parent=self)
self.setItemDelegate(selectedAncestorItemDelegate)
drawModeItemDelegate = DrawModeItemDelegate(appController._printTiming,
parent=self)
self.setItemDelegateForColumn(PrimViewColumnIndex.DRAWMODE,
drawModeItemDelegate)
def ShowDrawModeWidgetForItem(self, primViewItem):
self.openPersistentEditor(primViewItem, PrimViewColumnIndex.DRAWMODE)
def UpdatePrimViewDrawMode(self, rootItem=None):
"""Updates browser's "Draw Mode" columns."""
with Timer() as t:
self.setUpdatesEnabled(False)
# Update draw-model for the entire prim tree if the given
# rootItem is None.
if rootItem is None:
rootItem = self.invisibleRootItem().child(0)
if rootItem.childCount() == 0:
self._appController._populateChildren(rootItem)
rootsToProcess = [rootItem.child(i) for i in
range(rootItem.childCount())]
for item in rootsToProcess:
PrimViewItem.propagateDrawMode(item, self)
self.setUpdatesEnabled(True)
if self._appController._printTiming:
t.PrintTime("update draw mode column")
def ColumnPressCausesSelection(self, col):
"""If this method returns True for column `col`, then we want a
click in that column to cause the item to be selected."""
return col != PrimViewColumnIndex.VIS and col != PrimViewColumnIndex.DRAWMODE
def ExpandItemRecursively(self, item):
item = item.parent()
while item.parent():
if not item.isExpanded():
self.expandItem(item)
item = item.parent()
def FrameSelection(self):
if (self._appController):
selectedItems = [
self._appController._getItemAtPath(prim.GetPath())
for prim in self._appController._dataModel.selection.getPrims()]
for item in selectedItems:
self.ExpandItemRecursively(item)
self.scrollToItem(selectedItems[0])
# We set selectability based on the column we mousePress'd in, and then
# restore to true when leaving the widget, so that when we're not
# interacting with the browser, anyone can modify selection through the
# regular API's, which is important for the appController and other
# clients. If we retore it *before* leaving the widget, some internal
# QTreeWidget mechanism (an event filter?) _occasionally_ selects the item
# after a mouse release!
def mousePressEvent(self, ev):
item = self.itemAt(QtCore.QPoint(ev.x(), ev.y()))
if item:
col = self.columnAt(ev.x())
self._selectionModel.processSelections = self.ColumnPressCausesSelection(col)
super(PrimTreeWidget, self).mousePressEvent(ev)
def leaveEvent(self, ev):
super(PrimTreeWidget, self).leaveEvent(ev)
self._selectionModel.processSelections = True
# We override these selection and interaction-related API, and provide a
# batch wrapper for QTreeWidgetItem.setSelected in case, in the future,
# we have user plugins firing while we are still interacting with this
# widget, and they manipulate selection.
def clearSelection(self):
self._resetAncestorsOfSelected()
with SelectionEnabler(self._selectionModel):
super(PrimTreeWidget, self).clearSelection()
def reset(self):
self._resetAncestorsOfSelected()
with SelectionEnabler(self._selectionModel):
super(PrimTreeWidget, self).reset()
def selectAll(self):
self._resetAncestorsOfSelected()
with SelectionEnabler(self._selectionModel):
super(PrimTreeWidget, self).selectAll()
def keyPressEvent(self, ev):
with SelectionEnabler(self._selectionModel):
# Because setCurrentItem autoexpands the primview so that
# the current item is visible, we must set the current item
# only when we know it'll be needed for arrow navigation.
# We call this here before the selection data model clears
# the selection.
if ev.key() == QtCore.Qt.Key_Down \
or ev.key() == QtCore.Qt.Key_Up \
or ev.key() == QtCore.Qt.Key_Right \
or ev.key() == QtCore.Qt.Key_Left:
currentPrim = self._appController._dataModel.selection.getFocusPrim()
currentItem = self._appController._getItemAtPath(currentPrim.GetPath())
self.setCurrentItem(currentItem, 0, QtCore.QItemSelectionModel.NoUpdate)
super(PrimTreeWidget, self).keyPressEvent(ev)
# Handling the F hotkey comes after the super class's event handling,
# since the default behavior in the super class's keyPressEvent function
# is to set the current item to the first item found that alphabetically
# matches the key entered. Since we want to override this behavior for
# the F hotkey, we must handle it after the super class's keyPressEvent.
if ev.key() == KeyboardShortcuts.FramingKey:
self.FrameSelection()
def keyReleaseEvent(self, ev):
with SelectionEnabler(self._selectionModel):
super(PrimTreeWidget, self).keyReleaseEvent(ev)
def updateSelection(self, added, removed):
"""Mutate the widget's selected items, selecting items in `added`
and deselecting items in `removed`. Prefer this method for client
use over calling setSelected directly on PrimViewItems."""
with SelectionEnabler(self._selectionModel):
for item in added:
item.setSelected(True)
for item in removed:
item.setSelected(False)
self._refreshAncestorsOfSelected()
# This is a big hammer... if we instead built up a list of the
# ModelIndices of all the changed ancestors, we could instead make
# our selectionModel emit selectionChanged for just those items,
# instead. Does not currently seem to be impacting interactivity.
QtWidgets.QWidget.update(self)
def _resetAncestorsOfSelected(self):
for item in self._ancestorsOfSelected:
item.ancestorOfSelected = False
self._ancestorsOfSelected = []
# Refresh the list of ancestors of selected prims
def _refreshAncestorsOfSelected(self):
selectedItems = [
self._appController._getItemAtPath(prim.GetPath())
for prim in self._appController._dataModel.selection.getPrims()]
self._resetAncestorsOfSelected()
# Add all ancestor of the prim associated with the item
# to _ancestorsOfSelected, and mark them as selected ancestors
for item in selectedItems:
while item.parent():
item.parent().ancestorOfSelected = True
self._ancestorsOfSelected.append(item.parent())
item = item.parent()
| 21,809 | Python | 41.597656 | 89 | 0.661332 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/layerStackContextMenu.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .usdviewContextMenuItem import UsdviewContextMenuItem
import os, subprocess, sys
from pxr import Ar
#
# Specialized context menu for running commands in the layer stack view.
#
class LayerStackContextMenu(QtWidgets.QMenu):
def __init__(self, parent, item):
QtWidgets.QMenu.__init__(self, parent)
self._menuItems = _GetContextMenuItems(item)
for menuItem in self._menuItems:
if menuItem.isValid():
# create menu actions
action = self.addAction(menuItem.GetText(), menuItem.RunCommand)
# set enabled
if not menuItem.IsEnabled():
action.setEnabled(False)
def _GetContextMenuItems(item):
return [OpenLayerMenuItem(item),
UsdviewLayerMenuItem(item),
CopyLayerPathMenuItem(item),
CopyLayerIdentifierMenuItem(item),
CopyPathMenuItem(item)]
#
# The base class for layer stack context menu items.
#
class LayerStackContextMenuItem(UsdviewContextMenuItem):
def __init__(self, item):
self._item = item
def IsEnabled(self):
return True
def GetText(self):
return ""
def RunCommand(self):
pass
#
# Opens the layer using usdedit.
#
class OpenLayerMenuItem(LayerStackContextMenuItem):
# XXX: Note that this logic is duplicated from usddiff
# see bug 150247 for centralizing this API.
def _FindUsdEdit(self):
import platform
from distutils.spawn import find_executable
usdedit = find_executable('usdedit')
if not usdedit:
usdedit = find_executable('usdedit', path=os.path.abspath(os.path.dirname(sys.argv[0])))
if not usdedit and (platform.system() == 'Windows'):
for path in os.environ['PATH'].split(os.pathsep):
base = os.path.join(path, 'usdedit')
for ext in ['.cmd', '']:
if os.access(base + ext, os.X_OK):
usdedit = base + ext
return usdedit
def GetText(self):
from .common import PrettyFormatSize
fileSize = 0
if (hasattr(self._item, "layerPath")
and os.path.isfile(getattr(self._item, "layerPath"))):
fileSize = os.path.getsize(getattr(self._item, "layerPath"))
if fileSize:
return "Open Layer In Editor (%s)" % PrettyFormatSize(fileSize)
else:
return "Open Layer In Editor"
def IsEnabled(self):
return hasattr(self._item, "layerPath")
def RunCommand(self):
if not self._item:
return
# Get layer path from item
layerPath = getattr(self._item, "layerPath")
if not layerPath:
print("Error: Could not find layer file.")
return
if Ar.IsPackageRelativePath(layerPath):
layerName = os.path.basename(
Ar.SplitPackageRelativePathInner(layerPath)[1])
else:
layerName = os.path.basename(layerPath)
layerName += ".tmp"
usdeditExe = self._FindUsdEdit()
if not usdeditExe:
print("Warning: Could not find 'usdedit', expected it to be in PATH.")
return
print("Opening file: %s" % layerPath)
command = [usdeditExe,'-n',layerPath,'-p',layerName]
subprocess.Popen(command, close_fds=True)
#
# Opens the layer using usdview.
#
class UsdviewLayerMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Open Layer In usdview"
def IsEnabled(self):
return hasattr(self._item, "layerPath")
def RunCommand(self):
if not self._item:
return
# Get layer path from item
layerPath = getattr(self._item, "layerPath")
if not layerPath:
return
print("Spawning usdview %s" % layerPath)
os.system("usdview %s &" % layerPath)
#
# Copy the layer path to clipboard
#
class CopyLayerPathMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Copy Layer Path"
def RunCommand(self):
if not self._item:
return
layerPath = getattr(self._item, "layerPath")
if not layerPath:
return
cb = QtWidgets.QApplication.clipboard()
cb.setText(layerPath, QtGui.QClipboard.Selection )
cb.setText(layerPath, QtGui.QClipboard.Clipboard )
#
# Copy the layer identifier to clipboard
#
class CopyLayerIdentifierMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Copy Layer Identifier"
def RunCommand(self):
if not self._item:
return
identifier = getattr(self._item, "identifier")
if not identifier:
return
cb = QtWidgets.QApplication.clipboard()
cb.setText(identifier, QtGui.QClipboard.Selection )
cb.setText(identifier, QtGui.QClipboard.Clipboard )
#
# Copy the prim path to clipboard, if there is one
#
class CopyPathMenuItem(LayerStackContextMenuItem):
def GetText(self):
return "Copy Object Path"
def RunCommand(self):
if not self._item:
return
path = getattr(self._item, "path")
if not path:
return
path = str(path)
cb = QtWidgets.QApplication.clipboard()
cb.setText(path, QtGui.QClipboard.Selection )
cb.setText(path, QtGui.QClipboard.Clipboard )
def IsEnabled(self):
return hasattr(self._item, "path")
| 6,596 | Python | 28.986364 | 100 | 0.637811 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/attributeValueEditor.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Usd
from .qt import QtCore, QtWidgets
from .attributeValueEditorUI import Ui_AttributeValueEditor
from .common import GetPropertyColor, UIPropertyValueSourceColors
from .scalarTypes import ToString
# This is the widget that appears when selecting an attribute and
# opening the "Value" tab.
class AttributeValueEditor(QtWidgets.QWidget):
editComplete = QtCore.Signal('QString')
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self._ui = Ui_AttributeValueEditor()
self._ui.setupUi(self)
self._defaultView = self._ui.valueViewer
from .arrayAttributeView import ArrayAttributeView
self._extraAttrViews = [
ArrayAttributeView(self),
]
for attrView in self._extraAttrViews:
self._ui.stackedWidget.addWidget(attrView)
self.clear()
def setAppController(self, appController):
# pass the appController instance from which to retrieve
# variable data.
self._appController = appController
def populate(self, primPath, propName):
# called when the selected attribute has changed
self._primPath = primPath
try:
self._attribute = self._appController._propertiesDict[propName]
except KeyError:
self._attribute = None
self._isSet = True # an attribute is selected
self.refresh() # load the value at the current frame
def _FindView(self, attr):
# Early-out for CustomAttributes and Relationships
if not isinstance(attr, Usd.Attribute):
return None
for attrView in self._extraAttrViews:
if attrView.CanView(attr):
return attrView
return None
def refresh(self):
# usually called upon frame change or selected attribute change
if not self._isSet:
return
# attribute connections and relationship targets have no value to display
# in the value viewer.
if self._attribute is None:
return
# If the current attribute doesn't belong to the current prim, don't
# display its value.
if self._attribute.GetPrimPath() != self._primPath:
self._ui.valueViewer.setText("")
return
frame = self._appController._dataModel.currentFrame
# get the value of the attribute
if isinstance(self._attribute, Usd.Relationship):
self._val = self._attribute.GetTargets()
else: # Usd.Attribute or CustomAttribute
self._val = self._attribute.Get(frame)
whichView = self._FindView(self._attribute)
if whichView:
self._ui.stackedWidget.setCurrentWidget(whichView)
whichView.SetAttribute(self._attribute, frame)
else:
self._ui.stackedWidget.setCurrentWidget(self._defaultView)
txtColor = GetPropertyColor(self._attribute, frame)
# set text and color in the value viewer
self._ui.valueViewer.setTextColor(txtColor)
if isinstance(self._attribute, Usd.Relationship):
typeName = None
else:
typeName = self._attribute.GetTypeName()
rowText = ToString(self._val, typeName)
self._ui.valueViewer.setText(rowText)
def clear(self):
# set the value editor to 'no attribute selected' mode
self._isSet = False
self._ui.valueViewer.setText("")
# make sure we're showing the default view
self._ui.stackedWidget.setCurrentWidget(self._defaultView)
| 4,690 | Python | 35.084615 | 81 | 0.665672 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/frameSlider.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets, QtGui
class FrameSlider(QtWidgets.QSlider):
"""Custom QSlider class to allow scrubbing on left-click."""
PAUSE_TIMER_INTERVAL = 500
def __init__(self, parent=None):
super(FrameSlider, self).__init__(parent=parent)
# Create a mouse pause timer to trigger an update if the slider
# scrubbing pauses.
self._mousePauseTimer = QtCore.QTimer(self)
self._mousePauseTimer.setInterval(self.PAUSE_TIMER_INTERVAL)
self._mousePauseTimer.timeout.connect(self.mousePaused)
def mousePaused(self):
"""Slot called when the slider scrubbing is paused."""
self._mousePauseTimer.stop()
self.valueChanged.emit(self.sliderPosition())
def mousePressEvent(self, event):
# This is a temporary solution that should revisited in future.
#
# The issue is that the current QStyle on the application
# only allows the slider position to be set on a MiddleButton
# MouseEvent.
#
# The correct solution is for us to create a QProxyStyle for the
# application so we can edit the value of the
# QStyle.SH_Slider_AbsoluteSetButtons property (to include
# LeftButton). Unfortunately QProxyStyle is not yet available
# in this version of PySide.
#
# Instead, we are forced to duplicate the MouseEvent as a
# MiddleButton event. This creates the exact behavior we
# want to see from the QSlider.
styleHint = QtWidgets.QStyle.SH_Slider_AbsoluteSetButtons
if self.style().styleHint(styleHint) == QtCore.Qt.MiddleButton:
if event.button() == QtCore.Qt.LeftButton:
event = QtGui.QMouseEvent(
event.type(),
event.pos(),
QtCore.Qt.MiddleButton,
QtCore.Qt.MiddleButton,
event.modifiers()
)
super(FrameSlider, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
super(FrameSlider, self).mouseMoveEvent(event)
# Start the pause timer if tracking is disabled.
if not self.hasTracking():
self._mousePauseTimer.start()
def mouseReleaseEvent(self, event):
# Stop the pause timer.
self._mousePauseTimer.stop()
super(FrameSlider, self).mouseReleaseEvent(event)
| 3,471 | Python | 39.372093 | 74 | 0.674157 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/viewSettingsDataModel.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore
from pxr import UsdGeom, Sdf
from pxr.UsdAppUtils.complexityArgs import RefinementComplexities
from .common import (RenderModes, ColorCorrectionModes, PickModes,
SelectionHighlightModes, CameraMaskModes,
PrintWarning)
from . import settings2
from .settings2 import StateSource
from .constantGroup import ConstantGroup
from .freeCamera import FreeCamera
from .common import ClearColors, HighlightColors
# Map of clear color names to rgba color tuples.
_CLEAR_COLORS_DICT = {
ClearColors.BLACK: (0.0, 0.0, 0.0, 1.0),
ClearColors.DARK_GREY: (0.3, 0.3, 0.3, 1.0),
ClearColors.LIGHT_GREY: (0.7, 0.7, 0.7, 1.0),
ClearColors.WHITE: (1.0, 1.0, 1.0, 1.0)}
# Map of highlight color names to rgba color tuples.
_HIGHLIGHT_COLORS_DICT = {
HighlightColors.WHITE: (1.0, 1.0, 1.0, 0.5),
HighlightColors.YELLOW: (1.0, 1.0, 0.0, 0.5),
HighlightColors.CYAN: (0.0, 1.0, 1.0, 0.5)}
# Default values for default material components.
DEFAULT_AMBIENT = 0.2
DEFAULT_SPECULAR = 0.1
def visibleViewSetting(f):
def wrapper(self, *args, **kwargs):
f(self, *args, **kwargs)
# If f raises an exception, the signal is not emitted.
self.signalVisibleSettingChanged.emit()
self.signalSettingChanged.emit()
return wrapper
def invisibleViewSetting(f):
def wrapper(self, *args, **kwargs):
f(self, *args, **kwargs)
# If f raises an exception, the signal is not emitted.
self.signalSettingChanged.emit()
return wrapper
class ViewSettingsDataModel(QtCore.QObject, StateSource):
"""Data model containing settings related to the rendered view of a USD
file.
"""
# emitted when any view setting changes
signalSettingChanged = QtCore.Signal()
# emitted when any view setting which may affect the rendered image changes
signalVisibleSettingChanged = QtCore.Signal()
# emitted when any aspect of the defaultMaterial changes
signalDefaultMaterialChanged = QtCore.Signal()
# emitted when any setting affecting the GUI style changes
signalStyleSettingsChanged = QtCore.Signal()
def __init__(self, rootDataModel, parent):
QtCore.QObject.__init__(self)
StateSource.__init__(self, parent, "model")
self._rootDataModel = rootDataModel
self._cameraMaskColor = tuple(self.stateProperty("cameraMaskColor", default=[0.1, 0.1, 0.1, 1.0]))
self._cameraReticlesColor = tuple(self.stateProperty("cameraReticlesColor", default=[0.0, 0.7, 1.0, 1.0]))
self._defaultMaterialAmbient = self.stateProperty("defaultMaterialAmbient", default=DEFAULT_AMBIENT)
self._defaultMaterialSpecular = self.stateProperty("defaultMaterialSpecular", default=DEFAULT_SPECULAR)
self._redrawOnScrub = self.stateProperty("redrawOnScrub", default=True)
self._renderMode = self.stateProperty("renderMode", default=RenderModes.SMOOTH_SHADED)
self._freeCameraFOV = self.stateProperty("freeCameraFOV", default=60.0)
self._colorCorrectionMode = self.stateProperty("colorCorrectionMode", default=ColorCorrectionModes.SRGB)
self._pickMode = self.stateProperty("pickMode", default=PickModes.PRIMS)
# We need to store the trinary selHighlightMode state here,
# because the stageView only deals in True/False (because it
# cannot know anything about playback state).
self._selHighlightMode = self.stateProperty("selectionHighlightMode", default=SelectionHighlightModes.ONLY_WHEN_PAUSED)
# We store the highlightColorName so that we can compare state during
# initialization without inverting the name->value logic
self._highlightColorName = self.stateProperty("highlightColor", default="Yellow")
self._ambientLightOnly = self.stateProperty("cameraLightEnabled", default=True)
self._domeLightEnabled = self.stateProperty("domeLightEnabled", default=False)
self._clearColorText = self.stateProperty("backgroundColor", default="Grey (Dark)")
self._autoComputeClippingPlanes = self.stateProperty("autoComputeClippingPlanes", default=False)
self._showBBoxPlayback = self.stateProperty("showBBoxesDuringPlayback", default=False)
self._showBBoxes = self.stateProperty("showBBoxes", default=True)
self._showAABBox = self.stateProperty("showAABBox", default=True)
self._showOBBox = self.stateProperty("showOBBox", default=True)
self._displayGuide = self.stateProperty("displayGuide", default=False)
self._displayProxy = self.stateProperty("displayProxy", default=True)
self._displayRender = self.stateProperty("displayRender", default=False)
self._displayPrimId = self.stateProperty("displayPrimId", default=False)
self._enableSceneMaterials = self.stateProperty("enableSceneMaterials", default=True)
self._cullBackfaces = self.stateProperty("cullBackfaces", default=False)
self._showInactivePrims = self.stateProperty("showInactivePrims", default=True)
self._showAllMasterPrims = self.stateProperty("showAllMasterPrims", default=False)
self._showUndefinedPrims = self.stateProperty("showUndefinedPrims", default=False)
self._showAbstractPrims = self.stateProperty("showAbstractPrims", default=False)
self._rolloverPrimInfo = self.stateProperty("rolloverPrimInfo", default=False)
self._displayCameraOracles = self.stateProperty("cameraOracles", default=False)
self._cameraMaskMode = self.stateProperty("cameraMaskMode", default=CameraMaskModes.NONE)
self._showMask_Outline = self.stateProperty("cameraMaskOutline", default=False)
self._showReticles_Inside = self.stateProperty("cameraReticlesInside", default=False)
self._showReticles_Outside = self.stateProperty("cameraReticlesOutside", default=False)
self._showHUD = self.stateProperty("showHUD", default=True)
self._showHUD_Info = self.stateProperty("showHUDInfo", default=False)
# XXX Until we can make the "Subtree Info" stats-gathering faster
# we do not want the setting to persist from session to session.
self._showHUD_Info = False
self._showHUD_Complexity = self.stateProperty("showHUDComplexity", default=True)
self._showHUD_Performance = self.stateProperty("showHUDPerformance", default=True)
self._showHUD_GPUstats = self.stateProperty("showHUDGPUStats", default=False)
self._complexity = RefinementComplexities.LOW
self._freeCamera = None
self._cameraPath = None
self._fontSize = self.stateProperty("fontSize", default=10)
def onSaveState(self, state):
state["cameraMaskColor"] = list(self._cameraMaskColor)
state["cameraReticlesColor"] = list(self._cameraReticlesColor)
state["defaultMaterialAmbient"] = self._defaultMaterialAmbient
state["defaultMaterialSpecular"] = self._defaultMaterialSpecular
state["redrawOnScrub"] = self._redrawOnScrub
state["renderMode"] = self._renderMode
state["freeCameraFOV"] = self._freeCameraFOV
state["colorCorrectionMode"] = self._colorCorrectionMode
state["pickMode"] = self._pickMode
state["selectionHighlightMode"] = self._selHighlightMode
state["highlightColor"] = self._highlightColorName
state["cameraLightEnabled"] = self._ambientLightOnly
state["domeLightEnabled"] = self._domeLightEnabled
state["backgroundColor"] = self._clearColorText
state["autoComputeClippingPlanes"] = self._autoComputeClippingPlanes
state["showBBoxesDuringPlayback"] = self._showBBoxPlayback
state["showBBoxes"] = self._showBBoxes
state["showAABBox"] = self._showAABBox
state["showOBBox"] = self._showOBBox
state["displayGuide"] = self._displayGuide
state["displayProxy"] = self._displayProxy
state["displayRender"] = self._displayRender
state["displayPrimId"] = self._displayPrimId
state["enableSceneMaterials"] = self._enableSceneMaterials
state["cullBackfaces"] = self._cullBackfaces
state["showInactivePrims"] = self._showInactivePrims
state["showAllMasterPrims"] = self._showAllMasterPrims
state["showUndefinedPrims"] = self._showUndefinedPrims
state["showAbstractPrims"] = self._showAbstractPrims
state["rolloverPrimInfo"] = self._rolloverPrimInfo
state["cameraOracles"] = self._displayCameraOracles
state["cameraMaskMode"] = self._cameraMaskMode
state["cameraMaskOutline"] = self._showMask_Outline
state["cameraReticlesInside"] = self._showReticles_Inside
state["cameraReticlesOutside"] = self._showReticles_Outside
state["showHUD"] = self._showHUD
state["showHUDInfo"] = self._showHUD_Info
state["showHUDComplexity"] = self._showHUD_Complexity
state["showHUDPerformance"] = self._showHUD_Performance
state["showHUDGPUStats"] = self._showHUD_GPUstats
state["fontSize"] = self._fontSize
@property
def cameraMaskColor(self):
return self._cameraMaskColor
@cameraMaskColor.setter
@visibleViewSetting
def cameraMaskColor(self, color):
self._cameraMaskColor = color
@property
def cameraReticlesColor(self):
return self._cameraReticlesColor
@cameraReticlesColor.setter
@visibleViewSetting
def cameraReticlesColor(self, color):
self._cameraReticlesColor = color
@property
def defaultMaterialAmbient(self):
return self._defaultMaterialAmbient
@defaultMaterialAmbient.setter
@visibleViewSetting
def defaultMaterialAmbient(self, value):
if value != self._defaultMaterialAmbient:
self._defaultMaterialAmbient = value
self.signalDefaultMaterialChanged.emit()
@property
def defaultMaterialSpecular(self):
return self._defaultMaterialSpecular
@defaultMaterialSpecular.setter
@visibleViewSetting
def defaultMaterialSpecular(self, value):
if value != self._defaultMaterialSpecular:
self._defaultMaterialSpecular = value
self.signalDefaultMaterialChanged.emit()
@visibleViewSetting
def setDefaultMaterial(self, ambient, specular):
if (ambient != self._defaultMaterialAmbient
or specular != self._defaultMaterialSpecular):
self._defaultMaterialAmbient = ambient
self._defaultMaterialSpecular = specular
self.signalDefaultMaterialChanged.emit()
def resetDefaultMaterial(self):
self.setDefaultMaterial(DEFAULT_AMBIENT, DEFAULT_SPECULAR)
@property
def complexity(self):
return self._complexity
@complexity.setter
@visibleViewSetting
def complexity(self, value):
if value not in RefinementComplexities.ordered():
raise ValueError("Expected Complexity, got: '{}'.".format(value))
self._complexity = value
@property
def renderMode(self):
return self._renderMode
@renderMode.setter
@visibleViewSetting
def renderMode(self, value):
self._renderMode = value
@property
def freeCameraFOV(self):
return self._freeCameraFOV
@freeCameraFOV.setter
@visibleViewSetting
def freeCameraFOV(self, value):
if self._freeCamera:
# Setting the freeCamera's fov will trigger our own update
self._freeCamera.fov = value
else:
self._freeCameraFOV = value
@visibleViewSetting
def _updateFOV(self):
if self._freeCamera:
self._freeCameraFOV = self.freeCamera.fov
@property
def colorCorrectionMode(self):
return self._colorCorrectionMode
@colorCorrectionMode.setter
@visibleViewSetting
def colorCorrectionMode(self, value):
self._colorCorrectionMode = value
@property
def pickMode(self):
return self._pickMode
@pickMode.setter
@invisibleViewSetting
def pickMode(self, value):
self._pickMode = value
@property
def showAABBox(self):
return self._showAABBox
@showAABBox.setter
@visibleViewSetting
def showAABBox(self, value):
self._showAABBox = value
@property
def showOBBox(self):
return self._showOBBox
@showOBBox.setter
@visibleViewSetting
def showOBBox(self, value):
self._showOBBox = value
@property
def showBBoxes(self):
return self._showBBoxes
@showBBoxes.setter
@visibleViewSetting
def showBBoxes(self, value):
self._showBBoxes = value
@property
def autoComputeClippingPlanes(self):
return self._autoComputeClippingPlanes
@autoComputeClippingPlanes.setter
@visibleViewSetting
def autoComputeClippingPlanes(self, value):
self._autoComputeClippingPlanes = value
@property
def showBBoxPlayback(self):
return self._showBBoxPlayback
@showBBoxPlayback.setter
@visibleViewSetting
def showBBoxPlayback(self, value):
self._showBBoxPlayback = value
@property
def displayGuide(self):
return self._displayGuide
@displayGuide.setter
@visibleViewSetting
def displayGuide(self, value):
self._displayGuide = value
@property
def displayProxy(self):
return self._displayProxy
@displayProxy.setter
@visibleViewSetting
def displayProxy(self, value):
self._displayProxy = value
@property
def displayRender(self):
return self._displayRender
@displayRender.setter
@visibleViewSetting
def displayRender(self, value):
self._displayRender = value
@property
def displayCameraOracles(self):
return self._displayCameraOracles
@displayCameraOracles.setter
@visibleViewSetting
def displayCameraOracles(self, value):
self._displayCameraOracles = value
@property
def displayPrimId(self):
return self._displayPrimId
@displayPrimId.setter
@visibleViewSetting
def displayPrimId(self, value):
self._displayPrimId = value
@property
def enableSceneMaterials(self):
return self._enableSceneMaterials
@enableSceneMaterials.setter
@visibleViewSetting
def enableSceneMaterials(self, value):
self._enableSceneMaterials = value
@property
def cullBackfaces(self):
return self._cullBackfaces
@cullBackfaces.setter
@visibleViewSetting
def cullBackfaces(self, value):
self._cullBackfaces = value
@property
def showInactivePrims(self):
return self._showInactivePrims
@showInactivePrims.setter
@invisibleViewSetting
def showInactivePrims(self, value):
self._showInactivePrims = value
@property
def showAllMasterPrims(self):
return self._showAllMasterPrims
@showAllMasterPrims.setter
@invisibleViewSetting
def showAllMasterPrims(self, value):
self._showAllMasterPrims = value
@property
def showUndefinedPrims(self):
return self._showUndefinedPrims
@showUndefinedPrims.setter
@invisibleViewSetting
def showUndefinedPrims(self, value):
self._showUndefinedPrims = value
@property
def showAbstractPrims(self):
return self._showAbstractPrims
@showAbstractPrims.setter
@invisibleViewSetting
def showAbstractPrims(self, value):
self._showAbstractPrims = value
@property
def rolloverPrimInfo(self):
return self._rolloverPrimInfo
@rolloverPrimInfo.setter
@invisibleViewSetting
def rolloverPrimInfo(self, value):
self._rolloverPrimInfo = value
@property
def cameraMaskMode(self):
return self._cameraMaskMode
@cameraMaskMode.setter
@visibleViewSetting
def cameraMaskMode(self, value):
self._cameraMaskMode = value
@property
def showMask(self):
return self._cameraMaskMode in (CameraMaskModes.FULL, CameraMaskModes.PARTIAL)
@property
def showMask_Opaque(self):
return self._cameraMaskMode == CameraMaskModes.FULL
@property
def showMask_Outline(self):
return self._showMask_Outline
@showMask_Outline.setter
@visibleViewSetting
def showMask_Outline(self, value):
self._showMask_Outline = value
@property
def showReticles_Inside(self):
return self._showReticles_Inside
@showReticles_Inside.setter
@visibleViewSetting
def showReticles_Inside(self, value):
self._showReticles_Inside = value
@property
def showReticles_Outside(self):
return self._showReticles_Outside
@showReticles_Outside.setter
@visibleViewSetting
def showReticles_Outside(self, value):
self._showReticles_Outside = value
@property
def showHUD(self):
return self._showHUD
@showHUD.setter
@visibleViewSetting
def showHUD(self, value):
self._showHUD = value
@property
def showHUD_Info(self):
return self._showHUD_Info
@showHUD_Info.setter
@visibleViewSetting
def showHUD_Info(self, value):
self._showHUD_Info = value
@property
def showHUD_Complexity(self):
return self._showHUD_Complexity
@showHUD_Complexity.setter
@visibleViewSetting
def showHUD_Complexity(self, value):
self._showHUD_Complexity = value
@property
def showHUD_Performance(self):
return self._showHUD_Performance
@showHUD_Performance.setter
@visibleViewSetting
def showHUD_Performance(self, value):
self._showHUD_Performance = value
@property
def showHUD_GPUstats(self):
return self._showHUD_GPUstats
@showHUD_GPUstats.setter
@visibleViewSetting
def showHUD_GPUstats(self, value):
self._showHUD_GPUstats = value
@property
def ambientLightOnly(self):
return self._ambientLightOnly
@ambientLightOnly.setter
@visibleViewSetting
def ambientLightOnly(self, value):
self._ambientLightOnly = value
@property
def domeLightEnabled(self):
return self._domeLightEnabled
@domeLightEnabled.setter
@visibleViewSetting
def domeLightEnabled(self, value):
self._domeLightEnabled = value
@property
def clearColorText(self):
return self._clearColorText
@clearColorText.setter
@visibleViewSetting
def clearColorText(self, value):
if value not in ClearColors:
raise ValueError("Unknown clear color: '{}'".format(value))
self._clearColorText = value
@property
def clearColor(self):
return _CLEAR_COLORS_DICT[self._clearColorText]
@property
def highlightColorName(self):
return self._highlightColorName
@highlightColorName.setter
@visibleViewSetting
def highlightColorName(self, value):
if value not in HighlightColors:
raise ValueError("Unknown highlight color: '{}'".format(value))
self._highlightColorName = value
@property
def highlightColor(self):
return _HIGHLIGHT_COLORS_DICT[self._highlightColorName]
@property
def selHighlightMode(self):
return self._selHighlightMode
@selHighlightMode.setter
@visibleViewSetting
def selHighlightMode(self, value):
if value not in SelectionHighlightModes:
raise ValueError("Unknown highlight mode: '{}'".format(value))
self._selHighlightMode = value
@property
def redrawOnScrub(self):
return self._redrawOnScrub
@redrawOnScrub.setter
@visibleViewSetting
def redrawOnScrub(self, value):
self._redrawOnScrub = value
@property
def freeCamera(self):
return self._freeCamera
@freeCamera.setter
@visibleViewSetting
def freeCamera(self, value):
# ViewSettingsDataModel does not guarantee it will hold a valid
# FreeCamera, but if one is set, we will keep the dataModel's stateful
# FOV ('freeCameraFOV') in sync with the FreeCamera
if not isinstance(value, FreeCamera) and value != None:
raise TypeError("Free camera must be a FreeCamera object.")
if self._freeCamera:
self._freeCamera.signalFrustumChanged.disconnect(self._updateFOV)
self._freeCamera = value
if self._freeCamera:
self._freeCamera.signalFrustumChanged.connect(self._updateFOV)
self._freeCameraFOV = self._freeCamera.fov
@property
def cameraPath(self):
return self._cameraPath
@cameraPath.setter
@visibleViewSetting
def cameraPath(self, value):
if ((not isinstance(value, Sdf.Path) or not value.IsPrimPath())
and value is not None):
raise TypeError("Expected prim path, got: {}".format(value))
self._cameraPath = value
@property
def cameraPrim(self):
if self.cameraPath is not None and self._rootDataModel.stage is not None:
return self._rootDataModel.stage.GetPrimAtPath(self.cameraPath)
else:
return None
@cameraPrim.setter
def cameraPrim(self, value):
if value is not None:
if value.IsA(UsdGeom.Camera):
self.cameraPath = value.GetPrimPath()
else:
PrintWarning("Incorrect Prim Type",
"Attempted to view the scene using the prim '%s', but "
"the prim is not a UsdGeom.Camera." % (value.GetName()))
else:
self.cameraPath = None
@property
def fontSize(self):
return self._fontSize
@fontSize.setter
@visibleViewSetting
def fontSize(self, value):
if value != self._fontSize:
self._fontSize = value
self.signalStyleSettingsChanged.emit()
| 22,972 | Python | 32.783823 | 127 | 0.687924 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/stageView.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
'''
Module that provides the StageView class.
'''
from __future__ import print_function
from math import tan, floor, ceil, radians as rad, isinf
import os, sys
from time import time
from .qt import QtCore, QtGui, QtWidgets, QtOpenGL
from pxr import Tf
from pxr import Gf
from pxr import Glf
from pxr import Sdf, Usd, UsdGeom
from pxr import UsdImagingGL
from pxr import CameraUtil
from .common import (RenderModes, ColorCorrectionModes, ShadedRenderModes, Timer,
ReportMetricSize, SelectionHighlightModes, DEBUG_CLIPPING)
from .rootDataModel import RootDataModel
from .selectionDataModel import ALL_INSTANCES, SelectionDataModel
from .viewSettingsDataModel import ViewSettingsDataModel
from .freeCamera import FreeCamera
# A viewport rectangle to be used for GL must be integer values.
# In order to loose the least amount of precision the viewport
# is centered and adjusted to initially contain entirely the
# given viewport.
# If it turns out that doing so gives more than a pixel width
# or height of error the viewport is instead inset.
# This does mean that the returned viewport may have a slightly
# different aspect ratio to the given viewport.
def ViewportMakeCenteredIntegral(viewport):
# The values are initially integral and containing the
# the given rect
left = int(floor(viewport[0]))
bottom = int(floor(viewport[1]))
right = int(ceil(viewport[0] + viewport[2]))
top = int(ceil(viewport[1] + viewport[3]))
width = right - left
height = top - bottom
# Compare the integral height to the original height
# and do a centered 1 pixel adjustment if more than
# a pixel off.
if (height - viewport[3]) > 1.0:
bottom += 1
height -= 2
# Compare the integral width to the original width
# and do a centered 1 pixel adjustment if more than
# a pixel off.
if (width - viewport[2]) > 1.0:
left += 1
width -= 2
return (left, bottom, width, height)
class GLSLProgram():
def __init__(self, VS3, FS3, VS2, FS2, uniformDict):
from OpenGL import GL
self._glMajorVersion = int(GL.glGetString(GL.GL_VERSION)[0])
self.program = GL.glCreateProgram()
vertexShader = GL.glCreateShader(GL.GL_VERTEX_SHADER)
fragmentShader = GL.glCreateShader(GL.GL_FRAGMENT_SHADER)
if (self._glMajorVersion >= 3):
vsSource = VS3
fsSource = FS3
else:
vsSource = VS2
fsSource = FS2
GL.glShaderSource(vertexShader, vsSource)
GL.glCompileShader(vertexShader)
GL.glShaderSource(fragmentShader, fsSource)
GL.glCompileShader(fragmentShader)
GL.glAttachShader(self.program, vertexShader)
GL.glAttachShader(self.program, fragmentShader)
GL.glLinkProgram(self.program)
if GL.glGetProgramiv(self.program, GL.GL_LINK_STATUS) == GL.GL_FALSE:
print(GL.glGetShaderInfoLog(vertexShader))
print(GL.glGetShaderInfoLog(fragmentShader))
print(GL.glGetProgramInfoLog(self.program))
GL.glDeleteShader(vertexShader)
GL.glDeleteShader(fragmentShader)
GL.glDeleteProgram(self.program)
self.program = 0
GL.glDeleteShader(vertexShader)
GL.glDeleteShader(fragmentShader)
self.uniformLocations = {}
for param in uniformDict:
self.uniformLocations[param] = GL.glGetUniformLocation(self.program, param)
def uniform4f(self, param, x, y, z, w):
from OpenGL import GL
GL.glUniform4f(self.uniformLocations[param], x, y, z, w)
class Rect():
def __init__(self):
self.xywh = [0.0] * 4
@classmethod
def fromXYWH(cls, xywh):
self = cls()
self.xywh[:] = list(map(float, xywh[:4]))
return self
@classmethod
def fromCorners(cls, c0, c1):
self = cls()
self.xywh[0] = float(min(c0[0], c1[0]))
self.xywh[1] = float(min(c0[1], c1[1]))
self.xywh[2] = float(max(c0[0], c1[0])) - self.xywh[0]
self.xywh[3] = float(max(c0[1], c1[1])) - self.xywh[1]
return self
def scaledAndBiased(self, sxy, txy):
ret = self.__class__()
for c in range(2):
ret.xywh[c] = sxy[c] * self.xywh[c] + txy[c]
ret.xywh[c + 2] = sxy[c] * self.xywh[c + 2]
return ret
def _splitAlongY(self, y):
bottom = self.__class__()
top = self.__class__()
bottom.xywh[:] = self.xywh
top.xywh[:] = self.xywh
top.xywh[1] = y
bottom.xywh[3] = top.xywh[1] - bottom.xywh[1]
top.xywh[3] = top.xywh[3] - bottom.xywh[3]
return bottom, top
def _splitAlongX(self, x):
left = self.__class__()
right = self.__class__()
left.xywh[:] = self.xywh
right.xywh[:] = self.xywh
right.xywh[0] = x
left.xywh[2] = right.xywh[0] - left.xywh[0]
right.xywh[2] = right.xywh[2] - left.xywh[2]
return left, right
def difference(self, xywh):
#check x
if xywh[0] > self.xywh[0]:
#keep left, check right
left, right = self._splitAlongX(xywh[0])
return [left] + right.difference(xywh)
if (xywh[0] + xywh[2]) < (self.xywh[0] + self.xywh[2]):
#keep right
left, right = self._splitAlongX(xywh[0] + xywh[2])
return [right]
#check y
if xywh[1] > self.xywh[1]:
#keep bottom, check top
bottom, top = self._splitAlongY(xywh[1])
return [bottom] + top.difference(xywh)
if (xywh[1] + xywh[3]) < (self.xywh[1] + self.xywh[3]):
#keep top
bottom, top = self._splitAlongY(xywh[1] + xywh[3])
return [top]
return []
class OutlineRect(Rect):
_glslProgram = None
_vbo = 0
_vao = 0
def __init__(self):
Rect.__init__(self)
@classmethod
def compileProgram(self):
if self._glslProgram:
return self._glslProgram
from OpenGL import GL
import ctypes
# prep a quad line vbo
self._vbo = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._vbo)
st = [0, 0, 1, 0, 1, 1, 0, 1]
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(st)*4,
(ctypes.c_float*len(st))(*st), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
self._glslProgram = GLSLProgram(
# for OpenGL 3.1 or later
"""#version 140
uniform vec4 rect;
in vec2 st;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1); }""",
"""#version 140
out vec4 fragColor;
uniform vec4 color;
void main() { fragColor = color; }""",
# for OpenGL 2.1 (osx compatibility profile)
"""#version 120
uniform vec4 rect;
attribute vec2 st;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1); }""",
"""#version 120
uniform vec4 color;
void main() { gl_FragColor = color; }""",
["rect", "color"])
return self._glslProgram
def glDraw(self, color):
from OpenGL import GL
cls = self.__class__
program = cls.compileProgram()
if (program.program == 0):
return
GL.glUseProgram(program.program)
if (program._glMajorVersion >= 4):
GL.glDisable(GL.GL_SAMPLE_ALPHA_TO_COVERAGE)
# requires PyOpenGL 3.0.2 or later for glGenVertexArrays.
if (program._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (cls._vao == 0):
cls._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(cls._vao)
# for some reason, we need to bind at least 1 vertex attrib (is OSX)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, cls._vbo)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 2, GL.GL_FLOAT, False, 0, None)
program.uniform4f("color", *color)
program.uniform4f("rect", *self.xywh)
GL.glDrawArrays(GL.GL_LINE_LOOP, 0, 4)
class FilledRect(Rect):
_glslProgram = None
_vbo = 0
_vao = 0
def __init__(self):
Rect.__init__(self)
@classmethod
def compileProgram(self):
if self._glslProgram:
return self._glslProgram
from OpenGL import GL
import ctypes
# prep a quad line vbo
self._vbo = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._vbo)
st = [0, 0, 1, 0, 0, 1, 1, 1]
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(st)*4,
(ctypes.c_float*len(st))(*st), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
self._glslProgram = GLSLProgram(
# for OpenGL 3.1 or later
"""#version 140
uniform vec4 rect;
in vec2 st;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1); }""",
"""#version 140
out vec4 fragColor;
uniform vec4 color;
void main() { fragColor = color; }""",
# for OpenGL 2.1 (osx compatibility profile)
"""#version 120
uniform vec4 rect;
attribute vec2 st;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1); }""",
"""#version 120
uniform vec4 color;
void main() { gl_FragColor = color; }""",
["rect", "color"])
return self._glslProgram
def glDraw(self, color):
#don't draw if too small
if self.xywh[2] < 0.001 or self.xywh[3] < 0.001:
return
from OpenGL import GL
cls = self.__class__
program = cls.compileProgram()
if (program.program == 0):
return
GL.glUseProgram(program.program)
if (program._glMajorVersion >= 4):
GL.glDisable(GL.GL_SAMPLE_ALPHA_TO_COVERAGE)
# requires PyOpenGL 3.0.2 or later for glGenVertexArrays.
if (program._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (cls._vao == 0):
cls._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(cls._vao)
# for some reason, we need to bind at least 1 vertex attrib (is OSX)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, cls._vbo)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 2, GL.GL_FLOAT, False, 0, None)
program.uniform4f("color", *color)
program.uniform4f("rect", *self.xywh)
GL.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4)
class Prim2DSetupTask():
def __init__(self, viewport):
self._viewport = viewport[:]
def Sync(self, ctx):
pass
def Execute(self, ctx):
from OpenGL import GL
GL.glViewport(*self._viewport)
GL.glDisable(GL.GL_DEPTH_TEST)
GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
GL.glEnable(GL.GL_BLEND)
class Prim2DDrawTask():
def __init__(self):
self._prims = []
self._colors = []
self._pixelRatio = QtWidgets.QApplication.instance().devicePixelRatio()
def Sync(self, ctx):
for prim in self._prims:
prim.__class__.compileProgram()
def Execute(self, ctx):
from OpenGL import GL
for prim, color in zip(self._prims, self._colors):
prim.glDraw(color)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glDisableVertexAttribArray(0)
if (int(GL.glGetString(GL.GL_VERSION)[0]) >= 3 and hasattr(GL, 'glGenVertexArrays')):
GL.glBindVertexArray(0)
GL.glUseProgram(0)
class Outline(Prim2DDrawTask):
def __init__(self):
Prim2DDrawTask.__init__(self)
self._outlineColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(0.0, 0.0, 0.0, 1.0))
def updatePrims(self, croppedViewport, qglwidget):
width = float(qglwidget.width()) * self._pixelRatio
height = float(qglwidget.height()) * self._pixelRatio
prims = [ OutlineRect.fromXYWH(croppedViewport) ]
self._prims = [p.scaledAndBiased((2.0 / width, 2.0 / height), (-1, -1))
for p in prims]
self._colors = [ self._outlineColor ]
class Reticles(Prim2DDrawTask):
def __init__(self):
Prim2DDrawTask.__init__(self)
self._outlineColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(0.0, 0.7, 1.0, 0.9))
def updateColor(self, color):
self._outlineColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(*color))
def updatePrims(self, croppedViewport, qglwidget, inside, outside):
width = float(qglwidget.width()) * self._pixelRatio
height = float(qglwidget.height()) * self._pixelRatio
prims = [ ]
ascenders = [0, 0]
descenders = [0, 0]
if inside:
descenders = [7, 15]
if outside:
ascenders = [7, 15]
# vertical reticles on the top and bottom
for i in range(5):
w = 2.6
h = ascenders[i & 1] + descenders[i & 1]
x = croppedViewport[0] - (w // 2) + ((i + 1) * croppedViewport[2]) // 6
bottomY = croppedViewport[1] - ascenders[i & 1]
topY = croppedViewport[1] + croppedViewport[3] - descenders[i & 1]
prims.append(FilledRect.fromXYWH((x, bottomY, w, h)))
prims.append(FilledRect.fromXYWH((x, topY, w, h)))
# horizontal reticles on the left and right
for i in range(5):
w = ascenders[i & 1] + descenders[i & 1]
h = 2.6
leftX = croppedViewport[0] - ascenders[i & 1]
rightX = croppedViewport[0] + croppedViewport[2] - descenders[i & 1]
y = croppedViewport[1] - (h // 2) + ((i + 1) * croppedViewport[3]) // 6
prims.append(FilledRect.fromXYWH((leftX, y, w, h)))
prims.append(FilledRect.fromXYWH((rightX, y, w, h)))
self._prims = [p.scaledAndBiased((2.0 / width, 2.0 / height), (-1, -1))
for p in prims]
self._colors = [ self._outlineColor ] * len(self._prims)
class Mask(Prim2DDrawTask):
def __init__(self):
Prim2DDrawTask.__init__(self)
self._maskColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(0.0, 0.0, 0.0, 1.0))
def updateColor(self, color):
self._maskColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(*color))
def updatePrims(self, croppedViewport, qglwidget):
width = float(qglwidget.width()) * self._pixelRatio
height = float(qglwidget.height()) * self._pixelRatio
rect = FilledRect.fromXYWH((0, 0, width, height))
prims = rect.difference(croppedViewport)
self._prims = [p.scaledAndBiased((2.0 / width, 2.0 / height), (-1, -1))
for p in prims]
self._colors = [ self._maskColor ] * 2
class HUD():
class Group():
def __init__(self, name, w, h):
self.x = 0
self.y = 0
self.w = w
self.h = h
pixelRatio = QtWidgets.QApplication.instance().devicePixelRatio()
imageW = w * pixelRatio
imageH = h * pixelRatio
self.qimage = QtGui.QImage(imageW, imageH, QtGui.QImage.Format_ARGB32)
self.qimage.fill(QtGui.QColor(0, 0, 0, 0))
self.painter = QtGui.QPainter()
def __init__(self):
self._pixelRatio = QtWidgets.QApplication.instance().devicePixelRatio()
self._HUDLineSpacing = 15
self._HUDFont = QtGui.QFont("Menv Mono Numeric", 9*self._pixelRatio)
self._groups = {}
self._glslProgram = None
self._glMajorVersion = 0
self._vao = 0
def compileProgram(self):
from OpenGL import GL
import ctypes
# prep a quad vbo
self._vbo = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._vbo)
st = [0, 0, 1, 0, 0, 1, 1, 1]
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(st)*4,
(ctypes.c_float*len(st))(*st), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
self._glslProgram = GLSLProgram(
# for OpenGL 3.1 or later
"""#version 140
uniform vec4 rect;
in vec2 st;
out vec2 uv;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1);
uv = vec2(st.x, 1 - st.y); }""",
"""#version 140
in vec2 uv;
out vec4 color;
uniform sampler2D tex;
void main() { color = texture(tex, uv); }""",
# for OpenGL 2.1 (osx compatibility profile)
"""#version 120
uniform vec4 rect;
attribute vec2 st;
varying vec2 uv;
void main() {
gl_Position = vec4(rect.x + rect.z*st.x,
rect.y + rect.w*st.y, 0, 1);
uv = vec2(st.x, 1 - st.y); }""",
"""#version 120
varying vec2 uv;
uniform sampler2D tex;
void main() { gl_FragColor = texture2D(tex, uv); }""",
["rect", "tex"])
return True
def addGroup(self, name, w, h):
self._groups[name] = self.Group(name, w, h)
def updateGroup(self, name, x, y, col, dic, keys = None):
group = self._groups[name]
group.qimage.fill(QtGui.QColor(0, 0, 0, 0))
group.x = x
group.y = y
painter = group.painter
painter.begin(group.qimage)
from .prettyPrint import prettyPrint
if keys is None:
keys = sorted(dic.keys())
# find the longest key so we know how far from the edge to print
# add [0] at the end so that max() never gets an empty sequence
longestKeyLen = max([len(k) for k in dic.keys()]+[0])
margin = int(longestKeyLen*1.4)
painter.setFont(self._HUDFont)
color = QtGui.QColor()
yy = 10 * self._pixelRatio
lineSpacing = self._HUDLineSpacing * self._pixelRatio
for key in keys:
if key not in dic:
continue
line = key.rjust(margin) + ": " + str(prettyPrint(dic[key]))
# Shadow of text
shadow = Gf.ConvertDisplayToLinear(Gf.Vec3f(.2, .2, .2))
color.setRgbF(shadow[0], shadow[1], shadow[2])
painter.setPen(color)
painter.drawText(1, yy+1, line)
# Colored text
color.setRgbF(col[0], col[1], col[2])
painter.setPen(color)
painter.drawText(0, yy, line)
yy += lineSpacing
painter.end()
return y + lineSpacing
def draw(self, qglwidget):
from OpenGL import GL
if (self._glslProgram == None):
self.compileProgram()
if (self._glslProgram.program == 0):
return
GL.glUseProgram(self._glslProgram.program)
width = float(qglwidget.width())
height = float(qglwidget.height())
if (self._glslProgram._glMajorVersion >= 4):
GL.glDisable(GL.GL_SAMPLE_ALPHA_TO_COVERAGE)
# requires PyOpenGL 3.0.2 or later for glGenVertexArrays.
if (self._glslProgram._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (self._vao == 0):
self._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(self._vao)
# for some reason, we need to bind at least 1 vertex attrib (is OSX)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._vbo)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 2, GL.GL_FLOAT, False, 0, None)
# seems like a bug in Qt4.8/CoreProfile on OSX that GL_UNPACK_ROW_LENGTH has changed.
GL.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, 0)
for name in self._groups:
group = self._groups[name]
tex = qglwidget.bindTexture(group.qimage, GL.GL_TEXTURE_2D, GL.GL_RGBA,
QtOpenGL.QGLContext.NoBindOption)
GL.glUniform4f(self._glslProgram.uniformLocations["rect"],
2*group.x/width - 1,
1 - 2*group.y/height - 2*group.h/height,
2*group.w/width,
2*group.h/height)
GL.glUniform1i(self._glslProgram.uniformLocations["tex"], 0)
GL.glActiveTexture(GL.GL_TEXTURE0)
GL.glBindTexture(GL.GL_TEXTURE_2D, tex)
GL.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4)
GL.glDeleteTextures(tex)
GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glDisableVertexAttribArray(0)
if (self._vao != 0):
GL.glBindVertexArray(0)
GL.glUseProgram(0)
class StageView(QtOpenGL.QGLWidget):
'''
QGLWidget that displays a USD Stage. A StageView requires a dataModel
object from which it will query state it needs to properly image its
given UsdStage. See the nested DefaultDataModel class for the expected
API.
'''
# TODO: most, if not all of the state StageView requires (except possibly
# the stage?), should be migrated to come from the dataModel, and redrawing
# should be triggered by signals the dataModel emits.
class DefaultDataModel(RootDataModel):
def __init__(self):
super(StageView.DefaultDataModel, self).__init__()
self._selectionDataModel = SelectionDataModel(self)
self._viewSettingsDataModel = ViewSettingsDataModel(self, None)
@property
def selection(self):
return self._selectionDataModel
@property
def viewSettings(self):
return self._viewSettingsDataModel
###########
# Signals #
###########
signalBboxUpdateTimeChanged = QtCore.Signal(int)
# First arg is primPath, (which could be empty Path)
# Second arg is instanceIndex (or UsdImagingGL.ALL_INSTANCES for all
# instances)
# Third and fourth arg are primPath, instanceIndex, of root level
# boundable (if applicable).
# Fifth arg is selectedPoint
# Sixth and seventh args represent state at time of the pick
signalPrimSelected = QtCore.Signal(Sdf.Path, int, Sdf.Path, int, Gf.Vec3f,
QtCore.Qt.MouseButton,
QtCore.Qt.KeyboardModifiers)
# Only raised when StageView has been told to do so, setting
# rolloverPicking to True
signalPrimRollover = QtCore.Signal(Sdf.Path, int, Sdf.Path, int,
Gf.Vec3f, QtCore.Qt.KeyboardModifiers)
signalMouseDrag = QtCore.Signal()
signalErrorMessage = QtCore.Signal(str)
signalSwitchedToFreeCam = QtCore.Signal()
signalFrustumChanged = QtCore.Signal()
@property
def renderParams(self):
return self._renderParams
@renderParams.setter
def renderParams(self, params):
self._renderParams = params
@property
def autoClip(self):
return self._dataModel.viewSettings.autoComputeClippingPlanes
@property
def showReticles(self):
return ((self._dataModel.viewSettings.showReticles_Inside or self._dataModel.viewSettings.showReticles_Outside)
and self._dataModel.viewSettings.cameraPrim != None)
@property
def _fitCameraInViewport(self):
return ((self._dataModel.viewSettings.showMask or self._dataModel.viewSettings.showMask_Outline or self.showReticles)
and self._dataModel.viewSettings.cameraPrim != None)
@property
def _cropImageToCameraViewport(self):
return ((self._dataModel.viewSettings.showMask and self._dataModel.viewSettings.showMask_Opaque)
and self._dataModel.viewSettings.cameraPrim != None)
@property
def cameraPrim(self):
return self._dataModel.viewSettings.cameraPrim
@cameraPrim.setter
def cameraPrim(self, prim):
self._dataModel.viewSettings.cameraPrim = prim
@property
def rolloverPicking(self):
return self._rolloverPicking
@rolloverPicking.setter
def rolloverPicking(self, enabled):
self._rolloverPicking = enabled
self.setMouseTracking(enabled)
@property
def fpsHUDInfo(self):
return self._fpsHUDInfo
@fpsHUDInfo.setter
def fpsHUDInfo(self, info):
self._fpsHUDInfo = info
@property
def fpsHUDKeys(self):
return self._fpsHUDKeys
@fpsHUDKeys.setter
def fpsHUDKeys(self, keys):
self._fpsHUDKeys = keys
@property
def upperHUDInfo(self):
return self._upperHUDInfo
@upperHUDInfo.setter
def upperHUDInfo(self, info):
self._upperHUDInfo = info
@property
def HUDStatKeys(self):
return self._HUDStatKeys
@HUDStatKeys.setter
def HUDStatKeys(self, keys):
self._HUDStatKeys = keys
@property
def overrideNear(self):
return self._overrideNear
@overrideNear.setter
def overrideNear(self, value):
"""To remove the override, set to None. Causes FreeCamera to become
active."""
self._overrideNear = value
self.switchToFreeCamera()
self._dataModel.viewSettings.freeCamera.overrideNear = value
self.updateGL()
@property
def overrideFar(self):
return self._overrideFar
@overrideFar.setter
def overrideFar(self, value):
"""To remove the override, set to None. Causes FreeCamera to become
active."""
self._overrideFar = value
self.switchToFreeCamera()
self._dataModel.viewSettings.freeCamera.overrideFar = value
self.updateGL()
@property
def allSceneCameras(self):
return self._allSceneCameras
@allSceneCameras.setter
def allSceneCameras(self, value):
self._allSceneCameras = value
@property
def gfCamera(self):
"""Return the last computed Gf Camera"""
return self._lastComputedGfCamera
@property
def cameraFrustum(self):
"""Unlike the StageView.freeCamera property, which is invalid/None
whenever we are viewing from a scene/stage camera, the 'cameraFrustum'
property will always return the last-computed camera frustum, regardless
of source."""
return self._lastComputedGfCamera.frustum
@property
def rendererDisplayName(self):
return self._rendererDisplayName
@property
def rendererAovName(self):
return self._rendererAovName
def __init__(self, parent=None, dataModel=None, printTiming=False):
# Note: The default format *disables* the alpha component and so the
# default backbuffer uses GL_RGB.
glFormat = QtOpenGL.QGLFormat()
msaa = os.getenv("USDVIEW_ENABLE_MSAA", "1")
if msaa == "1":
glFormat.setSampleBuffers(True)
glFormat.setSamples(4)
# XXX: for OSX (QT5 required)
# glFormat.setProfile(QtOpenGL.QGLFormat.CoreProfile)
super(StageView, self).__init__(glFormat, parent)
self._dataModel = dataModel or StageView.DefaultDataModel()
self._printTiming = printTiming
self._isFirstImage = True
# update() whenever a visible view setting (one which affects the view)
# is changed.
self._dataModel.viewSettings.signalVisibleSettingChanged.connect(
self.update)
self._dataModel.signalStageReplaced.connect(self._stageReplaced)
self._dataModel.selection.signalPrimSelectionChanged.connect(
self._primSelectionChanged)
self._dataModel.viewSettings.freeCamera = FreeCamera(True,
self._dataModel.viewSettings.freeCameraFOV)
self._lastComputedGfCamera = None
# prep Mask regions
self._mask = Mask()
self._maskOutline = Outline()
self._reticles = Reticles()
# prep HUD regions
self._hud = HUD()
self._hud.addGroup("TopLeft", 250, 160) # subtree
self._hud.addGroup("TopRight", 140, 32) # Hydra: Enabled
self._hud.addGroup("BottomLeft", 250, 160) # GPU stats
self._hud.addGroup("BottomRight", 210, 32) # Camera, Complexity
self._stageIsZup = True
self._cameraMode = "none"
self._rolloverPicking = False
self._dragActive = False
self._lastX = 0
self._lastY = 0
self._renderer = None
self._renderPauseState = False
self._renderStopState = False
self._reportedContextError = False
self._renderModeDict = {
RenderModes.WIREFRAME: UsdImagingGL.DrawMode.DRAW_WIREFRAME,
RenderModes.WIREFRAME_ON_SURFACE:
UsdImagingGL.DrawMode.DRAW_WIREFRAME_ON_SURFACE,
RenderModes.SMOOTH_SHADED: UsdImagingGL.DrawMode.DRAW_SHADED_SMOOTH,
RenderModes.POINTS: UsdImagingGL.DrawMode.DRAW_POINTS,
RenderModes.FLAT_SHADED: UsdImagingGL.DrawMode.DRAW_SHADED_FLAT,
RenderModes.GEOM_ONLY: UsdImagingGL.DrawMode.DRAW_GEOM_ONLY,
RenderModes.GEOM_SMOOTH: UsdImagingGL.DrawMode.DRAW_GEOM_SMOOTH,
RenderModes.GEOM_FLAT: UsdImagingGL.DrawMode.DRAW_GEOM_FLAT,
RenderModes.HIDDEN_SURFACE_WIREFRAME:
UsdImagingGL.DrawMode.DRAW_WIREFRAME
}
self._renderParams = UsdImagingGL.RenderParams()
# Optionally override OCIO lut size. Similar env var available for
# other apps: ***_OCIO_LUT3D_EDGE_SIZE
ocioLutSize = os.getenv("USDVIEW_OCIO_LUT3D_EDGE_SIZE", 0)
if ocioLutSize > 0:
self._renderParams.lut3dSizeOCIO = ocioLutSize
self._dist = 50
self._bbox = Gf.BBox3d()
self._selectionBBox = Gf.BBox3d()
self._selectionBrange = Gf.Range3d()
self._selectionOrientedRange = Gf.Range3d()
self._bbcenterForBoxDraw = (0, 0, 0)
self._overrideNear = None
self._overrideFar = None
self._forceRefresh = False
self._renderTime = 0
self._allSceneCameras = None
# HUD properties
self._fpsHUDInfo = dict()
self._fpsHUDKeys = []
self._upperHUDInfo = dict()
self._HUDStatKeys = list()
self._glPrimitiveGeneratedQuery = None
self._glTimeElapsedQuery = None
self._simpleGLSLProgram = None
self._axisVBO = None
self._bboxVBO = None
self._cameraGuidesVBO = None
self._vao = 0
# Update all properties for the current stage.
self._stageReplaced()
def _getRenderer(self):
# Unfortunately, we cannot assume that initializeGL() was called
# before attempts to use the renderer (e.g. pick()), so we must
# create the renderer lazily, when we try to do real work with it.
if not self._renderer:
if self.context().isValid():
if self.context().initialized():
self._renderer = UsdImagingGL.Engine()
self._handleRendererChanged(self.GetCurrentRendererId())
elif not self._reportedContextError:
self._reportedContextError = True
raise RuntimeError("StageView could not initialize renderer without a valid GL context")
return self._renderer
def _handleRendererChanged(self, rendererId):
self._rendererDisplayName = self.GetRendererDisplayName(rendererId)
self._rendererAovName = "color"
self._renderPauseState = False
self._renderStopState = False
# XXX For HdSt we explicitely enable AOV via SetRendererAov
# This is because ImagingGL / TaskController are spawned via prims in
# Presto, so we default AOVs OFF until everything is AOV ready.
self.SetRendererAov(self.rendererAovName)
def _scaleMouseCoords(self, point):
return point * QtWidgets.QApplication.instance().devicePixelRatio()
def closeRenderer(self):
'''Close the current renderer.'''
with Timer() as t:
self._renderer = None
if self._printTiming:
t.PrintTime('shut down Hydra')
def GetRendererPlugins(self):
if self._renderer:
return self._renderer.GetRendererPlugins()
else:
return []
def GetRendererDisplayName(self, plugId):
if self._renderer:
return self._renderer.GetRendererDisplayName(plugId)
else:
return ""
def GetCurrentRendererId(self):
if self._renderer:
return self._renderer.GetCurrentRendererId()
else:
return ""
def SetRendererPlugin(self, plugId):
if self._renderer:
if self._renderer.SetRendererPlugin(plugId):
self._handleRendererChanged(plugId)
self.updateGL()
return True
else:
return False
return True
def GetRendererAovs(self):
if self._renderer:
return self._renderer.GetRendererAovs()
else:
return []
def SetRendererAov(self, aov):
if self._renderer:
if self._renderer.SetRendererAov(aov):
self._rendererAovName = aov
self.updateGL()
return True
else:
return False
return True
def GetRendererSettingsList(self):
if self._renderer:
return self._renderer.GetRendererSettingsList()
else:
return []
def GetRendererSetting(self, name):
if self._renderer:
return self._renderer.GetRendererSetting(name)
else:
return None
def SetRendererSetting(self, name, value):
if self._renderer:
self._renderer.SetRendererSetting(name, value)
self.updateGL()
def SetRendererPaused(self, paused):
if self._renderer and (not self._renderer.IsConverged()):
if paused:
self._renderPauseState = self._renderer.PauseRenderer()
else:
self._renderPauseState = not self._renderer.ResumeRenderer()
self.updateGL()
def IsPauseRendererSupported(self):
if self._renderer:
if self._renderer.IsPauseRendererSupported():
return True
return False
def IsRendererConverged(self):
return self._renderer and self._renderer.IsConverged()
def SetRendererStopped(self, stopped):
if self._renderer:
if stopped:
self._renderStopState = self._renderer.StopRenderer()
else:
self._renderStopState = not self._renderer.RestartRenderer()
self.updateGL()
def IsStopRendererSupported(self):
if self._renderer:
if self._renderer.IsStopRendererSupported():
return True
return False
def _stageReplaced(self):
'''Set the USD Stage this widget will be displaying. To decommission
(even temporarily) this widget, supply None as 'stage'.'''
self.allSceneCameras = None
if self._dataModel.stage:
self._stageIsZup = (
UsdGeom.GetStageUpAxis(self._dataModel.stage) == UsdGeom.Tokens.z)
self._dataModel.viewSettings.freeCamera = \
FreeCamera(self._stageIsZup,
self._dataModel.viewSettings.freeCameraFOV)
# simple GLSL program for axis/bbox drawings
def GetSimpleGLSLProgram(self):
if self._simpleGLSLProgram == None:
self._simpleGLSLProgram = GLSLProgram(
"""#version 140
uniform mat4 mvpMatrix;
in vec3 position;
void main() { gl_Position = vec4(position, 1)*mvpMatrix; }""",
"""#version 140
out vec4 outColor;
uniform vec4 color;
void main() { outColor = color; }""",
"""#version 120
uniform mat4 mvpMatrix;
attribute vec3 position;
void main() { gl_Position = vec4(position, 1)*mvpMatrix; }""",
"""#version 120
uniform vec4 color;
void main() { gl_FragColor = color; }""",
["mvpMatrix", "color"])
return self._simpleGLSLProgram
def DrawAxis(self, viewProjectionMatrix):
from OpenGL import GL
import ctypes
# grab the simple shader
glslProgram = self.GetSimpleGLSLProgram()
if (glslProgram.program == 0):
return
# vao
if (glslProgram._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (self._vao == 0):
self._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(self._vao)
# prep a vbo for axis
if (self._axisVBO is None):
self._axisVBO = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._axisVBO)
data = [1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0]
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(data)*4,
(ctypes.c_float*len(data))(*data), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._axisVBO)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 0, ctypes.c_void_p(0))
GL.glUseProgram(glslProgram.program)
# i *think* this actually wants the camera dist so that the axis stays
# somewhat fixed in screen-space size.
mvpMatrix = Gf.Matrix4f().SetScale(self._dist/20.0) * viewProjectionMatrix
matrix = (ctypes.c_float*16).from_buffer_copy(mvpMatrix)
GL.glUniformMatrix4fv(glslProgram.uniformLocations["mvpMatrix"],
1, GL.GL_TRUE, matrix)
GL.glUniform4f(glslProgram.uniformLocations["color"], 1, 0, 0, 1)
GL.glDrawArrays(GL.GL_LINES, 0, 2)
GL.glUniform4f(glslProgram.uniformLocations["color"], 0, 1, 0, 1)
GL.glDrawArrays(GL.GL_LINES, 2, 2)
GL.glUniform4f(glslProgram.uniformLocations["color"], 0, 0, 1, 1)
GL.glDrawArrays(GL.GL_LINES, 4, 2)
GL.glDisableVertexAttribArray(0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glUseProgram(0)
if (self._vao != 0):
GL.glBindVertexArray(0)
def DrawBBox(self, viewProjectionMatrix):
col = self._dataModel.viewSettings.clearColor
color = Gf.Vec3f(col[0]-.5 if col[0]>0.5 else col[0]+.5,
col[1]-.5 if col[1]>0.5 else col[1]+.5,
col[2]-.5 if col[2]>0.5 else col[2]+.5)
# Draw axis-aligned bounding box
if self._dataModel.viewSettings.showAABBox:
bsize = self._selectionBrange.max - self._selectionBrange.min
trans = Gf.Transform()
trans.SetScale(0.5*bsize)
trans.SetTranslation(self._bbcenterForBoxDraw)
self.drawWireframeCube(color,
Gf.Matrix4f(trans.GetMatrix()) * viewProjectionMatrix)
# Draw oriented bounding box
if self._dataModel.viewSettings.showOBBox:
bsize = self._selectionOrientedRange.max - self._selectionOrientedRange.min
center = bsize / 2. + self._selectionOrientedRange.min
trans = Gf.Transform()
trans.SetScale(0.5*bsize)
trans.SetTranslation(center)
self.drawWireframeCube(color,
Gf.Matrix4f(trans.GetMatrix()) *
Gf.Matrix4f(self._selectionBBox.matrix) *
viewProjectionMatrix)
# XXX:
# First pass at visualizing cameras in usdview-- just oracles for
# now. Eventually the logic should live in usdImaging, where the delegate
# would add the camera guide geometry to the GL buffers over the course over
# its stage traversal, and get time samples accordingly.
def DrawCameraGuides(self, mvpMatrix):
from OpenGL import GL
import ctypes
# prep a vbo for camera guides
if (self._cameraGuidesVBO is None):
self._cameraGuidesVBO = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._cameraGuidesVBO)
data = []
for camera in self._allSceneCameras:
# Don't draw guides for the active camera.
if camera == self._dataModel.viewSettings.cameraPrim or not (camera and camera.IsActive()):
continue
gfCamera = UsdGeom.Camera(camera).GetCamera(
self._dataModel.currentFrame)
frustum = gfCamera.frustum
# (Gf documentation seems to be wrong)-- Ordered as
# 0: left bottom near
# 1: right bottom near
# 2: left top near
# 3: right top near
# 4: left bottom far
# 5: right bottom far
# 6: left top far
# 7: right top far
oraclePoints = frustum.ComputeCorners()
# Near plane
indices = [0,1,1,3,3,2,2,0, # Near plane
4,5,5,7,7,6,6,4, # Far plane
3,7,0,4,1,5,2,6] # Lines between near and far planes.
data.extend([oraclePoints[i][j] for i in indices for j in range(3)])
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(data)*4,
(ctypes.c_float*len(data))(*data), GL.GL_STATIC_DRAW)
# grab the simple shader
glslProgram = self.GetSimpleGLSLProgram()
if (glslProgram.program == 0):
return
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 0, ctypes.c_void_p(0))
GL.glUseProgram(glslProgram.program)
matrix = (ctypes.c_float*16).from_buffer_copy(mvpMatrix)
GL.glUniformMatrix4fv(glslProgram.uniformLocations["mvpMatrix"],
1, GL.GL_TRUE, matrix)
# Grabbed fallback oracleColor from CamCamera.
GL.glUniform4f(glslProgram.uniformLocations["color"],
0.82745, 0.39608, 0.1647, 1)
GL.glDrawArrays(GL.GL_LINES, 0, len(data)//3)
GL.glDisableVertexAttribArray(0)
GL.glUseProgram(0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
def updateBboxPurposes(self):
includedPurposes = self._dataModel.includedPurposes
if self._dataModel.viewSettings.displayGuide:
includedPurposes.add(UsdGeom.Tokens.guide)
elif UsdGeom.Tokens.guide in includedPurposes:
includedPurposes.remove(UsdGeom.Tokens.guide)
if self._dataModel.viewSettings.displayProxy:
includedPurposes.add(UsdGeom.Tokens.proxy)
elif UsdGeom.Tokens.proxy in includedPurposes:
includedPurposes.remove(UsdGeom.Tokens.proxy)
if self._dataModel.viewSettings.displayRender:
includedPurposes.add(UsdGeom.Tokens.render)
elif UsdGeom.Tokens.render in includedPurposes:
includedPurposes.remove(UsdGeom.Tokens.render)
self._dataModel.includedPurposes = includedPurposes
# force the bbox to refresh
self._bbox = Gf.BBox3d()
def recomputeBBox(self):
selectedPrims = self._dataModel.selection.getLCDPrims()
try:
startTime = time()
self._bbox = self.getStageBBox()
if len(selectedPrims) == 1 and selectedPrims[0].GetPath() == '/':
if self._bbox.GetRange().IsEmpty():
self._selectionBBox = self._getDefaultBBox()
else:
self._selectionBBox = self._bbox
else:
self._selectionBBox = self.getSelectionBBox()
# BBox computation time for HUD
endTime = time()
ms = (endTime - startTime) * 1000.
self.signalBboxUpdateTimeChanged.emit(ms)
except RuntimeError:
# This may fail, but we want to keep the UI available,
# so print the error and attempt to continue loading
self.signalErrorMessage.emit("unable to get bounding box on "
"stage at frame {0}".format(self._dataModel.currentFrame))
import traceback
traceback.print_exc()
self._bbox = self._getEmptyBBox()
self._selectionBBox = self._getDefaultBBox()
self._selectionBrange = self._selectionBBox.ComputeAlignedRange()
self._selectionOrientedRange = self._selectionBBox.box
self._bbcenterForBoxDraw = self._selectionBBox.ComputeCentroid()
def resetCam(self, frameFit=1.1):
validFrameRange = (not self._selectionBrange.IsEmpty() and
self._selectionBrange.GetMax() != self._selectionBrange.GetMin())
if validFrameRange:
self.switchToFreeCamera()
self._dataModel.viewSettings.freeCamera.frameSelection(self._selectionBBox,
frameFit)
self.computeAndSetClosestDistance()
def updateView(self, resetCam=False, forceComputeBBox=False, frameFit=1.1):
'''Updates bounding boxes and camera. resetCam = True causes the camera to reframe
the specified prims. frameFit sets the ratio of the camera's frustum's
relevant dimension to the object's bounding box. 1.1, the default,
fits the prim's bounding box in the frame with a roughly 10% margin.
'''
# Only compute BBox if forced, if needed for drawing,
# or if this is the first time running.
computeBBox = forceComputeBBox or \
(self._dataModel.viewSettings.showBBoxes and
(self._dataModel.viewSettings.showAABBox or self._dataModel.viewSettings.showOBBox))\
or self._bbox.GetRange().IsEmpty()
if computeBBox:
self.recomputeBBox()
if resetCam:
self.resetCam(frameFit)
self.updateGL()
def updateSelection(self):
try:
renderer = self._getRenderer()
if not renderer:
# error has already been issued
return
renderer.ClearSelected()
psuRoot = self._dataModel.stage.GetPseudoRoot()
allInstances = self._dataModel.selection.getPrimInstances()
for prim in self._dataModel.selection.getLCDPrims():
if prim == psuRoot:
continue
primInstances = allInstances[prim]
if primInstances != ALL_INSTANCES:
for instanceIndex in primInstances:
renderer.AddSelected(prim.GetPath(), instanceIndex)
else:
renderer.AddSelected(
prim.GetPath(), UsdImagingGL.ALL_INSTANCES)
except Tf.ErrorException as e:
# If we encounter an error, we want to continue running. Just log
# the error and continue.
sys.stderr.write(
"ERROR: Usdview encountered an error while updating selection."
"{}\n".format(e))
finally:
# Make sure not to leak a reference to the renderer
renderer = None
def _getEmptyBBox(self):
# This returns the default empty bbox [FLT_MAX,-FLT_MAX]
return Gf.BBox3d()
def _getDefaultBBox(self):
return Gf.BBox3d(Gf.Range3d((-10,-10,-10), (10,10,10)))
def _isInfiniteBBox(self, bbox):
return isinf(bbox.GetRange().GetMin().GetLength()) or \
isinf(bbox.GetRange().GetMax().GetLength())
def getStageBBox(self):
bbox = self._dataModel.computeWorldBound(
self._dataModel.stage.GetPseudoRoot())
if bbox.GetRange().IsEmpty() or self._isInfiniteBBox(bbox):
bbox = self._getEmptyBBox()
return bbox
def getSelectionBBox(self):
bbox = Gf.BBox3d()
for n in self._dataModel.selection.getLCDPrims():
if n.IsActive() and not n.IsInMaster():
primBBox = self._dataModel.computeWorldBound(n)
bbox = Gf.BBox3d.Combine(bbox, primBBox)
return bbox
def renderSinglePass(self, renderMode, renderSelHighlights):
if not self._dataModel.stage:
return
renderer = self._getRenderer()
if not renderer:
# error has already been issued
return
# update rendering parameters
self._renderParams.frame = self._dataModel.currentFrame
self._renderParams.complexity = self._dataModel.viewSettings.complexity.value
self._renderParams.drawMode = renderMode
self._renderParams.showGuides = self._dataModel.viewSettings.displayGuide
self._renderParams.showProxy = self._dataModel.viewSettings.displayProxy
self._renderParams.showRender = self._dataModel.viewSettings.displayRender
self._renderParams.forceRefresh = self._forceRefresh
self._renderParams.cullStyle = \
(UsdImagingGL.CullStyle.CULL_STYLE_BACK_UNLESS_DOUBLE_SIDED
if self._dataModel.viewSettings.cullBackfaces
else UsdImagingGL.CullStyle.CULL_STYLE_NOTHING)
self._renderParams.gammaCorrectColors = False
self._renderParams.enableIdRender = self._dataModel.viewSettings.displayPrimId
self._renderParams.enableSampleAlphaToCoverage = not self._dataModel.viewSettings.displayPrimId
self._renderParams.highlight = renderSelHighlights
self._renderParams.enableSceneMaterials = self._dataModel.viewSettings.enableSceneMaterials
self._renderParams.colorCorrectionMode = self._dataModel.viewSettings.colorCorrectionMode
self._renderParams.clearColor = Gf.ConvertDisplayToLinear(Gf.Vec4f(self._dataModel.viewSettings.clearColor))
pseudoRoot = self._dataModel.stage.GetPseudoRoot()
renderer.SetSelectionColor(self._dataModel.viewSettings.highlightColor)
try:
renderer.Render(pseudoRoot, self._renderParams)
except Tf.ErrorException as e:
# If we encounter an error during a render, we want to continue
# running. Just log the error and continue.
sys.stderr.write(
"ERROR: Usdview encountered an error while rendering.{}\n".format(e))
finally:
# Make sure not to leak a reference to the renderer
renderer = None
self._forceRefresh = False
def initializeGL(self):
if not self.isValid():
return
from pxr import Glf
if not Glf.GlewInit():
return
Glf.RegisterDefaultDebugOutputMessageCallback()
def updateGL(self):
"""We override this virtual so that we can make it a no-op during
playback. The client driving playback at a particular rate should
instead call updateForPlayback() to image the next frame."""
if not self._dataModel.playing:
super(StageView, self).updateGL()
def updateForPlayback(self):
"""If playing, update the GL canvas. Otherwise a no-op"""
if self._dataModel.playing:
super(StageView, self).updateGL()
def getActiveSceneCamera(self):
cameraPrim = self._dataModel.viewSettings.cameraPrim
if cameraPrim and cameraPrim.IsActive():
return cameraPrim
return None
# XXX: Consolidate window/frustum conformance code that is littered in
# several places.
def computeWindowPolicy(self, cameraAspectRatio):
# The freeCam always uses 'MatchVertically'.
# When using a scene cam, we factor in the masking setting and window
# size to compute it.
windowPolicy = CameraUtil.MatchVertically
if self.getActiveSceneCamera():
if self._cropImageToCameraViewport:
targetAspect = (
float(self.size().width()) / max(1.0, self.size().height()))
if targetAspect < cameraAspectRatio:
windowPolicy = CameraUtil.MatchHorizontally
else:
if self._fitCameraInViewport:
windowPolicy = CameraUtil.Fit
return windowPolicy
def computeWindowSize(self):
size = self.size() * self.devicePixelRatioF()
return (int(size.width()), int(size.height()))
def computeWindowViewport(self):
return (0, 0) + self.computeWindowSize()
def resolveCamera(self):
"""Returns a tuple of the camera to use for rendering (either a scene
camera or a free camera) and that camera's original aspect ratio.
Depending on camera guide settings, the camera frustum may be conformed
to fit the window viewport. Emits a signalFrustumChanged if the
camera frustum has changed since the last time resolveCamera was called."""
# If 'camera' is None, make sure we have a valid freeCamera
sceneCam = self.getActiveSceneCamera()
if sceneCam:
gfCam = UsdGeom.Camera(sceneCam).GetCamera(
self._dataModel.currentFrame)
else:
self.switchToFreeCamera()
gfCam = self._dataModel.viewSettings.freeCamera.computeGfCamera(
self._bbox, autoClip=self.autoClip)
cameraAspectRatio = gfCam.aspectRatio
# Conform the camera's frustum to the window viewport, if necessary.
if not self._cropImageToCameraViewport:
targetAspect = float(self.size().width()) / max(1.0, self.size().height())
if self._fitCameraInViewport:
CameraUtil.ConformWindow(gfCam, CameraUtil.Fit, targetAspect)
else:
CameraUtil.ConformWindow(gfCam, CameraUtil.MatchVertically, targetAspect)
frustumChanged = ((not self._lastComputedGfCamera) or
self._lastComputedGfCamera.frustum != gfCam.frustum)
# We need to COPY the camera, not assign it...
self._lastComputedGfCamera = Gf.Camera(gfCam)
if frustumChanged:
self.signalFrustumChanged.emit()
return (gfCam, cameraAspectRatio)
def computeCameraViewport(self, cameraAspectRatio):
# Conform the camera viewport to the camera's aspect ratio,
# and center the camera viewport in the window viewport.
windowPolicy = CameraUtil.MatchVertically
targetAspect = (
float(self.size().width()) / max(1.0, self.size().height()))
if targetAspect < cameraAspectRatio:
windowPolicy = CameraUtil.MatchHorizontally
viewport = Gf.Range2d(Gf.Vec2d(0, 0),
Gf.Vec2d(self.computeWindowSize()))
viewport = CameraUtil.ConformedWindow(viewport, windowPolicy, cameraAspectRatio)
viewport = (viewport.GetMin()[0], viewport.GetMin()[1],
viewport.GetSize()[0], viewport.GetSize()[1])
viewport = ViewportMakeCenteredIntegral(viewport)
return viewport
def copyViewState(self):
"""Returns a copy of this StageView's view-affecting state,
which can be used later to restore the view via restoreViewState().
Take note that we do NOT include the StageView's notion of the
current time (used by prim-based cameras to extract their data),
since we do not want a restore operation to put us out of sync
with respect to our owner's time.
"""
viewState = {}
viewState["_cameraPrim"] = self._dataModel.viewSettings.cameraPrim
viewState["_stageIsZup"] = self._stageIsZup
viewState["_overrideNear"] = self._overrideNear
viewState["_overrideFar"] = self._overrideFar
# Since FreeCamera is a compound/class object, we must copy
# it more deeply
viewState["_freeCamera"] = self._dataModel.viewSettings.freeCamera.clone() if self._dataModel.viewSettings.freeCamera else None
return viewState
def restoreViewState(self, viewState):
"""Restore view parameters from 'viewState', and redraw"""
self._dataModel.viewSettings.cameraPrim = viewState["_cameraPrim"]
self._stageIsZup = viewState["_stageIsZup"]
self._overrideNear = viewState["_overrideNear"]
self._overrideFar = viewState["_overrideFar"]
restoredCamera = viewState["_freeCamera"]
# Detach our freeCamera from the given viewState, to
# insulate against changes to viewState by caller
self._dataModel.viewSettings.freeCamera = restoredCamera.clone() if restoredCamera else None
self.update()
def drawWireframeCube(self, col, mvpMatrix):
from OpenGL import GL
import ctypes, itertools
# grab the simple shader
glslProgram = self.GetSimpleGLSLProgram()
if (glslProgram.program == 0):
return
# vao
if (glslProgram._glMajorVersion >= 3 and hasattr(GL, 'glGenVertexArrays')):
if (self._vao == 0):
self._vao = GL.glGenVertexArrays(1)
GL.glBindVertexArray(self._vao)
# prep a vbo for bbox
if (self._bboxVBO is None):
self._bboxVBO = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._bboxVBO)
# create 12 edges
data = []
p = list(itertools.product([-1,1],[-1,1],[-1,1]))
for i in p:
data.extend([i[0], i[1], i[2]])
for i in p:
data.extend([i[1], i[2], i[0]])
for i in p:
data.extend([i[2], i[0], i[1]])
GL.glBufferData(GL.GL_ARRAY_BUFFER, len(data)*4,
(ctypes.c_float*len(data))(*data), GL.GL_STATIC_DRAW)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self._bboxVBO)
GL.glEnableVertexAttribArray(0)
GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 0, ctypes.c_void_p(0))
GL.glEnable(GL.GL_LINE_STIPPLE)
GL.glLineStipple(2,0xAAAA)
GL.glUseProgram(glslProgram.program)
matrix = (ctypes.c_float*16).from_buffer_copy(mvpMatrix)
GL.glUniformMatrix4fv(glslProgram.uniformLocations["mvpMatrix"],
1, GL.GL_TRUE, matrix)
GL.glUniform4f(glslProgram.uniformLocations["color"],
col[0], col[1], col[2], 1)
GL.glDrawArrays(GL.GL_LINES, 0, 24)
GL.glDisableVertexAttribArray(0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glUseProgram(0)
GL.glDisable(GL.GL_LINE_STIPPLE)
if (self._vao != 0):
GL.glBindVertexArray(0)
def paintGL(self):
if not self._dataModel.stage:
return
renderer = self._getRenderer()
if not renderer:
# error has already been issued
return
try:
from OpenGL import GL
if self._dataModel.viewSettings.showHUD_GPUstats:
if self._glPrimitiveGeneratedQuery is None:
self._glPrimitiveGeneratedQuery = Glf.GLQueryObject()
if self._glTimeElapsedQuery is None:
self._glTimeElapsedQuery = Glf.GLQueryObject()
self._glPrimitiveGeneratedQuery.BeginPrimitivesGenerated()
self._glTimeElapsedQuery.BeginTimeElapsed()
if not UsdImagingGL.Engine.IsColorCorrectionCapable():
from OpenGL.GL.EXT.framebuffer_sRGB import GL_FRAMEBUFFER_SRGB_EXT
GL.glEnable(GL_FRAMEBUFFER_SRGB_EXT)
# Clear the default FBO associated with the widget/context to
# fully transparent and *not* the bg color.
# The bg color is used as the clear color for the aov, and the
# results of rendering are composited over the FBO (and not blit).
GL.glClearColor(*Gf.Vec4f(0,0,0,0))
GL.glEnable(GL.GL_DEPTH_TEST)
GL.glDepthFunc(GL.GL_LESS)
GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
GL.glEnable(GL.GL_BLEND)
# Note: camera lights and camera guides require the
# resolved (adjusted) camera viewProjection matrix, which is
# why we resolve the camera above always.
(gfCamera, cameraAspect) = self.resolveCamera()
frustum = gfCamera.frustum
cameraViewport = self.computeCameraViewport(cameraAspect)
viewport = self.computeWindowViewport()
windowViewport = viewport
if self._cropImageToCameraViewport:
viewport = cameraViewport
cam_pos = frustum.position
cam_up = frustum.ComputeUpVector()
cam_right = Gf.Cross(frustum.ComputeViewDirection(), cam_up)
# not using the actual camera dist ...
cam_light_dist = self._dist
sceneCam = self.getActiveSceneCamera()
renderer.SetRenderViewport(viewport)
renderer.SetWindowPolicy(self.computeWindowPolicy(cameraAspect))
if sceneCam:
# When using a USD camera, simply set it as the active camera.
# Window policy conformance is handled in the engine/hydra.
renderer.SetCameraPath(sceneCam.GetPath())
else:
# When using the free cam (which isn't currently backed on the
# USD stage), we send the camera matrices to the engine.
renderer.SetCameraState(frustum.ComputeViewMatrix(),
frustum.ComputeProjectionMatrix())
viewProjectionMatrix = Gf.Matrix4f(frustum.ComputeViewMatrix()
* frustum.ComputeProjectionMatrix())
GL.glViewport(*windowViewport)
GL.glClear(GL.GL_COLOR_BUFFER_BIT|GL.GL_DEPTH_BUFFER_BIT)
# ensure viewport is right for the camera framing
GL.glViewport(*viewport)
# Set the clipping planes.
self._renderParams.clipPlanes = [Gf.Vec4d(i) for i in
gfCamera.clippingPlanes]
if len(self._dataModel.selection.getLCDPrims()) > 0:
sceneAmbient = (0.01, 0.01, 0.01, 1.0)
material = Glf.SimpleMaterial()
lights = []
# for renderModes that need lights
if self._dataModel.viewSettings.renderMode in ShadedRenderModes:
# ambient light located at the camera
if self._dataModel.viewSettings.ambientLightOnly:
l = Glf.SimpleLight()
l.ambient = (0, 0, 0, 0)
l.position = (cam_pos[0], cam_pos[1], cam_pos[2], 1)
lights.append(l)
# Default Dome Light
if self._dataModel.viewSettings.domeLightEnabled:
l = Glf.SimpleLight()
l.isDomeLight = True
if self._stageIsZup:
l.transform = Gf.Matrix4d().SetRotate(
Gf.Rotation(Gf.Vec3d.XAxis(), 90))
lights.append(l)
kA = self._dataModel.viewSettings.defaultMaterialAmbient
kS = self._dataModel.viewSettings.defaultMaterialSpecular
material.ambient = (kA, kA, kA, 1.0)
material.specular = (kS, kS, kS, 1.0)
material.shininess = 32.0
# modes that want no lighting simply leave lights as an empty list
renderer.SetLightingState(lights, material, sceneAmbient)
if self._dataModel.viewSettings.renderMode == RenderModes.HIDDEN_SURFACE_WIREFRAME:
GL.glEnable( GL.GL_POLYGON_OFFSET_FILL )
GL.glPolygonOffset( 1.0, 1.0 )
GL.glPolygonMode( GL.GL_FRONT_AND_BACK, GL.GL_FILL )
self.renderSinglePass(
UsdImagingGL.DrawMode.DRAW_GEOM_ONLY, False)
GL.glDisable( GL.GL_POLYGON_OFFSET_FILL )
# Use display space for the second clear because we
# composite the framebuffer contents with the
# color-corrected (i.e., display space) aov contents.
clearColor = Gf.Vec4f(self._dataModel.viewSettings.clearColor)
GL.glClearColor(*clearColor)
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
highlightMode = self._dataModel.viewSettings.selHighlightMode
if self._dataModel.playing:
# Highlight mode must be ALWAYS to draw highlights during playback.
drawSelHighlights = (
highlightMode == SelectionHighlightModes.ALWAYS)
else:
# Highlight mode can be ONLY_WHEN_PAUSED or ALWAYS to draw
# highlights when paused.
drawSelHighlights = (
highlightMode != SelectionHighlightModes.NEVER)
self.renderSinglePass(
self._renderModeDict[self._dataModel.viewSettings.renderMode],
drawSelHighlights)
if not UsdImagingGL.Engine.IsColorCorrectionCapable():
GL.glDisable(GL_FRAMEBUFFER_SRGB_EXT)
self.DrawAxis(viewProjectionMatrix)
# XXX:
# Draw camera guides-- no support for toggling guide visibility on
# individual cameras until we move this logic directly into
# usdImaging.
if self._dataModel.viewSettings.displayCameraOracles:
self.DrawCameraGuides(viewProjectionMatrix)
if self._dataModel.viewSettings.showBBoxes and\
(self._dataModel.viewSettings.showBBoxPlayback or not self._dataModel.playing):
self.DrawBBox(viewProjectionMatrix)
else:
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
if self._dataModel.viewSettings.showHUD_GPUstats:
self._glPrimitiveGeneratedQuery.End()
self._glTimeElapsedQuery.End()
# reset the viewport for 2D and HUD drawing
uiTasks = [ Prim2DSetupTask(self.computeWindowViewport()) ]
if self._dataModel.viewSettings.showMask:
color = self._dataModel.viewSettings.cameraMaskColor
if self._dataModel.viewSettings.showMask_Opaque:
color = color[0:3] + (1.0,)
else:
color = color[0:3] + (color[3] * 0.45,)
self._mask.updateColor(color)
self._mask.updatePrims(cameraViewport, self)
uiTasks.append(self._mask)
if self._dataModel.viewSettings.showMask_Outline:
self._maskOutline.updatePrims(cameraViewport, self)
uiTasks.append(self._maskOutline)
if self.showReticles:
color = self._dataModel.viewSettings.cameraReticlesColor
color = color[0:3] + (color[3] * 0.85,)
self._reticles.updateColor(color)
self._reticles.updatePrims(cameraViewport, self,
self._dataModel.viewSettings.showReticles_Inside, self._dataModel.viewSettings.showReticles_Outside)
uiTasks.append(self._reticles)
for task in uiTasks:
task.Sync(None)
for task in uiTasks:
task.Execute(None)
# check current state of renderer -- (not IsConverged()) means renderer is running
if self._renderStopState and (not renderer.IsConverged()):
self._renderStopState = False
# ### DRAW HUD ### #
if self._dataModel.viewSettings.showHUD:
self.drawHUD(renderer)
if (not self._dataModel.playing) & (not renderer.IsConverged()):
QtCore.QTimer.singleShot(5, self.update)
except Tf.ErrorException as e:
# If we encounter an error during a render, we want to continue
# running. Just log the error and continue.
sys.stderr.write(
"ERROR: Usdview encountered an error while rendering."
"{}\n".format(e))
finally:
# Make sure not to leak a reference to the renderer
renderer = None
def drawHUD(self, renderer):
# compute the time it took to render this frame,
# so we can display it in the HUD
ms = self._renderTime * 1000.
fps = float("inf")
if not self._renderTime == 0:
fps = 1./self._renderTime
# put the result in the HUD string
self.fpsHUDInfo['Render'] = "%.2f ms (%.2f FPS)" % (ms, fps)
col = Gf.Vec3f(.733,.604,.333)
# the subtree info does not update while animating, grey it out
if not self._dataModel.playing:
subtreeCol = col
else:
subtreeCol = Gf.Vec3f(.6,.6,.6)
# Subtree Info
if self._dataModel.viewSettings.showHUD_Info:
self._hud.updateGroup("TopLeft", 0, 14, subtreeCol,
self.upperHUDInfo,
self.HUDStatKeys)
else:
self._hud.updateGroup("TopLeft", 0, 0, subtreeCol, {})
# Complexity
if self._dataModel.viewSettings.showHUD_Complexity:
# Camera name
camName = "Free%s" % (" AutoClip" if self.autoClip else "")
if self._dataModel.viewSettings.cameraPrim:
camName = self._dataModel.viewSettings.cameraPrim.GetName()
toPrint = {"Complexity" : self._dataModel.viewSettings.complexity.name,
"Camera" : camName}
self._hud.updateGroup("BottomRight",
self.width()-210, self.height()-self._hud._HUDLineSpacing*2,
col, toPrint)
else:
self._hud.updateGroup("BottomRight", 0, 0, col, {})
# Hydra Enabled (Top Right)
hydraMode = "Disabled"
if UsdImagingGL.Engine.IsHydraEnabled():
hydraMode = self._rendererDisplayName
if not hydraMode:
hydraMode = "Enabled"
if self._renderPauseState:
toPrint = {"Hydra": "(paused)"}
elif self._renderStopState:
toPrint = {"Hydra": "(stopped)"}
else:
toPrint = {"Hydra": hydraMode}
if self._rendererAovName != "color":
toPrint[" AOV"] = self._rendererAovName
self._hud.updateGroup("TopRight", self.width()-160, 14, col,
toPrint, toPrint.keys())
# bottom left
from collections import OrderedDict
toPrint = OrderedDict()
# GPU stats (TimeElapsed is in nano seconds)
if self._dataModel.viewSettings.showHUD_GPUstats:
def _addSizeMetric(toPrint, stats, label, key):
if key in stats:
toPrint[label] = ReportMetricSize(stats[key])
rStats = renderer.GetRenderStats()
toPrint["GL prims "] = self._glPrimitiveGeneratedQuery.GetResult()
if not (self._renderPauseState or self._renderStopState):
toPrint["GPU time "] = "%.2f ms " % (self._glTimeElapsedQuery.GetResult() / 1000000.0)
_addSizeMetric(toPrint, rStats, "GPU mem ", "gpuMemoryUsed")
_addSizeMetric(toPrint, rStats, " primvar ", "primvar")
_addSizeMetric(toPrint, rStats, " topology", "topology")
_addSizeMetric(toPrint, rStats, " shader ", "drawingShader")
_addSizeMetric(toPrint, rStats, " texture ", "textureMemory")
if "numCompletedSamples" in rStats:
toPrint["Samples done "] = rStats["numCompletedSamples"]
# Playback Rate
if (not (self._renderPauseState or self._renderStopState)) and \
self._dataModel.viewSettings.showHUD_Performance:
for key in self.fpsHUDKeys:
toPrint[key] = self.fpsHUDInfo[key]
self._hud.updateGroup("BottomLeft",
0, self.height()-len(toPrint)*self._hud._HUDLineSpacing,
col, toPrint, toPrint.keys())
# draw HUD
self._hud.draw(self)
def sizeHint(self):
return QtCore.QSize(460, 460)
def switchToFreeCamera(self, computeAndSetClosestDistance=True):
"""
If our current camera corresponds to a prim, create a FreeCamera
that has the same view and use it.
"""
if self._dataModel.viewSettings.cameraPrim != None:
# cameraPrim may no longer be valid, so use the last-computed
# gf camera
if self._lastComputedGfCamera:
self._dataModel.viewSettings.freeCamera = FreeCamera.FromGfCamera(
self._lastComputedGfCamera, self._stageIsZup)
else:
self._dataModel.viewSettings.freeCamera = FreeCamera(
self._stageIsZup,
self._dataModel.viewSettings.freeCameraFOV)
# override clipping plane state is managed by StageView,
# so that it can be persistent. Therefore we must restore it
# now
self._dataModel.viewSettings.freeCamera.overrideNear = self._overrideNear
self._dataModel.viewSettings.freeCamera.overrideFar = self._overrideFar
self._dataModel.viewSettings.cameraPrim = None
if computeAndSetClosestDistance:
self.computeAndSetClosestDistance()
# let the controller know we've done this!
self.signalSwitchedToFreeCam.emit()
# It WBN to support marquee selection in the viewer also, at some point...
def mousePressEvent(self, event):
"""This widget claims the Alt modifier key as the enabler for camera
manipulation, and will consume mousePressEvents when Alt is present.
In any other modifier state, a mousePressEvent will result in a
pick operation, and the pressed button and active modifiers will be
made available to clients via a signalPrimSelected()."""
# It's important to set this first, since pickObject(), called below
# may produce the mouse-up event that will terminate the drag
# initiated by this mouse-press
self._dragActive = True
# Note: multiplying by devicePixelRatio is only necessary because this
# is a QGLWidget.
x = event.x() * self.devicePixelRatioF()
y = event.y() * self.devicePixelRatioF()
# Allow for either meta or alt key, since meta maps to Windows and Apple
# keys on various hardware/os combos, and some windowing systems consume
# one or the other by default, but hopefully not both.
if (event.modifiers() & (QtCore.Qt.AltModifier | QtCore.Qt.MetaModifier)):
if event.button() == QtCore.Qt.LeftButton:
self.switchToFreeCamera()
ctrlModifier = event.modifiers() & QtCore.Qt.ControlModifier
self._cameraMode = "truck" if ctrlModifier else "tumble"
if event.button() == QtCore.Qt.MidButton:
self.switchToFreeCamera()
self._cameraMode = "truck"
if event.button() == QtCore.Qt.RightButton:
self.switchToFreeCamera()
self._cameraMode = "zoom"
else:
self._cameraMode = "pick"
self.pickObject(x, y, event.button(), event.modifiers())
self._lastX = x
self._lastY = y
def mouseReleaseEvent(self, event):
self._cameraMode = "none"
self._dragActive = False
def mouseMoveEvent(self, event):
# Note: multiplying by devicePixelRatio is only necessary because this
# is a QGLWidget.
x = event.x() * self.devicePixelRatioF()
y = event.y() * self.devicePixelRatioF()
if self._dragActive:
dx = x - self._lastX
dy = y - self._lastY
if dx == 0 and dy == 0:
return
freeCam = self._dataModel.viewSettings.freeCamera
if self._cameraMode == "tumble":
freeCam.Tumble(0.25 * dx, 0.25*dy)
elif self._cameraMode == "zoom":
zoomDelta = -.002 * (dx + dy)
if freeCam.orthographic:
# orthographic cameras zoom by scaling fov
# fov is the height of the view frustum in world units
freeCam.fov *= (1 + zoomDelta)
else:
# perspective cameras dolly forward or back
freeCam.AdjustDistance(1 + zoomDelta)
elif self._cameraMode == "truck":
height = float(self.size().height())
pixelsToWorld = freeCam.ComputePixelsToWorldFactor(height)
self._dataModel.viewSettings.freeCamera.Truck(
-dx * pixelsToWorld,
dy * pixelsToWorld)
self._lastX = x
self._lastY = y
self.updateGL()
self.signalMouseDrag.emit()
elif self._cameraMode == "none":
# Mouse tracking is only enabled when rolloverPicking is enabled,
# and this function only gets called elsewise when mouse-tracking
# is enabled
self.pickObject(event.x(), event.y(), None, event.modifiers())
else:
event.ignore()
def wheelEvent(self, event):
self.switchToFreeCamera()
self._dataModel.viewSettings.freeCamera.AdjustDistance(
1-max(-0.5,min(0.5,(event.angleDelta().y()/1000.))))
self.updateGL()
def detachAndReClipFromCurrentCamera(self):
"""If we are currently rendering from a prim camera, switch to the
FreeCamera. Then reset the near/far clipping planes based on
distance to closest geometry."""
if not self._dataModel.viewSettings.freeCamera:
self.switchToFreeCamera()
else:
self.computeAndSetClosestDistance()
def computeAndSetClosestDistance(self):
'''Using the current FreeCamera's frustum, determine the world-space
closest rendered point to the camera. Use that point
to set our FreeCamera's closest visible distance.'''
# pick() operates at very low screen resolution, but that's OK for
# our purposes. Ironically, the same limited Z-buffer resolution for
# which we are trying to compensate may cause us to completely lose
# ALL of our geometry if we set the near-clip really small (which we
# want to do so we don't miss anything) when geometry is clustered
# closer to far-clip. So in the worst case, we may need to perform
# two picks, with the first pick() using a small near and far, and the
# second pick() using a near that keeps far within the safe precision
# range. We don't expect the worst-case to happen often.
if not self._dataModel.viewSettings.freeCamera:
return
cameraFrustum = self.resolveCamera()[0].frustum
trueFar = cameraFrustum.nearFar.max
smallNear = min(FreeCamera.defaultNear,
self._dataModel.viewSettings.freeCamera._selSize / 10.0)
cameraFrustum.nearFar = \
Gf.Range1d(smallNear, smallNear*FreeCamera.maxSafeZResolution)
pickResults = self.pick(cameraFrustum)
if pickResults[0] is None or pickResults[1] == Sdf.Path.emptyPath:
cameraFrustum.nearFar = \
Gf.Range1d(trueFar/FreeCamera.maxSafeZResolution, trueFar)
pickResults = self.pick(cameraFrustum)
if Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING):
print("computeAndSetClosestDistance: Needed to call pick() a second time")
if pickResults[0] is not None and pickResults[1] != Sdf.Path.emptyPath:
self._dataModel.viewSettings.freeCamera.setClosestVisibleDistFromPoint(pickResults[0])
self.updateView()
def pick(self, pickFrustum):
'''
Find closest point in scene rendered through 'pickFrustum'.
Returns a quintuple:
selectedPoint, selectedPrimPath, selectedInstancerPath,
selectedInstanceIndex, selectedInstancerContext
'''
renderer = self._getRenderer()
if not self._dataModel.stage or not renderer:
# error has already been issued
return None, Sdf.Path.emptyPath, None, None, None
# this import is here to make sure the create_first_image stat doesn't
# regress..
from OpenGL import GL
# Need a correct OpenGL Rendering context for FBOs
self.makeCurrent()
# update rendering parameters
self._renderParams.frame = self._dataModel.currentFrame
self._renderParams.complexity = self._dataModel.viewSettings.complexity.value
self._renderParams.drawMode = self._renderModeDict[self._dataModel.viewSettings.renderMode]
self._renderParams.showGuides = self._dataModel.viewSettings.displayGuide
self._renderParams.showProxy = self._dataModel.viewSettings.displayProxy
self._renderParams.showRender = self._dataModel.viewSettings.displayRender
self._renderParams.forceRefresh = self._forceRefresh
self._renderParams.cullStyle = \
(UsdImagingGL.CullStyle.CULL_STYLE_BACK_UNLESS_DOUBLE_SIDED
if self._dataModel.viewSettings.cullBackfaces
else UsdImagingGL.CullStyle.CULL_STYLE_NOTHING)
self._renderParams.gammaCorrectColors = False
self._renderParams.enableIdRender = True
self._renderParams.enableSampleAlphaToCoverage = False
self._renderParams.enableSceneMaterials = self._dataModel.viewSettings.enableSceneMaterials
results = renderer.TestIntersection(
pickFrustum.ComputeViewMatrix(),
pickFrustum.ComputeProjectionMatrix(),
self._dataModel.stage.GetPseudoRoot(), self._renderParams)
if Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING):
print("Pick results = {}".format(results))
return results
def computePickFrustum(self, x, y):
# compute pick frustum
(gfCamera, cameraAspect) = self.resolveCamera()
cameraFrustum = gfCamera.frustum
viewport = self.computeWindowViewport()
if self._cropImageToCameraViewport:
viewport = self.computeCameraViewport(cameraAspect)
# normalize position and pick size by the viewport size
point = Gf.Vec2d((x - viewport[0]) / float(viewport[2]),
(y - viewport[1]) / float(viewport[3]))
point[0] = (point[0] * 2.0 - 1.0)
point[1] = -1.0 * (point[1] * 2.0 - 1.0)
size = Gf.Vec2d(1.0 / viewport[2], 1.0 / viewport[3])
# "point" is normalized to the image viewport size, but if the image
# is cropped to the camera viewport, the image viewport won't fill the
# whole window viewport. Clicking outside the image will produce
# normalized coordinates > 1 or < -1; in this case, we should skip
# picking.
inImageBounds = (abs(point[0]) <= 1.0 and abs(point[1]) <= 1.0)
return (inImageBounds, cameraFrustum.ComputeNarrowedFrustum(point, size))
def pickObject(self, x, y, button, modifiers):
'''
Render stage into fbo with each piece as a different color.
Emits a signalPrimSelected or signalRollover depending on
whether 'button' is None.
'''
if not self._dataModel.stage:
return
renderer = self._getRenderer()
if not renderer:
# error has already been issued
return
try:
(inImageBounds, pickFrustum) = self.computePickFrustum(x,y)
if inImageBounds:
selectedPoint, selectedPrimPath, \
selectedInstanceIndex, selectedTLPath, selectedTLIndex = \
self.pick(pickFrustum)
else:
# If we're picking outside the image viewport (maybe because
# camera guides are on), treat that as a de-select.
selectedPoint, selectedPrimPath, \
selectedInstanceIndex, selectedTLPath, selectedTLIndex = \
None, Sdf.Path.emptyPath, -1, Sdf.Path.emptyPath, -1
# Correct for high DPI displays
coord = self._scaleMouseCoords( \
QtCore.QPoint(selectedPoint[0], selectedPoint[1]))
selectedPoint[0] = coord.x()
selectedPoint[1] = coord.y()
if button:
self.signalPrimSelected.emit(
selectedPrimPath, selectedInstanceIndex, selectedTLPath,
selectedTLIndex, selectedPoint, button, modifiers)
else:
self.signalPrimRollover.emit(
selectedPrimPath, selectedInstanceIndex, selectedTLPath,
selectedTLIndex, selectedPoint, modifiers)
except Tf.ErrorException as e:
# If we encounter an error, we want to continue running. Just log
# the error and continue.
sys.stderr.write(
"ERROR: Usdview encountered an error while picking."
"{}\n".format(e))
finally:
renderer = None
def glDraw(self):
# override glDraw so we can time it.
with Timer() as t:
QtOpenGL.QGLWidget.glDraw(self)
# Render creation is a deferred operation, so the render may not
# be initialized on entry to the function.
#
# This function itself can not create the render, as to create the
# renderer we need a valid GL context, which QT has not made current
# yet.
#
# So instead check that the render has been created after the fact.
# The point is to avoid reporting an invalid first image time.
if not self._renderer:
# error has already been issued
return
self._renderTime = t.interval
# If timings are being printed and this is the first time an image is
# being drawn, report how long it took to do so.
if self._printTiming and self._isFirstImage:
self._isFirstImage = False
t.PrintTime("create first image")
def SetForceRefresh(self, val):
self._forceRefresh = val or self._forceRefresh
def ExportFreeCameraToStage(self, stage, defcamName='usdviewCam',
imgWidth=None, imgHeight=None):
'''
Export the free camera to the specified USD stage, if it is
currently defined. If it is not active (i.e. we are viewing through
a stage camera), raise a ValueError.
'''
if not self._dataModel.viewSettings.freeCamera:
raise ValueError("StageView's Free Camera is not defined, so cannot"
" be exported")
imgWidth = imgWidth if imgWidth is not None else self.width()
imgHeight = imgHeight if imgHeight is not None else self.height()
defcam = UsdGeom.Camera.Define(stage, '/'+defcamName)
# Map free camera params to usd camera. We do **not** want to burn
# auto-clipping near/far into our exported camera
gfCamera = self._dataModel.viewSettings.freeCamera.computeGfCamera(self._bbox, autoClip=False)
targetAspect = float(imgWidth) / max(1.0, imgHeight)
CameraUtil.ConformWindow(
gfCamera, CameraUtil.MatchVertically, targetAspect)
when = (self._dataModel.currentFrame
if stage.HasAuthoredTimeCodeRange() else Usd.TimeCode.Default())
defcam.SetFromCamera(gfCamera, when)
def ExportSession(self, stagePath, defcamName='usdviewCam',
imgWidth=None, imgHeight=None):
'''
Export the free camera (if currently active) and session layer to a
USD file at the specified stagePath that references the current-viewed
stage.
'''
tmpStage = Usd.Stage.CreateNew(stagePath)
if self._dataModel.stage:
tmpStage.GetRootLayer().TransferContent(
self._dataModel.stage.GetSessionLayer())
if not self.cameraPrim:
# Export the free camera if it's the currently-visible camera
self.ExportFreeCameraToStage(tmpStage, defcamName, imgWidth,
imgHeight)
tmpStage.GetRootLayer().Save()
del tmpStage
# Reopen just the tmp layer, to sublayer in the pose cache without
# incurring Usd composition cost.
if self._dataModel.stage:
from pxr import Sdf
sdfLayer = Sdf.Layer.FindOrOpen(stagePath)
sdfLayer.subLayerPaths.append(
os.path.abspath(
self._dataModel.stage.GetRootLayer().realPath))
sdfLayer.Save()
def _primSelectionChanged(self):
# set highlighted paths to renderer
self.updateSelection()
self.update()
| 91,396 | Python | 38.531574 | 135 | 0.594687 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/__init__.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import sys, argparse, os
from .qt import QtWidgets, QtCore
from .common import Timer
from .appController import AppController
from pxr import UsdAppUtils, Tf
class InvalidUsdviewOption(Exception):
"""Raised when an invalid Usdview option is found in
Launcher.ValidateOptions or any methods which override it.
"""
pass
class Launcher(object):
'''
Base class for argument parsing, validation, and initialization for UsdView
Subclasses can choose to override
-- GetHelpDescription()
-- RegisterOptions()
-- ParseOptions()
-- ValidateOptions()
-- GetResolverContext()
'''
def __init__(self):
pass
def Run(self):
'''
The main entry point to launch a process using UsdView.
'''
parser = argparse.ArgumentParser(prog=sys.argv[0],
description=self.GetHelpDescription())
traceCollector = None
with Timer() as totalTimer:
self.RegisterPositionals(parser)
self.RegisterOptions(parser)
arg_parse_result = self.ParseOptions(parser)
self.ValidateOptions(arg_parse_result)
if arg_parse_result.traceToFile:
from pxr import Trace
traceCollector = Trace.Collector()
traceCollector.pythonTracingEnabled = True
traceCollector.enabled = True
self.__LaunchProcess(arg_parse_result)
if traceCollector:
traceCollector.enabled = False
if arg_parse_result.timing and arg_parse_result.quitAfterStartup:
totalTimer.PrintTime('open and close usdview')
if traceCollector:
if arg_parse_result.traceFormat == 'trace':
Trace.Reporter.globalReporter.Report(
arg_parse_result.traceToFile)
elif arg_parse_result.traceFormat == 'chrome':
Trace.Reporter.globalReporter.ReportChromeTracingToFile(
arg_parse_result.traceToFile)
else:
Tf.RaiseCodingError("Invalid trace format option provided: %s -"
"trace/chrome are the valid options" %
arg_parse_result.traceFormat)
def GetHelpDescription(self):
'''return the help description'''
return 'View a usd file'
def RegisterPositionals(self, parser):
'''
register positional arguments on the ArgParser
'''
parser.add_argument('usdFile', action='store',
type=str,
help='The file to view')
def RegisterOptions(self, parser):
'''
register optional arguments on the ArgParser
'''
from pxr import UsdUtils
parser.add_argument('--renderer', action='store',
type=str, dest='renderer',
choices=AppController.GetRendererOptionChoices(),
help="Which render backend to use (named as it "
"appears in the menu). Use '%s' to "
"turn off Hydra renderers." %
AppController.HYDRA_DISABLED_OPTION_STRING,
default='')
parser.add_argument('--select', action='store', default='/',
dest='primPath', type=str,
help='A prim path to initially select and frame')
UsdAppUtils.cameraArgs.AddCmdlineArgs(parser,
altHelpText=(
"Which camera to set the view to on open - may be given as "
"either just the camera's prim name (ie, just the last "
"element in the prim path), or as a full prim path. Note "
"that if only the prim name is used, and more than one camera "
"exists with the name, which is used will be effectively "
"random (default=%(default)s)"))
parser.add_argument('--mask', action='store',
dest='populationMask',
metavar='PRIMPATH[,PRIMPATH...]',
help='Limit stage population to these prims, '
'their descendants and ancestors. To specify '
'multiple paths, either use commas with no spaces '
'or quote the argument and separate paths by '
'commas and/or spaces.')
parser.add_argument('--clearsettings', action='store_true',
dest='clearSettings',
help='Restores usdview settings to default')
parser.add_argument('--defaultsettings', action='store_true',
dest='defaultSettings',
help='Launch usdview with default settings')
parser.add_argument('--norender', action='store_true',
dest='noRender',
help='Display only hierarchy browser')
parser.add_argument('--noplugins', action='store_true',
dest='noPlugins',
help='Do not load plugins')
parser.add_argument('--unloaded', action='store_true',
dest='unloaded',
help='Do not load payloads')
parser.add_argument('--timing', action='store_true',
dest='timing',
help='Echo timing stats to console. NOTE: timings will be unreliable when the --mallocTagStats option is also in use')
parser.add_argument('--traceToFile', action='store',
type=str,
dest='traceToFile',
default=None,
help='Start tracing at application startup and '
'write --traceFormat specified format output to the '
'specified trace file when the application quits')
parser.add_argument('--traceFormat', action='store',
type=str,
dest='traceFormat',
default='chrome',
choices=['chrome', 'trace'],
help='Output format for trace file specified by '
'--traceToFile. \'chrome\' files can be read in '
'chrome, \'trace\' files are simple text reports. '
'(default=%(default)s)')
parser.add_argument('--memstats', action='store', default='none',
dest='mallocTagStats', type=str,
choices=['none', 'stage', 'stageAndImaging'],
help='Use the Pxr MallocTags memory accounting system to profile USD, saving results to a tmp file, with a summary to the console. Will have no effect if MallocTags are not supported in the USD installation.')
parser.add_argument('--numThreads', action='store',
type=int, default=0,
help='Number of threads used for processing'
'(0 is max, negative numbers imply max - N)')
parser.add_argument('--ff', action='store',
dest='firstframe', type=int,
help='Set the first frame of the viewer')
parser.add_argument('--lf', action='store',
dest='lastframe', type=int,
help='Set the last frame of the viewer')
parser.add_argument('--cf', action='store',
dest='currentframe', type=int,
help='Set the current frame of the viewer')
UsdAppUtils.complexityArgs.AddCmdlineArgs(parser,
altHelpText=(
'Set the initial mesh refinement complexity (%(default)s).'))
parser.add_argument('--quitAfterStartup', action='store_true',
dest='quitAfterStartup',
help='quit immediately after start up')
parser.add_argument('--sessionLayer', default=None, type=str,
help= "If specified, the stage will be opened "
"with the 'sessionLayer' in place of the default "
"anonymous layer. As this changes the session "
"layer from anonymous to persistent, be "
"aware that layers saved from Export Overrides "
"will include the opinions in the persistent "
"session layer.")
def ParseOptions(self, parser):
'''
runs the parser on the arguments
'''
return parser.parse_args()
def ValidateOptions(self, arg_parse_result):
'''
Called by Run(), after ParseOptions() is called. Validates and
potentially modifies the parsed arguments. Raises InvalidUsdviewOption
if an invalid option is found. If a derived class has overridden
ParseOptions(), ValidateOptions() is an opportunity to process the
options and transmute other "core" options in response. If
overridden, derived classes should likely first call the base method.
'''
# split arg_parse_result.populationMask into paths.
if arg_parse_result.populationMask:
arg_parse_result.populationMask = (
arg_parse_result.populationMask.replace(',', ' ').split())
# Verify that the camera path is either an absolute path, or is just
# the name of a camera.
if arg_parse_result.camera:
camPath = arg_parse_result.camera
if camPath.isEmpty:
raise InvalidUsdviewOption(
"invalid camera path - %r" % camPath)
if not camPath.IsPrimPath():
raise InvalidUsdviewOption(
"invalid camera path - must be a raw prim path with no "
"variant selections or properties - got: %r" % camPath)
# If it's a multi-element path, make sure it is absolute.
if camPath.pathElementCount > 1:
if not camPath.IsAbsolutePath():
# perhaps we should error here? For now just pre-pending
# root, and printing warning...
from pxr import Sdf
print("WARNING: camera path %r was not absolute, prepending "
"%r to make it absolute" % (str(camPath),
str(Sdf.Path.absoluteRootPath)), file=sys.stderr)
arg_parse_result.camera = camPath.MakeAbsolutePath(
Sdf.Path.absoluteRootPath)
if arg_parse_result.clearSettings and arg_parse_result.defaultSettings:
raise InvalidUsdviewOption(
"cannot supply both --clearsettings and --defaultsettings.")
def GetResolverContext(self, usdFile):
"""
Create and return the ArResolverContext that will be used to Open
the Stage for the given usdFile. Base implementation
creates a default asset context for the usdFile asset, but derived
classes can do more sophisticated resolver and context configuration.
Will be called each time a new stage is opened.
It is not necessary to create an ArResolverContext for every UsdStage
one opens, as the Stage will use reasonable fallback behavior if no
context is provided. For usdview, configuring an asset context by
default is reasonable, and allows clients that embed usdview to
achieve different behavior when needed.
"""
from pxr import Ar
r = Ar.GetResolver()
r.ConfigureResolverForAsset(usdFile)
return r.CreateDefaultContextForAsset(usdFile)
def LaunchPreamble(self, arg_parse_result):
# Initialize concurrency limit as early as possible so that it is
# respected by subsequent imports.
from pxr import Work
Work.SetConcurrencyLimitArgument(arg_parse_result.numThreads)
if arg_parse_result.clearSettings:
AppController.clearSettings()
# Create the Qt application
app = QtWidgets.QApplication(sys.argv)
contextCreator = lambda usdFile: self.GetResolverContext(usdFile)
appController = AppController(arg_parse_result, contextCreator)
return (app, appController)
def __LaunchProcess(self, arg_parse_result):
'''
after the arguments have been parsed, launch the UI in a forked process
'''
# Initialize concurrency limit as early as possible so that it is
# respected by subsequent imports.
(app, appController) = self.LaunchPreamble(arg_parse_result)
if arg_parse_result.quitAfterStartup:
# Enqueue event to shutdown application. We don't use quit() because
# it doesn't trigger the closeEvent() on the main window which is
# used to orchestrate the shutdown.
QtCore.QTimer.singleShot(0, app.instance().closeAllWindows)
app.exec_()
| 14,564 | Python | 42.607784 | 238 | 0.572164 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/debugFlagsWidget.py | #
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from pxr import Tf
# Returns a list of debug flags whose names are prefixed by debugFlagPrefix
# followed by an '_'.
#
def _GetDebugFlagsWithPrefix(debugFlagPrefix):
debugFlagPrefix += "_"
return [flag for flag in Tf.Debug.GetDebugSymbolNames()
if flag.startswith(debugFlagPrefix)]
# Main DebugFlags editor widget
#
class DebugFlagsWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(DebugFlagsWidget, self).__init__(parent)
self.setObjectName("Debug Flags")
self.setMinimumSize(640, 300)
self._listView = QtWidgets.QListView()
self._tableWidget = QtWidgets.QTableWidget(0, 2)
# Configure and populate the left list view
self._listView.setEditTriggers(
QtWidgets.QAbstractItemView.NoEditTriggers)
self._populateDebugFlagsListView(self._listView)
self._listView.selectionModel().selectionChanged.connect(
self._onFlagSelectionChanged)
# Configure the table widget
self._tableWidget.horizontalHeader().setStretchLastSection(True)
self._tableWidget.horizontalHeader().setDefaultSectionSize(200)
self._tableWidget.setHorizontalHeaderLabels(
['Debug Symbol', 'Description'])
self._tableWidget.verticalHeader().hide()
self._tableWidget.itemClicked.connect(self._onDebugFlagChecked)
# Set the layout
lay = QtWidgets.QHBoxLayout()
lay.addWidget(self._listView, 0)
lay.addWidget(self._tableWidget, 1)
self.setLayout(lay)
def _populateDebugFlagsListView(self, listView):
allDebugFlags = Tf.Debug.GetDebugSymbolNames()
allDebugPrefixes = [ x[:x.find('_')] if x.find('_') > 0 else x
for x in allDebugFlags]
self._allDebugFlagPrefixes = list(sorted(set(allDebugPrefixes)))
listModel = QtCore.QStringListModel(self._allDebugFlagPrefixes)
listView.setModel(listModel)
def _populateDebugFlagsTableView(self, debugFlagPrefix):
debugFlags = _GetDebugFlagsWithPrefix(debugFlagPrefix)
self._tableWidget.setRowCount(len(debugFlags))
row = 0
for f in debugFlags:
item = QtWidgets.QTableWidgetItem()
item.setFlags(QtCore.Qt.ItemIsUserCheckable |
QtCore.Qt.ItemIsEnabled)
if Tf.Debug.IsDebugSymbolNameEnabled(f):
item.setCheckState(QtCore.Qt.Checked)
else:
item.setCheckState(QtCore.Qt.Unchecked)
item.setText(f)
self._tableWidget.setItem(row, 0, item)
item = QtWidgets.QTableWidgetItem()
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
item.setText(Tf.Debug.GetDebugSymbolDescription(f))
self._tableWidget.setItem(row, 1, item)
row += 1
def _onFlagSelectionChanged(self, selected, deselected):
if len(selected.indexes()) > 0:
self._populateDebugFlagsTableView(self._allDebugFlagPrefixes[
selected.indexes()[0].row()])
def _onDebugFlagChecked(self, item):
value = (item.checkState() == QtCore.Qt.Checked)
Tf.Debug.SetDebugSymbolsByName(item.text(), value)
| 4,363 | Python | 36.947826 | 75 | 0.678891 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primLegend.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtWidgets
from .primLegendUI import Ui_PrimLegend
from .common import (UIPrimTypeColors,
ColorizeLabelText, BoldenLabelText, ItalicizeLabelText)
class PrimLegend(QtWidgets.QWidget):
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self._ui = Ui_PrimLegend()
self._ui.setupUi(self)
# start out in a minimized/hidden state
self.setMaximumHeight(0)
self._isMinimized = True
graphicsScene = QtWidgets.QGraphicsScene()
# Set colors
self._ui.primLegendColorHasArcs.setScene(graphicsScene)
self._ui.primLegendColorNormal.setScene(graphicsScene)
self._ui.primLegendColorInstance.setScene(graphicsScene)
self._ui.primLegendColorMaster.setScene(graphicsScene)
self._ui.primLegendColorHasArcs.setForegroundBrush(UIPrimTypeColors.HAS_ARCS)
self._ui.primLegendColorNormal.setForegroundBrush(UIPrimTypeColors.NORMAL)
self._ui.primLegendColorInstance.setForegroundBrush(UIPrimTypeColors.INSTANCE)
self._ui.primLegendColorMaster.setForegroundBrush(UIPrimTypeColors.MASTER)
legendTextUpdate = lambda t, c: (('<font color=\"%s\">' % c.color().name())
+ t.text() + '</font>')
normalLegend = self._ui.primLegendLabelNormal
normalLegend.setText(legendTextUpdate(normalLegend, UIPrimTypeColors.NORMAL))
masterLegend = self._ui.primLegendLabelMaster
masterLegend.setText(legendTextUpdate(masterLegend, UIPrimTypeColors.MASTER))
instanceLegend = self._ui.primLegendLabelInstance
instanceLegend.setText(legendTextUpdate(instanceLegend, UIPrimTypeColors.INSTANCE))
hasArcsLegend = self._ui.primLegendLabelHasArcs
hasArcsLegend.setText(legendTextUpdate(hasArcsLegend, UIPrimTypeColors.HAS_ARCS))
undefinedFontLegend = self._ui.primLegendLabelFontsUndefined
undefinedFontLegend.setText(ItalicizeLabelText(undefinedFontLegend.text(),
undefinedFontLegend.text()))
definedFontLegend = self._ui.primLegendLabelFontsDefined
definedFontLegend.setText(BoldenLabelText(definedFontLegend.text(),
definedFontLegend.text()))
# Set three individual colors in the text line to indicate
# the dimmed version of each primary prim color
dimmedLegend = self._ui.primLegendLabelDimmed
dimmedLegendText = dimmedLegend.text()
dimmedLegendText = ColorizeLabelText(
dimmedLegendText, "Dimmed colors", 148, 105, 30)
dimmedLegendText = ColorizeLabelText(
dimmedLegendText, "denote", 78, 91, 145)
dimmedLegendText = ColorizeLabelText(
dimmedLegendText, "inactive prims", 151, 151, 151)
dimmedLegend.setText(dimmedLegendText)
def IsMinimized(self):
return self._isMinimized
def ToggleMinimized(self):
self._isMinimized = not self._isMinimized
def GetHeight(self):
return self.height()
def GetResetHeight(self):
return self.sizeHint().height()
| 4,258 | Python | 41.59 | 91 | 0.700798 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/arrayAttributeView.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
def _GetLengthOfRange(start, stop, step):
if step == 0:
return 0
k = 1 if step > 0 else -1
num = 1 + (stop - k - start) // step
# note, sign(stop - start) != sign(step) when we have an empty range. In those
# cases, "num" ends up non-positive, so we can just take the max(num, 0)
return max(0, num)
class _ArrayAttributeModel(QtCore.QAbstractListModel):
'''This is a data model that represents a slice into some array data.
'''
RawDataRole = QtCore.Qt.UserRole + 0
def __init__(self):
super(_ArrayAttributeModel, self).__init__()
self._arrayData = None
self._scalarTypeName = ""
self._slice = slice(None)
self._fetchMoreTimer = QtCore.QTimer()
self._fetchMoreTimer.setInterval(1000)
self._fetchMoreTimer.timeout.connect(self.TryToFetchMore)
self._fetchMoreTimer.start()
self._rowCount = 0
self._publishedRows = 0
def SetArrayDataAndTypeName(self, arrayData, scalarTypeName):
self._arrayData = arrayData
self._scalarTypeName = scalarTypeName
self._Reset()
def SetSlice(self, slice_):
if self._slice == slice_:
return
self._slice = slice_
self._Reset()
def _Reset(self):
self._publishedRows = 0
self._rowCount = 0
if self._arrayData is not None:
self._rowCount = _GetLengthOfRange(*self._slice.indices(len(self._arrayData)))
self.modelReset.emit()
def GetArrayData(self):
return self._arrayData
def GetScalarTypeName(self):
return self._scalarTypeName
def index(self, row, col, parent=QtCore.QModelIndex()):
return self.createIndex(row, col)
def parent(self, index):
return QtCore.QModelIndex()
def rowCount(self, parent=QtCore.QModelIndex()):
if not parent.isValid():
return self._publishedRows
return 0
def columnCount(self, parent=QtCore.QModelIndex()):
return 1
def data(self, index, role=QtCore.Qt.DisplayRole):
start, _, step = self._slice.indices(len(self._arrayData))
idx = start + index.row() * step
dataVal = self._arrayData[idx]
if role == QtCore.Qt.DisplayRole:
from .scalarTypes import ToString
return str(idx) + ": " + ToString(
dataVal, self._scalarTypeName)
elif role == _ArrayAttributeModel.RawDataRole:
return dataVal
return None
def fetchMore(self, index):
left = self._rowCount - self._publishedRows
toFetch = min(5000 if self._publishedRows == 0 else 100, left)
self.beginInsertRows(
index, self._publishedRows, self._publishedRows + toFetch - 1)
self._publishedRows += toFetch
self.endInsertRows()
def canFetchMore(self, index):
return self._publishedRows < self._rowCount
def TryToFetchMore(self):
rootIndex = QtCore.QModelIndex()
if self.canFetchMore(rootIndex):
self.fetchMore(rootIndex)
class ArrayAttributeView(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ArrayAttributeView, self).__init__(parent)
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
sliceLayout = QtWidgets.QHBoxLayout()
layout.addLayout(sliceLayout)
sliceLayout.addWidget(QtWidgets.QLabel("Slice:"))
self._lineEdit = _SliceLineEdit()
self._lineEdit.setPlaceholderText('e.g.: "0:5000", "::-1"')
sliceLayout.addWidget(self._lineEdit)
self._arrayAttrModel = _ArrayAttributeModel()
self._listView = QtWidgets.QListView()
self._listView.setUniformItemSizes(True)
self._listView.setViewMode(QtWidgets.QListView.ListMode)
self._listView.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self._listView.setModel(self._arrayAttrModel)
layout.addWidget(self._listView)
self._lineEdit.SliceChanged.connect(self._arrayAttrModel.SetSlice)
self._SetupContextMenu()
def SetAttribute(self, attr, frame):
from .scalarTypes import GetScalarTypeFromAttr
arrayData = attr.Get(frame)
scalarTypeName, _ = GetScalarTypeFromAttr(attr)
self._arrayAttrModel.SetArrayDataAndTypeName(arrayData, scalarTypeName)
def CanView(self, attr):
return attr.GetTypeName().isArray
def keyPressEvent(self, e):
# XXX note, this is extremely finicky. it does not really
# have keyboard focus.
if e.matches(QtGui.QKeySequence.Copy):
self.Copy()
else:
return super(ArrayAttributeView, self).keyPressEvent(e)
# context menu stuff
def _SetupContextMenu(self):
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self._ShowContextMenu)
def _ShowContextMenu(self, point):
menu = QtWidgets.QMenu(self)
if self._listView.selectedIndexes():
menu.addAction("Copy Selected", self.CopySelected)
else:
menu.addAction("Copy All", self.CopyAll)
menu.addAction("Select All", self.SelectAll)
menu.exec_(QtGui.QCursor.pos())
def CopyAll(self):
self._CopyValsToClipboard(self._arrayAttrModel.GetArrayData())
def CopySelected(self):
selectedIndexes = self._listView.selectedIndexes()
self._CopyValsToClipboard([
self._listView.model().data(idx, _ArrayAttributeModel.RawDataRole)
for idx in selectedIndexes])
def _CopyValsToClipboard(self, vals):
from .scalarTypes import ToClipboard
scalarTypeName = self._arrayAttrModel.GetScalarTypeName()
copyText = "[ %s ]" % (", ".join(
ToClipboard(val, scalarTypeName)
for val in vals))
QtWidgets.QApplication.clipboard().setText(copyText)
def SelectAll(self):
self._listView.selectAll()
def _IntOrNone(s):
if not s:
return None
return int(s)
def _GetSliceFromString(s):
s = slice(*map(_IntOrNone, s.split(':')))
if s.step == 0:
raise ValueError("Slice cannot be 0")
return s
class _SliceLineEdit(QtWidgets.QLineEdit):
"""LineEdit for inputing strings that represent slices"""
SliceChanged = QtCore.Signal(object)
def __init__(self, parent=None):
super(_SliceLineEdit, self).__init__(parent)
self.setValidator(_SliceLineEdit.Validator())
self.editingFinished.connect(self._OnEditingFinished)
class Validator(QtGui.QValidator):
def validate(self, s, pos):
s = s.strip()
try:
_GetSliceFromString(s)
return (QtGui.QValidator.Acceptable, s, pos)
except:
return (QtGui.QValidator.Intermediate, s, pos)
def setText(self, t):
super(_SliceLineEdit, self).setText(t)
self._OnEditingFinished()
def _OnEditingFinished(self):
self.SliceChanged.emit(_GetSliceFromString(self.text()))
| 8,189 | Python | 32.292683 | 90 | 0.651728 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/scalarTypes.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
def GetScalarTypeFromAttr(attr):
'''
returns the (scalar, isArray) where isArray is True if it was an array type
'''
# Usd.Attribute and customAttributes.CustomAttribute have a
# GetTypeName function, while Sdf.AttributeSpec has a typeName attr.
if hasattr(attr, 'GetTypeName'):
typeName = attr.GetTypeName()
elif hasattr(attr, 'typeName'):
typeName = attr.typeName
else:
typeName = ""
from pxr import Sdf
if isinstance(typeName, Sdf.ValueTypeName):
return typeName.scalarType, typeName.isArray
else:
return None, False
_toStringFnCache = {}
def ToString(v, valueType=None):
"""Returns a string representing a "detailed view" of the value v.
This string is used in the watch window"""
from pxr import Tf, Gf
global _toStringFnCache
# Check cache.
t = type(v)
cacheKey = (t, valueType)
fn = _toStringFnCache.get(cacheKey)
if fn:
return fn(v)
# Cache miss. Compute string typeName for the given value
# using the given valueType as a hint.
typeName = ""
from pxr import Sdf
if isinstance(valueType, Sdf.ValueTypeName):
tfType = valueType.type
else:
tfType = Tf.Type.Find(t)
if tfType != Tf.Type.Unknown:
typeName = tfType.typeName
# Pretty-print "None"
if v is None:
fn = lambda _: 'None'
# Pretty-print a bounding box
elif isinstance(v, Gf.BBox3d):
def bboxToString(v):
prettyMatrix = (
"%s\n%s\n%s\n%s" %
(v.matrix[0], v.matrix[1],
v.matrix[2], v.matrix[3])).replace("(","").replace(")","")
result = ("Endpts of box diagonal:\n"
"%s\n%s\n\nTransform matrix:\n%s\n"
% (v.box.GetCorner(0), v.box.GetCorner(7), prettyMatrix))
if (v.hasZeroAreaPrimitives):
result += "\nHas zero-area primitives\n"
else:
result += "\nDoes not have zero-area primitives\n"
worldSpaceRange = Gf.Range3d()
worldSpaceRange.UnionWith(v.matrix.Transform(v.GetRange().GetMin()))
worldSpaceRange.UnionWith(v.matrix.Transform(v.GetRange().GetMax()))
result += "\nWorld-space range:\n%s\n%s\n" % \
(worldSpaceRange.GetMin(), worldSpaceRange.GetMax())
return result
fn = lambda b: bboxToString(b)
# Pretty-print a GfMatrix*
elif typeName.startswith("GfMatrix"):
def matrixToString(v):
result = ""
numRows = int(typeName[8])
for i in range(numRows):
result += str(v[i]) + "\n"
result = result.replace("(","").replace(")","")
return result
fn = lambda m: matrixToString(m)
# Pretty-print a GfVec* or a GfRange*
elif typeName.startswith("GfVec") or typeName.startswith("GfRange"):
fn = lambda v: str(v)
# pretty print an int
elif isinstance(v, int):
fn = lambda i: "{:,d}".format(i)
# pretty print a float
elif isinstance(v, float):
fn = lambda f: "{:,.6f}".format(f)
# print a string as-is
elif isinstance(v, str):
fn = lambda s: s
else:
import pprint
fn = lambda v: pprint.pformat(v)
# Populate cache and invoke function to produce the string.
_toStringFnCache[cacheKey] = fn
return fn(v)
def ToClipboard(v, typeName=None):
# XXX: we can have this give you the repr
return ToString(v, typeName)
| 4,632 | Python | 32.572464 | 80 | 0.622409 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/preferencesUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'preferencesUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_Preferences(object):
def setupUi(self, Preferences):
if not Preferences.objectName():
Preferences.setObjectName(u"Preferences")
Preferences.resize(295, 99)
self.verticalLayout = QVBoxLayout(Preferences)
self.verticalLayout.setObjectName(u"verticalLayout")
self.prefsOverButtonsLayout = QVBoxLayout()
self.prefsOverButtonsLayout.setObjectName(u"prefsOverButtonsLayout")
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.fontSizeLabel = QLabel(Preferences)
self.fontSizeLabel.setObjectName(u"fontSizeLabel")
self.horizontalLayout_3.addWidget(self.fontSizeLabel)
self.fontSizeSpinBox = QSpinBox(Preferences)
self.fontSizeSpinBox.setObjectName(u"fontSizeSpinBox")
self.fontSizeSpinBox.setMinimum(6)
self.fontSizeSpinBox.setValue(10)
self.horizontalLayout_3.addWidget(self.fontSizeSpinBox)
self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(self.horizontalSpacer_2)
self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_3)
self.verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.prefsOverButtonsLayout.addItem(self.verticalSpacer)
self.line = QFrame(Preferences)
self.line.setObjectName(u"line")
self.line.setFrameShape(QFrame.HLine)
self.line.setFrameShadow(QFrame.Sunken)
self.prefsOverButtonsLayout.addWidget(self.line)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer)
self.buttonBox = QDialogButtonBox(Preferences)
self.buttonBox.setObjectName(u"buttonBox")
self.buttonBox.setStandardButtons(QDialogButtonBox.Apply|QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
self.horizontalLayout_2.addWidget(self.buttonBox)
self.prefsOverButtonsLayout.addLayout(self.horizontalLayout_2)
self.verticalLayout.addLayout(self.prefsOverButtonsLayout)
self.retranslateUi(Preferences)
QMetaObject.connectSlotsByName(Preferences)
# setupUi
def retranslateUi(self, Preferences):
Preferences.setWindowTitle(QCoreApplication.translate("Preferences", u"Preferences", None))
Preferences.setProperty("comment", QCoreApplication.translate("Preferences", u"\n"
" Copyright 2020 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
self.fontSizeLabel.setText(QCoreApplication.translate("Preferences", u"Font Size", None))
# retranslateUi
| 5,326 | Python | 47.427272 | 109 | 0.58374 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/appController.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
# Qt Components
from .qt import QtCore, QtGui, QtWidgets
# Stdlib components
import re, sys, os, cProfile, pstats, traceback
from itertools import groupby
from time import time, sleep
from collections import deque, OrderedDict
from functools import cmp_to_key
# Usd Library Components
from pxr import Usd, UsdGeom, UsdShade, UsdUtils, UsdImagingGL, Glf, Sdf, Tf, Ar
from pxr import UsdAppUtils
from pxr.UsdAppUtils.complexityArgs import RefinementComplexities
# UI Components
from ._usdviewq import Utils
from .stageView import StageView
from .mainWindowUI import Ui_MainWindow
from .primContextMenu import PrimContextMenu
from .headerContextMenu import HeaderContextMenu
from .layerStackContextMenu import LayerStackContextMenu
from .attributeViewContextMenu import AttributeViewContextMenu
from .customAttributes import (_GetCustomAttributes, CustomAttribute,
BoundingBoxAttribute, LocalToWorldXformAttribute,
ResolvedBoundMaterial)
from .primTreeWidget import PrimTreeWidget, PrimViewColumnIndex
from .primViewItem import PrimViewItem
from .variantComboBox import VariantComboBox
from .legendUtil import ToggleLegendWithBrowser
from . import prettyPrint, adjustClipping, adjustDefaultMaterial, preferences, settings
from .constantGroup import ConstantGroup
from .selectionDataModel import ALL_INSTANCES, SelectionDataModel
# Common Utilities
from .common import (UIBaseColors, UIPropertyValueSourceColors, UIFonts,
GetPropertyColor, GetPropertyTextFont,
Timer, Drange, BusyContext, DumpMallocTags,
GetValueAndDisplayString, ResetSessionVisibility,
InvisRootPrims, GetAssetCreationTime,
PropertyViewIndex, PropertyViewIcons, PropertyViewDataRoles,
RenderModes, ColorCorrectionModes, ShadedRenderModes,
PickModes, SelectionHighlightModes, CameraMaskModes,
PropTreeWidgetTypeIsRel, PrimNotFoundException,
GetRootLayerStackInfo, HasSessionVis, GetEnclosingModelPrim,
GetPrimsLoadability, ClearColors,
HighlightColors, KeyboardShortcuts)
from . import settings2
from .settings2 import StateSource
from .usdviewApi import UsdviewApi
from .rootDataModel import RootDataModel, ChangeNotice
from .viewSettingsDataModel import ViewSettingsDataModel
from . import plugin
from .pythonInterpreter import Myconsole
SETTINGS_VERSION = "1"
class HUDEntries(ConstantGroup):
# Upper HUD entries (declared in variables for abstraction)
PRIM = "Prims"
CV = "CVs"
VERT = "Verts"
FACE = "Faces"
# Lower HUD entries
PLAYBACK = "Playback"
RENDER = "Render"
GETBOUNDS = "BBox"
# Name for prims that have no type
NOTYPE = "Typeless"
class PropertyIndex(ConstantGroup):
VALUE, METADATA, LAYERSTACK, COMPOSITION = range(4)
class UIDefaults(ConstantGroup):
STAGE_VIEW_WIDTH = 604
PRIM_VIEW_WIDTH = 521
ATTRIBUTE_VIEW_WIDTH = 682
ATTRIBUTE_INSPECTOR_WIDTH = 443
TOP_HEIGHT = 538
BOTTOM_HEIGHT = 306
# Name of the Qt binding being used
QT_BINDING = QtCore.__name__.split('.')[0]
class UsdviewDataModel(RootDataModel):
def __init__(self, printTiming, settings2):
super(UsdviewDataModel, self).__init__(printTiming)
self._selectionDataModel = SelectionDataModel(self)
self._viewSettingsDataModel = ViewSettingsDataModel(self, settings2)
@property
def selection(self):
return self._selectionDataModel
@property
def viewSettings(self):
return self._viewSettingsDataModel
def _emitPrimsChanged(self, primChange, propertyChange):
# Override from base class: before alerting listening controllers,
# ensure our owned selectionDataModel is updated
if primChange == ChangeNotice.RESYNC:
self.selection.removeUnpopulatedPrims()
super(UsdviewDataModel, self)._emitPrimsChanged(primChange,
propertyChange)
class UIStateProxySource(StateSource):
"""XXX Temporary class which allows AppController to serve as two state sources.
All fields here will be moved back into AppController in the future.
"""
def __init__(self, mainWindow, parent, name):
StateSource.__init__(self, parent, name)
self._mainWindow = mainWindow
primViewColumnVisibility = self.stateProperty("primViewColumnVisibility",
default=[True, True, True, False], validator=lambda value:
len(value) == 4)
propertyViewColumnVisibility = self.stateProperty("propertyViewColumnVisibility",
default=[True, True, True], validator=lambda value: len(value) == 3)
attributeInspectorCurrentTab = self.stateProperty("attributeInspectorCurrentTab", default=PropertyIndex.VALUE)
# UI is different when --norender is used so just save the default splitter sizes.
# TODO Save the loaded state so it doesn't disappear after using --norender.
if not self._mainWindow._noRender:
stageViewWidth = self.stateProperty("stageViewWidth", default=UIDefaults.STAGE_VIEW_WIDTH)
primViewWidth = self.stateProperty("primViewWidth", default=UIDefaults.PRIM_VIEW_WIDTH)
attributeViewWidth = self.stateProperty("attributeViewWidth", default=UIDefaults.ATTRIBUTE_VIEW_WIDTH)
attributeInspectorWidth = self.stateProperty("attributeInspectorWidth", default=UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH)
topHeight = self.stateProperty("topHeight", default=UIDefaults.TOP_HEIGHT)
bottomHeight = self.stateProperty("bottomHeight", default=UIDefaults.BOTTOM_HEIGHT)
viewerMode = self.stateProperty("viewerMode", default=False)
if viewerMode:
self._mainWindow._ui.primStageSplitter.setSizes([0, 1])
self._mainWindow._ui.topBottomSplitter.setSizes([1, 0])
else:
self._mainWindow._ui.primStageSplitter.setSizes(
[primViewWidth, stageViewWidth])
self._mainWindow._ui.topBottomSplitter.setSizes(
[topHeight, bottomHeight])
self._mainWindow._ui.attribBrowserInspectorSplitter.setSizes(
[attributeViewWidth, attributeInspectorWidth])
self._mainWindow._viewerModeEscapeSizes = topHeight, bottomHeight, primViewWidth, stageViewWidth
else:
self._mainWindow._ui.primStageSplitter.setSizes(
[UIDefaults.PRIM_VIEW_WIDTH, UIDefaults.STAGE_VIEW_WIDTH])
self._mainWindow._ui.attribBrowserInspectorSplitter.setSizes(
[UIDefaults.ATTRIBUTE_VIEW_WIDTH, UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH])
self._mainWindow._ui.topBottomSplitter.setSizes(
[UIDefaults.TOP_HEIGHT, UIDefaults.BOTTOM_HEIGHT])
for i, visible in enumerate(primViewColumnVisibility):
self._mainWindow._ui.primView.setColumnHidden(i, not visible)
for i, visible in enumerate(propertyViewColumnVisibility):
self._mainWindow._ui.propertyView.setColumnHidden(i, not visible)
propertyIndex = attributeInspectorCurrentTab
if propertyIndex not in PropertyIndex:
propertyIndex = PropertyIndex.VALUE
self._mainWindow._ui.propertyInspector.setCurrentIndex(propertyIndex)
def onSaveState(self, state):
# UI is different when --norender is used so don't load the splitter sizes.
if not self._mainWindow._noRender:
primViewWidth, stageViewWidth = self._mainWindow._ui.primStageSplitter.sizes()
attributeViewWidth, attributeInspectorWidth = self._mainWindow._ui.attribBrowserInspectorSplitter.sizes()
topHeight, bottomHeight = self._mainWindow._ui.topBottomSplitter.sizes()
viewerMode = (bottomHeight == 0 and primViewWidth == 0)
# If viewer mode is active, save the escape sizes instead of the
# actual sizes. If there are no escape sizes, just save the defaults.
if viewerMode:
if self._mainWindow._viewerModeEscapeSizes is not None:
topHeight, bottomHeight, primViewWidth, stageViewWidth = self._mainWindow._viewerModeEscapeSizes
else:
primViewWidth = UIDefaults.STAGE_VIEW_WIDTH
stageViewWidth = UIDefaults.PRIM_VIEW_WIDTH
attributeViewWidth = UIDefaults.ATTRIBUTE_VIEW_WIDTH
attributeInspectorWidth = UIDefaults.ATTRIBUTE_INSPECTOR_WIDTH
topHeight = UIDefaults.TOP_HEIGHT
bottomHeight = UIDefaults.BOTTOM_HEIGHT
state["primViewWidth"] = primViewWidth
state["stageViewWidth"] = stageViewWidth
state["attributeViewWidth"] = attributeViewWidth
state["attributeInspectorWidth"] = attributeInspectorWidth
state["topHeight"] = topHeight
state["bottomHeight"] = bottomHeight
state["viewerMode"] = viewerMode
state["primViewColumnVisibility"] = [
not self._mainWindow._ui.primView.isColumnHidden(c)
for c in range(self._mainWindow._ui.primView.columnCount())]
state["propertyViewColumnVisibility"] = [
not self._mainWindow._ui.propertyView.isColumnHidden(c)
for c in range(self._mainWindow._ui.propertyView.columnCount())]
state["attributeInspectorCurrentTab"] = self._mainWindow._ui.propertyInspector.currentIndex()
class Blocker:
"""Object which can be used to temporarily block the execution of a body of
code. This object is a context manager, and enters a 'blocked' state when
used in a 'with' statement. The 'blocked()' method can be used to find if
the Blocker is in this 'blocked' state.
For example, this is used to prevent UI code from handling signals from the
selection data model while the UI code itself modifies selection.
"""
def __init__(self):
# A count is used rather than a 'blocked' flag to allow for nested
# blocking.
self._count = 0
def __enter__(self):
"""Enter the 'blocked' state until the context is exited."""
self._count += 1
def __exit__(self, *args):
"""Exit the 'blocked' state."""
self._count -= 1
def blocked(self):
"""Returns True if in the 'blocked' state, and False otherwise."""
return self._count > 0
class MainWindow(QtWidgets.QMainWindow):
"This class exists to simplify and streamline the shutdown process."
"The application may be closed via the File menu, or by closing the main"
"window, both of which result in the same behavior."
def __init__(self, closeFunc):
super(MainWindow, self).__init__(None) # no parent widget
self._closeFunc = closeFunc
def closeEvent(self, event):
self._closeFunc()
class AppController(QtCore.QObject):
HYDRA_DISABLED_OPTION_STRING = "HydraDisabled"
###########
# Signals #
###########
@classmethod
def clearSettings(cls):
settingsPath = cls._outputBaseDirectory()
if settingsPath is None:
return None
else:
settingsPath = os.path.join(settingsPath, 'state')
if not os.path.exists(settingsPath):
print('INFO: ClearSettings requested, but there '
'were no settings currently stored.')
return None
if not os.access(settingsPath, os.W_OK):
print('ERROR: Could not remove settings file.')
return None
else:
os.remove(settingsPath)
print('INFO: Settings restored to default.')
def _configurePlugins(self):
with Timer() as t:
self._plugRegistry = plugin.loadPlugins(
self._usdviewApi, self._mainWindow)
if self._printTiming:
t.PrintTime("configure and load plugins.")
def _openSettings2(self, defaultSettings):
settingsPathDir = self._outputBaseDirectory()
if (settingsPathDir is None) or defaultSettings:
# Create an ephemeral settings object by withholding the file path.
self._settings2 = settings2.Settings(SETTINGS_VERSION)
else:
settings2Path = os.path.join(settingsPathDir, "state.json")
self._settings2 = settings2.Settings(SETTINGS_VERSION, settings2Path)
def _setStyleSheetUsingState(self):
# We use a style file that is actually a template, which we fill
# in from state, and is how we change app font sizes, for example.
# Find the resource directory
resourceDir = os.path.dirname(os.path.realpath(__file__)) + "/"
# Qt style sheet accepts only forward slashes as path separators
resourceDir = resourceDir.replace("\\", "/")
fontSize = self._dataModel.viewSettings.fontSize
baseFontSizeStr = "%spt" % str(fontSize)
# The choice of 8 for smallest smallSize is for performance reasons,
# based on the "Gotham Rounded" font used by usdviewstyle.qss . If we
# allow it to float, we get a 2-3 hundred millisecond hit in startup
# time as Qt (apparently) manufactures a suitably sized font.
# Mysteriously, we don't see this cost for larger font sizes.
smallSize = 8 if fontSize < 12 else int(round(fontSize * 0.8))
smallFontSizeStr = "%spt" % str(smallSize)
# Apply the style sheet to it
sheet = open(os.path.join(resourceDir, 'usdviewstyle.qss'), 'r')
sheetString = sheet.read() % {
'RESOURCE_DIR' : resourceDir,
'BASE_FONT_SZ' : baseFontSizeStr,
'SMALL_FONT_SZ' : smallFontSizeStr }
app = QtWidgets.QApplication.instance()
app.setStyleSheet(sheetString)
def __del__(self):
# This is needed to free Qt items before exit; Qt hits failed GTK
# assertions without it.
self._primToItemMap.clear()
def __init__(self, parserData, resolverContextFn):
QtCore.QObject.__init__(self)
with Timer() as uiOpenTimer:
self._primToItemMap = {}
self._itemsToPush = []
self._currentSpec = None
self._currentLayer = None
self._console = None
self._debugFlagsWindow = None
self._interpreter = None
self._parserData = parserData
self._noRender = parserData.noRender
self._noPlugins = parserData.noPlugins
self._unloaded = parserData.unloaded
self._resolverContextFn = resolverContextFn
self._debug = os.getenv('USDVIEW_DEBUG', False)
self._printTiming = parserData.timing or self._debug
self._lastViewContext = {}
self._paused = False
self._stopped = False
if QT_BINDING == 'PySide':
self._statusFileName = 'state'
self._deprecatedStatusFileNames = ('.usdviewrc')
else:
self._statusFileName = 'state.%s'%QT_BINDING
self._deprecatedStatusFileNames = ('state', '.usdviewrc')
self._mallocTags = parserData.mallocTagStats
self._allowViewUpdates = True
# When viewer mode is active, the panel sizes are cached so they can
# be restored later.
self._viewerModeEscapeSizes = None
self._rendererNameOpt = parserData.renderer
if self._rendererNameOpt:
if self._rendererNameOpt == \
AppController.HYDRA_DISABLED_OPTION_STRING:
os.environ['HD_ENABLED'] = '0'
else:
os.environ['HD_DEFAULT_RENDERER'] = self._rendererNameOpt
self._openSettings2(parserData.defaultSettings)
self._dataModel = UsdviewDataModel(
self._printTiming, self._settings2)
# Now that we've read in our state and applied parserData
# overrides, we can process our styleSheet... *before* we
# start listening for style-related changes.
self._setStyleSheetUsingState()
self._mainWindow = MainWindow(lambda: self._cleanAndClose())
self._ui = Ui_MainWindow()
self._ui.setupUi(self._mainWindow)
self._mainWindow.setWindowTitle(parserData.usdFile)
self._statusBar = QtWidgets.QStatusBar(self._mainWindow)
self._mainWindow.setStatusBar(self._statusBar)
# Waiting to show the mainWindow till after setting the
# statusBar saves considerable GUI configuration time.
self._mainWindow.show()
self._mainWindow.setFocus()
# Install our custom event filter. The member assignment of the
# filter is just for lifetime management
from .appEventFilter import AppEventFilter
self._filterObj = AppEventFilter(self)
QtWidgets.QApplication.instance().installEventFilter(self._filterObj)
# Setup Usdview API and optionally load plugins. We do this before
# loading the stage in case a plugin wants to modify global settings
# that affect stage loading.
self._plugRegistry = None
self._usdviewApi = UsdviewApi(self)
if not self._noPlugins:
self._configurePlugins()
# read the stage here
stage = self._openStage(
self._parserData.usdFile, self._parserData.sessionLayer,
self._parserData.populationMask)
if not stage:
sys.exit(0)
if not stage.GetPseudoRoot():
print(parserData.usdFile, 'has no prims; exiting.')
sys.exit(0)
# We instantiate a UIStateProxySource only for its side-effects
uiProxy = UIStateProxySource(self, self._settings2, "ui")
self._dataModel.stage = stage
self._primViewSelectionBlocker = Blocker()
self._propertyViewSelectionBlocker = Blocker()
self._dataModel.selection.signalPrimSelectionChanged.connect(
self._primSelectionChanged)
self._dataModel.selection.signalPropSelectionChanged.connect(
self._propSelectionChanged)
self._dataModel.selection.signalComputedPropSelectionChanged.connect(
self._propSelectionChanged)
self._initialSelectPrim = self._dataModel.stage.GetPrimAtPath(
parserData.primPath)
if not self._initialSelectPrim:
print('Could not find prim at path <%s> to select. '\
'Ignoring...' % parserData.primPath)
self._initialSelectPrim = None
try:
self._dataModel.viewSettings.complexity = parserData.complexity
except ValueError:
fallback = RefinementComplexities.LOW
sys.stderr.write(("Error: Invalid complexity '{}'. "
"Using fallback '{}' instead.\n").format(
parserData.complexity, fallback.id))
self._dataModel.viewSettings.complexity = fallback
self._hasPrimResync = False
self._timeSamples = None
self._stageView = None
self._startingPrimCamera = None
if (parserData.camera.IsAbsolutePath() or
parserData.camera.pathElementCount > 1):
self._startingPrimCameraName = None
self._startingPrimCameraPath = parserData.camera
else:
self._startingPrimCameraName = parserData.camera.pathString
self._startingPrimCameraPath = None
settingsPathDir = self._outputBaseDirectory()
if settingsPathDir is None or parserData.defaultSettings:
# Create an ephemeral settings object with a non existent filepath
self._settings = settings.Settings('', seq=None, ephemeral=True)
else:
settingsPath = os.path.join(settingsPathDir, self._statusFileName)
for deprecatedName in self._deprecatedStatusFileNames:
deprecatedSettingsPath = \
os.path.join(settingsPathDir, deprecatedName)
if (os.path.isfile(deprecatedSettingsPath) and
not os.path.isfile(settingsPath)):
warning = ('\nWARNING: The settings file at: '
+ str(deprecatedSettingsPath) + ' is deprecated.\n'
+ 'These settings are not being used, the new '
+ 'settings file will be located at: '
+ str(settingsPath) + '.\n')
print(warning)
break
self._settings = settings.Settings(settingsPath)
try:
self._settings.load()
except IOError:
# try to force out a new settings file
try:
self._settings.save()
except:
settings.EmitWarning(settingsPath)
except EOFError:
# try to force out a new settings file
try:
self._settings.save()
except:
settings.EmitWarning(settingsPath)
except:
settings.EmitWarning(settingsPath)
self._dataModel.viewSettings.signalStyleSettingsChanged.connect(
self._setStyleSheetUsingState)
self._dataModel.signalPrimsChanged.connect(
self._onPrimsChanged)
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
self._timer = QtCore.QTimer(self)
# Timeout interval in ms. We set it to 0 so it runs as fast as
# possible. In advanceFrameForPlayback we use the sleep() call
# to slow down rendering to self.framesPerSecond fps.
self._timer.setInterval(0)
self._lastFrameTime = time()
# Initialize the upper HUD info
self._upperHUDInfo = dict()
# declare dictionary keys for the fps info too
self._fpsHUDKeys = (HUDEntries.RENDER, HUDEntries.PLAYBACK)
# Initialize fps HUD with empty strings
self._fpsHUDInfo = dict(zip(self._fpsHUDKeys,
["N/A", "N/A"]))
self._startTime = self._endTime = time()
# This timer is used to coalesce the primView resizes
# in certain cases. e.g. When you
# deactivate/activate a prim.
self._primViewResizeTimer = QtCore.QTimer(self)
self._primViewResizeTimer.setInterval(0)
self._primViewResizeTimer.setSingleShot(True)
self._primViewResizeTimer.timeout.connect(self._resizePrimView)
# This timer coalesces GUI resets when the USD stage is modified or
# reloaded.
self._guiResetTimer = QtCore.QTimer(self)
self._guiResetTimer.setInterval(0)
self._guiResetTimer.setSingleShot(True)
self._guiResetTimer.timeout.connect(self._resetGUI)
# Idle timer to push off-screen data to the UI.
self._primViewUpdateTimer = QtCore.QTimer(self)
self._primViewUpdateTimer.setInterval(0)
self._primViewUpdateTimer.timeout.connect(self._updatePrimView)
# This creates the _stageView and restores state from settings file
self._resetSettings()
# This is for validating frame values input on the "Frame" line edit
validator = QtGui.QDoubleValidator(self)
self._ui.frameField.setValidator(validator)
self._ui.rangeEnd.setValidator(validator)
self._ui.rangeBegin.setValidator(validator)
stepValidator = QtGui.QDoubleValidator(self)
stepValidator.setRange(0.01, 1e7, 2)
self._ui.stepSize.setValidator(stepValidator)
# This causes the last column of the attribute view (the value)
# to be stretched to fill the available space
self._ui.propertyView.header().setStretchLastSection(True)
self._ui.propertyView.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
self._ui.primView.setSelectionBehavior(
QtWidgets.QAbstractItemView.SelectRows)
# This allows ctrl and shift clicking for multi-selecting
self._ui.propertyView.setSelectionMode(
QtWidgets.QAbstractItemView.ExtendedSelection)
self._ui.propertyView.setHorizontalScrollMode(
QtWidgets.QAbstractItemView.ScrollPerPixel)
self._ui.frameSlider.setTracking(
self._dataModel.viewSettings.redrawOnScrub)
self._ui.colorGroup = QtWidgets.QActionGroup(self)
self._ui.colorGroup.setExclusive(True)
self._clearColorActions = (
self._ui.actionBlack,
self._ui.actionGrey_Dark,
self._ui.actionGrey_Light,
self._ui.actionWhite)
for action in self._clearColorActions:
self._ui.colorGroup.addAction(action)
self._ui.renderModeActionGroup = QtWidgets.QActionGroup(self)
self._ui.renderModeActionGroup.setExclusive(True)
self._renderModeActions = (
self._ui.actionWireframe,
self._ui.actionWireframeOnSurface,
self._ui.actionSmooth_Shaded,
self._ui.actionFlat_Shaded,
self._ui.actionPoints,
self._ui.actionGeom_Only,
self._ui.actionGeom_Smooth,
self._ui.actionGeom_Flat,
self._ui.actionHidden_Surface_Wireframe)
for action in self._renderModeActions:
self._ui.renderModeActionGroup.addAction(action)
self._ui.colorCorrectionActionGroup = QtWidgets.QActionGroup(self)
self._ui.colorCorrectionActionGroup.setExclusive(True)
self._colorCorrectionActions = (
self._ui.actionNoColorCorrection,
self._ui.actionSRGBColorCorrection,
self._ui.actionOpenColorIO)
for action in self._colorCorrectionActions:
self._ui.colorCorrectionActionGroup.addAction(action)
# XXX This should be a validator in ViewSettingsDataModel.
if self._dataModel.viewSettings.renderMode not in RenderModes:
fallback = str(
self._ui.renderModeActionGroup.actions()[0].text())
print("Warning: Unknown render mode '%s', falling back to '%s'" % (
self._dataModel.viewSettings.renderMode, fallback))
self._dataModel.viewSettings.renderMode = fallback
self._ui.pickModeActionGroup = QtWidgets.QActionGroup(self)
self._ui.pickModeActionGroup.setExclusive(True)
self._pickModeActions = (
self._ui.actionPick_Prims,
self._ui.actionPick_Models,
self._ui.actionPick_Instances,
self._ui.actionPick_Prototypes)
for action in self._pickModeActions:
self._ui.pickModeActionGroup.addAction(action)
# XXX This should be a validator in ViewSettingsDataModel.
if self._dataModel.viewSettings.pickMode not in PickModes:
fallback = str(self._ui.pickModeActionGroup.actions()[0].text())
print("Warning: Unknown pick mode '%s', falling back to '%s'" % (
self._dataModel.viewSettings.pickMode, fallback))
self._dataModel.viewSettings.pickMode = fallback
self._ui.selHighlightModeActionGroup = QtWidgets.QActionGroup(self)
self._ui.selHighlightModeActionGroup.setExclusive(True)
self._selHighlightActions = (
self._ui.actionNever,
self._ui.actionOnly_when_paused,
self._ui.actionAlways)
for action in self._selHighlightActions:
self._ui.selHighlightModeActionGroup.addAction(action)
self._ui.highlightColorActionGroup = QtWidgets.QActionGroup(self)
self._ui.highlightColorActionGroup.setExclusive(True)
self._selHighlightColorActions = (
self._ui.actionSelYellow,
self._ui.actionSelCyan,
self._ui.actionSelWhite)
for action in self._selHighlightColorActions:
self._ui.highlightColorActionGroup.addAction(action)
self._ui.interpolationActionGroup = QtWidgets.QActionGroup(self)
self._ui.interpolationActionGroup.setExclusive(True)
for interpolationType in Usd.InterpolationType.allValues:
action = self._ui.menuInterpolation.addAction(interpolationType.displayName)
action.setCheckable(True)
action.setChecked(
self._dataModel.stage.GetInterpolationType() == interpolationType)
self._ui.interpolationActionGroup.addAction(action)
self._ui.primViewDepthGroup = QtWidgets.QActionGroup(self)
for i in range(1, 9):
action = getattr(self._ui, "actionLevel_" + str(i))
self._ui.primViewDepthGroup.addAction(action)
# setup animation objects for the primView and propertyView
self._propertyLegendAnim = QtCore.QPropertyAnimation(
self._ui.propertyLegendContainer, b"maximumHeight")
self._primLegendAnim = QtCore.QPropertyAnimation(
self._ui.primLegendContainer, b"maximumHeight")
# set the context menu policy for the prim browser and attribute
# inspector headers. This is so we can have a context menu on the
# headers that allows you to select which columns are visible.
self._ui.propertyView.header()\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self._ui.primView.header()\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Set custom context menu for attribute browser
self._ui.propertyView\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Set custom context menu for layer stack browser
self._ui.layerStackView\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Set custom context menu for composition tree browser
self._ui.compositionTreeWidget\
.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
# Arc path is the most likely to need stretch.
twh = self._ui.compositionTreeWidget.header()
twh.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
twh.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
twh.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
twh.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
# Set the prim view header to have a fixed size type and vis columns
nvh = self._ui.primView.header()
nvh.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
nvh.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
nvh.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
nvh.resizeSection(3, 116)
nvh.setSectionResizeMode(3, QtWidgets.QHeaderView.Fixed)
pvh = self._ui.propertyView.header()
pvh.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
pvh.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
pvh.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
# XXX:
# To avoid QTBUG-12850 (https://bugreports.qt.io/browse/QTBUG-12850),
# we force the horizontal scrollbar to always be visible for all
# QTableWidget widgets in use.
self._ui.primView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.propertyView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.metadataView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.layerStackView.setHorizontalScrollBarPolicy(
QtCore.Qt.ScrollBarAlwaysOn)
self._ui.attributeValueEditor.setAppController(self)
self._ui.primView.InitControllers(self)
self._ui.currentPathWidget.editingFinished.connect(
self._currentPathChanged)
# XXX:
# To avoid PYSIDE-79 (https://bugreports.qt.io/browse/PYSIDE-79)
# with Qt4/PySide, we must hold the prim view's selectionModel
# in a local variable before connecting its signals.
primViewSelModel = self._ui.primView.selectionModel()
primViewSelModel.selectionChanged.connect(self._selectionChanged)
self._ui.primView.itemClicked.connect(self._itemClicked)
self._ui.primView.itemPressed.connect(self._itemPressed)
self._ui.primView.header().customContextMenuRequested.connect(
self._primViewHeaderContextMenu)
self._timer.timeout.connect(self._advanceFrameForPlayback)
self._ui.primView.customContextMenuRequested.connect(
self._primViewContextMenu)
self._ui.primView.expanded.connect(self._primViewExpanded)
self._ui.frameSlider.valueChanged.connect(self._setFrameIndex)
self._ui.frameSlider.sliderMoved.connect(self._sliderMoved)
self._ui.frameSlider.sliderReleased.connect(self._updateGUIForFrameChange)
self._ui.frameField.editingFinished.connect(self._frameStringChanged)
self._ui.rangeBegin.editingFinished.connect(self._rangeBeginChanged)
self._ui.stepSize.editingFinished.connect(self._stepSizeChanged)
self._ui.rangeEnd.editingFinished.connect(self._rangeEndChanged)
self._ui.actionFrame_Forward.triggered.connect(self._advanceFrame)
self._ui.actionFrame_Backwards.triggered.connect(self._retreatFrame)
self._ui.actionReset_View.triggered.connect(lambda: self._resetView())
self._ui.topBottomSplitter.splitterMoved.connect(self._cacheViewerModeEscapeSizes)
self._ui.primStageSplitter.splitterMoved.connect(self._cacheViewerModeEscapeSizes)
self._ui.actionToggle_Viewer_Mode.triggered.connect(
self._toggleViewerMode)
self._ui.showBBoxes.triggered.connect(self._toggleShowBBoxes)
self._ui.showAABBox.triggered.connect(self._toggleShowAABBox)
self._ui.showOBBox.triggered.connect(self._toggleShowOBBox)
self._ui.showBBoxPlayback.triggered.connect(
self._toggleShowBBoxPlayback)
self._ui.useExtentsHint.triggered.connect(self._setUseExtentsHint)
self._ui.showInterpreter.triggered.connect(self._showInterpreter)
self._ui.showDebugFlags.triggered.connect(self._showDebugFlags)
self._ui.redrawOnScrub.toggled.connect(self._redrawOptionToggled)
if self._stageView:
self._ui.actionAuto_Compute_Clipping_Planes.triggered.connect(
self._toggleAutoComputeClippingPlanes)
self._ui.actionAdjust_Clipping.triggered[bool].connect(
self._adjustClippingPlanes)
self._ui.actionAdjust_Default_Material.triggered[bool].connect(
self._adjustDefaultMaterial)
self._ui.actionPreferences.triggered[bool].connect(
self._togglePreferences)
self._ui.actionOpen.triggered.connect(self._openFile)
self._ui.actionSave_Overrides_As.triggered.connect(
self._saveOverridesAs)
self._ui.actionSave_Flattened_As.triggered.connect(
self._saveFlattenedAs)
self._ui.actionPause.triggered.connect(
self._togglePause)
self._ui.actionStop.triggered.connect(
self._toggleStop)
# Typically, a handler is registered to the 'aboutToQuit' signal
# to handle cleanup. However, with PySide2, stageView's GL context
# is destroyed by then, making it too late in the shutdown process
# to release any GL resources used by the renderer (relevant for
# Storm's GL renderer).
# To work around this, orchestrate shutdown via the main window's
# closeEvent() handler.
self._ui.actionQuit.triggered.connect(QtWidgets.QApplication.instance().closeAllWindows)
# To measure Qt shutdown time, register a handler to stop the timer.
QtWidgets.QApplication.instance().aboutToQuit.connect(self._stopQtShutdownTimer)
self._ui.actionReopen_Stage.triggered.connect(self._reopenStage)
self._ui.actionReload_All_Layers.triggered.connect(self._reloadStage)
self._ui.actionToggle_Framed_View.triggered.connect(self._toggleFramedView)
self._ui.actionAdjust_FOV.triggered.connect(self._adjustFOV)
self._ui.complexityGroup = QtWidgets.QActionGroup(self._mainWindow)
self._ui.complexityGroup.setExclusive(True)
self._complexityActions = (
self._ui.actionLow,
self._ui.actionMedium,
self._ui.actionHigh,
self._ui.actionVery_High)
for action in self._complexityActions:
self._ui.complexityGroup.addAction(action)
self._ui.complexityGroup.triggered.connect(self._changeComplexity)
self._ui.actionDisplay_Guide.triggered.connect(
self._toggleDisplayGuide)
self._ui.actionDisplay_Proxy.triggered.connect(
self._toggleDisplayProxy)
self._ui.actionDisplay_Render.triggered.connect(
self._toggleDisplayRender)
self._ui.actionDisplay_Camera_Oracles.triggered.connect(
self._toggleDisplayCameraOracles)
self._ui.actionDisplay_PrimId.triggered.connect(
self._toggleDisplayPrimId)
self._ui.actionEnable_Scene_Materials.triggered.connect(
self._toggleEnableSceneMaterials)
self._ui.actionCull_Backfaces.triggered.connect(
self._toggleCullBackfaces)
self._ui.propertyInspector.currentChanged.connect(
self._updatePropertyInspector)
self._ui.propertyView.itemSelectionChanged.connect(
self._propertyViewSelectionChanged)
self._ui.propertyView.currentItemChanged.connect(
self._propertyViewCurrentItemChanged)
self._ui.propertyView.header().customContextMenuRequested.\
connect(self._propertyViewHeaderContextMenu)
self._ui.propertyView.customContextMenuRequested.connect(
self._propertyViewContextMenu)
self._ui.layerStackView.customContextMenuRequested.connect(
self._layerStackContextMenu)
self._ui.compositionTreeWidget.customContextMenuRequested.connect(
self._compositionTreeContextMenu)
self._ui.compositionTreeWidget.currentItemChanged.connect(
self._onCompositionSelectionChanged)
self._ui.renderModeActionGroup.triggered.connect(self._changeRenderMode)
self._ui.colorCorrectionActionGroup.triggered.connect(
self._changeColorCorrection)
self._ui.pickModeActionGroup.triggered.connect(self._changePickMode)
self._ui.selHighlightModeActionGroup.triggered.connect(
self._changeSelHighlightMode)
self._ui.highlightColorActionGroup.triggered.connect(
self._changeHighlightColor)
self._ui.interpolationActionGroup.triggered.connect(
self._changeInterpolationType)
self._ui.actionAmbient_Only.triggered[bool].connect(
self._ambientOnlyClicked)
self._ui.actionDomeLight.triggered[bool].connect(self._onDomeLightClicked)
self._ui.colorGroup.triggered.connect(self._changeBgColor)
# Configuring the PrimView's Show menu. In addition to the
# "designed" menu items, we inject a PrimView HeaderContextMenu
self._ui.primViewDepthGroup.triggered.connect(self._changePrimViewDepth)
self._ui.actionExpand_All.triggered.connect(
lambda: self._expandToDepth(1000000))
self._ui.actionCollapse_All.triggered.connect(
self._ui.primView.collapseAll)
self._ui.actionShow_Inactive_Prims.triggered.connect(
self._toggleShowInactivePrims)
self._ui.actionShow_All_Master_Prims.triggered.connect(
self._toggleShowMasterPrims)
self._ui.actionShow_Undefined_Prims.triggered.connect(
self._toggleShowUndefinedPrims)
self._ui.actionShow_Abstract_Prims.triggered.connect(
self._toggleShowAbstractPrims)
# Since setting column visibility is probably not a common
# operation, it's actually good to have Columns at the end.
self._ui.menuShow.addSeparator()
self._ui.menuShow.addMenu(HeaderContextMenu(self._ui.primView))
self._ui.actionRollover_Prim_Info.triggered.connect(
self._toggleRolloverPrimInfo)
self._ui.primViewLineEdit.returnPressed.connect(
self._ui.primViewFindNext.click)
self._ui.primViewFindNext.clicked.connect(self._primViewFindNext)
self._ui.attrViewLineEdit.returnPressed.connect(
self._ui.attrViewFindNext.click)
self._ui.attrViewFindNext.clicked.connect(self._attrViewFindNext)
self._ui.primLegendQButton.clicked.connect(
self._primLegendToggleCollapse)
self._ui.propertyLegendQButton.clicked.connect(
self._propertyLegendToggleCollapse)
self._ui.playButton.clicked.connect(self._playClicked)
self._ui.actionCameraMask_Full.triggered.connect(
self._updateCameraMaskMenu)
self._ui.actionCameraMask_Partial.triggered.connect(
self._updateCameraMaskMenu)
self._ui.actionCameraMask_None.triggered.connect(
self._updateCameraMaskMenu)
self._ui.actionCameraMask_Outline.triggered.connect(
self._updateCameraMaskOutlineMenu)
self._ui.actionCameraMask_Color.triggered.connect(
self._pickCameraMaskColor)
self._ui.actionCameraReticles_Inside.triggered.connect(
self._updateCameraReticlesInsideMenu)
self._ui.actionCameraReticles_Outside.triggered.connect(
self._updateCameraReticlesOutsideMenu)
self._ui.actionCameraReticles_Color.triggered.connect(
self._pickCameraReticlesColor)
self._ui.actionHUD.triggered.connect(self._showHUDChanged)
self._ui.actionHUD_Info.triggered.connect(self._showHUD_InfoChanged)
self._ui.actionHUD_Complexity.triggered.connect(
self._showHUD_ComplexityChanged)
self._ui.actionHUD_Performance.triggered.connect(
self._showHUD_PerformanceChanged)
self._ui.actionHUD_GPUstats.triggered.connect(
self._showHUD_GPUstatsChanged)
self._mainWindow.addAction(self._ui.actionIncrementComplexity1)
self._mainWindow.addAction(self._ui.actionIncrementComplexity2)
self._mainWindow.addAction(self._ui.actionDecrementComplexity)
self._ui.actionIncrementComplexity1.triggered.connect(
self._incrementComplexity)
self._ui.actionIncrementComplexity2.triggered.connect(
self._incrementComplexity)
self._ui.actionDecrementComplexity.triggered.connect(
self._decrementComplexity)
self._ui.attributeValueEditor.editComplete.connect(self.editComplete)
# Edit Prim menu
self._ui.menuEdit.aboutToShow.connect(self._updateEditMenu)
self._ui.menuNavigation.aboutToShow.connect(self._updateNavigationMenu)
self._ui.actionFind_Prims.triggered.connect(
self._ui.primViewLineEdit.setFocus)
self._ui.actionSelect_Stage_Root.triggered.connect(
self.selectPseudoroot)
self._ui.actionSelect_Model_Root.triggered.connect(
self.selectEnclosingModel)
self._ui.actionSelect_Bound_Preview_Material.triggered.connect(
self.selectBoundPreviewMaterial)
self._ui.actionSelect_Bound_Full_Material.triggered.connect(
self.selectBoundFullMaterial)
self._ui.actionSelect_Preview_Binding_Relationship.triggered.connect(
self.selectPreviewBindingRel)
self._ui.actionSelect_Full_Binding_Relationship.triggered.connect(
self.selectFullBindingRel)
self._ui.actionMake_Visible.triggered.connect(self.visSelectedPrims)
# Add extra, Presto-inspired shortcut for Make Visible
self._ui.actionMake_Visible.setShortcuts(["Shift+H", "Ctrl+Shift+H"])
self._ui.actionMake_Invisible.triggered.connect(self.invisSelectedPrims)
self._ui.actionVis_Only.triggered.connect(self.visOnlySelectedPrims)
self._ui.actionRemove_Session_Visibility.triggered.connect(
self.removeVisSelectedPrims)
self._ui.actionReset_All_Session_Visibility.triggered.connect(
self.resetSessionVisibility)
self._ui.actionLoad.triggered.connect(self.loadSelectedPrims)
self._ui.actionUnload.triggered.connect(self.unloadSelectedPrims)
self._ui.actionActivate.triggered.connect(self.activateSelectedPrims)
self._ui.actionDeactivate.triggered.connect(self.deactivateSelectedPrims)
# We refresh as if all view settings changed. In the future, we
# should do more granular refreshes. This first requires more
# granular signals from ViewSettingsDataModel.
self._dataModel.viewSettings.signalSettingChanged.connect(
self._viewSettingChanged)
# Update view menu actions and submenus with initial state.
self._refreshViewMenubar()
# We manually call processEvents() here to make sure that the prim
# browser and other widgetry get drawn before we draw the first image in
# the viewer, which might take a long time.
if self._stageView:
self._stageView.setUpdatesEnabled(False)
self._mainWindow.update()
QtWidgets.QApplication.processEvents()
if self._printTiming:
uiOpenTimer.PrintTime('bring up the UI')
self._drawFirstImage()
QtWidgets.QApplication.restoreOverrideCursor()
def _drawFirstImage(self):
if self._stageView:
self._stageView.setUpdatesEnabled(True)
with BusyContext():
try:
self._resetView(self._initialSelectPrim)
except Exception:
pass
QtWidgets.QApplication.processEvents()
# configure render plugins after stageView initialized its renderer.
self._configureRendererPlugins()
self._configureColorManagement()
if self._mallocTags == 'stageAndImaging':
DumpMallocTags(self._dataModel.stage,
"stage-loading and imaging")
def statusMessage(self, msg, timeout = 0):
self._statusBar.showMessage(msg, timeout * 1000)
def editComplete(self, msg):
title = self._mainWindow.windowTitle()
if title[-1] != '*':
self._mainWindow.setWindowTitle(title + ' *')
self.statusMessage(msg, 12)
with Timer() as t:
if self._stageView:
self._stageView.updateView(resetCam=False, forceComputeBBox=True)
if self._printTiming:
t.PrintTime("'%s'" % msg)
def _openStage(self, usdFilePath, sessionFilePath, populationMaskPaths):
def _GetFormattedError(reasons=None):
err = ("Error: Unable to open stage '{0}'\n".format(usdFilePath))
if reasons:
err += "\n".join(reasons) + "\n"
return err
if not Ar.GetResolver().Resolve(usdFilePath):
sys.stderr.write(_GetFormattedError(["File not found"]))
sys.exit(1)
if self._mallocTags != 'none':
Tf.MallocTag.Initialize()
with Timer() as t:
loadSet = Usd.Stage.LoadNone if self._unloaded else Usd.Stage.LoadAll
popMask = (None if populationMaskPaths is None else
Usd.StagePopulationMask())
# Open as a layer first to make sure its a valid file format
try:
layer = Sdf.Layer.FindOrOpen(usdFilePath)
except Tf.ErrorException as e:
sys.stderr.write(_GetFormattedError(
[err.commentary.strip() for err in e.args]))
sys.exit(1)
if sessionFilePath:
try:
sessionLayer = Sdf.Layer.Find(sessionFilePath)
if sessionLayer:
sessionLayer.Reload()
else:
sessionLayer = Sdf.Layer.FindOrOpen(sessionFilePath)
except Tf.ErrorException as e:
sys.stderr.write(_GetFormattedError(
[err.commentary.strip() for err in e.args]))
sys.exit(1)
else:
sessionLayer = Sdf.Layer.CreateAnonymous()
if popMask:
for p in populationMaskPaths:
popMask.Add(p)
stage = Usd.Stage.OpenMasked(layer,
sessionLayer,
self._resolverContextFn(usdFilePath),
popMask, loadSet)
else:
stage = Usd.Stage.Open(layer,
sessionLayer,
self._resolverContextFn(usdFilePath),
loadSet)
if not stage:
sys.stderr.write(_GetFormattedError())
else:
if self._printTiming:
t.PrintTime('open stage "%s"' % usdFilePath)
stage.SetEditTarget(stage.GetSessionLayer())
if self._mallocTags == 'stage':
DumpMallocTags(stage, "stage-loading")
return stage
def _closeStage(self):
# Close the USD stage.
if self._stageView:
self._stageView.closeRenderer()
self._dataModel.stage = None
def _startQtShutdownTimer(self):
self._qtShutdownTimer = Timer()
self._qtShutdownTimer.__enter__()
def _stopQtShutdownTimer(self):
self._qtShutdownTimer.__exit__()
if self._printTiming:
self._qtShutdownTimer.PrintTime('tear down the UI')
def _setPlayShortcut(self):
self._ui.playButton.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Space))
# Non-topology dependent UI changes
def _reloadFixedUI(self, resetStageDataOnly=False):
# If animation is playing, stop it.
if self._dataModel.playing:
self._ui.playButton.click()
# frame range supplied by user
ff = self._parserData.firstframe
lf = self._parserData.lastframe
# frame range supplied by stage
stageStartTimeCode = self._dataModel.stage.GetStartTimeCode()
stageEndTimeCode = self._dataModel.stage.GetEndTimeCode()
# final range results
self.realStartTimeCode = None
self.realEndTimeCode = None
self.framesPerSecond = self._dataModel.stage.GetFramesPerSecond()
if self.framesPerSecond < 1:
err = ("Error: Invalid value for field framesPerSecond of %.2f. Using default value of 24 \n" % self.framesPerSecond)
sys.stderr.write(err)
self.statusMessage(err)
self.framesPerSecond = 24.0
if not resetStageDataOnly:
self.step = self._dataModel.stage.GetTimeCodesPerSecond() / self.framesPerSecond
self._ui.stepSize.setText(str(self.step))
# if one option is provided(lastframe or firstframe), we utilize it
if ff is not None and lf is not None:
self.realStartTimeCode = ff
self.realEndTimeCode = lf
elif ff is not None:
self.realStartTimeCode = ff
self.realEndTimeCode = stageEndTimeCode
elif lf is not None:
self.realStartTimeCode = stageStartTimeCode
self.realEndTimeCode = lf
elif self._dataModel.stage.HasAuthoredTimeCodeRange():
self.realStartTimeCode = stageStartTimeCode
self.realEndTimeCode = stageEndTimeCode
self._ui.stageBegin.setText(str(stageStartTimeCode))
self._ui.stageEnd.setText(str(stageEndTimeCode))
# Use a valid current frame supplied by user, or allow _UpdateTimeSamples
# to set the current frame.
cf = self._parserData.currentframe
if cf:
if (cf < self.realStartTimeCode or cf > self.realEndTimeCode):
sys.stderr.write('Warning: Invalid current frame specified (%s)\n' % (cf))
else:
self._dataModel.currentFrame = Usd.TimeCode(cf)
self._UpdateTimeSamples(resetStageDataOnly)
def _UpdateTimeSamples(self, resetStageDataOnly=False):
if self.realStartTimeCode is not None and self.realEndTimeCode is not None:
if self.realStartTimeCode > self.realEndTimeCode:
sys.stderr.write('Warning: Invalid frame range (%s, %s)\n'
% (self.realStartTimeCode, self.realEndTimeCode))
self._timeSamples = []
else:
self._timeSamples = Drange(self.realStartTimeCode,
self.realEndTimeCode,
self.step)
else:
self._timeSamples = []
self._geomCounts = dict()
self._hasTimeSamples = (len(self._timeSamples) > 0)
self._setPlaybackAvailability() # this sets self._playbackAvailable
if self._hasTimeSamples:
self._ui.rangeBegin.setText(str(self._timeSamples[0]))
self._ui.rangeEnd.setText(str(self._timeSamples[-1]))
if ( self._dataModel.currentFrame.IsDefault() or
self._dataModel.currentFrame < self._timeSamples[0] ):
self._dataModel.currentFrame = Usd.TimeCode(self._timeSamples[0])
if self._dataModel.currentFrame > self._timeSamples[-1]:
self._dataModel.currentFrame = Usd.TimeCode(self._timeSamples[-1])
else:
self._dataModel.currentFrame = Usd.TimeCode(0.0)
if not resetStageDataOnly:
self._ui.frameField.setText(
str(self._dataModel.currentFrame.GetValue()))
if self._playbackAvailable:
if not resetStageDataOnly:
self._ui.frameSlider.setRange(0, len(self._timeSamples) - 1)
self._ui.frameSlider.setValue(0)
self._setPlayShortcut()
self._ui.playButton.setCheckable(True)
# Ensure the play button state respects the current playback state
self._ui.playButton.setChecked(self._dataModel.playing)
def _clearCaches(self, preserveCamera=False):
"""Clears value and computation caches maintained by the controller.
Does NOT initiate any GUI updates"""
self._geomCounts = dict()
self._dataModel._clearCaches()
self._refreshCameraListAndMenu(preserveCurrCamera = preserveCamera)
@staticmethod
def GetRendererOptionChoices():
ids = UsdImagingGL.Engine.GetRendererPlugins()
choices = []
if ids:
choices = [UsdImagingGL.Engine.GetRendererDisplayName(x)
for x in ids]
choices.append(AppController.HYDRA_DISABLED_OPTION_STRING)
else:
choices = [AppController.HYDRA_DISABLED_OPTION_STRING]
return choices
# Render plugin support
def _rendererPluginChanged(self, plugin):
if self._stageView:
if not self._stageView.SetRendererPlugin(plugin):
# If SetRendererPlugin failed, we need to reset the check mark
# to whatever the currently loaded renderer is.
for action in self._ui.rendererPluginActionGroup.actions():
if action.text() == self._stageView.rendererDisplayName:
action.setChecked(True)
break
# Then display an error message to let the user know something
# went wrong, and disable the menu item so it can't be selected
# again.
for action in self._ui.rendererPluginActionGroup.actions():
if action.pluginType == plugin:
self.statusMessage(
'Renderer not supported: %s' % action.text())
action.setText(action.text() + " (unsupported)")
action.setDisabled(True)
break
else:
# Refresh the AOV menu, settings menu, and pause menu item
self._configureRendererAovs()
self._configureRendererSettings()
self._configurePauseAction()
self._configureStopAction()
def _configureRendererPlugins(self):
if self._stageView:
self._ui.rendererPluginActionGroup = QtWidgets.QActionGroup(self)
self._ui.rendererPluginActionGroup.setExclusive(True)
pluginTypes = self._stageView.GetRendererPlugins()
for pluginType in pluginTypes:
name = self._stageView.GetRendererDisplayName(pluginType)
action = self._ui.menuRendererPlugin.addAction(name)
action.setCheckable(True)
action.pluginType = pluginType
self._ui.rendererPluginActionGroup.addAction(action)
action.triggered[bool].connect(lambda _, pluginType=pluginType:
self._rendererPluginChanged(pluginType))
# Now set the checked box on the current renderer (it should
# have been set by now).
currentRendererId = self._stageView.GetCurrentRendererId()
foundPlugin = False
for action in self._ui.rendererPluginActionGroup.actions():
if action.pluginType == currentRendererId:
action.setChecked(True)
foundPlugin = True
break
# Disable the menu if no plugins were found
self._ui.menuRendererPlugin.setEnabled(foundPlugin)
# Refresh the AOV menu, settings menu, and pause menu item
self._configureRendererAovs()
self._configureRendererSettings()
self._configurePauseAction()
self._configureStopAction()
# Renderer AOV support
def _rendererAovChanged(self, aov):
if self._stageView:
self._stageView.SetRendererAov(aov)
self._ui.aovOtherAction.setText("Other...")
def _configureRendererAovs(self):
if self._stageView:
self._ui.rendererAovActionGroup = QtWidgets.QActionGroup(self)
self._ui.rendererAovActionGroup.setExclusive(True)
self._ui.menuRendererAovs.clear()
aovs = self._stageView.GetRendererAovs()
for aov in aovs:
action = self._ui.menuRendererAovs.addAction(aov)
action.setCheckable(True)
if (aov == "color"):
action.setChecked(True)
action.aov = aov
self._ui.rendererAovActionGroup.addAction(action)
action.triggered[bool].connect(lambda _, aov=aov:
self._rendererAovChanged(aov))
self._ui.menuRendererAovs.addSeparator()
self._ui.aovOtherAction = self._ui.menuRendererAovs.addAction("Other...")
self._ui.aovOtherAction.setCheckable(True)
self._ui.aovOtherAction.aov = "Other"
self._ui.rendererAovActionGroup.addAction(self._ui.aovOtherAction)
self._ui.aovOtherAction.triggered[bool].connect(self._otherAov)
self._ui.menuRendererAovs.setEnabled(len(aovs) != 0)
def _otherAov(self):
# If we've already selected "Other..." as an AOV, populate the current
# AOV name.
initial = ""
if self._ui.aovOtherAction.text() != "Other...":
initial = self._stageView.rendererAovName
aov, ok = QtWidgets.QInputDialog.getText(self._mainWindow, "Other AOVs",
"Enter the aov name. Visualize primvars with \"primvars:name\".",
QtWidgets.QLineEdit.Normal, initial)
if (ok and len(aov) > 0):
self._rendererAovChanged(str(aov))
self._ui.aovOtherAction.setText("Other (%r)..." % str(aov))
else:
for action in self._ui.rendererAovActionGroup.actions():
if action.text() == self._stageView.rendererAovName:
action.setChecked(True)
break
def _rendererSettingsFlagChanged(self, action):
if self._stageView:
self._stageView.SetRendererSetting(action.key, action.isChecked())
def _configureRendererSettings(self):
if self._stageView:
self._ui.menuRendererSettings.clear()
self._ui.settingsFlagActions = []
settings = self._stageView.GetRendererSettingsList()
moreSettings = False
for setting in settings:
if setting.type != UsdImagingGL.RendererSettingType.FLAG:
moreSettings = True
continue
action = self._ui.menuRendererSettings.addAction(setting.name)
action.setCheckable(True)
action.key = str(setting.key)
action.setChecked(self._stageView.GetRendererSetting(setting.key))
action.triggered[bool].connect(lambda _, action=action:
self._rendererSettingsFlagChanged(action))
self._ui.settingsFlagActions.append(action)
if moreSettings:
self._ui.menuRendererSettings.addSeparator()
self._ui.settingsMoreAction = self._ui.menuRendererSettings.addAction("More...")
self._ui.settingsMoreAction.setCheckable(False)
self._ui.settingsMoreAction.triggered[bool].connect(self._moreRendererSettings)
self._ui.menuRendererSettings.setEnabled(len(settings) != 0)
# Close the old "More..." dialog if it's still open
if hasattr(self._ui, 'settingsMoreDialog'):
self._ui.settingsMoreDialog.reject()
def _moreRendererSettings(self):
# Recreate the settings dialog
self._ui.settingsMoreDialog = QtWidgets.QDialog(self._mainWindow)
self._ui.settingsMoreDialog.setWindowTitle("Hydra Settings")
self._ui.settingsMoreWidgets = []
layout = QtWidgets.QVBoxLayout()
# Add settings
groupBox = QtWidgets.QGroupBox()
formLayout = QtWidgets.QFormLayout()
groupBox.setLayout(formLayout)
layout.addWidget(groupBox)
formLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
formLayout.setFormAlignment(QtCore.Qt.AlignRight)
settings = self._stageView.GetRendererSettingsList()
for setting in settings:
if setting.type == UsdImagingGL.RendererSettingType.FLAG:
checkBox = QtWidgets.QCheckBox()
checkBox.setChecked(self._stageView.GetRendererSetting(setting.key))
checkBox.key = str(setting.key)
checkBox.defValue = setting.defValue
formLayout.addRow(setting.name, checkBox)
self._ui.settingsMoreWidgets.append(checkBox)
if setting.type == UsdImagingGL.RendererSettingType.INT:
spinBox = QtWidgets.QSpinBox()
spinBox.setMinimum(-2 ** 31)
spinBox.setMaximum(2 ** 31 - 1)
spinBox.setValue(self._stageView.GetRendererSetting(setting.key))
spinBox.key = str(setting.key)
spinBox.defValue = setting.defValue
formLayout.addRow(setting.name, spinBox)
self._ui.settingsMoreWidgets.append(spinBox)
if setting.type == UsdImagingGL.RendererSettingType.FLOAT:
spinBox = QtWidgets.QDoubleSpinBox()
spinBox.setDecimals(10)
spinBox.setMinimum(-2 ** 31)
spinBox.setMaximum(2 ** 31 - 1)
spinBox.setValue(self._stageView.GetRendererSetting(setting.key))
spinBox.key = str(setting.key)
spinBox.defValue = setting.defValue
formLayout.addRow(setting.name, spinBox)
self._ui.settingsMoreWidgets.append(spinBox)
if setting.type == UsdImagingGL.RendererSettingType.STRING:
lineEdit = QtWidgets.QLineEdit()
lineEdit.setText(self._stageView.GetRendererSetting(setting.key))
lineEdit.key = str(setting.key)
lineEdit.defValue = setting.defValue
formLayout.addRow(setting.name, lineEdit)
self._ui.settingsMoreWidgets.append(lineEdit)
# Add buttons
buttonBox = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok |
QtWidgets.QDialogButtonBox.Cancel |
QtWidgets.QDialogButtonBox.RestoreDefaults |
QtWidgets.QDialogButtonBox.Apply)
layout.addWidget(buttonBox)
buttonBox.rejected.connect(self._ui.settingsMoreDialog.reject)
buttonBox.accepted.connect(self._ui.settingsMoreDialog.accept)
self._ui.settingsMoreDialog.accepted.connect(self._applyMoreRendererSettings)
defaultButton = buttonBox.button(QtWidgets.QDialogButtonBox.RestoreDefaults)
defaultButton.clicked.connect(self._resetMoreRendererSettings)
applyButton = buttonBox.button(QtWidgets.QDialogButtonBox.Apply)
applyButton.clicked.connect(self._applyMoreRendererSettings)
self._ui.settingsMoreDialog.setLayout(layout)
self._ui.settingsMoreDialog.show()
def _applyMoreRendererSettings(self):
for widget in self._ui.settingsMoreWidgets:
if isinstance(widget, QtWidgets.QCheckBox):
self._stageView.SetRendererSetting(widget.key, widget.isChecked())
if isinstance(widget, QtWidgets.QSpinBox):
self._stageView.SetRendererSetting(widget.key, widget.value())
if isinstance(widget, QtWidgets.QDoubleSpinBox):
self._stageView.SetRendererSetting(widget.key, widget.value())
if isinstance(widget, QtWidgets.QLineEdit):
self._stageView.SetRendererSetting(widget.key, widget.text())
for action in self._ui.settingsFlagActions:
action.setChecked(self._stageView.GetRendererSetting(action.key))
def _resetMoreRendererSettings(self):
for widget in self._ui.settingsMoreWidgets:
if isinstance(widget, QtWidgets.QCheckBox):
widget.setChecked(widget.defValue)
if isinstance(widget, QtWidgets.QSpinBox):
widget.setValue(widget.defValue)
if isinstance(widget, QtWidgets.QDoubleSpinBox):
widget.setValue(widget.defValue)
if isinstance(widget, QtWidgets.QLineEdit):
widget.setText(widget.defValue)
def _configurePauseAction(self):
if self._stageView:
# This is called when the user picks a new renderer, which
# always starts in an unpaused state.
self._paused = False
self._ui.actionPause.setEnabled(
self._stageView.IsPauseRendererSupported())
self._ui.actionPause.setChecked(self._paused and
self._stageView.IsPauseRendererSupported())
def _configureStopAction(self):
if self._stageView:
# This is called when the user picks a new renderer, which
# always starts in an unstopped state.
self._stopped = False
self._ui.actionStop.setEnabled(
self._stageView.IsStopRendererSupported())
self._ui.actionStop.setChecked(self._stopped and
self._stageView.IsStopRendererSupported())
def _configureColorManagement(self):
enableMenu = (not self._noRender and
UsdImagingGL.Engine.IsColorCorrectionCapable())
self._ui.menuColorCorrection.setEnabled(enableMenu)
# Topology-dependent UI changes
def _reloadVaryingUI(self):
self._clearCaches()
if self._debug:
cProfile.runctx('self._resetPrimView(restoreSelection=False)', globals(), locals(), 'resetPrimView')
p = pstats.Stats('resetPrimView')
p.strip_dirs().sort_stats(-1).print_stats()
else:
self._resetPrimView(restoreSelection=False)
if not self._stageView:
# The second child is self._ui.glFrame, which disappears if
# its size is set to zero.
if self._noRender:
# remove glFrame from the ui
self._ui.glFrame.setParent(None)
# move the attributeBrowser into the primSplitter instead
self._ui.primStageSplitter.addWidget(self._ui.attributeBrowserFrame)
else:
self._stageView = StageView(parent=self._mainWindow,
dataModel=self._dataModel,
printTiming=self._printTiming)
self._stageView.fpsHUDInfo = self._fpsHUDInfo
self._stageView.fpsHUDKeys = self._fpsHUDKeys
self._stageView.signalPrimSelected.connect(self.onPrimSelected)
self._stageView.signalPrimRollover.connect(self.onRollover)
self._stageView.signalMouseDrag.connect(self.onStageViewMouseDrag)
self._stageView.signalErrorMessage.connect(self.statusMessage)
layout = QtWidgets.QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self._ui.glFrame.setLayout(layout)
layout.addWidget(self._stageView)
self._primSearchResults = deque([])
self._attrSearchResults = deque([])
self._primSearchString = ""
self._attrSearchString = ""
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
if self._stageView:
self._stageView.setFocus(QtCore.Qt.TabFocusReason)
self._stageView.rolloverPicking = self._dataModel.viewSettings.rolloverPrimInfo
def _scheduleResizePrimView(self):
""" Schedules a resize of the primView widget.
This will call _resizePrimView when the timer expires
(uses timer coalescing to prevent redundant resizes from occurring).
"""
self._primViewResizeTimer.start(0)
def _resizePrimView(self):
""" Used to coalesce excess calls to resizeColumnToContents.
"""
self._ui.primView.resizeColumnToContents(0)
# Retrieve the list of prims currently expanded in the primTreeWidget
def _getExpandedPrimViewPrims(self):
rootItem = self._ui.primView.invisibleRootItem()
expandedItems = list()
# recursive function for adding all expanded items to expandedItems
def findExpanded(item):
if item.isExpanded():
expandedItems.append(item)
for i in range(item.childCount()):
findExpanded(item.child(i))
findExpanded(rootItem)
expandedPrims = [item.prim for item in expandedItems]
return expandedPrims
# This appears to be "reasonably" performant in normal sized pose caches.
# If it turns out to be too slow, or if we want to do a better job of
# preserving the view the user currently has, we could look into ways of
# reconstructing just the prim tree under the "changed" prim(s). The
# (far and away) faster solution would be to implement our own TreeView
# and model in C++.
def _resetPrimView(self, restoreSelection=True):
expandedPrims = self._getExpandedPrimViewPrims()
with Timer() as t, BusyContext():
startingDepth = 3
self._computeDisplayPredicate()
with self._primViewSelectionBlocker:
self._ui.primView.setUpdatesEnabled(False)
self._ui.primView.clear()
self._primToItemMap.clear()
self._itemsToPush = []
# force new search since we are blowing away the primViewItems
# that may be cached in _primSearchResults
self._primSearchResults = []
self._populateRoots()
# it's confusing to see timing for expand followed by reset with
# the times being similar (esp when they are large)
if not expandedPrims:
self._expandToDepth(startingDepth, suppressTiming=True)
if restoreSelection:
self._refreshPrimViewSelection(expandedPrims)
self._ui.primView.setUpdatesEnabled(True)
self._refreshCameraListAndMenu(preserveCurrCamera = True)
if self._printTiming:
t.PrintTime("reset Prim Browser to depth %d" % startingDepth)
def _resetGUI(self):
"""Perform a full refresh/resync of all GUI contents. This should be
called whenever the USD stage is modified, and assumes that all data
previously fetched from the stage is invalid. In the future, more
granular updates will be supported by listening to UsdNotice objects on
the active stage.
If a prim resync is needed then we fully update the prim view,
otherwise can just do a simplified update to the prim view.
"""
with BusyContext():
if self._hasPrimResync:
self._resetPrimView()
self._hasPrimResync = False
else:
self._resetPrimViewVis(selItemsOnly=False)
self._updatePropertyView()
self._populatePropertyInspector()
self._updateMetadataView()
self._updateLayerStackView()
self._updateCompositionView()
if self._stageView:
self._stageView.update()
def updateGUI(self):
"""Will schedule a full refresh/resync of the GUI contents.
Prefer this to calling _resetGUI() directly, since it will
coalesce multiple calls to this method in to a single refresh.
"""
self._guiResetTimer.start()
def _resetPrimViewVis(self, selItemsOnly=True,
authoredVisHasChanged=True):
"""Updates browser rows' Vis columns... can update just selected
items (and their descendants and ancestors), or all items in the
primView. When authoredVisHasChanged is True, we force each item
to discard any value caches it may be holding onto."""
with Timer() as t:
self._ui.primView.setUpdatesEnabled(False)
rootsToProcess = self.getSelectedItems() if selItemsOnly else \
[self._ui.primView.invisibleRootItem()]
for item in rootsToProcess:
PrimViewItem.propagateVis(item, authoredVisHasChanged)
self._ui.primView.setUpdatesEnabled(True)
if self._printTiming:
t.PrintTime("update vis column")
def _updatePrimView(self):
# Process some more prim view items.
n = min(100, len(self._itemsToPush))
if n:
items = self._itemsToPush[-n:]
del self._itemsToPush[-n:]
for item in items:
item.push()
else:
self._primViewUpdateTimer.stop()
# Option windows ==========================================================
def _setComplexity(self, complexity):
"""Set the complexity and update the UI."""
self._dataModel.viewSettings.complexity = complexity
def _incrementComplexity(self):
"""Jump up to the next level of complexity."""
self._setComplexity(RefinementComplexities.next(
self._dataModel.viewSettings.complexity))
def _decrementComplexity(self):
"""Jump back to the previous level of complexity."""
self._setComplexity(RefinementComplexities.prev(
self._dataModel.viewSettings.complexity))
def _changeComplexity(self, action):
"""Update the complexity from a selected QAction."""
self._setComplexity(RefinementComplexities.fromName(action.text()))
def _adjustFOV(self):
fov = QtWidgets.QInputDialog.getDouble(self._mainWindow, "Adjust FOV",
"Enter a value between 0 and 180", self._dataModel.viewSettings.freeCameraFOV, 0, 180)
if (fov[1]):
self._dataModel.viewSettings.freeCameraFOV = fov[0]
def _adjustClippingPlanes(self, checked):
# Eventually, this will not be accessible when _stageView is None.
# Until then, silently ignore.
if self._stageView:
if (checked):
self._adjustClippingDlg = adjustClipping.AdjustClipping(self._mainWindow,
self._stageView)
self._adjustClippingDlg.finished.connect(
lambda status : self._ui.actionAdjust_Clipping.setChecked(False))
self._adjustClippingDlg.show()
else:
self._adjustClippingDlg.close()
def _adjustDefaultMaterial(self, checked):
if (checked):
self._adjustDefaultMaterialDlg = adjustDefaultMaterial.AdjustDefaultMaterial(
self._mainWindow, self._dataModel.viewSettings)
self._adjustDefaultMaterialDlg.finished.connect(lambda status :
self._ui.actionAdjust_Default_Material.setChecked(False))
self._adjustDefaultMaterialDlg.show()
else:
self._adjustDefaultMaterialDlg.close()
def _togglePreferences(self, checked):
if (checked):
self._preferencesDlg = preferences.Preferences(
self._mainWindow, self._dataModel)
self._preferencesDlg.finished.connect(lambda status :
self._ui.actionPreferences.setChecked(False))
self._preferencesDlg.show()
else:
self._preferencesDlg.close()
def _redrawOptionToggled(self, checked):
self._dataModel.viewSettings.redrawOnScrub = checked
self._ui.frameSlider.setTracking(
self._dataModel.viewSettings.redrawOnScrub)
# Frame-by-frame/Playback functionality ===================================
def _setPlaybackAvailability(self, enabled = True):
isEnabled = len(self._timeSamples) > 1 and enabled
self._playbackAvailable = isEnabled
#If playback is disabled, but the animation is playing...
if not isEnabled and self._dataModel.playing:
self._ui.playButton.click()
self._ui.playButton.setEnabled(isEnabled)
self._ui.frameSlider.setEnabled(isEnabled)
self._ui.actionFrame_Forward.setEnabled(isEnabled)
self._ui.actionFrame_Backwards.setEnabled(isEnabled)
self._ui.frameField.setEnabled(isEnabled
if self._hasTimeSamples else False)
self._ui.frameLabel.setEnabled(isEnabled
if self._hasTimeSamples else False)
self._ui.stageBegin.setEnabled(isEnabled)
self._ui.stageEnd.setEnabled(isEnabled)
self._ui.redrawOnScrub.setEnabled(isEnabled)
self._ui.stepSizeLabel.setEnabled(isEnabled)
self._ui.stepSize.setEnabled(isEnabled)
def _playClicked(self):
if self._ui.playButton.isChecked():
# Enable tracking whilst playing
self._ui.frameSlider.setTracking(True)
# Start playback.
self._dataModel.playing = True
self._ui.playButton.setText("Stop")
# setText() causes the shortcut to be reset to whatever
# Qt thinks it should be based on the text. We know better.
self._setPlayShortcut()
self._fpsHUDInfo[HUDEntries.PLAYBACK] = "..."
self._timer.start()
# For performance, don't update the prim tree view while playing.
self._primViewUpdateTimer.stop()
self._playbackIndex = 0
else:
self._ui.frameSlider.setTracking(self._ui.redrawOnScrub.isChecked())
# Stop playback.
self._dataModel.playing = False
self._ui.playButton.setText("Play")
# setText() causes the shortcut to be reset to whatever
# Qt thinks it should be based on the text. We know better.
self._setPlayShortcut()
self._fpsHUDInfo[HUDEntries.PLAYBACK] = "N/A"
self._timer.stop()
self._primViewUpdateTimer.start()
self._updateOnFrameChange()
def _advanceFrameForPlayback(self):
sleep(max(0, 1. / self.framesPerSecond - (time() - self._lastFrameTime)))
self._lastFrameTime = time()
if self._playbackIndex == 0:
self._startTime = time()
if self._playbackIndex == 4:
self._endTime = time()
delta = (self._endTime - self._startTime)/4.
ms = delta * 1000.
fps = 1. / delta
self._fpsHUDInfo[HUDEntries.PLAYBACK] = "%.2f ms (%.2f FPS)" % (ms, fps)
self._playbackIndex = (self._playbackIndex + 1) % 5
self._advanceFrame()
def _advanceFrame(self):
if self._playbackAvailable:
value = self._ui.frameSlider.value() + 1
if value > self._ui.frameSlider.maximum():
value = self._ui.frameSlider.minimum()
self._ui.frameSlider.setValue(value)
def _retreatFrame(self):
if self._playbackAvailable:
value = self._ui.frameSlider.value() - 1
if value < self._ui.frameSlider.minimum():
value = self._ui.frameSlider.maximum()
self._ui.frameSlider.setValue(value)
def _findClosestFrameIndex(self, timeSample):
"""Find the closest frame index for the given `timeSample`.
Args:
timeSample (float): A time sample value.
Returns:
int: The closest matching frame index or 0 if one cannot be
found.
"""
closestIndex = int(round((timeSample - self._timeSamples[0]) / self.step))
# Bounds checking
# 0 <= closestIndex <= number of time samples - 1
closestIndex = max(0, closestIndex)
closestIndex = min(len(self._timeSamples) - 1, closestIndex)
return closestIndex
def _rangeBeginChanged(self):
value = float(self._ui.rangeBegin.text())
if value != self.realStartTimeCode:
self.realStartTimeCode = value
self._UpdateTimeSamples(resetStageDataOnly=False)
def _stepSizeChanged(self):
value = float(self._ui.stepSize.text())
if value != self.step:
self.step = value
self._UpdateTimeSamples(resetStageDataOnly=False)
def _rangeEndChanged(self):
value = float(self._ui.rangeEnd.text())
if value != self.realEndTimeCode:
self.realEndTimeCode = value
self._UpdateTimeSamples(resetStageDataOnly=False)
def _frameStringChanged(self):
value = float(self._ui.frameField.text())
self.setFrame(value)
def _sliderMoved(self, frameIndex):
"""Slot called when the frame slider is moved by a user.
Args:
frameIndex (int): The new frame index value.
"""
# If redraw on scrub is disabled, ensure we still update the
# frame field.
if not self._ui.redrawOnScrub.isChecked():
self.setFrameField(self._timeSamples[frameIndex])
def setFrameField(self, frame):
"""Set the frame field to the given `frame`.
Args:
frame (str|int|float): The new frame value.
"""
frame = round(float(frame), ndigits=2)
self._ui.frameField.setText(str(frame))
# Prim/Attribute search functionality =====================================
def _findPrims(self, pattern, useRegex=True):
"""Search the Usd Stage for matching prims
"""
# If pattern doesn't contain regexp special chars, drop
# down to simple search, as it's faster
if useRegex and re.match("^[0-9_A-Za-z]+$", pattern):
useRegex = False
if useRegex:
isMatch = re.compile(pattern, re.IGNORECASE).search
else:
pattern = pattern.lower()
isMatch = lambda x: pattern in x.lower()
matches = [prim.GetPath() for prim
in Usd.PrimRange.Stage(self._dataModel.stage,
self._displayPredicate)
if isMatch(prim.GetName())]
if self._dataModel.viewSettings.showAllMasterPrims:
for master in self._dataModel.stage.GetMasters():
matches += [prim.GetPath() for prim
in Usd.PrimRange(master, self._displayPredicate)
if isMatch(prim.GetName())]
return matches
def _primViewFindNext(self):
if (self._primSearchString == self._ui.primViewLineEdit.text() and
len(self._primSearchResults) > 0 and
self._lastPrimSearched == self._dataModel.selection.getFocusPrim()):
# Go to the next result of the currently ongoing search.
# First time through, we'll be converting from SdfPaths
# to items (see the append() below)
nextResult = self._primSearchResults.popleft()
if isinstance(nextResult, Sdf.Path):
nextResult = self._getItemAtPath(nextResult)
if nextResult:
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
self._dataModel.selection.addPrim(nextResult.prim)
self._primSearchResults.append(nextResult)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
self._ui.primView.setCurrentItem(nextResult)
# The path is effectively pruned if we couldn't map the
# path to an item
else:
# Begin a new search
with Timer() as t:
self._primSearchString = self._ui.primViewLineEdit.text()
self._primSearchResults = self._findPrims(str(self._ui.primViewLineEdit.text()))
self._primSearchResults = deque(self._primSearchResults)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
selectedPrim = self._dataModel.selection.getFocusPrim()
# reorders search results so results are centered on selected
# prim. this could be optimized, but a binary search with a
# custom operator for the result closest to and after the
# selected prim is messier to implement.
if (selectedPrim != None and
selectedPrim != self._dataModel.stage.GetPseudoRoot() and
len(self._primSearchResults) > 0):
for i in range(len(self._primSearchResults)):
searchResultPath = self._primSearchResults[0]
selectedPath = selectedPrim.GetPath()
if self._comparePaths(searchResultPath, selectedPath) < 1:
self._primSearchResults.rotate(-1)
else:
break
if (len(self._primSearchResults) > 0):
self._primViewFindNext()
if self._printTiming:
t.PrintTime("match '%s' (%d matches)" %
(self._primSearchString,
len(self._primSearchResults)))
# returns -1 if path1 appears before path2 in flattened tree
# returns 0 if path1 and path2 are equal
# returns 1 if path2 appears before path1 in flattened tree
def _comparePaths(self, path1, path2):
# function for removing a certain number of elements from a path
def stripPath(path, numElements):
strippedPath = path
for i in range(numElements):
strippedPath = strippedPath.GetParentPath()
return strippedPath
lca = path1.GetCommonPrefix(path2)
path1NumElements = path1.pathElementCount
path2NumElements = path2.pathElementCount
lcaNumElements = lca.pathElementCount
if path1 == path2:
return 0
if lca == path1:
return -1
if lca == path2:
return 1
path1Stripped = stripPath(path1, path1NumElements - (lcaNumElements + 1))
path2Stripped = stripPath(path2, path2NumElements - (lcaNumElements + 1))
lcaChildrenPrims = self._getFilteredChildren(self._dataModel.stage.GetPrimAtPath(lca))
lcaChildrenPaths = [prim.GetPath() for prim in lcaChildrenPrims]
indexPath1 = lcaChildrenPaths.index(path1Stripped)
indexPath2 = lcaChildrenPaths.index(path2Stripped)
if (indexPath1 < indexPath2):
return -1
if (indexPath1 > indexPath2):
return 1
else:
return 0
def _primLegendToggleCollapse(self):
ToggleLegendWithBrowser(self._ui.primLegendContainer,
self._ui.primLegendQButton,
self._primLegendAnim)
def _propertyLegendToggleCollapse(self):
ToggleLegendWithBrowser(self._ui.propertyLegendContainer,
self._ui.propertyLegendQButton,
self._propertyLegendAnim)
def _attrViewFindNext(self):
if (self._attrSearchString == self._ui.attrViewLineEdit.text() and
len(self._attrSearchResults) > 0 and
self._lastPrimSearched == self._dataModel.selection.getFocusPrim()):
# Go to the next result of the currently ongoing search
nextResult = self._attrSearchResults.popleft()
itemName = str(nextResult.text(PropertyViewIndex.NAME))
selectedProp = self._propertiesDict[itemName]
if isinstance(selectedProp, CustomAttribute):
self._dataModel.selection.clearProps()
self._dataModel.selection.setComputedProp(selectedProp)
else:
self._dataModel.selection.setProp(selectedProp)
self._dataModel.selection.clearComputedProps()
self._ui.propertyView.scrollToItem(nextResult)
self._attrSearchResults.append(nextResult)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
self._ui.attributeValueEditor.populate(
self._dataModel.selection.getFocusPrim().GetPath(), itemName)
self._updateMetadataView(self._getSelectedObject())
self._updateLayerStackView(self._getSelectedObject())
else:
# Begin a new search
self._attrSearchString = self._ui.attrViewLineEdit.text()
attrSearchItems = self._ui.propertyView.findItems(
self._ui.attrViewLineEdit.text(),
QtCore.Qt.MatchRegExp,
PropertyViewIndex.NAME)
# Now just search for the string itself
otherSearch = self._ui.propertyView.findItems(
self._ui.attrViewLineEdit.text(),
QtCore.Qt.MatchContains,
PropertyViewIndex.NAME)
combinedItems = attrSearchItems + otherSearch
# We find properties first, then connections/targets
# Based on the default recursive match finding in Qt.
combinedItems.sort()
self._attrSearchResults = deque(combinedItems)
self._lastPrimSearched = self._dataModel.selection.getFocusPrim()
if (len(self._attrSearchResults) > 0):
self._attrViewFindNext()
@classmethod
def _outputBaseDirectory(cls):
if os.getenv('PXR_USDVIEW_SUPPRESS_STATE_SAVING', "0") == "1":
return None
homeDirRoot = os.getenv('HOME') or os.path.expanduser('~')
baseDir = os.path.join(homeDirRoot, '.usdview')
try:
if not os.path.exists(baseDir):
os.makedirs(baseDir)
return baseDir
except OSError:
sys.stderr.write("ERROR: Unable to create base directory '%s' "
"for settings file, settings will not be saved.\n"
% baseDir)
return None
# View adjustment functionality ===========================================
def _storeAndReturnViewState(self):
lastView = self._lastViewContext
self._lastViewContext = self._stageView.copyViewState()
return lastView
def _frameSelection(self):
if self._stageView:
# Save all the pertinent attribute values (for _toggleFramedView)
self._storeAndReturnViewState() # ignore return val - we're stomping it
self._stageView.updateView(True, True) # compute bbox on frame selection
def _toggleFramedView(self):
if self._stageView:
self._stageView.restoreViewState(self._storeAndReturnViewState())
def _resetSettings(self):
"""Reloads the UI and Sets up the initial settings for the
_stageView object created in _reloadVaryingUI"""
# Seems like a good time to clear the texture registry
Glf.TextureRegistry.Reset()
# RELOAD fixed and varying UI
self._reloadFixedUI()
self._reloadVaryingUI()
if self._stageView:
self._stageView.update()
self._ui.actionFreeCam._prim = None
self._ui.actionFreeCam.triggered.connect(
lambda : self._cameraSelectionChanged(None))
if self._stageView:
self._stageView.signalSwitchedToFreeCam.connect(
lambda : self._cameraSelectionChanged(None))
self._refreshCameraListAndMenu(preserveCurrCamera = False)
def _updateForStageChanges(self, hasPrimResync=True):
"""Assuming there have been authoring changes to the already-loaded
stage, make the minimal updates to the UI required to maintain a
consistent state. This may still be over-zealous until we know
what actually changed, but we should be able to preserve camera and
playback positions (unless viewing through a stage camera that no
longer exists"""
self._hasPrimResync = hasPrimResync or self._hasPrimResync
self._clearCaches(preserveCamera=True)
# Update the UIs (it gets all of them) and StageView on a timer
self.updateGUI()
def _cacheViewerModeEscapeSizes(self, pos=None, index=None):
topHeight, bottomHeight = self._ui.topBottomSplitter.sizes()
primViewWidth, stageViewWidth = self._ui.primStageSplitter.sizes()
if bottomHeight > 0 or primViewWidth > 0:
self._viewerModeEscapeSizes = topHeight, bottomHeight, primViewWidth, stageViewWidth
else:
self._viewerModeEscapeSizes = None
def _toggleViewerMode(self):
topHeight, bottomHeight = self._ui.topBottomSplitter.sizes()
primViewWidth, stageViewWidth = self._ui.primStageSplitter.sizes()
if bottomHeight > 0 or primViewWidth > 0:
topHeight += bottomHeight
bottomHeight = 0
stageViewWidth += primViewWidth
primViewWidth = 0
else:
if self._viewerModeEscapeSizes is not None:
topHeight, bottomHeight, primViewWidth, stageViewWidth = self._viewerModeEscapeSizes
else:
bottomHeight = UIDefaults.BOTTOM_HEIGHT
topHeight = UIDefaults.TOP_HEIGHT
primViewWidth = UIDefaults.PRIM_VIEW_WIDTH
stageViewWidth = UIDefaults.STAGE_VIEW_WIDTH
self._ui.topBottomSplitter.setSizes([topHeight, bottomHeight])
self._ui.primStageSplitter.setSizes([primViewWidth, stageViewWidth])
def _resetView(self,selectPrim = None):
""" Reverts the GL frame to the initial camera view,
and clears selection (sets to pseudoRoot), UNLESS 'selectPrim' is
not None, in which case we'll select and frame it."""
self._ui.primView.clearSelection()
pRoot = self._dataModel.stage.GetPseudoRoot()
if selectPrim is None:
# if we had a command-line specified selection, re-frame it
selectPrim = self._initialSelectPrim or pRoot
item = self._getItemAtPath(selectPrim.GetPath())
# Our response to selection-change includes redrawing. We do NOT
# want that to happen here, since we are subsequently going to
# change the camera framing (and redraw, again), which can cause
# flickering. So make sure we don't redraw!
self._allowViewUpdates = False
self._ui.primView.setCurrentItem(item)
self._allowViewUpdates = True
if self._stageView:
if (selectPrim and selectPrim != pRoot) or not self._startingPrimCamera:
# _frameSelection translates the camera from wherever it happens
# to be at the time. If we had a starting selection AND a
# primCam, then before framing, switch back to the prim camera
if selectPrim == self._initialSelectPrim and self._startingPrimCamera:
self._dataModel.viewSettings.cameraPrim = self._startingPrimCamera
self._frameSelection()
else:
self._dataModel.viewSettings.cameraPrim = self._startingPrimCamera
self._stageView.updateView()
def _changeRenderMode(self, mode):
self._dataModel.viewSettings.renderMode = str(mode.text())
def _changeColorCorrection(self, mode):
self._dataModel.viewSettings.colorCorrectionMode = str(mode.text())
def _changePickMode(self, mode):
self._dataModel.viewSettings.pickMode = str(mode.text())
def _changeSelHighlightMode(self, mode):
self._dataModel.viewSettings.selHighlightMode = str(mode.text())
def _changeHighlightColor(self, color):
self._dataModel.viewSettings.highlightColorName = str(color.text())
def _changeInterpolationType(self, interpolationType):
for t in Usd.InterpolationType.allValues:
if t.displayName == str(interpolationType.text()):
self._dataModel.stage.SetInterpolationType(t)
self._resetSettings()
break
def _ambientOnlyClicked(self, checked=None):
if self._stageView and checked is not None:
self._dataModel.viewSettings.ambientLightOnly = checked
def _onDomeLightClicked(self, checked=None):
if self._stageView and checked is not None:
self._dataModel.viewSettings.domeLightEnabled = checked
def _changeBgColor(self, mode):
self._dataModel.viewSettings.clearColorText = str(mode.text())
def _toggleShowBBoxPlayback(self):
"""Called when the menu item for showing BBoxes
during playback is activated or deactivated."""
self._dataModel.viewSettings.showBBoxPlayback = (
self._ui.showBBoxPlayback.isChecked())
def _toggleAutoComputeClippingPlanes(self):
autoClip = self._ui.actionAuto_Compute_Clipping_Planes.isChecked()
self._dataModel.viewSettings.autoComputeClippingPlanes = autoClip
if autoClip:
self._stageView.detachAndReClipFromCurrentCamera()
def _setUseExtentsHint(self):
self._dataModel.useExtentsHint = self._ui.useExtentsHint.isChecked()
self._updatePropertyView()
#recompute and display bbox
self._refreshBBox()
def _toggleShowBBoxes(self):
"""Called when the menu item for showing BBoxes
is activated."""
self._dataModel.viewSettings.showBBoxes = self._ui.showBBoxes.isChecked()
#recompute and display bbox
self._refreshBBox()
def _toggleShowAABBox(self):
"""Called when Axis-Aligned bounding boxes
are activated/deactivated via menu item"""
self._dataModel.viewSettings.showAABBox = self._ui.showAABBox.isChecked()
# recompute and display bbox
self._refreshBBox()
def _toggleShowOBBox(self):
"""Called when Oriented bounding boxes
are activated/deactivated via menu item"""
self._dataModel.viewSettings.showOBBox = self._ui.showOBBox.isChecked()
# recompute and display bbox
self._refreshBBox()
def _refreshBBox(self):
"""Recompute and hide/show Bounding Box."""
if self._stageView:
self._stageView.updateView(forceComputeBBox=True)
def _toggleDisplayGuide(self):
self._dataModel.viewSettings.displayGuide = (
self._ui.actionDisplay_Guide.isChecked())
def _toggleDisplayProxy(self):
self._dataModel.viewSettings.displayProxy = (
self._ui.actionDisplay_Proxy.isChecked())
def _toggleDisplayRender(self):
self._dataModel.viewSettings.displayRender = (
self._ui.actionDisplay_Render.isChecked())
def _toggleDisplayCameraOracles(self):
self._dataModel.viewSettings.displayCameraOracles = (
self._ui.actionDisplay_Camera_Oracles.isChecked())
def _toggleDisplayPrimId(self):
self._dataModel.viewSettings.displayPrimId = (
self._ui.actionDisplay_PrimId.isChecked())
def _toggleEnableSceneMaterials(self):
self._dataModel.viewSettings.enableSceneMaterials = (
self._ui.actionEnable_Scene_Materials.isChecked())
def _toggleCullBackfaces(self):
self._dataModel.viewSettings.cullBackfaces = (
self._ui.actionCull_Backfaces.isChecked())
def _showInterpreter(self):
if self._interpreter is None:
self._interpreter = QtWidgets.QDialog(self._mainWindow)
self._interpreter.setObjectName("Interpreter")
self._console = Myconsole(self._interpreter, self._usdviewApi)
self._interpreter.setFocusProxy(self._console) # this is important!
lay = QtWidgets.QVBoxLayout()
lay.addWidget(self._console)
self._interpreter.setLayout(lay)
# dock the interpreter window next to the main usdview window
self._interpreter.move(self._mainWindow.x() + self._mainWindow.frameGeometry().width(),
self._mainWindow.y())
self._interpreter.resize(600, self._mainWindow.size().height()//2)
self._interpreter.show()
self._interpreter.activateWindow()
self._interpreter.setFocus()
def _showDebugFlags(self):
if self._debugFlagsWindow is None:
from .debugFlagsWidget import DebugFlagsWidget
self._debugFlagsWindow = DebugFlagsWidget()
self._debugFlagsWindow.show()
# Screen capture functionality ===========================================
def GrabWindowShot(self):
'''Returns a QImage of the full usdview window '''
# generate an image of the window. Due to how Qt's rendering
# works, this will not pick up the GL Widget(_stageView)'s
# contents, and we'll need to compose it separately.
windowShot = QtGui.QImage(self._mainWindow.size(),
QtGui.QImage.Format_ARGB32_Premultiplied)
painter = QtGui.QPainter(windowShot)
self._mainWindow.render(painter, QtCore.QPoint())
if self._stageView:
# overlay the QGLWidget on and return the composed image
# we offset by a single point here because of Qt.Pos funkyness
offset = QtCore.QPoint(0,1)
pos = self._stageView.mapTo(self._mainWindow, self._stageView.pos()) - offset
painter.drawImage(pos, self.GrabViewportShot())
return windowShot
def GrabViewportShot(self):
'''Returns a QImage of the current stage view in usdview.'''
if self._stageView:
return self._stageView.grabFrameBuffer()
else:
return None
# File handling functionality =============================================
def _cleanAndClose(self):
# This function is called by the main window's closeEvent handler.
self._settings2.save()
# If the current path widget is focused when closing usdview, it can
# trigger an "editingFinished()" signal, which will look for a prim in
# the scene (which is already deleted). This prevents that.
# XXX:
# This method is reentrant and calling disconnect twice on a signal
# causes an exception to be thrown.
try:
self._ui.currentPathWidget.editingFinished.disconnect(
self._currentPathChanged)
except RuntimeError:
pass
# Shut down some timers and our eventFilter
self._primViewUpdateTimer.stop()
self._guiResetTimer.stop()
QtWidgets.QApplication.instance().removeEventFilter(self._filterObj)
# If the timer is currently active, stop it from being invoked while
# the USD stage is being torn down.
if self._timer.isActive():
self._timer.stop()
# Close stage and release renderer resources (if applicable).
self._closeStage()
# Start timer to measure Qt shutdown time
self._startQtShutdownTimer()
def _openFile(self):
extensions = Sdf.FileFormat.FindAllFileFormatExtensions()
builtInFiles = lambda f: f.startswith(".usd")
notBuiltInFiles = lambda f: not f.startswith(".usd")
extensions = list(filter(builtInFiles, extensions)) + \
list(filter(notBuiltInFiles, extensions))
fileFilter = "USD Compatible Files (" + " ".join("*." + e for e in extensions) + ")"
(filename, _) = QtWidgets.QFileDialog.getOpenFileName(
self._mainWindow,
caption="Select file",
dir=".",
filter=fileFilter,
selectedFilter=fileFilter)
if len(filename) > 0:
self._parserData.usdFile = str(filename)
self._mainWindow.setWindowTitle(filename)
self._reopenStage()
def _getSaveFileName(self, caption, recommendedFilename):
(saveName, _) = QtWidgets.QFileDialog.getSaveFileName(
self._mainWindow,
caption,
'./' + recommendedFilename,
'USD Files (*.usd)'
';;USD ASCII Files (*.usda)'
';;USD Crate Files (*.usdc)'
';;Any USD File (*.usd *.usda *.usdc)',
'Any USD File (*.usd *.usda *.usdc)')
if len(saveName) == 0:
return ''
_, ext = os.path.splitext(saveName)
if ext not in ('.usd', '.usda', '.usdc'):
saveName += '.usd'
return saveName
def _saveOverridesAs(self):
recommendedFilename = self._parserData.usdFile.rsplit('.', 1)[0]
recommendedFilename += '_overrides.usd'
saveName = self._getSaveFileName(
'Save Overrides As', recommendedFilename)
if len(saveName) == 0:
return
if not self._dataModel.stage:
return
with BusyContext():
# In the future, we may allow usdview to be brought up with no file,
# in which case it would create an in-memory root layer, to which
# all edits will be targeted. In order to future proof
# this, first fetch the root layer, and if it is anonymous, just
# export it to the given filename. If it isn't anonmyous (i.e., it
# is a regular usd file on disk), export the session layer and add
# the stage root file as a sublayer.
rootLayer = self._dataModel.stage.GetRootLayer()
if not rootLayer.anonymous:
self._dataModel.stage.GetSessionLayer().Export(
saveName, 'Created by UsdView')
targetLayer = Sdf.Layer.FindOrOpen(saveName)
UsdUtils.CopyLayerMetadata(rootLayer, targetLayer,
skipSublayers=True)
# We don't ever store self.realStartTimeCode or
# self.realEndTimeCode in a layer, so we need to author them
# here explicitly.
if self.realStartTimeCode:
targetLayer.startTimeCode = self.realStartTimeCode
if self.realEndTimeCode:
targetLayer.endTimeCode = self.realEndTimeCode
targetLayer.subLayerPaths.append(
self._dataModel.stage.GetRootLayer().realPath)
targetLayer.RemoveInertSceneDescription()
targetLayer.Save()
else:
self._dataModel.stage.GetRootLayer().Export(
saveName, 'Created by UsdView')
def _saveFlattenedAs(self):
recommendedFilename = self._parserData.usdFile.rsplit('.', 1)[0]
recommendedFilename += '_flattened.usd'
saveName = self._getSaveFileName(
'Save Flattened As', recommendedFilename)
if len(saveName) == 0:
return
with BusyContext():
self._dataModel.stage.Export(saveName)
def _togglePause(self):
if self._stageView.IsPauseRendererSupported():
self._paused = not self._paused
self._stageView.SetRendererPaused(self._paused)
self._ui.actionPause.setChecked(self._paused)
def _toggleStop(self):
if self._stageView.IsStopRendererSupported():
# Ask the renderer whether its currently stopped or not
# as the value of the _stopped variable can become out of
# date if for example any camera munging happens
self._stopped = self._stageView.IsRendererConverged()
self._stopped = not self._stopped
self._stageView.SetRendererStopped(self._stopped)
self._ui.actionStop.setChecked(self._stopped)
def _reopenStage(self):
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
# Pause the stage view while we update
if self._stageView:
self._stageView.setUpdatesEnabled(False)
try:
# Clear out any Usd objects that may become invalid.
self._dataModel.selection.clear()
self._currentSpec = None
self._currentLayer = None
# Close the current stage so that we don't keep it in memory
# while trying to open another stage.
self._closeStage()
stage = self._openStage(
self._parserData.usdFile, self._parserData.sessionLayer,
self._parserData.populationMask)
# We need this for layers which were cached in memory but changed on
# disk. The additional Reload call should be cheap when nothing
# actually changed.
stage.Reload()
self._dataModel.stage = stage
self._resetSettings()
self._resetView()
self._stepSizeChanged()
except Exception as err:
self.statusMessage('Error occurred reopening Stage: %s' % err)
traceback.print_exc()
finally:
if self._stageView:
self._stageView.setUpdatesEnabled(True)
QtWidgets.QApplication.restoreOverrideCursor()
self.statusMessage('Stage Reopened')
def _reloadStage(self):
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
try:
self._dataModel.stage.Reload()
# Seems like a good time to clear the texture registry
Glf.TextureRegistry.Reset()
# reset timeline, and playback settings from stage metadata
self._reloadFixedUI(resetStageDataOnly=True)
except Exception as err:
self.statusMessage('Error occurred rereading all layers for Stage: %s' % err)
finally:
QtWidgets.QApplication.restoreOverrideCursor()
self.statusMessage('All Layers Reloaded.')
def _cameraSelectionChanged(self, camera):
self._dataModel.viewSettings.cameraPrim = camera
def _refreshCameraListAndMenu(self, preserveCurrCamera):
self._allSceneCameras = Utils._GetAllPrimsOfType(
self._dataModel.stage, Tf.Type.Find(UsdGeom.Camera))
currCamera = self._startingPrimCamera
if self._stageView:
currCamera = self._dataModel.viewSettings.cameraPrim
self._stageView.allSceneCameras = self._allSceneCameras
# if the stageView is holding an expired camera, clear it first
# and force search for a new one
if currCamera != None and not (currCamera and currCamera.IsActive()):
currCamera = None
self._dataModel.viewSettings.cameraPrim = None
preserveCurrCamera = False
if not preserveCurrCamera:
cameraWasSet = False
def setCamera(camera):
self._startingPrimCamera = currCamera = camera
self._dataModel.viewSettings.cameraPrim = camera
cameraWasSet = True
if self._startingPrimCameraPath:
prim = self._dataModel.stage.GetPrimAtPath(
self._startingPrimCameraPath)
if not prim.IsValid():
msg = sys.stderr
print("WARNING: Camera path %r did not exist in stage"
% self._startingPrimCameraPath, file=msg)
self._startingPrimCameraPath = None
elif not prim.IsA(UsdGeom.Camera):
msg = sys.stderr
print("WARNING: Camera path %r was not a UsdGeom.Camera"
% self._startingPrimCameraPath, file=msg)
self._startingPrimCameraPath = None
else:
setCamera(prim)
if not cameraWasSet and self._startingPrimCameraName:
for camera in self._allSceneCameras:
if camera.GetName() == self._startingPrimCameraName:
setCamera(camera)
break
# Now that we have the current camera and all cameras, build the menu
self._ui.menuCamera.clear()
if len(self._allSceneCameras) == 0:
self._ui.menuCamera.setEnabled(False)
else:
self._ui.menuCamera.setEnabled(True)
currCameraPath = None
if currCamera:
currCameraPath = currCamera.GetPath()
for camera in self._allSceneCameras:
action = self._ui.menuCamera.addAction(camera.GetName())
action.setData(camera.GetPath())
action.setToolTip(str(camera.GetPath()))
action.setCheckable(True)
action.triggered[bool].connect(
lambda _, cam = camera: self._cameraSelectionChanged(cam))
action.setChecked(action.data() == currCameraPath)
def _updatePropertiesFromPropertyView(self):
"""Update the data model's property selection to match property view's
current selection.
"""
selectedProperties = dict()
for item in self._ui.propertyView.selectedItems():
# We define data 'roles' in the property viewer to distinguish between things
# like attributes and attributes with connections, relationships and relationships
# with targets etc etc.
role = item.data(PropertyViewIndex.TYPE, QtCore.Qt.ItemDataRole.WhatsThisRole)
if role in (PropertyViewDataRoles.CONNECTION, PropertyViewDataRoles.TARGET):
# Get the owning property's set of selected targets.
propName = str(item.parent().text(PropertyViewIndex.NAME))
prop = self._propertiesDict[propName]
targets = selectedProperties.setdefault(prop, set())
# Add the target to the set of targets.
targetPath = Sdf.Path(str(item.text(PropertyViewIndex.NAME)))
if role == PropertyViewDataRoles.CONNECTION:
prim = self._dataModel.stage.GetPrimAtPath(
targetPath.GetPrimPath())
target = prim.GetProperty(targetPath.name)
else: # role == PropertyViewDataRoles.TARGET
target = self._dataModel.stage.GetPrimAtPath(
targetPath)
targets.add(target)
else:
propName = str(item.text(PropertyViewIndex.NAME))
prop = self._propertiesDict[propName]
selectedProperties.setdefault(prop, set())
with self._dataModel.selection.batchPropChanges:
self._dataModel.selection.clearProps()
for prop, targets in selectedProperties.items():
if not isinstance(prop, CustomAttribute):
self._dataModel.selection.addProp(prop)
for target in targets:
self._dataModel.selection.addPropTarget(prop, target)
with self._dataModel.selection.batchComputedPropChanges:
self._dataModel.selection.clearComputedProps()
for prop, targets in selectedProperties.items():
if isinstance(prop, CustomAttribute):
self._dataModel.selection.addComputedProp(prop)
def _propertyViewSelectionChanged(self):
"""Called whenever property view's selection changes."""
if self._propertyViewSelectionBlocker.blocked():
return
self._updatePropertiesFromPropertyView()
def _propertyViewCurrentItemChanged(self, currentItem, lastItem):
"""Called whenever property view's current item changes."""
if self._propertyViewSelectionBlocker.blocked():
return
# If a selected item becomes the current item, it will not fire a
# selection changed signal but we still want to change the property
# selection.
if currentItem is not None and currentItem.isSelected():
self._updatePropertiesFromPropertyView()
def _propSelectionChanged(self):
"""Called whenever the property selection in the data model changes.
Updates any UI that relies on the selection state.
"""
self._updatePropertyViewSelection()
self._populatePropertyInspector()
self._updatePropertyInspector()
def _populatePropertyInspector(self):
focusPrimPath = None
focusPropName = None
focusProp = self._dataModel.selection.getFocusProp()
if focusProp is None:
focusPrimPath, focusPropName = (
self._dataModel.selection.getFocusComputedPropPath())
else:
focusPrimPath = focusProp.GetPrimPath()
focusPropName = focusProp.GetName()
if focusPropName is not None:
# inform the value editor that we selected a new attribute
self._ui.attributeValueEditor.populate(focusPrimPath, focusPropName)
else:
self._ui.attributeValueEditor.clear()
def _onCompositionSelectionChanged(self, curr=None, prev=None):
self._currentSpec = getattr(curr, 'spec', None)
self._currentLayer = getattr(curr, 'layer', None)
def _updatePropertyInspector(self, index=None, obj=None):
# index must be the first parameter since this method is used as
# propertyInspector tab widget's currentChanged(int) signal callback
if index is None:
index = self._ui.propertyInspector.currentIndex()
if obj is None:
obj = self._getSelectedObject()
if index == PropertyIndex.METADATA:
self._updateMetadataView(obj)
elif index == PropertyIndex.LAYERSTACK:
self._updateLayerStackView(obj)
elif index == PropertyIndex.COMPOSITION:
self._updateCompositionView(obj)
def _refreshAttributeValue(self):
self._ui.attributeValueEditor.refresh()
def _propertyViewContextMenu(self, point):
item = self._ui.propertyView.itemAt(point)
if item:
self.contextMenu = AttributeViewContextMenu(self._mainWindow,
item, self._dataModel)
self.contextMenu.exec_(QtGui.QCursor.pos())
def _layerStackContextMenu(self, point):
item = self._ui.layerStackView.itemAt(point)
if item:
self.contextMenu = LayerStackContextMenu(self._mainWindow, item)
self.contextMenu.exec_(QtGui.QCursor.pos())
def _compositionTreeContextMenu(self, point):
item = self._ui.compositionTreeWidget.itemAt(point)
self.contextMenu = LayerStackContextMenu(self._mainWindow, item)
self.contextMenu.exec_(QtGui.QCursor.pos())
# Headers & Columns =================================================
def _propertyViewHeaderContextMenu(self, point):
self.contextMenu = HeaderContextMenu(self._ui.propertyView)
self.contextMenu.exec_(QtGui.QCursor.pos())
def _primViewHeaderContextMenu(self, point):
self.contextMenu = HeaderContextMenu(self._ui.primView)
self.contextMenu.exec_(QtGui.QCursor.pos())
# Widget management =================================================
def _changePrimViewDepth(self, action):
"""Signal handler for view-depth menu items
"""
actionTxt = str(action.text())
# recover the depth factor from the action's name
depth = int(actionTxt[actionTxt.find(" ")+1])
self._expandToDepth(depth)
def _expandToDepth(self, depth, suppressTiming=False):
"""Expands treeview prims to the given depth
"""
with Timer() as t, BusyContext():
# Populate items down to depth. Qt will expand items at depth
# depth-1 so we need to have items at depth. We know something
# changed if any items were added to _itemsToPush.
n = len(self._itemsToPush)
self._populateItem(self._dataModel.stage.GetPseudoRoot(),
maxDepth=depth)
changed = (n != len(self._itemsToPush))
# Expand the tree to depth.
self._ui.primView.expandToDepth(depth-1)
if changed:
# Resize column.
self._scheduleResizePrimView()
# Start pushing prim data to the UI during idle cycles.
# Qt doesn't need the data unless the item is actually
# visible (or affects what's visible) but to avoid
# jerky scrolling when that data is pulled during the
# scroll, we can do it ahead of time. But don't do it
# if we're currently playing to maximize playback
# performance.
if not self._dataModel.playing:
self._primViewUpdateTimer.start()
if self._printTiming and not suppressTiming:
t.PrintTime("expand Prim browser to depth %d" % depth)
def _primViewExpanded(self, index):
"""Signal handler for expanded(index), facilitates lazy tree population
"""
self._populateChildren(self._ui.primView.itemFromIndex(index))
self._scheduleResizePrimView()
def _toggleShowInactivePrims(self):
self._dataModel.viewSettings.showInactivePrims = (
self._ui.actionShow_Inactive_Prims.isChecked())
# Note: _toggleShowInactivePrims, _toggleShowMasterPrims,
# _toggleShowUndefinedPrims, and _toggleShowAbstractPrims all call
# _resetPrimView after being toggled, but only from menu items.
# In the future, we should do this when a signal from
# ViewSettingsDataModel is emitted so the prim view always updates
# when they are changed.
self._dataModel.selection.removeInactivePrims()
self._resetPrimView()
def _toggleShowMasterPrims(self):
self._dataModel.viewSettings.showAllMasterPrims = (
self._ui.actionShow_All_Master_Prims.isChecked())
self._dataModel.selection.removeMasterPrims()
self._resetPrimView()
def _toggleShowUndefinedPrims(self):
self._dataModel.viewSettings.showUndefinedPrims = (
self._ui.actionShow_Undefined_Prims.isChecked())
self._dataModel.selection.removeUndefinedPrims()
self._resetPrimView()
def _toggleShowAbstractPrims(self):
self._dataModel.viewSettings.showAbstractPrims = (
self._ui.actionShow_Abstract_Prims.isChecked())
self._dataModel.selection.removeAbstractPrims()
self._resetPrimView()
def _toggleRolloverPrimInfo(self):
self._dataModel.viewSettings.rolloverPrimInfo = (
self._ui.actionRollover_Prim_Info.isChecked())
if self._stageView:
self._stageView.rolloverPicking = self._dataModel.viewSettings.rolloverPrimInfo
def _tallyPrimStats(self, prim):
def _GetType(prim):
typeString = prim.GetTypeName()
return HUDEntries.NOTYPE if not typeString else typeString
childTypeDict = {}
primCount = 0
for child in Usd.PrimRange(prim):
typeString = _GetType(child)
# skip pseudoroot
if typeString is HUDEntries.NOTYPE and not prim.GetParent():
continue
primCount += 1
childTypeDict[typeString] = 1 + childTypeDict.get(typeString, 0)
return (primCount, childTypeDict)
def _populateChildren(self, item, depth=0, maxDepth=1, childrenToAdd=None):
"""Populates the children of the given item in the prim viewer.
If childrenToAdd is given its a list of prims to add as
children."""
if depth < maxDepth and item.prim.IsActive():
if item.needsChildrenPopulated() or childrenToAdd:
# Populate all the children.
if not childrenToAdd:
childrenToAdd = self._getFilteredChildren(item.prim)
item.addChildren([self._populateItem(child, depth+1, maxDepth)
for child in childrenToAdd])
elif depth + 1 < maxDepth:
# The children already exist but we're recursing deeper.
for i in range(item.childCount()):
self._populateChildren(item.child(i), depth+1, maxDepth)
def _populateItem(self, prim, depth=0, maxDepth=0):
"""Populates a prim viewer item."""
item = self._primToItemMap.get(prim)
if not item:
# Create a new item. If we want its children we obviously
# have to create those too.
children = self._getFilteredChildren(prim)
item = PrimViewItem(prim, self, len(children) != 0)
self._primToItemMap[prim] = item
self._populateChildren(item, depth, maxDepth, children)
# Push the item after the children so ancestors are processed
# before descendants.
self._itemsToPush.append(item)
else:
# Item already exists. Its children may or may not exist.
# Either way, we need to have them to get grandchildren.
self._populateChildren(item, depth, maxDepth)
return item
def _populateRoots(self):
invisibleRootItem = self._ui.primView.invisibleRootItem()
rootPrim = self._dataModel.stage.GetPseudoRoot()
rootItem = self._populateItem(rootPrim)
self._populateChildren(rootItem)
if self._dataModel.viewSettings.showAllMasterPrims:
self._populateChildren(rootItem,
childrenToAdd=self._dataModel.stage.GetMasters())
# Add all descendents all at once.
invisibleRootItem.addChild(rootItem)
def _getFilteredChildren(self, prim):
return prim.GetFilteredChildren(self._displayPredicate)
def _computeDisplayPredicate(self):
# Take current browser filtering into account when discovering
# prims while traversing
self._displayPredicate = None
if not self._dataModel.viewSettings.showInactivePrims:
self._displayPredicate = Usd.PrimIsActive \
if self._displayPredicate is None \
else self._displayPredicate & Usd.PrimIsActive
if not self._dataModel.viewSettings.showUndefinedPrims:
self._displayPredicate = Usd.PrimIsDefined \
if self._displayPredicate is None \
else self._displayPredicate & Usd.PrimIsDefined
if not self._dataModel.viewSettings.showAbstractPrims:
self._displayPredicate = ~Usd.PrimIsAbstract \
if self._displayPredicate is None \
else self._displayPredicate & ~Usd.PrimIsAbstract
if self._displayPredicate is None:
self._displayPredicate = Usd._PrimFlagsPredicate.Tautology()
# Unless user experience indicates otherwise, we think we always
# want to show instance proxies
self._displayPredicate = Usd.TraverseInstanceProxies(self._displayPredicate)
def _getItemAtPath(self, path, ensureExpanded=False):
# If the prim hasn't been expanded yet, drill down into it.
# Note the explicit str(path) in the following expr is necessary
# because path may be a QString.
path = path if isinstance(path, Sdf.Path) else Sdf.Path(str(path))
parent = self._dataModel.stage.GetPrimAtPath(path)
if not parent:
raise RuntimeError("Prim not found at path in stage: %s" % str(path))
pseudoRoot = self._dataModel.stage.GetPseudoRoot()
if parent not in self._primToItemMap:
# find the first loaded parent
childList = []
while parent != pseudoRoot \
and not parent in self._primToItemMap:
childList.append(parent)
parent = parent.GetParent()
# go one step further, since the first item found could be hidden
# under a norgie and we would want to populate its siblings as well
if parent != pseudoRoot:
childList.append(parent)
# now populate down to the child
for parent in reversed(childList):
try:
item = self._primToItemMap[parent]
self._populateChildren(item)
if ensureExpanded:
item.setExpanded(True)
except:
item = None
# finally, return the requested item, which now should be in
# the map. If something has been added, this can fail. Not
# sure how to rebuild or add this to the map in a minimal way,
# but after the first hiccup, I don't see any ill
# effects. Would love to know a better way...
# - wave 04.17.2018
prim = self._dataModel.stage.GetPrimAtPath(path)
try:
item = self._primToItemMap[prim]
except:
item = None
return item
def selectPseudoroot(self):
"""Selects only the pseudoroot."""
self._dataModel.selection.clearPrims()
def selectEnclosingModel(self):
"""Iterates through all selected prims, selecting their containing model
instead if they are not a model themselves.
"""
oldPrims = self._dataModel.selection.getPrims()
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in oldPrims:
model = GetEnclosingModelPrim(prim)
if model:
self._dataModel.selection.addPrim(model)
else:
self._dataModel.selection.addPrim(prim)
def selectBoundMaterialForPurpose(self, materialPurpose):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
oldPrims = self._dataModel.selection.getPrims()
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in oldPrims:
(boundMaterial, bindingRel) = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=materialPurpose)
if boundMaterial:
self._dataModel.selection.addPrim(boundMaterial.GetPrim())
def selectBindingRelForPurpose(self, materialPurpose):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
relsToSelect = []
oldPrims = self._dataModel.selection.getPrims()
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in oldPrims:
(boundMaterial, bindingRel) = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=materialPurpose)
if boundMaterial and bindingRel:
self._dataModel.selection.addPrim(bindingRel.GetPrim())
relsToSelect.append(bindingRel)
with self._dataModel.selection.batchPropChanges:
self._dataModel.selection.clearProps()
for rel in relsToSelect:
self._dataModel.selection.addProp(rel)
def selectBoundPreviewMaterial(self):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
self.selectBoundMaterialForPurpose(
materialPurpose=UsdShade.Tokens.preview)
def selectBoundFullMaterial(self):
"""Iterates through all selected prims, selecting their bound preview
materials.
"""
self.selectBoundMaterialForPurpose(
materialPurpose=UsdShade.Tokens.full)
def selectPreviewBindingRel(self):
"""Iterates through all selected prims, computing their resolved
"preview" bindings and selecting the cooresponding binding relationship.
"""
self.selectBindingRelForPurpose(materialPurpose=UsdShade.Tokens.preview)
def selectFullBindingRel(self):
"""Iterates through all selected prims, computing their resolved
"full" bindings and selecting the cooresponding binding relationship.
"""
self.selectBindingRelForPurpose(materialPurpose=UsdShade.Tokens.full)
def _getCommonPrims(self, pathsList):
commonPrefix = os.path.commonprefix(pathsList)
### To prevent /Canopies/TwigA and /Canopies/TwigB
### from registering /Canopies/Twig as prefix
return commonPrefix.rsplit('/', 1)[0]
def _primSelectionChanged(self, added, removed):
"""Called when the prim selection is updated in the data model. Updates
any UI that depends on the state of the selection.
"""
with self._primViewSelectionBlocker:
self._updatePrimViewSelection(added, removed)
self._updatePrimPathText()
if self._stageView:
self._updateHUDPrimStats()
self._updateHUDGeomCounts()
self._stageView.updateView()
self._updatePropertyInspector(
obj=self._dataModel.selection.getFocusPrim())
self._updatePropertyView()
self._refreshAttributeValue()
def _getPrimsFromPaths(self, paths):
"""Get all prims from a list of paths."""
prims = []
for path in paths:
# Ensure we have an Sdf.Path, not a string.
sdfPath = Sdf.Path(str(path))
prim = self._dataModel.stage.GetPrimAtPath(
sdfPath.GetAbsoluteRootOrPrimPath())
if not prim:
raise PrimNotFoundException(sdfPath)
prims.append(prim)
return prims
def _updatePrimPathText(self):
self._ui.currentPathWidget.setText(
', '.join([str(prim.GetPath())
for prim in self._dataModel.selection.getPrims()]))
def _currentPathChanged(self):
"""Called when the currentPathWidget text is changed"""
newPaths = self._ui.currentPathWidget.text()
pathList = re.split(", ?", newPaths)
pathList = [path for path in pathList if len(path) != 0]
try:
prims = self._getPrimsFromPaths(pathList)
except PrimNotFoundException as ex:
# _getPrimsFromPaths couldn't find one of the prims
sys.stderr.write("ERROR: %s\n" % str(ex))
self._updatePrimPathText()
return
explicitProps = any(Sdf.Path(str(path)).IsPropertyPath()
for path in pathList)
if len(prims) == 1 and not explicitProps:
self._dataModel.selection.switchToPrimPath(prims[0].GetPath())
else:
with self._dataModel.selection.batchPrimChanges:
self._dataModel.selection.clearPrims()
for prim in prims:
self._dataModel.selection.addPrim(prim)
with self._dataModel.selection.batchPropChanges:
self._dataModel.selection.clearProps()
for path, prim in zip(pathList, prims):
sdfPath = Sdf.Path(str(path))
if sdfPath.IsPropertyPath():
self._dataModel.selection.addPropPath(path)
self._dataModel.selection.clearComputedProps()
# A function for maintaining the primview. For each prim in prims,
# first check that it exists. Then if its item has not
# yet been populated, use _getItemAtPath to populate its "chain"
# of parents, so that the prim's item can be accessed. If it
# does already exist in the _primToItemMap, either expand or
# unexpand the item.
def _expandPrims(self, prims, expand=True):
if prims:
for prim in prims:
if prim:
item = self._primToItemMap.get(prim)
if not item:
primPath = prim.GetPrimPath()
item = self._getItemAtPath(primPath)
# Depending on our "Show Prim" settings, a valid,
# yet inactive, undefined, or abstract prim may
# not yield an item at all.
if item:
item.setExpanded(expand)
def _refreshPrimViewSelection(self, expandedPrims):
"""Refresh the selected prim view items to match the selection data
model.
"""
self._ui.primView.clearSelection()
selectedItems = [
self._getItemAtPath(prim.GetPath())
for prim in self._dataModel.selection.getPrims()]
if len(selectedItems) > 0:
self._ui.primView.setCurrentItem(selectedItems[0])
# unexpand items that were expanded through setting the current item
currExpandedPrims = self._getExpandedPrimViewPrims()
self._expandPrims(currExpandedPrims, expand=False)
# expand previously expanded items in primview
self._expandPrims(expandedPrims)
self._ui.primView.updateSelection(selectedItems, [])
def _updatePrimViewSelection(self, added, removed):
"""Do an incremental update to primView's selection using the added and
removed prim paths from the selectionDataModel.
"""
addedItems = [
self._getItemAtPath(path)
for path in added ]
removedItems = [ self._getItemAtPath(path) for path in removed ]
self._ui.primView.updateSelection(addedItems, removedItems)
def _primsFromSelectionRanges(self, ranges):
"""Iterate over all prims in a QItemSelection from primView."""
for itemRange in ranges:
for index in itemRange.indexes():
if index.column() == 0:
item = self._ui.primView.itemFromIndex(index)
yield item.prim
def _selectionChanged(self, added, removed):
"""Called when primView's selection is changed. If the selection was
changed by a user, update the selection data model with the changes.
"""
if self._primViewSelectionBlocker.blocked():
return
items = self._ui.primView.selectedItems()
if len(items) == 1:
self._dataModel.selection.switchToPrimPath(items[0].prim.GetPath())
else:
with self._dataModel.selection.batchPrimChanges:
for prim in self._primsFromSelectionRanges(added):
self._dataModel.selection.addPrim(prim)
for prim in self._primsFromSelectionRanges(removed):
self._dataModel.selection.removePrim(prim)
def _itemClicked(self, item, col):
# If user clicked in a selected row, we will toggle all selected items;
# otherwise, just the clicked one.
if col == PrimViewColumnIndex.VIS:
itemsToToggle = [ item ]
if item.isSelected():
itemsToToggle = [
self._getItemAtPath(prim.GetPath(), ensureExpanded=True)
for prim in self._dataModel.selection.getPrims()]
changedAny = False
with Timer() as t:
for toToggle in itemsToToggle:
# toggleVis() returns True if the click caused a visibility
# change.
changedOne = toToggle.toggleVis()
if changedOne:
PrimViewItem.propagateVis(toToggle)
changedAny = True
if changedAny:
self.editComplete('Updated prim visibility')
if self._printTiming:
t.PrintTime("update vis column")
def _itemPressed(self, item, col):
if col == PrimViewColumnIndex.DRAWMODE:
self._ui.primView.ShowDrawModeWidgetForItem(item)
def _getPathsFromItems(self, items, prune = False):
# this function returns a list of paths given a list of items if
# prune=True, it excludes certain paths if a parent path is already
# there this avoids double-rendering if both a prim and its parent
# are selected.
#
# Don't include the pseudoroot, though, if it's still selected, because
# leaving it in the pruned list will cause everything else to get
# pruned away!
allPaths = [itm.prim.GetPath() for itm in items]
if not prune:
return allPaths
if len(allPaths) > 1:
allPaths = [p for p in allPaths if p != Sdf.Path.absoluteRootPath]
return Sdf.Path.RemoveDescendentPaths(allPaths)
def _primViewContextMenu(self, point):
item = self._ui.primView.itemAt(point)
self._showPrimContextMenu(item)
def _showPrimContextMenu(self, item):
self.contextMenu = PrimContextMenu(self._mainWindow, item, self)
self.contextMenu.exec_(QtGui.QCursor.pos())
def setFrame(self, frame):
"""Set the `frame`.
Args:
frame (float): The new frame value.
"""
frameIndex = self._findClosestFrameIndex(frame)
self._setFrameIndex(frameIndex)
def _setFrameIndex(self, frameIndex):
"""Set the `frameIndex`.
Args:
frameIndex (int): The new frame index value.
"""
# Ensure the frameIndex exists, if not, return.
try:
frame = self._timeSamples[frameIndex]
except IndexError:
return
currentFrame = Usd.TimeCode(frame)
if self._dataModel.currentFrame != currentFrame:
self._dataModel.currentFrame = currentFrame
self._ui.frameSlider.setValue(frameIndex)
self._updateOnFrameChange()
self.setFrameField(self._dataModel.currentFrame.GetValue())
def _updateGUIForFrameChange(self):
"""Called when the frame changes have finished.
e.g When the playback/scrubbing has stopped.
"""
# slow stuff that we do only when not playing
# topology might have changed, recalculate
self._updateHUDGeomCounts()
self._updatePropertyView()
self._refreshAttributeValue()
# value sources of an attribute can change upon frame change
# due to value clips, so we must update the layer stack.
self._updateLayerStackView()
# refresh the visibility column
self._resetPrimViewVis(selItemsOnly=False, authoredVisHasChanged=False)
def _updateOnFrameChange(self):
"""Called when the frame changes, updates the renderer and such"""
# do not update HUD/BBOX if scrubbing or playing
if not (self._dataModel.playing or self._ui.frameSlider.isSliderDown()):
self._updateGUIForFrameChange()
if self._stageView:
# this is the part that renders
if self._dataModel.playing:
highlightMode = self._dataModel.viewSettings.selHighlightMode
if highlightMode == SelectionHighlightModes.ALWAYS:
# We don't want to resend the selection to the renderer
# every frame during playback unless we are actually going
# to see the selection (which is only when highlight mode is
# ALWAYS).
self._stageView.updateSelection()
self._stageView.updateForPlayback()
else:
self._stageView.updateSelection()
self._stageView.updateView()
def saveFrame(self, fileName):
if self._stageView:
pm = QtGui.QPixmap.grabWindow(self._stageView.winId())
pm.save(fileName, 'TIFF')
def _getPropertiesDict(self):
propertiesDict = OrderedDict()
# leave attribute viewer empty if multiple prims selected
if len(self._dataModel.selection.getPrims()) != 1:
return propertiesDict
prim = self._dataModel.selection.getFocusPrim()
composed = _GetCustomAttributes(prim, self._dataModel)
inheritedPrimvars = UsdGeom.PrimvarsAPI(prim).FindInheritablePrimvars()
# There may be overlap between inheritedProps and prim attributes,
# but that's OK because propsDict will uniquify them below
inheritedProps = [primvar.GetAttr() for primvar in inheritedPrimvars]
props = prim.GetAttributes() + prim.GetRelationships() + inheritedProps
def _cmp(v1, v2):
if v1 < v2:
return -1
if v2 < v1:
return 1
return 0
def cmpFunc(propA, propB):
aName = propA.GetName()
bName = propB.GetName()
return _cmp(aName.lower(), bName.lower())
props.sort(key=cmp_to_key(cmpFunc))
# Add the special composed attributes usdview generates
# at the top of our property list.
for prop in composed:
propertiesDict[prop.GetName()] = prop
for prop in props:
propertiesDict[prop.GetName()] = prop
return propertiesDict
def _propertyViewDeselectItem(self, item):
item.setSelected(False)
for i in range(item.childCount()):
item.child(i).setSelected(False)
def _updatePropertyViewSelection(self):
"""Updates property view's selected items to match the data model."""
focusPrim = self._dataModel.selection.getFocusPrim()
propTargets = self._dataModel.selection.getPropTargets()
computedProps = self._dataModel.selection.getComputedPropPaths()
selectedPrimPropNames = dict()
selectedPrimPropNames.update({prop.GetName(): targets
for prop, targets in propTargets.items()})
selectedPrimPropNames.update({propName: set()
for primPath, propName in computedProps})
rootItem = self._ui.propertyView.invisibleRootItem()
with self._propertyViewSelectionBlocker:
for i in range(rootItem.childCount()):
item = rootItem.child(i)
propName = str(item.text(PropertyViewIndex.NAME))
if propName in selectedPrimPropNames:
item.setSelected(True)
# Select relationships and connections.
targets = {prop.GetPath()
for prop in selectedPrimPropNames[propName]}
for j in range(item.childCount()):
childItem = item.child(j)
targetPath = Sdf.Path(
str(childItem.text(PropertyViewIndex.NAME)))
if targetPath in targets:
childItem.setSelected(True)
else:
self._propertyViewDeselectItem(item)
def _updatePropertyViewInternal(self):
frame = self._dataModel.currentFrame
treeWidget = self._ui.propertyView
treeWidget.setTextElideMode(QtCore.Qt.ElideMiddle)
scrollPosition = treeWidget.verticalScrollBar().value()
# get a dictionary of prim attribs/members and store it in self._propertiesDict
self._propertiesDict = self._getPropertiesDict()
with self._propertyViewSelectionBlocker:
treeWidget.clear()
self._populatePropertyInspector()
curPrimSelection = self._dataModel.selection.getFocusPrim()
currRow = 0
for key, primProperty in self._propertiesDict.items():
targets = None
isInheritedProperty = isinstance(primProperty, Usd.Property) and \
(primProperty.GetPrim() != curPrimSelection)
if type(primProperty) == Usd.Attribute:
if primProperty.HasAuthoredConnections():
typeContent = PropertyViewIcons.ATTRIBUTE_WITH_CONNECTIONS()
typeRole = PropertyViewDataRoles.ATTRIBUTE_WITH_CONNNECTIONS
targets = primProperty.GetConnections()
else:
typeContent = PropertyViewIcons.ATTRIBUTE()
typeRole = PropertyViewDataRoles.ATTRIBUTE
elif isinstance(primProperty, ResolvedBoundMaterial):
typeContent = PropertyViewIcons.COMPOSED()
typeRole = PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS
elif isinstance(primProperty, CustomAttribute):
typeContent = PropertyViewIcons.COMPOSED()
typeRole = PropertyViewDataRoles.COMPOSED
elif isinstance(primProperty, Usd.Relationship):
# Otherwise we have a relationship
targets = primProperty.GetTargets()
if targets:
typeContent = PropertyViewIcons.RELATIONSHIP_WITH_TARGETS()
typeRole = PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS
else:
typeContent = PropertyViewIcons.RELATIONSHIP()
typeRole = PropertyViewDataRoles.RELATIONSHIP
else:
PrintWarning("Property '%s' has unknown property type <%s>." %
(key, type(primProperty)))
continue
valFunc, attrText = GetValueAndDisplayString(primProperty, frame)
item = QtWidgets.QTreeWidgetItem(["", str(key), attrText])
item.rawValue = valFunc()
treeWidget.addTopLevelItem(item)
treeWidget.topLevelItem(currRow).setIcon(PropertyViewIndex.TYPE,
typeContent)
treeWidget.topLevelItem(currRow).setData(PropertyViewIndex.TYPE,
QtCore.Qt.ItemDataRole.WhatsThisRole,
typeRole)
currItem = treeWidget.topLevelItem(currRow)
valTextFont = GetPropertyTextFont(primProperty, frame)
if valTextFont:
currItem.setFont(PropertyViewIndex.VALUE, valTextFont)
currItem.setFont(PropertyViewIndex.NAME, valTextFont)
else:
currItem.setFont(PropertyViewIndex.NAME, UIFonts.BOLD)
fgColor = GetPropertyColor(primProperty, frame)
# Inherited properties are colored 15% darker, along with the
# addition of "(i)" in the type column.
if isInheritedProperty:
# Add "(i)" to the type column to indicate an inherited
# property.
treeWidget.topLevelItem(currRow).setText(PropertyViewIndex.TYPE,
"(i)")
fgColor = fgColor.darker(115)
currItem.setFont(PropertyViewIndex.TYPE, UIFonts.INHERITED)
currItem.setForeground(PropertyViewIndex.NAME, fgColor)
currItem.setForeground(PropertyViewIndex.VALUE, fgColor)
if targets:
childRow = 0
for t in targets:
valTextFont = GetPropertyTextFont(primProperty, frame) or \
UIFonts.BOLD
# USD does not provide or infer values for relationship or
# connection targets, so we don't display them here.
currItem.addChild(
QtWidgets.QTreeWidgetItem(["", str(t), ""]))
currItem.setFont(PropertyViewIndex.VALUE, valTextFont)
child = currItem.child(childRow)
if typeRole == PropertyViewDataRoles.RELATIONSHIP_WITH_TARGETS:
child.setIcon(PropertyViewIndex.TYPE,
PropertyViewIcons.TARGET())
child.setData(PropertyViewIndex.TYPE,
QtCore.Qt.ItemDataRole.WhatsThisRole,
PropertyViewDataRoles.TARGET)
else:
child.setIcon(PropertyViewIndex.TYPE,
PropertyViewIcons.CONNECTION())
child.setData(PropertyViewIndex.TYPE,
QtCore.Qt.ItemDataRole.WhatsThisRole,
PropertyViewDataRoles.CONNECTION)
childRow += 1
currRow += 1
self._updatePropertyViewSelection()
# For some reason, resetting the scrollbar position here only works on a
# frame change, not when the prim changes. When the prim changes, the
# scrollbar always stays at the top of the list and setValue() has no
# effect.
treeWidget.verticalScrollBar().setValue(scrollPosition)
def _updatePropertyView(self):
""" Sets the contents of the attribute value viewer """
cursorOverride = not self._timer.isActive()
if cursorOverride:
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
try:
self._updatePropertyViewInternal()
except Exception as err:
print("Problem encountered updating attribute view: %s" % err)
raise
finally:
if cursorOverride:
QtWidgets.QApplication.restoreOverrideCursor()
def _getSelectedObject(self):
focusPrim = self._dataModel.selection.getFocusPrim()
attrs = self._ui.propertyView.selectedItems()
if len(attrs) == 0:
return focusPrim
selectedAttribute = attrs[0]
attrName = str(selectedAttribute.text(PropertyViewIndex.NAME))
if PropTreeWidgetTypeIsRel(selectedAttribute):
return focusPrim.GetRelationship(attrName)
obj = focusPrim.GetAttribute(attrName)
if not obj:
# Check if it is an inherited primvar.
inheritedPrimvar = UsdGeom.PrimvarsAPI(
focusPrim).FindPrimvarWithInheritance(attrName)
if inheritedPrimvar:
obj = inheritedPrimvar.GetAttr()
return obj
def _findIndentPos(self, s):
for index, char in enumerate(s):
if char != ' ':
return index
return len(s) - 1
def _maxToolTipWidth(self):
return 90
def _maxToolTipHeight(self):
return 32
def _trimWidth(self, s, isList=False):
# We special-case the display offset because list
# items will have </li> tags embedded in them.
offset = 10 if isList else 5
if len(s) >= self._maxToolTipWidth():
# For strings, well do special ellipsis behavior
# which displays the last 5 chars with an ellipsis
# in between. For other values, we simply display a
# trailing ellipsis to indicate more data.
if s[0] == '\'' and s[-1] == '\'':
return (s[:self._maxToolTipWidth() - offset]
+ '...'
+ s[len(s) - offset:])
else:
return s[:self._maxToolTipWidth()] + '...'
return s
def _limitToolTipSize(self, s, isList=False):
ttStr = ''
lines = s.split('<br>')
for index, line in enumerate(lines):
if index+1 > self._maxToolTipHeight():
break
ttStr += self._trimWidth(line, isList)
if not isList and index != len(lines)-1:
ttStr += '<br>'
if (len(lines) > self._maxToolTipHeight()):
ellipsis = ' '*self._findIndentPos(line) + '...'
if isList:
ellipsis = '<li>' + ellipsis + '</li>'
else:
ellipsis += '<br>'
ttStr += ellipsis
ttStr += self._trimWidth(lines[len(lines)-2], isList)
return ttStr
def _addRichTextIndicators(self, s):
# - We'll need to use html-style spaces to ensure they are respected
# in the toolTip which uses richtext formatting.
# - We wrap the tooltip as a paragraph to ensure 's are
# respected by Qt's rendering engine.
return '<p>' + s.replace(' ', ' ') + '</p>'
def _limitValueDisplaySize(self, s):
maxValueChars = 300
return s[:maxValueChars]
def _cleanStr(self, s, repl):
# Remove redundant char seqs and strip newlines.
replaced = str(s).replace('\n', repl)
filtered = [u for (u, _) in groupby(replaced.split())]
return ' '.join(filtered)
def _formatMetadataValueView(self, val):
from pprint import pformat, pprint
valStr = self._cleanStr(val, ' ')
ttStr = ''
isList = False
# For iterable things, like VtArrays and lists, we want to print
# a nice numbered list.
if isinstance(val, list) or getattr(val, "_isVtArray", False):
isList = True
# We manually supply the index for our list elements
# because Qt's richtext processor starts the <ol> numbering at 1.
for index, value in enumerate(val):
last = len(val) - 1
trimmed = self._cleanStr(value, ' ')
ttStr += ("<li>" + str(index) + ": " + trimmed + "</li><br>")
elif isinstance(val, dict):
# We stringify all dict elements so they display more nicely.
# For example, by default, the pprint operation would print a
# Vt Array as Vt.Array(N, (E1, ....). By running it through
# str(..). we'd get [(E1, E2), ....] which is more useful to
# the end user trying to examine their data.
for k, v in val.items():
val[k] = str(v)
# We'll need to strip the quotes generated by the str' operation above
stripQuotes = lambda s: s.replace('\'', '').replace('\"', "")
valStr = stripQuotes(self._cleanStr(val, ' '))
formattedDict = pformat(val)
formattedDictLines = formattedDict.split('\n')
for index, line in enumerate(formattedDictLines):
ttStr += (stripQuotes(line)
+ ('' if index == len(formattedDictLines) - 1 else '<br>'))
else:
ttStr = self._cleanStr(val, '<br>')
valStr = self._limitValueDisplaySize(valStr)
ttStr = self._addRichTextIndicators(
self._limitToolTipSize(ttStr, isList))
return valStr, ttStr
def _updateMetadataView(self, obj=None):
""" Sets the contents of the metadata viewer"""
# XXX: this method gets called multiple times on selection, it
# would be nice to clean that up and ensure we only update as needed.
tableWidget = self._ui.metadataView
self._propertiesDict = self._getPropertiesDict()
# Setup table widget
tableWidget.clearContents()
tableWidget.setRowCount(0)
if obj is None:
obj = self._getSelectedObject()
if not obj:
return
m = obj.GetAllMetadata()
# We have to explicitly add in metadata related to composition arcs
# and value clips here, since GetAllMetadata prunes them out.
#
# XXX: Would be nice to have some official facility to query
# this.
compKeys = [# composition related metadata
"references", "inheritPaths", "specializes",
"payload", "subLayers"]
for k in compKeys:
v = obj.GetMetadata(k)
if not v is None:
m[k] = v
clipMetadata = obj.GetMetadata("clips")
if clipMetadata is None:
clipMetadata = {}
numClipRows = 0
for (clip, data) in clipMetadata.items():
numClipRows += len(data)
m["clips"] = clipMetadata
numMetadataRows = (len(m) - 1) + numClipRows
# Variant selections that don't have a defined variant set will be
# displayed as well to aid debugging. Collect them separately from
# the variant sets.
variantSets = {}
setlessVariantSelections = {}
if (isinstance(obj, Usd.Prim)):
# Get all variant selections as setless and remove the ones we find
# sets for.
setlessVariantSelections = obj.GetVariantSets().GetAllVariantSelections()
variantSetNames = obj.GetVariantSets().GetNames()
for variantSetName in variantSetNames:
variantSet = obj.GetVariantSet(variantSetName)
variantNames = variantSet.GetVariantNames()
variantSelection = variantSet.GetVariantSelection()
combo = VariantComboBox(None, obj, variantSetName, self._mainWindow)
# First index is always empty to indicate no (or invalid)
# variant selection.
combo.addItem('')
for variantName in variantNames:
combo.addItem(variantName)
indexToSelect = combo.findText(variantSelection)
combo.setCurrentIndex(indexToSelect)
variantSets[variantSetName] = combo
# Remove found variant set from setless.
setlessVariantSelections.pop(variantSetName, None)
tableWidget.setRowCount(numMetadataRows + len(variantSets) +
len(setlessVariantSelections) + 2)
rowIndex = 0
# Although most metadata should be presented alphabetically,the most
# user-facing items should be placed at the beginning of the metadata
# list, these consist of [object type], [path], variant sets, active,
# assetInfo, and kind.
def populateMetadataTable(key, val, rowIndex):
attrName = QtWidgets.QTableWidgetItem(str(key))
tableWidget.setItem(rowIndex, 0, attrName)
valStr, ttStr = self._formatMetadataValueView(val)
attrVal = QtWidgets.QTableWidgetItem(valStr)
attrVal.setToolTip(ttStr)
tableWidget.setItem(rowIndex, 1, attrVal)
sortedKeys = sorted(m.keys())
reorderedKeys = ["kind", "assetInfo", "active"]
for key in reorderedKeys:
if key in sortedKeys:
sortedKeys.remove(key)
sortedKeys.insert(0, key)
object_type = "Attribute" if type(obj) is Usd.Attribute \
else "Prim" if type(obj) is Usd.Prim \
else "Relationship" if type(obj) is Usd.Relationship \
else "Unknown"
populateMetadataTable("[object type]", object_type, rowIndex)
rowIndex += 1
populateMetadataTable("[path]", str(obj.GetPath()), rowIndex)
rowIndex += 1
for variantSetName, combo in variantSets.items():
attrName = QtWidgets.QTableWidgetItem(str(variantSetName+ ' variant'))
tableWidget.setItem(rowIndex, 0, attrName)
tableWidget.setCellWidget(rowIndex, 1, combo)
combo.currentIndexChanged.connect(
lambda i, combo=combo: combo.updateVariantSelection(
i, self._printTiming))
rowIndex += 1
# Add all the setless variant selections directly after the variant
# combo boxes
for variantSetName, variantSelection in setlessVariantSelections.items():
attrName = QtWidgets.QTableWidgetItem(str(variantSetName+ ' variant'))
tableWidget.setItem(rowIndex, 0, attrName)
valStr, ttStr = self._formatMetadataValueView(variantSelection)
# Italicized label to stand out when debugging a scene.
label = QtWidgets.QLabel('<i>' + valStr + '</i>')
label.setIndent(3)
label.setToolTip(ttStr)
tableWidget.setCellWidget(rowIndex, 1, label)
rowIndex += 1
for key in sortedKeys:
if key == "clips":
for (clip, metadataGroup) in m[key].items():
attrName = QtWidgets.QTableWidgetItem(str('clips:' + clip))
tableWidget.setItem(rowIndex, 0, attrName)
for metadata in metadataGroup.keys():
dataPair = (metadata, metadataGroup[metadata])
valStr, ttStr = self._formatMetadataValueView(dataPair)
attrVal = QtWidgets.QTableWidgetItem(valStr)
attrVal.setToolTip(ttStr)
tableWidget.setItem(rowIndex, 1, attrVal)
rowIndex += 1
elif key == "customData":
populateMetadataTable(key, obj.GetCustomData(), rowIndex)
rowIndex += 1
else:
populateMetadataTable(key, m[key], rowIndex)
rowIndex += 1
tableWidget.resizeColumnToContents(0)
def _updateCompositionView(self, obj=None):
""" Sets the contents of the composition tree view"""
treeWidget = self._ui.compositionTreeWidget
treeWidget.clear()
# Update current spec & current layer, and push those updates
# to the python console
self._onCompositionSelectionChanged()
# If no prim or attribute selected, nothing to show.
if obj is None:
obj = self._getSelectedObject()
if not obj:
return
# For brevity, we display only the basename of layer paths.
def LabelForLayer(l):
return ('~session~' if l == self._dataModel.stage.GetSessionLayer()
else l.GetDisplayName())
# Create treeview items for all sublayers in the layer tree.
def WalkSublayers(parent, node, layerTree, sublayer=False):
layer = layerTree.layer
spec = layer.GetObjectAtPath(node.path)
item = QtWidgets.QTreeWidgetItem(
parent,
[
LabelForLayer(layer),
'sublayer' if sublayer else node.arcType.displayName,
str(node.GetPathAtIntroduction()),
'yes' if bool(spec) else 'no'
] )
# attributes for selection:
item.layer = layer
item.spec = spec
item.identifier = layer.identifier
# attributes for LayerStackContextMenu:
if layer.realPath:
item.layerPath = layer.realPath
if spec:
item.path = node.path
item.setExpanded(True)
item.setToolTip(0, layer.identifier)
if not spec:
for i in range(item.columnCount()):
item.setForeground(i, UIPropertyValueSourceColors.NONE)
for subtree in layerTree.childTrees:
WalkSublayers(item, node, subtree, True)
return item
# Create treeview items for all nodes in the composition index.
def WalkNodes(parent, node):
nodeItem = WalkSublayers(parent, node, node.layerStack.layerTree)
for child in node.children:
WalkNodes(nodeItem, child)
path = obj.GetPath().GetAbsoluteRootOrPrimPath()
prim = self._dataModel.stage.GetPrimAtPath(path)
if not prim:
return
# Populate the treeview with items from the prim index.
index = prim.GetPrimIndex()
if index.IsValid():
WalkNodes(treeWidget, index.rootNode)
def _updateLayerStackView(self, obj=None):
""" Sets the contents of the layer stack viewer"""
tableWidget = self._ui.layerStackView
# Setup table widget
tableWidget.clearContents()
tableWidget.setRowCount(0)
if obj is None:
obj = self._getSelectedObject()
if not obj:
return
path = obj.GetPath()
# The pseudoroot is different enough from prims and properties that
# it makes more sense to process it separately
if path == Sdf.Path.absoluteRootPath:
layers = GetRootLayerStackInfo(
self._dataModel.stage.GetRootLayer())
tableWidget.setColumnCount(2)
tableWidget.horizontalHeaderItem(1).setText('Layer Offset')
tableWidget.setRowCount(len(layers))
for i, layer in enumerate(layers):
layerItem = QtWidgets.QTableWidgetItem(layer.GetHierarchicalDisplayString())
layerItem.layerPath = layer.layer.realPath
layerItem.identifier = layer.layer.identifier
toolTip = "<b>identifier:</b> @%s@ <br> <b>resolved path:</b> %s" % \
(layer.layer.identifier, layerItem.layerPath)
toolTip = self._limitToolTipSize(toolTip)
layerItem.setToolTip(toolTip)
tableWidget.setItem(i, 0, layerItem)
offsetItem = QtWidgets.QTableWidgetItem(layer.GetOffsetString())
offsetItem.layerPath = layer.layer.realPath
offsetItem.identifier = layer.layer.identifier
toolTip = self._limitToolTipSize(str(layer.offset))
offsetItem.setToolTip(toolTip)
tableWidget.setItem(i, 1, offsetItem)
tableWidget.resizeColumnToContents(0)
else:
specs = []
tableWidget.setColumnCount(3)
header = tableWidget.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
tableWidget.horizontalHeaderItem(1).setText('Path')
if path.IsPropertyPath():
prop = obj.GetPrim().GetProperty(path.name)
specs = prop.GetPropertyStack(self._dataModel.currentFrame)
c3 = "Value" if (len(specs) == 0 or
isinstance(specs[0], Sdf.AttributeSpec)) else "Target Paths"
tableWidget.setHorizontalHeaderItem(2,
QtWidgets.QTableWidgetItem(c3))
else:
specs = obj.GetPrim().GetPrimStack()
tableWidget.setHorizontalHeaderItem(2,
QtWidgets.QTableWidgetItem('Metadata'))
tableWidget.setRowCount(len(specs))
for i, spec in enumerate(specs):
layerItem = QtWidgets.QTableWidgetItem(spec.layer.GetDisplayName())
layerItem.setToolTip(self._limitToolTipSize(spec.layer.realPath))
tableWidget.setItem(i, 0, layerItem)
pathItem = QtWidgets.QTableWidgetItem(spec.path.pathString)
pathItem.setToolTip(self._limitToolTipSize(spec.path.pathString))
tableWidget.setItem(i, 1, pathItem)
if path.IsPropertyPath():
_, valStr = GetValueAndDisplayString(spec,
self._dataModel.currentFrame)
ttStr = valStr
valueItem = QtWidgets.QTableWidgetItem(valStr)
sampleBased = spec.layer.GetNumTimeSamplesForPath(path) > 0
valueItemColor = (UIPropertyValueSourceColors.TIME_SAMPLE if
sampleBased else UIPropertyValueSourceColors.DEFAULT)
valueItem.setForeground(valueItemColor)
valueItem.setToolTip(ttStr)
else:
metadataKeys = spec.GetMetaDataInfoKeys()
metadataDict = {}
for mykey in metadataKeys:
if spec.HasInfo(mykey):
metadataDict[mykey] = spec.GetInfo(mykey)
valStr, ttStr = self._formatMetadataValueView(metadataDict)
valueItem = QtWidgets.QTableWidgetItem(valStr)
valueItem.setToolTip(ttStr)
tableWidget.setItem(i, 2, valueItem)
# Add the data the context menu needs
for j in range(3):
item = tableWidget.item(i, j)
item.layerPath = spec.layer.realPath
item.path = spec.path.pathString
item.identifier = spec.layer.identifier
def _isHUDVisible(self):
"""Checks if the upper HUD is visible by looking at the global HUD
visibility menu as well as the 'Subtree Info' menu"""
return self._dataModel.viewSettings.showHUD and self._dataModel.viewSettings.showHUD_Info
def _updateCameraMaskMenu(self):
if self._ui.actionCameraMask_Full.isChecked():
self._dataModel.viewSettings.cameraMaskMode = CameraMaskModes.FULL
elif self._ui.actionCameraMask_Partial.isChecked():
self._dataModel.viewSettings.cameraMaskMode = CameraMaskModes.PARTIAL
else:
self._dataModel.viewSettings.cameraMaskMode = CameraMaskModes.NONE
def _updateCameraMaskOutlineMenu(self):
self._dataModel.viewSettings.showMask_Outline = (
self._ui.actionCameraMask_Outline.isChecked())
def _pickCameraMaskColor(self):
QtWidgets.QColorDialog.setCustomColor(0, 0xFF000000)
QtWidgets.QColorDialog.setCustomColor(1, 0xFF808080)
color = QtWidgets.QColorDialog.getColor()
color = (
color.redF(),
color.greenF(),
color.blueF(),
color.alphaF()
)
self._dataModel.viewSettings.cameraMaskColor = color
def _updateCameraReticlesInsideMenu(self):
self._dataModel.viewSettings.showReticles_Inside = (
self._ui.actionCameraReticles_Inside.isChecked())
def _updateCameraReticlesOutsideMenu(self):
self._dataModel.viewSettings.showReticles_Outside = (
self._ui.actionCameraReticles_Outside.isChecked())
def _pickCameraReticlesColor(self):
QtWidgets.QColorDialog.setCustomColor(0, 0xFF000000)
QtWidgets.QColorDialog.setCustomColor(1, 0xFF0080FF)
color = QtWidgets.QColorDialog.getColor()
color = (
color.redF(),
color.greenF(),
color.blueF(),
color.alphaF()
)
self._dataModel.viewSettings.cameraReticlesColor = color
def _showHUDChanged(self):
self._dataModel.viewSettings.showHUD = self._ui.actionHUD.isChecked()
def _showHUD_InfoChanged(self):
self._dataModel.viewSettings.showHUD_Info = (
self._ui.actionHUD_Info.isChecked())
def _showHUD_ComplexityChanged(self):
self._dataModel.viewSettings.showHUD_Complexity = (
self._ui.actionHUD_Complexity.isChecked())
def _showHUD_PerformanceChanged(self):
self._dataModel.viewSettings.showHUD_Performance = (
self._ui.actionHUD_Performance.isChecked())
def _showHUD_GPUstatsChanged(self):
self._dataModel.viewSettings.showHUD_GPUstats = (
self._ui.actionHUD_GPUstats.isChecked())
def _getHUDStatKeys(self):
''' returns the keys of the HUD with PRIM and NOTYPE and the top and
CV, VERT, and FACE at the bottom.'''
keys = [k for k in self._upperHUDInfo.keys() if k not in (
HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE, HUDEntries.PRIM, HUDEntries.NOTYPE)]
keys = [HUDEntries.PRIM, HUDEntries.NOTYPE] + keys + [HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE]
return keys
def _updateHUDPrimStats(self):
"""update the upper HUD with the proper prim information"""
self._upperHUDInfo = dict()
if self._isHUDVisible():
currentPaths = [n.GetPath()
for n in self._dataModel.selection.getLCDPrims()
if n.IsActive()]
for pth in currentPaths:
count,types = self._tallyPrimStats(
self._dataModel.stage.GetPrimAtPath(pth))
# no entry for Prim counts? initilize it
if HUDEntries.PRIM not in self._upperHUDInfo:
self._upperHUDInfo[HUDEntries.PRIM] = 0
self._upperHUDInfo[HUDEntries.PRIM] += count
for typeKey in types.keys():
# no entry for this prim type? initilize it
if typeKey not in self._upperHUDInfo:
self._upperHUDInfo[typeKey] = 0
self._upperHUDInfo[typeKey] += types[typeKey]
if self._stageView:
self._stageView.upperHUDInfo = self._upperHUDInfo
self._stageView.HUDStatKeys = self._getHUDStatKeys()
def _updateHUDGeomCounts(self):
"""updates the upper HUD with the right geom counts
calls _getGeomCounts() to get the info, which means it could be cached"""
if not self._isHUDVisible():
return
# we get multiple geom dicts, if we have multiple prims selected
geomDicts = [self._getGeomCounts(n, self._dataModel.currentFrame)
for n in self._dataModel.selection.getLCDPrims()]
for key in (HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE):
self._upperHUDInfo[key] = 0
for gDict in geomDicts:
self._upperHUDInfo[key] += gDict[key]
if self._stageView:
self._stageView.upperHUDInfo = self._upperHUDInfo
self._stageView.HUDStatKeys = self._getHUDStatKeys()
def _clearGeomCountsForPrimPath(self, primPath):
entriesToRemove = []
# Clear all entries whose prim is either an ancestor or a descendant
# of the given prim path.
for (p, frame) in self._geomCounts:
if (primPath.HasPrefix(p.GetPath()) or p.GetPath().HasPrefix(primPath)):
entriesToRemove.append((p, frame))
for entry in entriesToRemove:
del self._geomCounts[entry]
def _getGeomCounts( self, prim, frame ):
"""returns cached geom counts if available, or calls _calculateGeomCounts()"""
if (prim,frame) not in self._geomCounts:
self._calculateGeomCounts( prim, frame )
return self._geomCounts[(prim,frame)]
def _accountForFlattening(self,shape):
"""Helper function for computing geomCounts"""
if len(shape) == 1:
return shape[0] // 3
else:
return shape[0]
def _calculateGeomCounts(self, prim, frame):
"""Computes the number of CVs, Verts, and Faces for each prim and each
frame in the stage (for use by the HUD)"""
# This is expensive enough that we should give the user feedback
# that something is happening...
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.BusyCursor)
try:
thisDict = {HUDEntries.CV: 0, HUDEntries.VERT: 0, HUDEntries.FACE: 0}
if prim.IsA(UsdGeom.Curves):
curves = UsdGeom.Curves(prim)
vertexCounts = curves.GetCurveVertexCountsAttr().Get(frame)
if vertexCounts is not None:
for count in vertexCounts:
thisDict[HUDEntries.CV] += count
elif prim.IsA(UsdGeom.Mesh):
mesh = UsdGeom.Mesh(prim)
faceVertexCount = mesh.GetFaceVertexCountsAttr().Get(frame)
faceVertexIndices = mesh.GetFaceVertexIndicesAttr().Get(frame)
if faceVertexCount is not None and faceVertexIndices is not None:
uniqueVerts = set(faceVertexIndices)
thisDict[HUDEntries.VERT] += len(uniqueVerts)
thisDict[HUDEntries.FACE] += len(faceVertexCount)
self._geomCounts[(prim,frame)] = thisDict
for child in prim.GetChildren():
childResult = self._getGeomCounts(child, frame)
for key in (HUDEntries.CV, HUDEntries.VERT, HUDEntries.FACE):
self._geomCounts[(prim,frame)][key] += childResult[key]
except Exception as err:
print("Error encountered while computing prim subtree HUD info: %s" % err)
finally:
QtWidgets.QApplication.restoreOverrideCursor()
def _updateNavigationMenu(self):
"""Make the Navigation menu items enabled or disabled depending on the
selected prim."""
anyModels = False
anyBoundPreviewMaterials = False
anyBoundFullMaterials = False
for prim in self._dataModel.selection.getPrims():
if prim.IsA(UsdGeom.Imageable):
imageable = UsdGeom.Imageable(prim)
anyModels = anyModels or GetEnclosingModelPrim(prim) is not None
(previewMat,previewBindingRel) =\
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.preview)
anyBoundPreviewMaterials |= bool(previewMat)
(fullMat,fullBindingRel) =\
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.full)
anyBoundFullMaterials |= bool(fullMat)
self._ui.actionSelect_Model_Root.setEnabled(anyModels)
self._ui.actionSelect_Bound_Preview_Material.setEnabled(
anyBoundPreviewMaterials)
self._ui.actionSelect_Preview_Binding_Relationship.setEnabled(
anyBoundPreviewMaterials)
self._ui.actionSelect_Bound_Full_Material.setEnabled(
anyBoundFullMaterials)
self._ui.actionSelect_Full_Binding_Relationship.setEnabled(
anyBoundFullMaterials)
def _updateEditMenu(self):
"""Make the Edit Prim menu items enabled or disabled depending on the
selected prim."""
# Use the descendent-pruned selection set to avoid redundant
# traversal of the stage to answer isLoaded...
anyLoadable, unused = GetPrimsLoadability(
self._dataModel.selection.getLCDPrims())
removeEnabled = False
anyImageable = False
anyActive = False
anyInactive = False
for prim in self._dataModel.selection.getPrims():
if prim.IsA(UsdGeom.Imageable):
imageable = UsdGeom.Imageable(prim)
anyImageable = anyImageable or bool(imageable)
removeEnabled = removeEnabled or HasSessionVis(prim)
if prim.IsActive():
anyActive = True
else:
anyInactive = True
self._ui.actionRemove_Session_Visibility.setEnabled(removeEnabled)
self._ui.actionMake_Visible.setEnabled(anyImageable)
self._ui.actionVis_Only.setEnabled(anyImageable)
self._ui.actionMake_Invisible.setEnabled(anyImageable)
self._ui.actionLoad.setEnabled(anyLoadable)
self._ui.actionUnload.setEnabled(anyLoadable)
self._ui.actionActivate.setEnabled(anyInactive)
self._ui.actionDeactivate.setEnabled(anyActive)
def getSelectedItems(self):
return [self._primToItemMap[n]
for n in self._dataModel.selection.getPrims()
if n in self._primToItemMap]
def _getPrimFromPropString(self, p):
return self._dataModel.stage.GetPrimAtPath(p.split('.')[0])
def visSelectedPrims(self):
with BusyContext():
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.MakeVisible()
self.editComplete('Made selected prims visible')
def visOnlySelectedPrims(self):
with BusyContext():
ResetSessionVisibility(self._dataModel.stage)
InvisRootPrims(self._dataModel.stage)
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.MakeVisible()
self.editComplete('Made ONLY selected prims visible')
def invisSelectedPrims(self):
with BusyContext():
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.MakeInvisible()
self.editComplete('Made selected prims invisible')
def removeVisSelectedPrims(self):
with BusyContext():
for p in self._dataModel.selection.getPrims():
imgbl = UsdGeom.Imageable(p)
if imgbl:
imgbl.GetVisibilityAttr().Clear()
self.editComplete("Removed selected prims' visibility opinions")
def resetSessionVisibility(self):
with BusyContext():
ResetSessionVisibility(self._dataModel.stage)
self.editComplete('Removed ALL session visibility opinions.')
def _setSelectedPrimsActivation(self, active):
"""Activate or deactivate all selected prims."""
with BusyContext():
# We can only activate/deactivate prims which are not in a master.
paths = []
for item in self.getSelectedItems():
if item.prim.IsPseudoRoot():
print("WARNING: Cannot change activation of pseudoroot.")
elif item.isInMaster:
print("WARNING: The prim <" + str(item.prim.GetPrimPath()) +
"> is in a master. Cannot change activation.")
else:
paths.append(item.prim.GetPrimPath())
# If we are deactivating prims, clear the selection so it doesn't
# hold onto paths from inactive prims.
if not active:
self._dataModel.selection.clear()
# If we try to deactivate prims one at a time in Usd, some may have
# become invalid by the time we get to them. Instead, we set the
# active state all at once through Sdf.
layer = self._dataModel.stage.GetEditTarget().GetLayer()
with Sdf.ChangeBlock():
for path in paths:
sdfPrim = Sdf.CreatePrimInLayer(layer, path)
sdfPrim.active = active
pathNames = ", ".join(path.name for path in paths)
if active:
self.editComplete("Activated {}.".format(pathNames))
else:
self.editComplete("Deactivated {}.".format(pathNames))
def activateSelectedPrims(self):
self._setSelectedPrimsActivation(True)
def deactivateSelectedPrims(self):
self._setSelectedPrimsActivation(False)
def loadSelectedPrims(self):
with BusyContext():
primNames=[]
for item in self.getSelectedItems():
item.setLoaded(True)
primNames.append(item.name)
self.editComplete("Loaded %s." % primNames)
def unloadSelectedPrims(self):
with BusyContext():
primNames=[]
for item in self.getSelectedItems():
item.setLoaded(False)
primNames.append(item.name)
self.editComplete("Unloaded %s." % primNames)
def onStageViewMouseDrag(self):
return
def onPrimSelected(self, path, instanceIndex, topLevelPath, topLevelInstanceIndex, point, button, modifiers):
# Ignoring middle button until we have something
# meaningfully different for it to do
if button in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton]:
# Expected context-menu behavior is that even with no
# modifiers, if we are activating on something already selected,
# do not change the selection
doContext = (button == QtCore.Qt.RightButton and path
and path != Sdf.Path.emptyPath)
doSelection = True
if doContext:
for selPrim in self._dataModel.selection.getPrims():
selPath = selPrim.GetPath()
if (selPath != Sdf.Path.absoluteRootPath and
path.HasPrefix(selPath)):
doSelection = False
break
if doSelection:
self._dataModel.selection.setPoint(point)
shiftPressed = modifiers & QtCore.Qt.ShiftModifier
ctrlPressed = modifiers & QtCore.Qt.ControlModifier
if path != Sdf.Path.emptyPath:
prim = self._dataModel.stage.GetPrimAtPath(path)
# Model picking ignores instancing, but selects the enclosing
# model of the picked prim.
if self._dataModel.viewSettings.pickMode == PickModes.MODELS:
if prim.IsModel():
model = prim
else:
model = GetEnclosingModelPrim(prim)
if model:
prim = model
instanceIndex = ALL_INSTANCES
# Prim picking selects the top level boundable: either the
# gprim, the top-level point instancer (if it's point
# instanced), or the top level USD instance (if it's marked
# instantiable), whichever is closer to namespace root.
# It discards the instance index.
elif self._dataModel.viewSettings.pickMode == PickModes.PRIMS:
topLevelPrim = self._dataModel.stage.GetPrimAtPath(topLevelPath)
if topLevelPrim:
prim = topLevelPrim
while prim.IsInstanceProxy():
prim = prim.GetParent()
instanceIndex = ALL_INSTANCES
# Instance picking selects the top level boundable, like
# prim picking; but if that prim is a point instancer or
# a USD instance, it selects the particular instance
# containing the picked object.
elif self._dataModel.viewSettings.pickMode == PickModes.INSTANCES:
topLevelPrim = self._dataModel.stage.GetPrimAtPath(topLevelPath)
if topLevelPrim:
prim = topLevelPrim
instanceIndex = topLevelInstanceIndex
if prim.IsInstanceProxy():
while prim.IsInstanceProxy():
prim = prim.GetParent()
instanceIndex = ALL_INSTANCES
# Prototype picking selects a specific instance of the
# actual picked gprim, if the gprim is point-instanced.
# This differs from instance picking by selecting the gprim,
# rather than the prototype subtree; and selecting only one
# drawn instance, rather than all sub-instances of a top-level
# instance (for nested point instancers).
# elif self._dataModel.viewSettings.pickMode == PickModes.PROTOTYPES:
# Just pass the selection info through!
if shiftPressed:
# Clicking prim while holding shift adds it to the
# selection.
self._dataModel.selection.addPrim(prim, instanceIndex)
elif ctrlPressed:
# Clicking prim while holding ctrl toggles it in the
# selection.
self._dataModel.selection.togglePrim(prim, instanceIndex)
else:
# Clicking prim with no modifiers sets it as the
# selection.
self._dataModel.selection.switchToPrimPath(
prim.GetPath(), instanceIndex)
elif not shiftPressed and not ctrlPressed:
# Clicking the background with no modifiers clears the
# selection.
self._dataModel.selection.clear()
if doContext:
item = self._getItemAtPath(path)
self._showPrimContextMenu(item)
# context menu steals mouse release event from the StageView.
# We need to give it one so it can track its interaction
# mode properly
mrEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease,
QtGui.QCursor.pos(),
QtCore.Qt.RightButton,
QtCore.Qt.MouseButtons(QtCore.Qt.RightButton),
QtCore.Qt.KeyboardModifiers())
QtWidgets.QApplication.sendEvent(self._stageView, mrEvent)
def onRollover(self, path, instanceIndex, topLevelPath, topLevelInstanceIndex, modifiers):
prim = self._dataModel.stage.GetPrimAtPath(path)
if prim:
headerStr = ""
propertyStr = ""
materialStr = ""
aiStr = ""
vsStr = ""
model = GetEnclosingModelPrim(prim)
def _MakeModelRelativePath(path, model,
boldPrim=True, boldModel=False):
makeRelative = model and path.HasPrefix(model.GetPath())
if makeRelative:
path = path.MakeRelativePath(model.GetPath().GetParentPath())
pathParts = str(path).split('/')
if boldModel and makeRelative:
pathParts[0] = "<b>%s</b>" % pathParts[0]
if boldPrim:
pathParts[-1] = "<b>%s</b>" % pathParts[-1]
return '/'.join(pathParts)
def _HTMLEscape(s):
return s.replace('&', '&'). \
replace('<', '<'). \
replace('>', '>')
# First add in all model-related data, if present
if model:
groupPath = model.GetPath().GetParentPath()
# Make the model name and prim name bold.
primModelPath = _MakeModelRelativePath(prim.GetPath(),
model, True, True)
headerStr = "%s<br><nobr><small>in group:</small> %s</nobr>" % \
(str(primModelPath),str(groupPath))
# asset info, including computed creation date
mAPI = Usd.ModelAPI(model)
assetInfo = mAPI.GetAssetInfo()
aiStr = "<hr><b>assetInfo</b> for %s:" % model.GetName()
if assetInfo and len(assetInfo) > 0:
specs = model.GetPrimStack()
name, time, owner = GetAssetCreationTime(specs,
mAPI.GetAssetIdentifier())
for key, value in assetInfo.items():
aiStr += "<br> -- <em>%s</em> : %s" % (key, _HTMLEscape(str(value)))
aiStr += "<br><em><small>%s created on %s by %s</small></em>" % \
(_HTMLEscape(name), _HTMLEscape(time),
_HTMLEscape(owner))
else:
aiStr += "<br><small><em>No assetInfo!</em></small>"
# variantSets are by no means required/expected, so if there
# are none, don't bother to declare so.
mVarSets = model.GetVariantSets()
setNames = mVarSets.GetNames()
if len(setNames) > 0:
vsStr = "<hr><b>variantSets</b> on %s:" % model.GetName()
for name in setNames:
sel = mVarSets.GetVariantSelection(name)
vsStr += "<br> -- <em>%s</em> = %s" % (name, sel)
else:
headerStr = _MakeModelRelativePath(path, None)
# Property info: advise about rare visibility and purpose conditions
img = UsdGeom.Imageable(prim)
propertyStr = "<hr><b>Property Summary for %s '%s':</b>" % \
(prim.GetTypeName(), prim.GetName())
# Now cherry pick "important" attrs... could do more, here
if img:
if img.GetVisibilityAttr().ValueMightBeTimeVarying():
propertyStr += "<br> -- <em>visibility</em> varies over time"
purpose = img.GetPurposeAttr().Get()
inheritedPurpose = img.ComputePurpose()
if inheritedPurpose != UsdGeom.Tokens.default_:
propertyStr += "<br> -- <em>purpose</em> is <b>%s</b>%s " %\
(inheritedPurpose, "" if purpose == inheritedPurpose \
else ", <small>(inherited)</small>")
gprim = UsdGeom.Gprim(prim)
if gprim:
ds = gprim.GetDoubleSidedAttr().Get()
orient = gprim.GetOrientationAttr().Get()
propertyStr += "<br> -- <em>doubleSided</em> = %s" % \
( "true" if ds else "false")
propertyStr += "<br> -- <em>orientation</em> = %s" % orient
ptBased = UsdGeom.PointBased(prim)
if ptBased:
# XXX WBN to not have to read points in to get array size
# XXX2 Should try to determine varying topology
points = ptBased.GetPointsAttr().Get(
self._dataModel.currentFrame)
propertyStr += "<br> -- %d points" % len(points)
mesh = UsdGeom.Mesh(prim)
if mesh:
propertyStr += "<br> -- <em>subdivisionScheme</em> = %s" %\
mesh.GetSubdivisionSchemeAttr().Get()
topLevelPrim = self._dataModel.stage.GetPrimAtPath(topLevelPath)
pi = UsdGeom.PointInstancer(topLevelPrim)
if pi:
indices = pi.GetProtoIndicesAttr().Get(
self._dataModel.currentFrame)
propertyStr += "<br> -- <em>%d instances</em>" % len(indices)
protos = pi.GetPrototypesRel().GetForwardedTargets()
propertyStr += "<br> -- <em>%d unique prototypes</em>" % len(protos)
if topLevelInstanceIndex >= 0 and topLevelInstanceIndex < len(indices):
protoIndex = indices[topLevelInstanceIndex]
if protoIndex < len(protos):
currProtoPath = protos[protoIndex]
# If, as is common, proto is beneath the PI,
# strip the PI's prefix for display
if currProtoPath.HasPrefix(path):
currProtoPath = currProtoPath.MakeRelativePath(path)
propertyStr += "<br> -- <em>instance of prototype <%s></em>" % str(currProtoPath)
# Material info - this IS expected
materialStr = "<hr><b>Material assignment:</b>"
materialAssigns = {}
materialAssigns['generic'] = (genericMat, genericBindingRel) = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.allPurpose)
materialAssigns[UsdShade.Tokens.preview] = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.preview)
materialAssigns[UsdShade.Tokens.full] = \
UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial(
materialPurpose=UsdShade.Tokens.full)
gotValidMaterial = False
for purpose, materialAssign in materialAssigns.items():
(material, bindingRel) = materialAssign
if not material:
continue
gotValidMaterial = True
# skip specific purpose binding display if it is the same
# as the generic binding.
if purpose != 'generic' and bindingRel == genericBindingRel:
continue
# if the material is in the same model, make path
# model-relative
materialStr += "<br><em>%s</em>: %s" % (purpose,
_MakeModelRelativePath(material.GetPath(), model))
bindingRelPath = _MakeModelRelativePath(
bindingRel.GetPath(), model)
materialStr += "<br><small><em>Material binding "\
"relationship: %s</em></small>" % str(bindingRelPath)
if not gotValidMaterial:
materialStr += "<small><em>No assigned Material!</em></small>"
# Instance / master info, if this prim is a native instance, else
# instance index/id if it's from a PointInstancer
instanceStr = ""
if prim.IsInstance():
instanceStr = "<hr><b>Instancing:</b><br>"
instanceStr += "<nobr><small><em>Instance of master:</em></small> %s</nobr>" % \
str(prim.GetMaster().GetPath())
elif topLevelInstanceIndex != -1:
instanceStr = "<hr><b>Instance Id:</b> %d" % topLevelInstanceIndex
# Then put it all together
tip = headerStr + propertyStr + materialStr + instanceStr + aiStr + vsStr
else:
tip = ""
QtWidgets.QToolTip.showText(QtGui.QCursor.pos(), tip, self._stageView)
def processNavKeyEvent(self, kpEvent):
# This method is a standin for a hotkey processor... for now greatly
# limited in scope, as we mostly use Qt's builtin hotkey dispatch.
# Since we want navigation keys to be hover-context-sensitive, we
# cannot use the native mechanism.
key = kpEvent.key()
if key == QtCore.Qt.Key_Right:
self._advanceFrame()
return True
elif key == QtCore.Qt.Key_Left:
self._retreatFrame()
return True
elif key == KeyboardShortcuts.FramingKey:
self._frameSelection()
return False
def _viewSettingChanged(self):
self._refreshViewMenubar()
self._displayPurposeChanged()
self._HUDInfoChanged()
def _refreshViewMenubar(self):
"""Refresh the menubar actions associated with a view setting. This
includes updating checked/unchecked and enabled/disabled states for
actions and submenus to match the values in the ViewSettingsDataModel.
"""
self._refreshRenderModeMenu()
self._refreshColorCorrectionModeMenu()
self._refreshPickModeMenu()
self._refreshComplexityMenu()
self._refreshBBoxMenu()
self._refreshLightsMenu()
self._refreshClearColorsMenu()
self._refreshCameraMenu()
self._refreshCameraGuidesMenu()
self._refreshCameraMaskMenu()
self._refreshCameraReticlesMenu()
self._refreshDisplayPurposesMenu()
self._refreshViewMenu()
self._refreshHUDMenu()
self._refreshShowPrimMenu()
self._refreshRedrawOnScrub()
self._refreshRolloverPrimInfoMenu()
self._refreshSelectionHighlightingMenu()
self._refreshSelectionHighlightColorMenu()
def _refreshRenderModeMenu(self):
for action in self._renderModeActions:
action.setChecked(
str(action.text()) == self._dataModel.viewSettings.renderMode)
def _refreshColorCorrectionModeMenu(self):
for action in self._colorCorrectionActions:
action.setChecked(
str(action.text()) == self._dataModel.viewSettings.colorCorrectionMode)
def _refreshPickModeMenu(self):
for action in self._pickModeActions:
action.setChecked(
str(action.text()) == self._dataModel.viewSettings.pickMode)
def _refreshComplexityMenu(self):
complexityName = self._dataModel.viewSettings.complexity.name
for action in self._complexityActions:
action.setChecked(str(action.text()) == complexityName)
def _refreshBBoxMenu(self):
self._ui.showBBoxes.setChecked(self._dataModel.viewSettings.showBBoxes)
self._ui.showAABBox.setChecked(self._dataModel.viewSettings.showAABBox)
self._ui.showOBBox.setChecked(self._dataModel.viewSettings.showOBBox)
self._ui.showBBoxPlayback.setChecked(
self._dataModel.viewSettings.showBBoxPlayback)
def _refreshLightsMenu(self):
# lighting is not activated until a shaded mode is selected
self._ui.menuLights.setEnabled(
self._dataModel.viewSettings.renderMode in ShadedRenderModes)
self._ui.actionAmbient_Only.setChecked(
self._dataModel.viewSettings.ambientLightOnly)
self._ui.actionDomeLight.setChecked(
self._dataModel.viewSettings.domeLightEnabled)
def _refreshClearColorsMenu(self):
clearColorText = self._dataModel.viewSettings.clearColorText
for action in self._clearColorActions:
action.setChecked(str(action.text()) == clearColorText)
def getActiveCamera(self):
return self._dataModel.viewSettings.cameraPrim
def _refreshCameraMenu(self):
cameraPath = self._dataModel.viewSettings.cameraPath
for action in self._ui.menuCamera.actions():
action.setChecked(action.data() == cameraPath)
def _refreshCameraGuidesMenu(self):
self._ui.actionDisplay_Camera_Oracles.setChecked(
self._dataModel.viewSettings.displayCameraOracles)
self._ui.actionCameraMask_Outline.setChecked(
self._dataModel.viewSettings.showMask_Outline)
def _refreshCameraMaskMenu(self):
viewSettings = self._dataModel.viewSettings
self._ui.actionCameraMask_Full.setChecked(
viewSettings.cameraMaskMode == CameraMaskModes.FULL)
self._ui.actionCameraMask_Partial.setChecked(
viewSettings.cameraMaskMode == CameraMaskModes.PARTIAL)
self._ui.actionCameraMask_None.setChecked(
viewSettings.cameraMaskMode == CameraMaskModes.NONE)
def _refreshCameraReticlesMenu(self):
self._ui.actionCameraReticles_Inside.setChecked(
self._dataModel.viewSettings.showReticles_Inside)
self._ui.actionCameraReticles_Outside.setChecked(
self._dataModel.viewSettings.showReticles_Outside)
def _refreshDisplayPurposesMenu(self):
self._ui.actionDisplay_Guide.setChecked(
self._dataModel.viewSettings.displayGuide)
self._ui.actionDisplay_Proxy.setChecked(
self._dataModel.viewSettings.displayProxy)
self._ui.actionDisplay_Render.setChecked(
self._dataModel.viewSettings.displayRender)
def _refreshViewMenu(self):
self._ui.actionEnable_Scene_Materials.setChecked(
self._dataModel.viewSettings.enableSceneMaterials)
self._ui.actionDisplay_PrimId.setChecked(
self._dataModel.viewSettings.displayPrimId)
self._ui.actionCull_Backfaces.setChecked(
self._dataModel.viewSettings.cullBackfaces)
self._ui.actionAuto_Compute_Clipping_Planes.setChecked(
self._dataModel.viewSettings.autoComputeClippingPlanes)
def _refreshHUDMenu(self):
self._ui.actionHUD.setChecked(self._dataModel.viewSettings.showHUD)
self._ui.actionHUD_Info.setChecked(
self._dataModel.viewSettings.showHUD_Info)
self._ui.actionHUD_Complexity.setChecked(
self._dataModel.viewSettings.showHUD_Complexity)
self._ui.actionHUD_Performance.setChecked(
self._dataModel.viewSettings.showHUD_Performance)
self._ui.actionHUD_GPUstats.setChecked(
self._dataModel.viewSettings.showHUD_GPUstats)
def _refreshShowPrimMenu(self):
self._ui.actionShow_Inactive_Prims.setChecked(
self._dataModel.viewSettings.showInactivePrims)
self._ui.actionShow_All_Master_Prims.setChecked(
self._dataModel.viewSettings.showAllMasterPrims)
self._ui.actionShow_Undefined_Prims.setChecked(
self._dataModel.viewSettings.showUndefinedPrims)
self._ui.actionShow_Abstract_Prims.setChecked(
self._dataModel.viewSettings.showAbstractPrims)
def _refreshRedrawOnScrub(self):
self._ui.redrawOnScrub.setChecked(
self._dataModel.viewSettings.redrawOnScrub)
def _refreshRolloverPrimInfoMenu(self):
self._ui.actionRollover_Prim_Info.setChecked(
self._dataModel.viewSettings.rolloverPrimInfo)
def _refreshSelectionHighlightingMenu(self):
for action in self._selHighlightActions:
action.setChecked(
str(action.text())
== self._dataModel.viewSettings.selHighlightMode)
def _refreshSelectionHighlightColorMenu(self):
for action in self._selHighlightColorActions:
action.setChecked(
str(action.text())
== self._dataModel.viewSettings.highlightColorName)
def _displayPurposeChanged(self):
self._updatePropertyView()
if self._stageView:
self._stageView.updateBboxPurposes()
self._stageView.updateView()
def _HUDInfoChanged(self):
"""Called when a HUD setting that requires info refresh has changed."""
if self._isHUDVisible():
self._updateHUDPrimStats()
self._updateHUDGeomCounts()
def _onPrimsChanged(self, primsChange, propertiesChange):
"""Called when prims in the USD stage have changed."""
from .rootDataModel import ChangeNotice
self._updateForStageChanges(
hasPrimResync=(primsChange==ChangeNotice.RESYNC))
| 216,121 | Python | 42.138124 | 129 | 0.607174 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/settings2.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import os, sys, json
class _StateProp(object):
"""Defines a state property on a StateSource object."""
def __init__(self, name, default, propType, validator):
self.name = name
self.default = default
self.propType = propType
self.validator = validator
class StateSource(object):
"""An object which has some savable application state."""
def __init__(self, parent, name):
self._parentStateSource = parent
self._childStateSources = dict()
self._stateSourceName = name
self._stateSourceProperties = dict()
# Register child source with the parent.
if self._parentStateSource is not None:
self._parentStateSource._registerChildStateSource(self)
def _registerChildStateSource(self, child):
"""Registers a child StateSource with this source object."""
self._childStateSources[child._stateSourceName] = child
def _getState(self):
"""Get this source's state dict from its parent source."""
if self._parentStateSource is None:
return dict()
else:
return self._parentStateSource._getChildState(self._stateSourceName)
def _getChildState(self, childName):
"""Get a child source's state dict. This method guarantees that a dict
will be return but does not guarantee anything about the contents of
the dict.
"""
state = self._getState()
if childName in state:
childState = state[childName]
# Child state could be loaded from file as any JSON-serializable
# type (int, str, etc.). Only return it if it is a dict. Otherwise,
# fallback to empty dict.
if isinstance(childState, dict):
return childState
# Create a new state dict for the child and save it in this source's
# state dict.
childState = dict()
state[childName] = childState
return childState
def _typeCheck(self, value, prop):
"""Validate a value against a StateProp."""
# Make sure the value has the correct type.
valueType = type(value)
if valueType is not prop.propType:
if sys.version_info.major >= 3:
str_types = [str]
else:
str_types = [str, unicode]
if valueType is int and prop.propType is float:
pass # ints are valid for float types.
elif prop.propType in str_types and valueType in str_types:
pass # str and unicode can be used interchangeably.
else:
print("Value {} has type {} but state property {} has type {}.".format(
repr(value), valueType, repr(prop.name), prop.propType),
file=sys.stderr)
print(" Using default value {}.".format(repr(prop.default)),
file=sys.stderr)
return False
# Make sure value passes custom validation. Otherwise, use default value.
if prop.validator(value):
return True
else:
print("Value {} did not pass custom validation for state property {}.".format(
repr(value), repr(prop.name)), file=sys.stderr)
print(" Using default value {}.".format(repr(prop.default)),
file=sys.stderr)
return False
def _saveState(self):
"""Saves the source's state to the settings object's state buffer."""
newState = dict()
# Save state properties.
self.onSaveState(newState)
# Validate state properties.
for name, value in tuple(newState.items()):
if name not in self._stateSourceProperties:
print("State property {} not defined. It will be removed.".format(
repr(name)), file=sys.stderr)
del newState[name]
prop = self._stateSourceProperties[name]
if self._typeCheck(value, prop):
newState[name] = value
else:
newState[name] = prop.default
# Make sure no state properties were forgotten.
for prop in self._stateSourceProperties.values():
if prop.name not in newState:
print("State property {} not saved.".format(repr(prop.name)),
file=sys.stderr)
# Update the real state dict with the new state. This preserves unused
# data loaded from the state file.
self._getState().update(newState)
# Save all child states.
for child in self._childStateSources.values():
child._saveState()
def stateProperty(self, name, default, propType=None, validator=lambda value: True):
"""Validates and creates a new StateProp for this source. The property's
value is returned so this method can be used during StateSource
initialization."""
# Make sure there are no conflicting state properties.
if name in self._stateSourceProperties:
raise RuntimeError("State property name {} already in use.".format(
repr(name)))
# Grab state property type from default value if it was not defined.
if propType is None:
propType = type(default)
# Make sure default value is valid.
if not isinstance(default, propType):
raise RuntimeError("Default value {} does not match type {}.".format(
repr(default), repr(propType)))
if not validator(default):
raise RuntimeError("Default value {} does not pass custom validation "
"for state property {}.".format(repr(default), repr(name)))
prop = _StateProp(name, default, propType, validator)
self._stateSourceProperties[name] = prop
# Load the value from the state dict and validate it.
state = self._getState()
value = state.get(name, default)
if self._typeCheck(value, prop):
return value
else:
return prop.default
def onSaveState(self, state):
"""Save the source's state properties to a dict."""
raise NotImplementedError
class Settings(StateSource):
"""An object which encapsulates saving and loading of application state to
a state file. When created, it loads state from a state file and stores it
in a buffer. Its children sources can fetch their piece of state from the
buffer. On save, this object tells its children to save their current
states, then saves the buffer back to the state file.
"""
def __init__(self, version, stateFilePath=None):
# Settings should be the only StateSource with no parent or name.
StateSource.__init__(self, None, None)
self._version = version
self._stateFilePath = stateFilePath
self._versionsStateBuffer = None
self._stateBuffer = None
self._isEphemeral = (self._stateFilePath is None)
self._loadState()
def _loadState(self):
"""Loads and returns application state from a state file. If the file is
not found, contains invalid JSON, does not contain a dictionary, an
empty state is returned instead.
"""
# Load the dict containing all versions of app state.
if not self._isEphemeral:
try:
with open(self._stateFilePath, "r") as fp:
self._versionsStateBuffer = json.load(fp)
except IOError as e:
if os.path.isfile(self._stateFilePath):
print("Error opening state file: " + str(e), file=sys.stderr)
else:
print("State file not found, a new one will be created.",
file=sys.stderr)
except ValueError:
print("State file contained invalid JSON. Please fix or delete " +
"it. Default settings will be used for this instance of " +
"USDView, but will not be saved.", file=sys.stderr)
self._isEphemeral = True
# Make sure JSON returned a dict.
if not isinstance(self._versionsStateBuffer, dict):
self._versionsStateBuffer = dict()
# Load the correct version of the state dict.
self._stateBuffer = self._versionsStateBuffer.get(self._version, None)
if not isinstance(self._stateBuffer, dict):
self._stateBuffer = dict()
self._versionsStateBuffer[self._version] = self._stateBuffer
# overrides StateSource._getState
def _getState(self):
"""Gets the buffered state rather than asking its parent for its state.
"""
return self._stateBuffer
def save(self):
"""Inform all children to save their states, then write the state buffer
back to the state file.
"""
if not self._isEphemeral:
self._saveState()
try:
with open(self._stateFilePath, "w") as fp:
json.dump(self._versionsStateBuffer, fp,
indent=2, separators=(",", ": "))
except IOError as e:
print("Could not save state file: " + str(e), file=sys.stderr)
def onSaveState(self, state):
"""Settings object has no state properties."""
pass
| 10,551 | Python | 39.274809 | 90 | 0.610748 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/variantComboBox.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .common import Timer
class VariantComboBox(QtWidgets.QComboBox):
def __init__(self, parent, prim, variantSetName, mainWindow):
QtWidgets.QComboBox.__init__(self, parent)
self.prim = prim
self.variantSetName = variantSetName
def updateVariantSelection(self, index, printTiming):
variantSet = self.prim.GetVariantSet(self.variantSetName)
currentVariantSelection = variantSet.GetVariantSelection()
newVariantSelection = str(self.currentText())
if currentVariantSelection != newVariantSelection:
with Timer() as t:
variantSet.SetVariantSelection(newVariantSelection)
if printTiming:
t.PrintTime("change variantSet %s to %s" %
(variantSet.GetName(), newVariantSelection))
| 1,925 | Python | 40.869564 | 74 | 0.721039 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/freeCamera.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from math import atan, radians as rad
from pxr import Gf, Tf
from .qt import QtCore
from .common import DEBUG_CLIPPING
# FreeCamera inherits from QObject only so that it can send signals...
# which is really a pretty nice, easy to use notification system.
class FreeCamera(QtCore.QObject):
# Allows FreeCamera owner to act when the camera's relationship to
# its viewed content changes. For instance, to compute the value
# to supply for setClosestVisibleDistFromPoint()
signalFrustumChanged = QtCore.Signal()
defaultNear = 1
defaultFar = 2000000
# Experimentally on Nvidia M6000, if Far/Near is greater than this,
# then geometry in the back half of the volume will disappear
maxSafeZResolution = 1e6
# Experimentally on Nvidia M6000, if Far/Near is greater than this,
# then we will often see Z-fighting artifacts even for geometry that
# is close to camera, when rendering for picking
maxGoodZResolution = 5e4
def __init__(self, isZUp, fov=60.0):
"""FreeCamera can be either a Z up or Y up camera, based on 'zUp'"""
super(FreeCamera, self).__init__()
self._camera = Gf.Camera()
self._camera.SetPerspectiveFromAspectRatioAndFieldOfView(
1.0, fov, Gf.Camera.FOVVertical)
self._overrideNear = None
self._overrideFar = None
self.resetClippingPlanes()
self._isZUp = isZUp
self._cameraTransformDirty = True
self._rotTheta = 0
self._rotPhi = 0
self._rotPsi = 0
self._center = Gf.Vec3d(0,0,0)
self._dist = 100
self._camera.focusDistance = self._dist
self._closestVisibleDist = None
self._lastFramedDist = None
self._lastFramedClosestDist = None
self._selSize = 10
if isZUp:
# This is also Gf.Camera.Y_UP_TO_Z_UP_MATRIX
self._YZUpMatrix = Gf.Matrix4d().SetRotate(
Gf.Rotation(Gf.Vec3d.XAxis(), -90))
self._YZUpInvMatrix = self._YZUpMatrix.GetInverse()
else:
self._YZUpMatrix = Gf.Matrix4d(1.0)
self._YZUpInvMatrix = Gf.Matrix4d(1.0)
# Why a clone() method vs copy.deepcopy()ing the FreeCamera ?
# 1) Several of the Gf classes are not python-picklable (requirement of
# deepcopy), nor is GfCamera. Adding that infrastructure for this
# single client seems weighty.
# 2) We could make FreeCamera itself be picklable... that solution would
# require twice as much code as clone(). If we wind up extracting
# FreeCamera to be a more general building block, it may be worth it,
# and clone() would transition to __getstate__().
def clone(self):
clone = FreeCamera(self._isZUp)
clone._camera = Gf.Camera(self._camera)
# skipping stereo attrs for now
clone._rotTheta = self._rotTheta
clone._rotPhi = self._rotPhi
clone._rotPsi = self._rotPsi
clone._center = Gf.Vec3d(self._center)
clone._dist = self._dist
clone._closestVisibleDist = self._closestVisibleDist
clone._lastFramedClosestDist = self._lastFramedClosestDist
clone._lastFramedDist = self._lastFramedDist
clone._selSize = self._selSize
clone._overrideNear = self._overrideNear
clone._overrideFar = self._overrideFar
clone._YZUpMatrix = Gf.Matrix4d(self._YZUpMatrix)
clone._YZUpInvMatrix = Gf.Matrix4d(self._YZUpInvMatrix)
return clone
def _pushToCameraTransform(self):
"""
Updates the camera's transform matrix, that is, the matrix that brings
the camera to the origin, with the camera view pointing down:
+Y if this is a Zup camera, or
-Z if this is a Yup camera .
"""
if not self._cameraTransformDirty:
return
def RotMatrix(vec, angle):
return Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(vec, angle))
# self._YZUpInvMatrix influences the behavior about how the
# FreeCamera will tumble. It is the identity or a rotation about the
# x-Axis.
self._camera.transform = (
Gf.Matrix4d().SetTranslate(Gf.Vec3d.ZAxis() * self.dist) *
RotMatrix(Gf.Vec3d.ZAxis(), -self._rotPsi) *
RotMatrix(Gf.Vec3d.XAxis(), -self._rotPhi) *
RotMatrix(Gf.Vec3d.YAxis(), -self._rotTheta) *
self._YZUpInvMatrix *
Gf.Matrix4d().SetTranslate(self.center))
self._camera.focusDistance = self.dist
self._cameraTransformDirty = False
def _pullFromCameraTransform(self):
"""
Updates parameters (center, rotTheta, etc.) from the camera transform.
"""
# reads the transform set on the camera and updates all the other
# parameters. This is the inverse of _pushToCameraTransform
cam_transform = self._camera.transform
dist = self._camera.focusDistance
frustum = self._camera.frustum
cam_pos = frustum.position
cam_axis = frustum.ComputeViewDirection()
# Compute translational parts
self._dist = dist
self._selSize = dist / 10.0
self._center = cam_pos + dist * cam_axis
# self._YZUpMatrix influences the behavior about how the
# FreeCamera will tumble. It is the identity or a rotation about the
# x-Axis.
# Compute rotational part
transform = cam_transform * self._YZUpMatrix
transform.Orthonormalize()
rotation = transform.ExtractRotation()
# Decompose and set angles
self._rotTheta, self._rotPhi, self._rotPsi = -rotation.Decompose(
Gf.Vec3d.YAxis(), Gf.Vec3d.XAxis(), Gf.Vec3d.ZAxis())
self._cameraTransformDirty = True
def _rangeOfBoxAlongRay(self, camRay, bbox, debugClipping=False):
maxDist = -float('inf')
minDist = float('inf')
boxRange = bbox.GetRange()
boxXform = bbox.GetMatrix()
for i in range (8):
# for each corner of the bounding box, transform to world
# space and project
point = boxXform.Transform(boxRange.GetCorner(i))
pointDist = camRay.FindClosestPoint(point)[1]
# find the projection of that point of the camera ray
# and find the farthest and closest point.
if pointDist > maxDist:
maxDist = pointDist
if pointDist < minDist:
minDist = pointDist
if debugClipping:
print("Projected bounds near/far: %f, %f" % (minDist, maxDist))
# if part of the bbox is behind the ray origin (i.e. camera),
# we clamp minDist to be positive. Otherwise, reduce minDist by a bit
# so that geometry at exactly the edge of the bounds won't be clipped -
# do the same for maxDist, also!
if minDist < FreeCamera.defaultNear:
minDist = FreeCamera.defaultNear
else:
minDist *= 0.99
maxDist *= 1.01
if debugClipping:
print("Contracted bounds near/far: %f, %f" % (minDist, maxDist))
return minDist, maxDist
def setClippingPlanes(self, stageBBox):
'''Computes and sets automatic clipping plane distances using the
camera's position and orientation, the bouding box
surrounding the stage, and the distance to the closest rendered
object in the central view of the camera (closestVisibleDist).
If either of the "override" clipping attributes are not None,
we use those instead'''
debugClipping = Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING)
# If the scene bounding box is empty, or we are fully on manual
# override, then just initialize to defaults.
if stageBBox.GetRange().IsEmpty() or \
(self._overrideNear and self._overrideFar) :
computedNear, computedFar = FreeCamera.defaultNear, FreeCamera.defaultFar
else:
# The problem: We want to include in the camera frustum all the
# geometry the viewer should be able to see, i.e. everything within
# the inifinite frustum starting at distance epsilon from the
# camera itself. However, the further the imageable geometry is
# from the near-clipping plane, the less depth precision we will
# have to resolve nearly colinear/incident polygons (which we get
# especially with any doubleSided geometry). We can run into such
# situations astonishingly easily with large sets when we are
# focussing in on just a part of a set that spans 10^5 units or
# more.
#
# Our solution: Begin by projecting the endpoints of the imageable
# world's bounds onto the ray piercing the center of the camera
# frustum, and take the near/far clipping distances from its
# extent, clamping at a positive value for near. To address the
# z-buffer precision issue, we rely on someone having told us how
# close the closest imageable geometry actually is to the camera,
# by having called setClosestVisibleDistFromPoint(). This gives us
# the most liberal near distance we can use and not clip the
# geometry we are looking at. We actually choose some fraction of
# that distance instead, because we do not expect the someone to
# recompute the closest point with every camera manipulation, as
# it can be expensive (we do emit signalFrustumChanged to notify
# them, however). We only use this if the current range of the
# bbox-based frustum will have precision issues.
frustum = self._camera.frustum
camPos = frustum.position
camRay = Gf.Ray(camPos, frustum.ComputeViewDirection())
computedNear, computedFar = self._rangeOfBoxAlongRay(camRay,
stageBBox,
debugClipping)
precisionNear = computedFar / FreeCamera.maxGoodZResolution
if debugClipping:
print("Proposed near for precision: {}, closestDist: {}"\
.format(precisionNear, self._closestVisibleDist))
if self._closestVisibleDist:
# Because of our concern about orbit/truck causing
# clipping, make sure we don't go closer than half the
# distance to the closest visible point
halfClose = self._closestVisibleDist / 2.0
if self._closestVisibleDist < self._lastFramedClosestDist:
# This can happen if we have zoomed in closer since
# the last time setClosestVisibleDistFromPoint() was called.
# Clamp to precisionNear, which gives a balance between
# clipping as we zoom in, vs bad z-fighting as we zoom in.
# See AdjustDistance() for comment about better solution.
halfClose = max(precisionNear, halfClose, computedNear)
if debugClipping:
print("ADJUSTING: Accounting for zoom-in")
if halfClose < computedNear:
# If there's stuff very very close to the camera, it
# may have been clipped by computedNear. Get it back!
computedNear = halfClose
if debugClipping:
print("ADJUSTING: closestDist was closer than bboxNear")
elif precisionNear > computedNear:
computedNear = min((precisionNear + halfClose) / 2.0,
halfClose)
if debugClipping:
print("ADJUSTING: gaining precision by pushing out")
near = self._overrideNear or computedNear
far = self._overrideFar or computedFar
# Make sure far is greater than near
far = max(near+1, far)
if debugClipping:
print("***Final Near/Far: {}, {}".format(near, far))
self._camera.clippingRange = Gf.Range1f(near, far)
def computeGfCamera(self, stageBBox, autoClip=False):
"""Makes sure the FreeCamera's computed parameters are up-to-date, and
returns the GfCamera object. If 'autoClip' is True, then compute
"optimal" positions for the near/far clipping planes based on the
current closestVisibleDist, in order to maximize Z-buffer resolution"""
self._pushToCameraTransform()
if autoClip:
self.setClippingPlanes(stageBBox)
else:
self.resetClippingPlanes()
return self._camera
def resetClippingPlanes(self):
"""Set near and far back to their uncomputed defaults."""
near = self._overrideNear or FreeCamera.defaultNear
far = self._overrideFar or FreeCamera.defaultFar
self._camera.clippingRange = Gf.Range1f(near, far)
def frameSelection(self, selBBox, frameFit):
# needs to be recomputed
self._closestVisibleDist = None
self.center = selBBox.ComputeCentroid()
selRange = selBBox.ComputeAlignedRange()
self._selSize = max(*selRange.GetSize())
if self.orthographic:
self.fov = self._selSize * frameFit
self.dist = self._selSize + FreeCamera.defaultNear
else:
halfFov = self.fov*0.5 or 0.5 # don't divide by zero
lengthToFit = self._selSize * frameFit * 0.5
self.dist = lengthToFit / atan(rad(halfFov))
# Very small objects that fill out their bounding boxes (like cubes)
# may well pierce our 1 unit default near-clipping plane. Make sure
# that doesn't happen.
if self.dist < FreeCamera.defaultNear + self._selSize * 0.5:
self.dist = FreeCamera.defaultNear + lengthToFit
def setClosestVisibleDistFromPoint(self, point):
frustum = self._camera.frustum
camPos = frustum.position
camRay = Gf.Ray(camPos, frustum.ComputeViewDirection())
self._closestVisibleDist = camRay.FindClosestPoint(point)[1]
self._lastFramedDist = self.dist
self._lastFramedClosestDist = self._closestVisibleDist
if Tf.Debug.IsDebugSymbolNameEnabled(DEBUG_CLIPPING):
print("Resetting closest distance to {}; CameraPos: {}, closestPoint: {}".format(self._closestVisibleDist, camPos, point))
def ComputePixelsToWorldFactor(self, viewportHeight):
'''Computes the ratio that converts pixel distance into world units.
It treats the pixel distances as if they were projected to a plane going
through the camera center.'''
self._pushToCameraTransform()
if self.orthographic:
return self.fov / viewportHeight
else:
frustumHeight = self._camera.frustum.window.GetSize()[1]
return frustumHeight * self._dist / viewportHeight
def Tumble(self, dTheta, dPhi):
''' Tumbles the camera around the center point by (dTheta, dPhi) degrees. '''
self._rotTheta += dTheta
self._rotPhi += dPhi
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def AdjustDistance(self, scaleFactor):
'''Scales the distance of the freeCamera from it's center typically by
scaleFactor unless it puts the camera into a "stuck" state.'''
# When dist gets very small, you can get stuck and not be able to
# zoom back out, if you just keep multiplying. Switch to addition
# in that case, choosing an incr that works for the scale of the
# framed geometry.
if scaleFactor > 1 and self.dist < 2:
selBasedIncr = self._selSize / 25.0
scaleFactor -= 1.0
self.dist += min(selBasedIncr, scaleFactor)
else:
self.dist *= scaleFactor
# Make use of our knowledge that we are changing distance to camera
# to also adjust _closestVisibleDist to keep it useful. Make sure
# not to recede farther than the last *computed* closeDist, since that
# will generally cause unwanted clipping of close objects.
# XXX: This heuristic does a good job of preventing undesirable
# clipping as we zoom in and out, but sacrifices the z-buffer
# precision we worked hard to get. If Hd/UsdImaging could cheaply
# provide us with the closest-point from the last-rendered image,
# we could use it safely here to update _closestVisibleDist much
# more accurately than this calculation.
if self._closestVisibleDist:
if self.dist > self._lastFramedDist:
self._closestVisibleDist = self._lastFramedClosestDist
else:
self._closestVisibleDist = \
self._lastFramedClosestDist - \
self._lastFramedDist + \
self.dist
def Truck(self, deltaRight, deltaUp):
''' Moves the camera by (deltaRight, deltaUp) in worldspace coordinates.
This is similar to a camera Truck/Pedestal.
'''
# need to update the camera transform before we access the frustum
self._pushToCameraTransform()
frustum = self._camera.frustum
cam_up = frustum.ComputeUpVector()
cam_right = Gf.Cross(frustum.ComputeViewDirection(), cam_up)
self._center += (deltaRight * cam_right + deltaUp * cam_up)
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def PanTilt(self, dPan, dTilt):
''' Rotates the camera around the current camera base (approx. the film
plane). Both parameters are in degrees.
This moves the center point that we normally tumble around.
This is similar to a camera Pan/Tilt.
'''
self._camera.transform = (
Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(Gf.Vec3d.XAxis(), dTilt)) *
Gf.Matrix4d(1.0).SetRotate(Gf.Rotation(Gf.Vec3d.YAxis(), dPan)) *
self._camera.transform)
self._pullFromCameraTransform()
# When we Pan/Tilt, we don't want to roll the camera so we just zero it
# out here.
self._rotPsi = 0.0
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
def Walk(self, dForward, dRight):
''' Specialized camera movement that moves it on the "horizontal" plane
'''
# need to update the camera transform before we access the frustum
self._pushToCameraTransform()
frustum = self._camera.frustum
cam_up = frustum.ComputeUpVector().GetNormalized()
cam_forward = frustum.ComputeViewDirection().GetNormalized()
cam_right = Gf.Cross(cam_forward, cam_up)
delta = dForward * cam_forward + dRight * cam_right
self._center += delta
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@staticmethod
def FromGfCamera(gfCamera, isZUp):
self = FreeCamera(isZUp)
self._camera = gfCamera
self._pullFromCameraTransform()
return self
@property
def rotTheta(self):
return self._rotTheta
@rotTheta.setter
def rotTheta(self, value):
self._rotTheta = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def rotPhi(self):
return self._rotPhi
@rotPhi.setter
def rotPhi(self, value):
self._rotPhi = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def center(self):
return self._center
@center.setter
def center(self, value):
self._center = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def dist(self):
return self._dist
@dist.setter
def dist(self, value):
self._dist = value
self._cameraTransformDirty = True
self.signalFrustumChanged.emit()
@property
def orthographic(self):
return self._camera.projection == Gf.Camera.Orthographic
@orthographic.setter
def orthographic(self, orthographic):
if orthographic:
self._camera.projection = Gf.Camera.Orthographic
else:
self._camera.projection = Gf.Camera.Perspective
self.signalFrustumChanged.emit()
@property
def fov(self):
"""The vertical field of view, in degrees, for perspective cameras.
For orthographic cameras fov is the height of the view frustum, in
world units.
"""
if self._camera.projection == Gf.Camera.Perspective:
return self._camera.GetFieldOfView(Gf.Camera.FOVVertical)
else:
return (self._camera.verticalAperture * Gf.Camera.APERTURE_UNIT)
@fov.setter
def fov(self, value):
if self._camera.projection == Gf.Camera.Perspective:
self._camera.SetPerspectiveFromAspectRatioAndFieldOfView(
self._camera.aspectRatio, value, Gf.Camera.FOVVertical)
else:
self._camera.SetOrthographicFromAspectRatioAndSize(
self._camera.aspectRatio, value, Gf.Camera.FOVVertical)
self.signalFrustumChanged.emit()
@property
def near(self):
return self._camera.clippingRange.min
@property
def far(self):
return self._camera.clippingRange.max
# no setters for near and far - one must set overrideNear/Far instead
@property
def overrideNear(self):
return self._overrideNear
@overrideNear.setter
def overrideNear(self, value):
"""To remove the override, set to None"""
self._overrideNear = value
@property
def overrideFar(self):
return self._overrideFar
@overrideFar.setter
def overrideFar(self, value):
"""To remove the override, set to None"""
self._overrideFar = value
| 23,336 | Python | 40.37766 | 134 | 0.631385 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/propertyLegend.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
""" This module provides the help dialog(also known as the property legend)
in Usdview's MainWindow. This provides a key describing the items displayed
in the property browser.
"""
from .qt import QtWidgets
from .propertyLegendUI import Ui_PropertyLegend
from .common import UIBaseColors, UIPropertyValueSourceColors, ItalicizeLabelText, PropertyViewIcons
class PropertyLegend(QtWidgets.QWidget):
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
self._ui = Ui_PropertyLegend()
self._ui.setupUi(self)
# The property legend always starts off collapsed.
self.setMaximumHeight(0)
self._isMinimized = True
self._iconDisplaySize = (16, 16)
graphicsScene = QtWidgets.QGraphicsScene()
self._ui.propertyLegendColorFallback.setScene(graphicsScene)
self._ui.propertyLegendColorDefault.setScene(graphicsScene)
self._ui.propertyLegendColorTimeSample.setScene(graphicsScene)
self._ui.propertyLegendColorNoValue.setScene(graphicsScene)
self._ui.propertyLegendColorValueClips.setScene(graphicsScene)
self._ui.propertyLegendColorCustom.setScene(graphicsScene)
# set color of attribute viewer legend boxes
self._ui.propertyLegendColorFallback.setForegroundBrush(
UIPropertyValueSourceColors.FALLBACK)
self._ui.propertyLegendColorDefault.setForegroundBrush(
UIPropertyValueSourceColors.DEFAULT)
self._ui.propertyLegendColorTimeSample.setForegroundBrush(
UIPropertyValueSourceColors.TIME_SAMPLE)
self._ui.propertyLegendColorNoValue.setForegroundBrush(
UIPropertyValueSourceColors.NONE)
self._ui.propertyLegendColorValueClips.setForegroundBrush(
UIPropertyValueSourceColors.VALUE_CLIPS)
self._ui.propertyLegendColorCustom.setForegroundBrush(
UIBaseColors.RED)
# set color of attribute viewer text items
legendTextUpdate = lambda t, c: (
('<font color=\"%s\">' % c.color().name()) + t.text() + '</font>')
timeSampleLegend = self._ui.propertyLegendLabelTimeSample
timeSampleLegend.setText(
legendTextUpdate(timeSampleLegend, UIPropertyValueSourceColors.TIME_SAMPLE))
fallbackLegend = self._ui.propertyLegendLabelFallback
fallbackLegend.setText(
legendTextUpdate(fallbackLegend, UIPropertyValueSourceColors.FALLBACK))
valueClipLegend = self._ui.propertyLegendLabelValueClips
valueClipLegend.setText(
legendTextUpdate(valueClipLegend, UIPropertyValueSourceColors.VALUE_CLIPS))
noValueLegend = self._ui.propertyLegendLabelNoValue
noValueLegend.setText(
legendTextUpdate(noValueLegend, UIPropertyValueSourceColors.NONE))
defaultLegend = self._ui.propertyLegendLabelDefault
defaultLegend.setText(
legendTextUpdate(defaultLegend, UIPropertyValueSourceColors.DEFAULT))
customLegend = self._ui.propertyLegendLabelCustom
customLegend.setText(
legendTextUpdate(customLegend, UIBaseColors.RED))
interpolatedStr = 'Interpolated'
tsLabel = self._ui.propertyLegendLabelTimeSample
tsLabel.setText(ItalicizeLabelText(tsLabel.text(), interpolatedStr))
vcLabel = self._ui.propertyLegendLabelValueClips
vcLabel.setText(ItalicizeLabelText(vcLabel.text(), interpolatedStr))
# Load up and set the icons for the property legend
self._ui.propertyLegendTargetIcon.setPixmap(
PropertyViewIcons.TARGET().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendConnIcon.setPixmap(
PropertyViewIcons.CONNECTION().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendAttrPlainIcon.setPixmap(
PropertyViewIcons.ATTRIBUTE().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendRelPlainIcon.setPixmap(
PropertyViewIcons.RELATIONSHIP().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendAttrWithConnIcon.setPixmap(
PropertyViewIcons.ATTRIBUTE_WITH_CONNECTIONS().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendRelWithTargetIcon.setPixmap(
PropertyViewIcons.RELATIONSHIP_WITH_TARGETS().pixmap(*self._iconDisplaySize))
self._ui.propertyLegendCompIcon.setPixmap(
PropertyViewIcons.COMPOSED().pixmap(*self._iconDisplaySize))
def IsMinimized(self):
return self._isMinimized
def ToggleMinimized(self):
self._isMinimized = not self._isMinimized
def GetHeight(self):
return self.height()
def GetResetHeight(self):
return self.sizeHint().height()
| 5,787 | Python | 43.523077 | 100 | 0.724555 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/appEventFilter.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Qt Components
from .qt import QtCore, QtGui, QtWidgets
from .common import KeyboardShortcuts
class AppEventFilter(QtCore.QObject):
'''This class's primary responsibility is delivering key events to
"the right place". Given usdview's simplistic approach to shortcuts
(i.e. just uses the native Qt mechanism that does not allow for
context-sensitive keypress dispatching), we take a simplistic approach
to routing: use Qt's preferred mechanism of processing keyPresses
only in widgets that have focus; therefore, the primary behavior of this
filter is to track mouse-position in order to set widget focus, so that
widgets with keyboard navigation behaviors operate when the mouse is over
them.
We add one special behaviors on top of that, which is to turn unaccepted
left/right events into up/down events for TreeView widgets, because we
do not have a specialized class on which to provide this nice navigation
behavior.'''
# in future it would be a hotkey dispatcher instead of appController
# that we'd dispatch to, but we don't have one yet
def __init__(self, appController):
QtCore.QObject.__init__(self)
self._appController = appController
def IsNavKey(self, key, modifiers):
# Note that the arrow keys are considered part of the keypad on macOS.
return (key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right,
QtCore.Qt.Key_Up, QtCore.Qt.Key_Down,
QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown,
QtCore.Qt.Key_Home, QtCore.Qt.Key_End,
KeyboardShortcuts.FramingKey)
and modifiers in (QtCore.Qt.NoModifier,
QtCore.Qt.KeypadModifier))
def _IsWindow(self, obj):
if isinstance(obj, QtWidgets.QWidget):
return obj.isWindow()
else:
return isinstance(obj, QtGui.QWindow)
def TopLevelWindow(self, obj):
parent = obj.parent()
return obj if (self._IsWindow(obj) or not parent) else self.TopLevelWindow(parent)
def WantsNavKeys(self, w):
if not w or self._IsWindow(w):
return False
# The broader test would be QtWidgets.QAbstractItemView,
# but pragmatically, the TableViews in usdview don't really
# benefit much from keyboard navigation, and we'd rather
# allow the arrow keys drive the playhead when such widgets would
# otherwise get focus
elif isinstance(w, QtWidgets.QTreeView):
return True
else:
return self.WantsNavKeys(w.parent())
def NavigableOrTopLevelObject(self, w):
if (not w or
self._IsWindow(w) or
isinstance(w, QtWidgets.QTreeView) or
isinstance(w, QtWidgets.QDialog)):
return w
else:
parent = w.parent()
return w if not parent else self.NavigableOrTopLevelObject(parent)
def JealousFocus(self, w):
return (isinstance(w, QtWidgets.QLineEdit) or
isinstance(w, QtWidgets.QComboBox) or
isinstance(w, QtWidgets.QTextEdit) or
isinstance(w, QtWidgets.QAbstractSlider) or
isinstance(w, QtWidgets.QAbstractSpinBox) or
isinstance(w, QtWidgets.QWidget) and w.windowModality() in [QtCore.Qt.WindowModal,
QtCore.Qt.ApplicationModal])
def SetFocusFromMousePos(self, backupWidget):
# It's possible the mouse isn't over any of our windows at the time,
# in which case use the top-level window of backupWidget.
overObject = QtWidgets.QApplication.widgetAt(QtGui.QCursor.pos())
topLevelObject = self.NavigableOrTopLevelObject(overObject)
focusObject = topLevelObject if topLevelObject else self.TopLevelWindow(backupWidget)
if focusObject and isinstance(focusObject, QtWidgets.QWidget):
focusObject.setFocus()
def eventFilter(self, widget, event):
# There is currently no filtering we want to do for modal or popups
if (QtWidgets.QApplication.activeModalWidget() or
QtWidgets.QApplication.activePopupWidget()):
return False
currFocusWidget = QtWidgets.QApplication.focusWidget()
if event.type() == QtCore.QEvent.KeyPress:
key = event.key()
isNavKey = self.IsNavKey(key, event.modifiers())
if key == QtCore.Qt.Key_Escape:
# ESC resets focus based on mouse position, regardless of
# who currently holds focus
self.SetFocusFromMousePos(widget)
return True
elif currFocusWidget and self.JealousFocus(currFocusWidget):
# Don't touch if there's a greedy focus widget
return False
elif (isNavKey and self.WantsNavKeys(currFocusWidget)):
# Special handling for navigation keys:
# 1. When a "navigable" widget is focussed (a TreeView),
# route arrow keys to the widget and consume them
# 2. To make for snappier navigation, when the TreeView
# won't accept a left/right because an item is already
# opened or closed, turn it into an up/down event. It
# WBN if this behavior could be part of the widgets
# themselves, but currently, usdview does not specialize
# a class for its TreeView widgets.
event.setAccepted(False)
currFocusWidget.event(event)
accepted = event.isAccepted()
if (not accepted and
key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right)):
advance = (key == QtCore.Qt.Key_Right)
altNavKey = QtCore.Qt.Key_Down if advance else QtCore.Qt.Key_Up
subEvent = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
altNavKey,
event.modifiers())
QtWidgets.QApplication.postEvent(currFocusWidget, subEvent)
event.setAccepted(True)
return True
elif isNavKey:
if self._appController.processNavKeyEvent(event):
return True
elif (event.type() == QtCore.QEvent.MouseMove and
not self.JealousFocus(currFocusWidget)):
self.SetFocusFromMousePos(widget)
# Note we do not consume the event!
# During startup, Qt seems to queue up events on objects that may
# have disappeared by the time the eventFilter is called upon. This
# is true regardless of how late we install the eventFilter, and
# whether we process pending events before installing. So we
# silently ignore Runtime errors that occur as a result.
try:
return QtCore.QObject.eventFilter(self, widget, event)
except RuntimeError:
return True
| 8,300 | Python | 46.982659 | 104 | 0.628795 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/pythonInterpreter.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from pxr import Tf
from .qt import QtCore, QtGui, QtWidgets
from .usdviewApi import UsdviewApi
from code import InteractiveInterpreter
import os, sys, keyword
# just a handy debugging method
def _PrintToErr(line):
old = sys.stdout
sys.stdout = sys.__stderr__
print(line)
sys.stdout = old
def _Redirected(method):
def new(self, *args, **kw):
old = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = self, self, self
try:
ret = method(self, *args, **kw)
finally:
sys.stdin, sys.stdout, sys.stderr = old
return ret
return new
class _Completer(object):
"""Taken from rlcompleter, with readline references stripped, and a local
dictionary to use."""
def __init__(self, locals):
self.locals = locals
def Complete(self, text, state):
"""Return the next possible completion for 'text'.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'.
"""
if state == 0:
if "." in text:
self.matches = self._AttrMatches(text)
else:
self.matches = self._GlobalMatches(text)
try:
return self.matches[state]
except IndexError:
return None
def _GlobalMatches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names
currently defines in __main__ that match.
"""
builtin_mod = None
if sys.version_info.major >= 3:
import builtins
builtin_mod = builtins
else:
import __builtin__
builtin_mod = __builtin__
import __main__
matches = set()
n = len(text)
for l in [keyword.kwlist,builtin_mod.__dict__.keys(),
__main__.__dict__.keys(), self.locals.keys()]:
for word in l:
if word[:n] == text and word != "__builtins__":
matches.add(word)
return list(matches)
def _AttrMatches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in the globals of __main__, it will be evaluated
and its attributes (as revealed by dir()) are used as possible
completions. (For class instances, class members are are also
considered.)
WARNING: this can still invoke arbitrary C code, if an object
with a __getattr__ hook is evaluated.
"""
import re, __main__
assert len(text)
# This is all a bit hacky, but that's tab-completion for you.
# Now find the last index in the text of a set of characters, and split
# the string into a prefix and suffix token there. The suffix token
# will be used for completion.
splitChars = ' )(;,+=*/-%!<>'
index = -1
for char in splitChars:
index = max(text.rfind(char), index)
if index >= len(text)-1:
return []
prefix = ''
suffix = text
if index >= 0:
prefix = text[:index+1]
suffix = text[index+1:]
m = re.match(r"([^.]+(\.[^.]+)*)\.(.*)", suffix)
if not m:
return []
expr, attr = m.group(1, 3)
try:
myobject = eval(expr, __main__.__dict__, self.locals)
except (AttributeError, NameError, SyntaxError):
return []
words = set(dir(myobject))
if hasattr(myobject,'__class__'):
words.add('__class__')
words = words.union(set(_GetClassMembers(myobject.__class__)))
words = list(words)
matches = set()
n = len(attr)
for word in words:
if word[:n] == attr and word != "__builtins__":
matches.add("%s%s.%s" % (prefix, expr, word))
return list(matches)
def _GetClassMembers(cls):
ret = dir(cls)
if hasattr(cls, '__bases__'):
for base in cls.__bases__:
ret = ret + _GetClassMembers(base)
return ret
class Interpreter(InteractiveInterpreter):
def __init__(self, locals = None):
InteractiveInterpreter.__init__(self,locals)
self._outputBrush = None
# overridden
def showsyntaxerror(self, filename = None):
self._outputBrush = QtGui.QBrush(QtGui.QColor('#ffcc63'))
try:
InteractiveInterpreter.showsyntaxerror(self, filename)
finally:
self._outputBrush = None
# overridden
def showtraceback(self):
self._outputBrush = QtGui.QBrush(QtGui.QColor('#ff0000'))
try:
InteractiveInterpreter.showtraceback(self)
finally:
self._outputBrush = None
def GetOutputBrush(self):
return self._outputBrush
# Modified from site.py in the Python distribution.
#
# This allows each interpreter editor to have it's own Helper object.
# The built-in pydoc.help grabs sys.stdin and sys.stdout the first time it
# is run and then never lets them go.
class _Helper(object):
"""Define a replacement for the built-in 'help'.
This is a wrapper around pydoc.Helper (with a twist).
"""
def __init__(self, input, output):
import pydoc
self._helper = pydoc.Helper(input, output)
def __repr__(self):
return "Type help() for interactive help, " \
"or help(object) for help about object."
def __call__(self, *args, **kwds):
return self._helper(*args, **kwds)
class Controller(QtCore.QObject):
"""
Controller is a Python shell written using Qt.
This class is a controller between Python and something which acts
like a QTextEdit.
"""
_isAnyReadlineEventLoopActive = False
def __init__(self, textEdit, initialPrompt, locals = None):
"""Constructor.
The optional 'locals' argument specifies the dictionary in
which code will be executed; it defaults to a newly created
dictionary with key "__name__" set to "__console__" and key
"__doc__" set to None.
"""
super(Controller, self).__init__()
self.interpreter = Interpreter(locals)
self.interpreter.locals['help'] = _Helper(self, self)
self.completer = _Completer(self.interpreter.locals)
# last line + last incomplete lines
self.lines = []
# flag: the interpreter needs more input to run the last lines.
self.more = 0
# history
self.history = []
self.historyPointer = None
self.historyInput = ''
# flag: readline() is being used for e.g. raw_input and input().
# We use a nested QEventloop here because we want to emulate
# modeless UI even though the readline protocol requires blocking calls.
self.readlineEventLoop = QtCore.QEventLoop(textEdit)
# interpreter prompt.
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
self.textEdit = textEdit
self.textEdit.destroyed.connect(self._TextEditDestroyedSlot)
self.textEdit.returnPressed.connect(self._ReturnPressedSlot)
self.textEdit.requestComplete.connect(self._CompleteSlot)
self.textEdit.requestNext.connect(self._NextSlot)
self.textEdit.requestPrev.connect(self._PrevSlot)
appInstance = QtWidgets.QApplication.instance()
appInstance.aboutToQuit.connect(self._QuitSlot)
self.textEdit.setTabChangesFocus(False)
self.textEdit.setWordWrapMode(QtGui.QTextOption.WrapAnywhere)
self.textEdit.setWindowTitle('Interpreter')
self.textEdit.promptLength = len(sys.ps1)
# Do initial auto-import.
self._DoAutoImports()
# interpreter banner
self.write('Python %s on %s.\n' % (sys.version, sys.platform))
# Run $PYTHONSTARTUP startup script.
startupFile = os.getenv('PYTHONSTARTUP')
if startupFile:
path = os.path.realpath(os.path.expanduser(startupFile))
if os.path.isfile(path):
self.ExecStartupFile(path)
self.write(initialPrompt)
self.write(sys.ps1)
self.SetInputStart()
def _DoAutoImports(self):
modules = Tf.ScriptModuleLoader().GetModulesDict()
for name, mod in modules.items():
self.interpreter.runsource('import ' + mod.__name__ +
' as ' + name + '\n')
@_Redirected
def ExecStartupFile(self, path):
# fix for bug 9104
# this sets __file__ in the globals dict while we are execing these
# various startup scripts, so that they can access the location from
# which they are being run.
# also, update the globals dict after we exec the file (bug 9529)
self.interpreter.runsource( 'g = dict(globals()); g["__file__"] = ' +
'"%s"; execfile("%s", g);' % (path, path) +
'del g["__file__"]; globals().update(g);' )
self.SetInputStart()
self.lines = []
def SetInputStart(self):
cursor = self.textEdit.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self.textEdit.SetStartOfInput(cursor.position())
def _QuitSlot(self):
if self.readlineEventLoop:
if self.readlineEventLoop.isRunning():
self.readlineEventLoop.Exit()
def _TextEditDestroyedSlot(self):
self.readlineEventLoop = None
def _ReturnPressedSlot(self):
if self.readlineEventLoop.isRunning():
self.readlineEventLoop.Exit()
else:
self._Run()
def flush(self):
"""
Simulate stdin, stdout, and stderr.
"""
pass
def isatty(self):
"""
Simulate stdin, stdout, and stderr.
"""
return 1
def readline(self):
"""
Simulate stdin, stdout, and stderr.
"""
# XXX: Prevent more than one interpreter from blocking on a readline()
# call. Starting more than one subevent loop does not work,
# because they must exit in the order that they were created.
if Controller._isAnyReadlineEventLoopActive:
raise RuntimeError("Simultaneous readline() calls in multiple "
"interpreters are not supported.")
cursor = self.textEdit.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self.SetInputStart()
self.textEdit.setTextCursor(cursor)
try:
Controller._isAnyReadlineEventLoopActive = True
# XXX TODO - Make this suck less if possible. We're invoking a
# subeventloop here, which means until we return from this
# readline we'll never get up to the main event loop. To avoid
# using a subeventloop, we would need to return control to the
# main event loop in the main thread, suspending the execution of
# the code that called into here, which also lives in the main
# thread. This essentially requires a
# co-routine/continuation-based solution capable of dealing with
# an arbitrary stack of interleaved Python/C calls (e.g. greenlet).
self.readlineEventLoop.Exec()
finally:
Controller._isAnyReadlineEventLoopActive = False
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.MoveAnchor)
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.KeepAnchor)
txt = str(cursor.selectedText())
if len(txt) == 0:
return '\n'
else:
self.write('\n')
return txt
@_Redirected
def write(self, text):
'Simulate stdin, stdout, and stderr.'
# Move the cursor to the end of the document
self.textEdit.moveCursor(QtGui.QTextCursor.End)
# Clear any existing text format. We will explicitly set the format
# later to something else if need be.
self.textEdit.ResetCharFormat()
# Copy the textEdit's current cursor.
cursor = self.textEdit.textCursor()
try:
# If there's a designated output brush, merge that character format
# into the cursor's character format.
if self.interpreter.GetOutputBrush():
cf = QtGui.QTextCharFormat()
cf.setForeground(self.interpreter.GetOutputBrush())
cursor.mergeCharFormat(cf)
# Write the text to the textEdit.
cursor.insertText(text)
finally:
# Set the textEdit's cursor to the end of input
self.textEdit.moveCursor(QtGui.QTextCursor.End)
# get the length of a string in pixels bases on our current font
@staticmethod
def _GetStringLengthInPixels(cf, string):
font = cf.font()
fm = QtGui.QFontMetrics(font)
strlen = fm.width(string)
return strlen
def _CompleteSlot(self):
cf = self.textEdit.currentCharFormat()
line = self._GetInputLine()
cursor = self.textEdit.textCursor()
origPos = cursor.position()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.KeepAnchor)
text = str(cursor.selectedText())
tokens = text.split()
token = ''
if len(tokens) != 0:
token = tokens[-1]
completions = []
p = self.completer.Complete(token,len(completions))
while p != None:
completions.append(p)
p = self.completer.Complete(token, len(completions))
if len(completions) == 0:
return
elif len(completions) != 1:
self.write("\n")
contentsRect = self.textEdit.contentsRect()
# get the width inside the margins to eventually determine the
# number of columns in our text table based on the max string width
# of our completed words XXX TODO - paging based on widget height
width = contentsRect.right() - contentsRect.left()
maxLength = 0
for i in completions:
maxLength = max(maxLength, self._GetStringLengthInPixels(cf, i))
# pad it a bit
maxLength = maxLength + self._GetStringLengthInPixels(cf, ' ')
# how many columns can we fit on screen?
numCols = max(1,width // maxLength)
# how many rows do we need to fit our data
numRows = (len(completions) // numCols) + 1
columnWidth = QtGui.QTextLength(QtGui.QTextLength.FixedLength,
maxLength)
tableFormat = QtGui.QTextTableFormat()
tableFormat.setAlignment(QtCore.Qt.AlignLeft)
tableFormat.setCellPadding(0)
tableFormat.setCellSpacing(0)
tableFormat.setColumnWidthConstraints([columnWidth] * numCols)
tableFormat.setBorder(0)
cursor = self.textEdit.textCursor()
# Make the completion table insertion a single edit block
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.End)
textTable = cursor.insertTable(numRows, numCols, tableFormat)
completions.sort()
index = 0
completionsLength = len(completions)
for col in range(0,numCols):
for row in range(0,numRows):
cellNum = (row * numCols) + col
if (cellNum >= completionsLength):
continue
tableCell = textTable.cellAt(row,col)
cellCursor = tableCell.firstCursorPosition()
cellCursor.insertText(completions[index], cf)
index +=1
cursor.endEditBlock()
self.textEdit.setTextCursor(cursor)
self.write("\n")
if self.more:
self.write(sys.ps2)
else:
self.write(sys.ps1)
self.SetInputStart()
# complete up to the common prefix
cp = os.path.commonprefix(completions)
# make sure that we keep everything after the cursor the same as it
# was previously
i = line.rfind(token)
textToRight = line[i+len(token):]
line = line[0:i] + cp + textToRight
self.write(line)
# replace the line and reset the cursor
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput() + len(line) -
len(textToRight))
self.textEdit.setTextCursor(cursor)
else:
i = line.rfind(token)
line = line[0:i] + completions[0] + line[i+len(token):]
# replace the line and reset the cursor
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.MoveAnchor)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.insertText(line)
cursor.setPosition(origPos + len(completions[0]) - len(token))
self.textEdit.setTextCursor(cursor)
def _NextSlot(self):
if len(self.history):
# if we have no history pointer, we can't go forward..
if (self.historyPointer == None):
return
# if we are at the end of our history stack, we can't go forward
elif (self.historyPointer == len(self.history) - 1):
self._ClearLine()
self.write(self.historyInput)
self.historyPointer = None
return
self.historyPointer += 1
self._Recall()
def _PrevSlot(self):
if len(self.history):
# if we have no history pointer, set it to the most recent
# item in the history stack, and stash away our current input
if (self.historyPointer == None):
self.historyPointer = len(self.history)
self.historyInput = self._GetInputLine()
# if we are at the end of our history, beep
elif (self.historyPointer <= 0):
return
self.historyPointer -= 1
self._Recall()
def _IsBlank(self, txt):
return len(txt.strip()) == 0
def _GetInputLine(self):
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.MoveAnchor)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
txt = str(cursor.selectedText())
return txt
def _ClearLine(self):
cursor = self.textEdit.textCursor()
cursor.setPosition(self.textEdit.StartOfInput(),
QtGui.QTextCursor.MoveAnchor)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
@_Redirected
def _Run(self):
"""
Append the last line to the history list, let the interpreter execute
the last line(s), and clean up accounting for the interpreter results:
(1) the interpreter succeeds
(2) the interpreter fails, finds no errors and wants more line(s)
(3) the interpreter fails, finds errors and writes them to sys.stderr
"""
self.historyPointer = None
inputLine = self._GetInputLine()
if (inputLine != ""):
self.history.append(inputLine)
self.lines.append(inputLine)
source = '\n'.join(self.lines)
self.write('\n')
self.more = self.interpreter.runsource(source)
if self.more:
self.write(sys.ps2)
self.SetInputStart()
else:
self.write(sys.ps1)
self.SetInputStart()
self.lines = []
def _Recall(self):
"""
Display the current item from the command history.
"""
self._ClearLine()
self.write(self.history[self.historyPointer])
class View(QtWidgets.QTextEdit):
"""View is a QTextEdit which provides some extra
facilities to help implement an interpreter console. In particular,
QTextEdit does not provide for complete control over the buffer being
edited. Some signals are emitted *after* action has already been
taken, disallowing controller classes from really controlling the widget.
This widget fixes that.
"""
returnPressed = QtCore.Signal()
requestPrev = QtCore.Signal()
requestNext = QtCore.Signal()
requestComplete = QtCore.Signal()
def __init__(self, parent=None):
super(View, self).__init__(parent)
self.promptLength = 0
self.__startOfInput = 0
self.setUndoRedoEnabled(False)
self.setAcceptRichText(False)
self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.tripleClickTimer = QtCore.QBasicTimer()
self.tripleClickPoint = QtCore.QPoint()
self._ignoreKeyPresses = True
self.ResetCharFormat()
def SetStartOfInput(self, position):
self.__startOfInput = position
def StartOfInput(self):
return self.__startOfInput
def ResetCharFormat(self):
charFormat = QtGui.QTextCharFormat()
charFormat.setFontFamily('monospace')
self.setCurrentCharFormat(charFormat)
def _PositionInInputArea(self, position):
return position - self.__startOfInput
def _PositionIsInInputArea(self, position):
return self._PositionInInputArea(position) >= 0
def _CursorIsInInputArea(self):
return self._PositionIsInInputArea(self.textCursor().position())
def _SelectionIsInInputArea(self):
if (not self.textCursor().hasSelection()):
return False
selStart = self.textCursor().selectionStart()
selEnd = self.textCursor().selectionEnd()
return self._PositionIsInInputArea(selStart) and \
self._PositionIsInInputArea(selEnd)
def _MoveCursorToStartOfInput(self, select=False):
cursor = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
cursor.movePosition(QtGui.QTextCursor.End, anchor)
cursor.setPosition(self.__startOfInput, anchor)
self.setTextCursor(cursor)
def _MoveCursorToEndOfInput(self, select=False):
c = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
c.movePosition(QtGui.QTextCursor.End, anchor)
self.setTextCursor(c)
def _WritableCharsToLeftOfCursor(self):
return (self._PositionInInputArea(self.textCursor().position()) > 0)
def mousePressEvent(self, e):
app = QtWidgets.QApplication.instance()
# is this a triple click?
if ((e.button() & QtCore.Qt.LeftButton) and
self.tripleClickTimer.isActive() and
(e.globalPos() - self.tripleClickPoint).manhattanLength() <
app.startDragDistance() ):
# instead of duplicating the triple click code completely, we just
# pass it along. but we modify the selection that comes out of it
# to exclude the prompt, if appropriate
super(View, self).mousePressEvent(e)
if (self._CursorIsInInputArea()):
selStart = self.textCursor().selectionStart()
selEnd = self.textCursor().selectionEnd()
if (self._PositionInInputArea(selStart) < 0):
# remove selection up until start of input
self._MoveCursorToStartOfInput(False)
cursor = self.textCursor()
cursor.setPosition(selEnd, QtGui.QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
else:
super(View, self).mousePressEvent(e)
def mouseDoubleClickEvent(self, e):
super(View, self).mouseDoubleClickEvent(e)
app = QtWidgets.QApplication.instance()
self.tripleClickTimer.start(app.doubleClickInterval(), self)
# make a copy here, otherwise tripleClickPoint will always = globalPos
self.tripleClickPoint = QtCore.QPoint(e.globalPos())
def timerEvent(self, e):
if (e.timerId() == self.tripleClickTimer.timerId()):
self.tripleClickTimer.stop()
else:
super(View, self).timerEvent(e)
def enterEvent(self, e):
self._ignoreKeyPresses = False
def leaveEvent(self, e):
self._ignoreKeyPresses = True
def dragEnterEvent(self, e):
self._ignoreKeyPresses = False
super(View, self).dragEnterEvent(e)
def dragLeaveEvent(self, e):
self._ignoreKeyPresses = True
super(View, self).dragLeaveEvent(e)
def insertFromMimeData(self, source):
if not self._CursorIsInInputArea():
self._MoveCursorToEndOfInput()
if source.hasText():
text = source.text().replace('\r', '')
textLines = text.split('\n')
if (textLines[-1] == ''):
textLines = textLines[:-1]
for i in range(len(textLines)):
line = textLines[i]
cursor = self.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(line)
cursor.movePosition(QtGui.QTextCursor.End)
self.setTextCursor(cursor)
if i < len(textLines) - 1:
self.returnPressed.emit()
def keyPressEvent(self, e):
"""
Handle user input a key at a time.
"""
if (self._ignoreKeyPresses):
e.ignore()
return
key = e.key()
ctrl = e.modifiers() & QtCore.Qt.ControlModifier
alt = e.modifiers() & QtCore.Qt.AltModifier
shift = e.modifiers() & QtCore.Qt.ShiftModifier
cursorInInput = self._CursorIsInInputArea()
selectionInInput = self._SelectionIsInInputArea()
hasSelection = self.textCursor().hasSelection()
canBackspace = self._WritableCharsToLeftOfCursor()
canEraseSelection = selectionInInput and cursorInInput
if key == QtCore.Qt.Key_Backspace:
if (canBackspace and not hasSelection) or canEraseSelection:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Delete:
if (cursorInInput and not hasSelection) or canEraseSelection:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Left:
pos = self._PositionInInputArea(self.textCursor().position())
if pos == 0:
e.ignore()
else:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Right:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter:
# move cursor to end of line.
# emit signal to tell controller enter was pressed.
if not cursorInInput:
self._MoveCursorToStartOfInput(False)
cursor = self.textCursor()
cursor.movePosition(QtGui.QTextCursor.EndOfBlock)
self.setTextCursor(cursor)
# emit returnPressed
self.returnPressed.emit()
elif (key == QtCore.Qt.Key_Up
or key == QtCore.Qt.Key_Down
# support Ctrl+P and Ctrl+N for history
# navigation along with arrows
or (ctrl and (key == QtCore.Qt.Key_P
or key == QtCore.Qt.Key_N))
# support Ctrl+E/End and Ctrl+A/Home for terminal
# style nav. to the ends of the line
or (ctrl and (key == QtCore.Qt.Key_A
or key == QtCore.Qt.Key_E))
or (key == QtCore.Qt.Key_Home
or key == QtCore.Qt.Key_End)):
if cursorInInput:
if (key == QtCore.Qt.Key_Up or key == QtCore.Qt.Key_P):
self.requestPrev.emit()
if (key == QtCore.Qt.Key_Down or key == QtCore.Qt.Key_N):
self.requestNext.emit()
if (key == QtCore.Qt.Key_A or key == QtCore.Qt.Key_Home):
self._MoveCursorToStartOfInput(select=shift)
if (key == QtCore.Qt.Key_E or key == QtCore.Qt.Key_End):
self._MoveCursorToEndOfInput(select=shift)
e.ignore()
else:
super(View, self).keyPressEvent(e)
elif key == QtCore.Qt.Key_Tab:
self.AutoComplete()
e.accept()
elif ((ctrl and key == QtCore.Qt.Key_C) or
(shift and key == QtCore.Qt.Key_Insert)):
# Copy should never move cursor.
super(View, self).keyPressEvent(e)
elif ((ctrl and key == QtCore.Qt.Key_X) or
(shift and key == QtCore.Qt.Key_Delete)):
# Disallow cut from outside the input area so users don't
# affect the scrollback buffer.
if not selectionInInput:
e.ignore()
else:
super(View, self).keyPressEvent(e)
elif (key == QtCore.Qt.Key_Control or
key == QtCore.Qt.Key_Alt or
key == QtCore.Qt.Key_Shift):
# Ignore modifier keypresses by themselves so the cursor
# doesn't jump to the end of input when users begin a
# key combination.
e.ignore()
else:
# All other keypresses should append to the end of input.
if not cursorInInput:
self._MoveCursorToEndOfInput()
super(View, self).keyPressEvent(e)
def AutoComplete(self):
if self._CursorIsInInputArea():
self.requestComplete.emit()
def _MoveCursorToBeginning(self, select=False):
if self._CursorIsInInputArea():
self._MoveCursorToStartOfInput(select)
else:
cursor = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
cursor.setPosition(0, anchor)
self.setTextCursor(cursor)
def _MoveCursorToEnd(self, select=False):
if self._CursorIsInInputArea():
self._MoveCursorToEndOfInput(select)
else:
cursor = self.textCursor()
anchor = QtGui.QTextCursor.MoveAnchor
if (select):
anchor = QtGui.QTextCursor.KeepAnchor
cursor.setPosition(self.__startOfInput, anchor)
cursor.movePosition(QtGui.QTextCursor.Up, anchor)
cursor.movePosition(QtGui.QTextCursor.EndOfLine, anchor)
self.setTextCursor(cursor)
def MoveCursorToBeginning(self):
self._MoveCursorToBeginning(False)
def MoveCursorToEnd(self):
self._MoveCursorToEnd(False)
def SelectToTop(self):
self._MoveCursorToBeginning(True)
def SelectToBottom(self):
self._MoveCursorToEnd(True)
FREQUENTLY_USED = [
"dataModel", "stage", "frame", "prim", "property", "spec", "layer"]
INITIAL_PROMPT = """
Use the `usdviewApi` variable to interact with UsdView.
Type `help(usdviewApi)` to view available API methods and properties.
Frequently used properties:
{}\n""".format(
"".join(" usdviewApi.{} - {}\n".format(
name, getattr(UsdviewApi, name).__doc__)
for name in FREQUENTLY_USED))
class Myconsole(View):
def __init__(self, parent, usdviewApi):
super(Myconsole, self).__init__(parent)
self.setObjectName("Myconsole")
# Inject the UsdviewApi into the interpreter variables.
interpreterLocals = vars()
interpreterLocals["usdviewApi"] = usdviewApi
# Make a Controller.
self._controller = Controller(self, INITIAL_PROMPT, interpreterLocals)
def locals(self):
return self._controller.interpreter.locals
| 33,935 | Python | 34.35 | 80 | 0.590423 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primContextMenuItems.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtGui, QtWidgets
from .usdviewContextMenuItem import UsdviewContextMenuItem
import os
import sys
#
# Edit the following to alter the per-prim context menu.
#
# Every entry should be an object derived from PrimContextMenuItem,
# defined below.
#
def _GetContextMenuItems(appController, item):
return [JumpToEnclosingModelItem(appController, item),
SelectBoundPreviewMaterialMenuItem(appController, item),
SelectBoundFullMaterialMenuItem(appController, item),
SeparatorMenuItem(appController, item),
ToggleVisibilityMenuItem(appController, item),
VisOnlyMenuItem(appController, item),
RemoveVisMenuItem(appController, item),
SeparatorMenuItem(appController, item),
LoadOrUnloadMenuItem(appController, item),
ActiveMenuItem(appController, item),
SeparatorMenuItem(appController, item),
CopyPrimPathMenuItem(appController, item),
CopyModelPathMenuItem(appController, item),
SeparatorMenuItem(appController, item),
IsolateAssetMenuItem(appController, item),
SetAsActiveCamera(appController, item)]
#
# The base class for per-prim context menu items.
#
class PrimContextMenuItem(UsdviewContextMenuItem):
def __init__(self, appController, item):
self._selectionDataModel = appController._dataModel.selection
self._currentFrame = appController._dataModel.currentFrame
self._appController = appController
self._item = item
def IsEnabled(self):
return True
def IsSeparator(self):
return False
def GetText(self):
return ""
def RunCommand(self):
return True
#
# Puts a separator in the context menu
#
class SeparatorMenuItem(PrimContextMenuItem):
def IsSeparator(self):
return True
#
# Replace each selected prim with its enclosing model prim, if it has one,
# in the selection set
#
class JumpToEnclosingModelItem(PrimContextMenuItem):
def IsEnabled(self):
from .common import GetEnclosingModelPrim
for p in self._selectionDataModel.getPrims():
if GetEnclosingModelPrim(p) is not None:
return True
return False
def GetText(self):
return "Jump to Enclosing Model"
def RunCommand(self):
self._appController.selectEnclosingModel()
#
# Replace each selected prim with the "preview" Material it is bound to.
#
class SelectBoundPreviewMaterialMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from pxr import UsdShade
self._boundPreviewMaterial = None
self._bindingRel = None
for p in self._selectionDataModel.getPrims():
(self._boundPreviewMaterial, self._bindingRel) = \
UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial(
UsdShade.Tokens.preview)
if self._boundPreviewMaterial:
break
def IsEnabled(self):
return bool(self._boundPreviewMaterial)
def GetText(self):
if self._boundPreviewMaterial:
isPreviewBindingRel = 'preview' in self._bindingRel.SplitName()
return "Select Bound Preview Material (%s%s)" % (
self._boundPreviewMaterial.GetPrim().GetName(),
"" if isPreviewBindingRel else " from generic binding")
else:
return "Select Bound Preview Material (None)"
def RunCommand(self):
self._appController.selectBoundPreviewMaterial()
#
# Replace each selected prim with the "preview" Material it is bound to.
#
class SelectBoundFullMaterialMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from pxr import UsdShade
self._boundFullMaterial = None
self._bindingRel = None
for p in self._selectionDataModel.getPrims():
(self._boundFullMaterial, self._bindingRel) = \
UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial(
UsdShade.Tokens.full)
if self._boundFullMaterial:
break
def IsEnabled(self):
return bool(self._boundFullMaterial)
def GetText(self):
if self._boundFullMaterial:
isFullBindingRel = 'full' in self._bindingRel.SplitName()
return "Select Bound Full Material (%s%s)" % (
self._boundFullMaterial.GetPrim().GetName(),
"" if isFullBindingRel else " from generic binding")
else:
return "Select Bound Full Material (None)"
def RunCommand(self):
self._appController.selectBoundFullMaterial()
#
# Allows you to activate/deactivate a prim in the graph
#
class ActiveMenuItem(PrimContextMenuItem):
def GetText(self):
if self._selectionDataModel.getFocusPrim().IsActive():
return "Deactivate"
else:
return "Activate"
def RunCommand(self):
active = self._selectionDataModel.getFocusPrim().IsActive()
if active:
self._appController.deactivateSelectedPrims()
else:
self._appController.activateSelectedPrims()
#
# Allows you to vis or invis a prim in the graph, based on its current
# resolved visibility
#
class ToggleVisibilityMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from pxr import UsdGeom
self._imageable = False
self._isVisible = False
for prim in self._selectionDataModel.getPrims():
imgbl = UsdGeom.Imageable(prim)
if imgbl:
self._imageable = True
self._isVisible = (imgbl.ComputeVisibility(self._currentFrame)
== UsdGeom.Tokens.inherited)
break
def IsEnabled(self):
return self._imageable
def GetText(self):
return "Make Invisible" if self._isVisible else "Make Visible"
def RunCommand(self):
if self._isVisible:
self._appController.invisSelectedPrims()
else:
self._appController.visSelectedPrims()
#
# Allows you to vis-only a prim in the graph
#
class VisOnlyMenuItem(PrimContextMenuItem):
def IsEnabled(self):
from pxr import UsdGeom
for prim in self._selectionDataModel.getPrims():
if prim.IsA(UsdGeom.Imageable):
return True
return False
def GetText(self):
return "Vis Only"
def RunCommand(self):
self._appController.visOnlySelectedPrims()
#
# Remove any vis/invis authored on selected prims
#
class RemoveVisMenuItem(PrimContextMenuItem):
def IsEnabled(self):
from .common import HasSessionVis
for prim in self._selectionDataModel.getPrims():
if HasSessionVis(prim):
return True
return False
def GetText(self):
return "Remove Session Visibility"
def RunCommand(self):
self._appController.removeVisSelectedPrims()
#
# Toggle load-state on the selected prims, if loadable
#
class LoadOrUnloadMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from .common import GetPrimsLoadability
# Use the descendent-pruned selection set to avoid redundant
# traversal of the stage to answer isLoaded...
self._loadable, self._loaded = GetPrimsLoadability(
self._selectionDataModel.getLCDPrims())
def IsEnabled(self):
return self._loadable
def GetText(self):
return "Unload" if self._loaded else "Load"
def RunCommand(self):
if self._loaded:
self._appController.unloadSelectedPrims()
else:
self._appController.loadSelectedPrims()
#
# Copies the paths of the currently selected prims to the clipboard
#
class CopyPrimPathMenuItem(PrimContextMenuItem):
def GetText(self):
if len(self._selectionDataModel.getPrims()) > 1:
return "Copy Prim Paths"
return "Copy Prim Path"
def RunCommand(self):
pathlist = [str(p.GetPath())
for p in self._selectionDataModel.getPrims()]
pathStrings = '\n'.join(pathlist)
cb = QtWidgets.QApplication.clipboard()
cb.setText(pathStrings, QtGui.QClipboard.Selection )
cb.setText(pathStrings, QtGui.QClipboard.Clipboard )
#
# Copies the path of the first-selected prim's enclosing model
# to the clipboard, if the prim is inside a model
#
class CopyModelPathMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
from .common import GetEnclosingModelPrim
if len(self._selectionDataModel.getPrims()) == 1:
self._modelPrim = GetEnclosingModelPrim(
self._selectionDataModel.getFocusPrim())
else:
self._modelPrim = None
def IsEnabled(self):
return self._modelPrim
def GetText(self):
name = ( "(%s)" % self._modelPrim.GetName() ) if self._modelPrim else ""
return "Copy Enclosing Model %s Path" % name
def RunCommand(self):
modelPath = str(self._modelPrim.GetPath())
cb = QtWidgets.QApplication.clipboard()
cb.setText(modelPath, QtGui.QClipboard.Selection )
cb.setText(modelPath, QtGui.QClipboard.Clipboard )
#
# Copies the current prim and subtree to a file of the user's choosing
# XXX This is not used, and does not work. Leaving code in for now for
# future reference/inspiration
#
class IsolateCopyPrimMenuItem(PrimContextMenuItem):
def GetText(self):
return "Isolate Copy of Prim..."
def RunCommand(self):
focusPrim = self._selectionDataModel.getFocusPrim()
inFile = focusPrim.GetScene().GetUsdFile()
guessOutFile = os.getcwd() + "/" + focusPrim.GetName() + "_copy.usd"
(outFile, _) = QtWidgets.QFileDialog.getSaveFileName(None,
"Specify the Usd file to create", guessOutFile, 'Usd files (*.usd)')
if (outFile.rsplit('.')[-1] != 'usd'):
outFile += '.usd'
if inFile == outFile:
sys.stderr.write( "Cannot isolate a copy to the source usd!\n" )
return
sys.stdout.write( "Writing copy to new file '%s' ... " % outFile )
sys.stdout.flush()
os.system( 'usdcopy -inUsd ' + inFile +
' -outUsd ' + outFile + ' ' +
' -sourcePath ' + focusPrim.GetPath() + '; ' +
'usdview ' + outFile + ' &')
sys.stdout.write( "Done!\n" )
def IsEnabled(self):
numSelectedPrims = len(self._selectionDataModel.getPrims())
focusPrimActive = self._selectionDataModel.getFocusPrim().GetActive()
return numSelectedPrims == 1 and focusPrimActive
#
# Launches usdview on the asset instantiated at the selected prim, as
# defined by USD assetInfo present on the prim
#
class IsolateAssetMenuItem(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
self._assetName = None
if len(self._selectionDataModel.getPrims()) == 1:
from pxr import Usd
model = Usd.ModelAPI(self._selectionDataModel.getFocusPrim())
name = model.GetAssetName()
identifier = model.GetAssetIdentifier()
if name and identifier:
# Ar API is still settling out...
# from pxr import Ar
# identifier = Ar.GetResolver().Resolve("", identifier.path)
from pxr import Sdf
layer = Sdf.Layer.Find(identifier.path)
if layer:
self._assetName = name
self._filePath = layer.realPath
def IsEnabled(self):
return self._assetName
def GetText(self):
name = ( " '%s'" % self._assetName ) if self._assetName else ""
return "usdview asset%s" % name
def RunCommand(self):
print("Spawning usdview %s" % self._filePath)
os.system("usdview %s &" % self._filePath)
#
# If the selected prim is a camera and not the currently active camera, display
# an enabled menu item to set it as the active camera.
#
class SetAsActiveCamera(PrimContextMenuItem):
def __init__(self, appController, item):
PrimContextMenuItem.__init__(self, appController, item)
self._nonActiveCameraPrim = None
if len(self._selectionDataModel.getPrims()) is 1:
prim = self._selectionDataModel.getPrims()[0]
from pxr import UsdGeom
cam = UsdGeom.Camera(prim)
if cam:
if prim != appController.getActiveCamera():
self._nonActiveCameraPrim = prim
def IsEnabled(self):
return self._nonActiveCameraPrim
def GetText(self):
return "Set As Active Camera"
def RunCommand(self):
self._appController._cameraSelectionChanged(self._nonActiveCameraPrim)
| 14,333 | Python | 31.577273 | 80 | 0.650945 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/plugin.py | #
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import sys
import importlib
from pxr import Tf
from pxr import Plug
from .qt import QtGui
class DuplicateCommandPlugin(Exception):
"""Exception raised when two command plugins are registered with the same
name.
"""
def __init__(self, name):
super(DuplicateCommandPlugin, self).__init__(
("A command plugin with the name '{}' has already been "
"registered.").format(name))
self.name = name
class DeferredImport(object):
"""Defers importing a module until one of the target callable objects is
called for the first time. Note that there is no way to know if a callable
object exists in the target module or even if the target module exists until
import time. All objects that are referenced are assumed to exist until
proven otherwise when they are called (at which point an ImportError is
raised).
Example:
math = DeferredImport("math")
# You can pull as many callable objects from `math` as desired, even if they
# don't actually exist in `math`.
sqrt = math.sqrt
cos = math.cos
foo = math.foo # does not exist in the real `math` module
# The `math` module will only be imported when this next line runs because
# this is the first invocation of a callable object from `math`.
cos(0)
# This will raise an ImportError because `math.foo` doesn't really exist.
foo(0)
"""
def __init__(self, moduleName, packageName=None):
self._moduleName = moduleName
self._packageName = packageName
self._module = None
def __getattr__(self, attr):
"""Returns a function which calls the target function of the module and
passes along any parameters. The module is lazy-imported when a function
returned by this method is called for the first time.
"""
def f(*args, **kwargs):
if self._module is None:
# Try to import the target module.
try:
self._module = importlib.import_module(
self._moduleName, package=self._packageName)
except ImportError:
raise ImportError(
"Failed deferred import: module '{}' not found.".format(
self._moduleName))
# Try to get the target function from the imported module.
try:
moduleFunction = getattr(self._module, attr)
except AttributeError:
raise ImportError(("Failed deferred import: callable object "
" '{}' from module '{}' not found").format(
attr, self._moduleName))
# Module and function loaded successfully. Now we can call the
# function and pass it the parameters.
return moduleFunction(*args, **kwargs)
# Return the deferring function. It will be called at some point after
# this method returns.
return f
class PluginContainer(object):
"""A base class for a container which holds some Usdview plugins. Specific
containers should inherit from this class and define the 'registerPlugins'
and 'configureView' methods.
"""
def deferredImport(self, moduleName):
"""Return a DeferredImport object which can be used to lazy load
functions when they are invoked for the first time.
"""
return DeferredImport(moduleName, self.__module__)
def registerPlugins(self, plugRegistry, plugCtx):
"""This method is called after the container is discovered by Usdview,
and should call 'registerCommandPlugin' one or more times on the
plugRegistry to add commands to Usdview.
"""
raise NotImplementedError
def configureView(self, plugRegistry, plugUIBuilder):
"""This method is called directly after 'registerPlugins' and can be
used to add menus which invoke a plugin command using the plugUIBuilder.
"""
raise NotImplementedError
# We load the PluginContainer using libplug so it needs to be a defined Tf.Type.
PluginContainerTfType = Tf.Type.Define(PluginContainer)
class CommandPlugin(object):
"""A Usdview command plugin object. The plugin's `callback` parameter must
be a callable object which takes a UsdviewApi object as its only parameter.
"""
def __init__(self, name, displayName, callback, description, usdviewApi):
self._name = name
self._displayName = displayName
self._callback = callback
self._usdviewApi = usdviewApi
self._description = description
@property
def name(self):
"""Return the command's name."""
return self._name
@property
def displayName(self):
"""Return the command's display name."""
return self._displayName
@property
def description(self):
"""Return the command description."""
return self._description
def run(self):
"""Run the command's callback function."""
self._callback(self._usdviewApi)
class PluginMenu(object):
"""Object which adds Usdview command plugins to a QMenu."""
def __init__(self, qMenu):
self._qMenu = qMenu
self._submenus = dict()
def addItem(self, commandPlugin, shortcut=None):
"""Add a new command plugin to the menu. Optionally, provide a hotkey/
shortcut.
"""
action = self._qMenu.addAction(commandPlugin.displayName,
lambda: commandPlugin.run())
action.setToolTip(commandPlugin.description)
if shortcut is not None:
action.setShortcut(QtGui.QKeySequence(shortcut))
def findOrCreateSubmenu(self, menuName):
"""Get a PluginMenu object for the submenu with the given name. If no
submenu with the given name exists, it is created.
"""
if menuName in self._submenus:
return self._submenus[menuName]
else:
subQMenu = self._qMenu.addMenu(menuName)
subQMenu.setToolTipsVisible(True)
submenu = PluginMenu(subQMenu)
self._submenus[menuName] = submenu
return submenu
def addSeparator(self):
"""Add a separator to the menu."""
self._qMenu.addSeparator()
class PluginRegistry(object):
"""Manages all plugins loaded by Usdview."""
def __init__(self, usdviewApi):
self._usdviewApi = usdviewApi
self._commandPlugins = dict()
def registerCommandPlugin(self, name, displayName, callback,
description=""):
"""Creates, registers, and returns a new command plugin.
The plugin's `name` parameter is used to find the plugin from the
registry later. It is good practice to prepend the plugin container's
name to the plugin's `name` parameter to avoid duplicate names
(i.e. "MyPluginContainer.myPluginName"). If a duplicate name is found, a
DuplicateCommandPlugin exception will be raised.
The `displayName` parameter is the name displayed to users.
The plugin's `callback` parameter must be a callable object which takes
a UsdviewApi object as its only parameter.
The optional `description` parameter is a short description of what the
command does which can be displayed to users.
"""
plugin = CommandPlugin(name, displayName, callback, description,
self._usdviewApi)
if name in self._commandPlugins:
raise DuplicateCommandPlugin(name)
self._commandPlugins[name] = plugin
return plugin
def getCommandPlugin(self, name):
"""Finds and returns a registered command plugin. If no plugin with the
given name is registered, return None instead.
"""
return self._commandPlugins.get(name, None)
class PluginUIBuilder(object):
"""Used by plugins to construct UI elements in Usdview."""
def __init__(self, mainWindow):
self._mainWindow = mainWindow
self._menus = dict()
def findOrCreateMenu(self, menuName):
"""Get a PluginMenu object for the menu with the given name. If no menu
with the given name exists, it is created.
"""
if menuName in self._menus:
return self._menus[menuName]
else:
qMenu = self._mainWindow.menuBar().addMenu(menuName)
qMenu.setToolTipsVisible(True)
menu = PluginMenu(qMenu)
self._menus[menuName] = menu
return menu
def loadPlugins(usdviewApi, mainWindow):
"""Find and load all Usdview plugins."""
# Find all the defined container types using libplug.
containerTypes = Plug.Registry.GetAllDerivedTypes(
PluginContainerTfType)
# Find all plugins and plugin container types through libplug.
plugins = dict()
for containerType in containerTypes:
plugin = Plug.Registry().GetPluginForType(containerType)
pluginContainerTypes = plugins.setdefault(plugin, [])
pluginContainerTypes.append(containerType)
# Load each plugin in alphabetical order by name. For each plugin, load all
# of its containers in alphabetical order by type name.
allContainers = []
for plugin in sorted(plugins.keys(), key=lambda plugin: plugin.name):
plugin.Load()
pluginContainerTypes = sorted(
plugins[plugin], key=lambda containerType: containerType.typeName)
for containerType in pluginContainerTypes:
if containerType.pythonClass is None:
print(("WARNING: Missing plugin container '{}' from plugin "
"'{}'. Make sure the container is a defined Tf.Type and "
"the container's import path matches the path in "
"plugInfo.json.").format(
containerType.typeName, plugin.name), file=sys.stderr)
continue
container = containerType.pythonClass()
allContainers.append(container)
# No plugins to load, so don't create a registry.
if len(allContainers) == 0:
return None
# Register all plugins from each container. If there is a naming conflict,
# abort plugin initialization.
registry = PluginRegistry(usdviewApi)
for container in allContainers:
try:
container.registerPlugins(registry, usdviewApi)
except DuplicateCommandPlugin as e:
print("WARNING: {}".format(e), file=sys.stderr)
print("Plugins will not be loaded.", file=sys.stderr)
return None
# Allow each plugin to construct UI elements.
uiBuilder = PluginUIBuilder(mainWindow)
for container in allContainers:
container.configureView(registry, uiBuilder)
return registry
| 11,947 | Python | 33.333333 | 80 | 0.652549 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/settings.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
"""A module for persisting usdview settings
"""
from __future__ import print_function
import sys
if sys.version_info.major >= 3:
from pickle import dumps, loads
else:
from cPickle import dumps, loads
def EmitWarning(filePath):
"""Send a warning because the settings file should never fail to load
"""
import traceback
import sys
msg = sys.stderr
print("------------------------------------------------------------", file=msg)
print("WARNING: Unknown problem while trying to access settings:", file=msg)
print("------------------------------------------------------------", file=msg)
print("This message is being sent because the settings file (%s) " \
"could not be read" % filePath, file=msg)
print("--", file=msg)
traceback.print_exc(file=msg)
print("--", file=msg)
print("Please file a bug if this warning persists", file=msg)
print("Attempting to continue... ", file=msg)
print("------------------------------------------------------------", file=msg)
class Settings(dict):
"""A small wrapper around the standard Python dictionary.
See help(dict) for initialization arguments This class uses python naming
conventions, because it inherits from dict.
"""
def __init__(self, filename, seq=None, ephemeral=False, **kwargs):
self._filename = filename
# Ephemeral settings objects are created in the presence of
# file system failures, such as the inability to create a .usdview
# directory to store our settings. In these cases we won't perform
# and save or load operations.
self._ephemeral = ephemeral
if self._ephemeral:
return
if seq:
dict.__init__(self, seq)
elif kwargs:
dict.__init__(self, **kwargs)
def save(self, ignoreErrors=False):
"""Write the settings out to the file at filename
"""
if self._ephemeral:
return
try:
# Explicly specify protocol 0 for cPickle/pickle.dumps to maintain
# backwards compatibility. In Python 2 protocol 0 was the default
# for cPickle.dump, but this changed in Python 3. In pickle.dumps
# the return value is unicode, but we know it contains lower ascii
# because we specify protocol 0, so we need to decode/encode as
# utf-8 to convert to a writable string but that should not change
# the data.
contents = dumps(self, protocol = 0)
with open(self._filename, "w") as f:
f.write(contents.decode('utf-8'))
except:
if ignoreErrors:
return False
raise
return True
def load(self, ignoreErrors=False):
"""Load the settings from the file at filename
"""
if self._ephemeral:
return
try:
# In Python 3, pickle.load will not accept an input file that is
# opened in text mode. Opening in binary won't work on windows
# because of \r\n line endings. Reading in the settings file as
# text and converting to utf-8 should work on all
# platforms/versions.
with open(self._filename, "r") as f:
contents = f.read().encode('utf-8')
self.update(loads(contents))
except:
if ignoreErrors:
return False
raise
return True
def setAndSave(self, **kwargs):
"""Sets keyword arguments as settings and quietly saves
"""
if self._ephemeral:
return
self.update(kwargs)
self.save(ignoreErrors=True)
| 4,791 | Python | 36.4375 | 83 | 0.611981 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/rootDataModel.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Usd, UsdGeom, UsdShade
from .qt import QtCore
from .common import Timer, IncludedPurposes
from .constantGroup import ConstantGroup
class ChangeNotice(ConstantGroup):
NONE = 0
RESYNC = 1
INFOCHANGES = 2
class RootDataModel(QtCore.QObject):
"""Data model providing centralized, moderated access to fundamental
information used throughout Usdview controllers, data models, and plugins.
"""
# Emitted when a new stage is set.
signalStageReplaced = QtCore.Signal()
signalPrimsChanged = QtCore.Signal(ChangeNotice, ChangeNotice)
def __init__(self, printTiming=False):
QtCore.QObject.__init__(self)
self._stage = None
self._printTiming = printTiming
self._currentFrame = Usd.TimeCode.Default()
self._playing = False
self._bboxCache = UsdGeom.BBoxCache(self._currentFrame,
[IncludedPurposes.DEFAULT, IncludedPurposes.PROXY], True)
self._xformCache = UsdGeom.XformCache(self._currentFrame)
self._pcListener = None
@property
def stage(self):
"""Get the current Usd.Stage object."""
return self._stage
@stage.setter
def stage(self, value):
"""Sets the current Usd.Stage object, and emits a signal if it is
different from the previous stage.
"""
validStage = (value is None) or isinstance(value, Usd.Stage)
if not validStage:
raise ValueError("Expected USD Stage, got: {}".format(repr(value)))
if value is not self._stage:
if self._pcListener:
self._pcListener.Revoke()
self._pcListener = None
if value is None:
with Timer() as t:
self._stage = None
if self._printTiming:
t.PrintTime('close stage')
else:
self._stage = value
if self._stage:
from pxr import Tf
self._pcListener = \
Tf.Notice.Register(Usd.Notice.ObjectsChanged,
self.__OnPrimsChanged, self._stage)
self.signalStageReplaced.emit()
def _emitPrimsChanged(self, primChange, propertyChange):
self.signalPrimsChanged.emit(primChange, propertyChange)
def __OnPrimsChanged(self, notice, sender):
primChange = ChangeNotice.NONE
propertyChange = ChangeNotice.NONE
for p in notice.GetResyncedPaths():
if p.IsPrimPath():
primChange = ChangeNotice.RESYNC
if p.IsPropertyPath():
propertyChange = ChangeNotice.RESYNC
if primChange == ChangeNotice.NONE or propertyChange == ChangeNotice.NONE:
for p in notice.GetChangedInfoOnlyPaths():
if p.IsPrimPath() and primChange == ChangeNotice.NONE:
primChange = ChangeNotice.INFOCHANGES
if p.IsPropertyPath() and propertyChange == ChangeNotice.NONE:
propertyChange = ChangeNotice.INFOCHANGES
self._emitPrimsChanged(primChange, propertyChange)
@property
def currentFrame(self):
"""Get a Usd.TimeCode object which represents the current frame being
considered in Usdview."""
return self._currentFrame
@currentFrame.setter
def currentFrame(self, value):
"""Set the current frame to a new Usd.TimeCode object."""
if not isinstance(value, Usd.TimeCode):
raise ValueError("Expected Usd.TimeCode, got: {}".format(value))
self._currentFrame = value
self._bboxCache.SetTime(self._currentFrame)
self._xformCache.SetTime(self._currentFrame)
@property
def playing(self):
return self._playing
@playing.setter
def playing(self, value):
self._playing = value
# XXX This method should be removed after bug 114225 is resolved. Changes to
# the stage will then be used to trigger the caches to be cleared, so
# RootDataModel clients will not even need to know the caches exist.
def _clearCaches(self):
"""Clears internal caches of bounding box and transform data. Should be
called when the current stage is changed in a way which affects this
data."""
self._bboxCache.Clear()
self._xformCache.Clear()
@property
def useExtentsHint(self):
"""Return True if bounding box calculations use extents hints from
prims.
"""
return self._bboxCache.GetUseExtentsHint()
@useExtentsHint.setter
def useExtentsHint(self, value):
"""Set whether whether bounding box calculations should use extents
from prims.
"""
if not isinstance(value, bool):
raise ValueError("useExtentsHint must be of type bool.")
if value != self._bboxCache.GetUseExtentsHint():
# Unfortunate that we must blow the entire BBoxCache, but we have no
# other alternative, currently.
purposes = self._bboxCache.GetIncludedPurposes()
self._bboxCache = UsdGeom.BBoxCache(
self._currentFrame, purposes, value)
@property
def includedPurposes(self):
"""Get the set of included purposes used for bounding box calculations.
"""
return set(self._bboxCache.GetIncludedPurposes())
@includedPurposes.setter
def includedPurposes(self, value):
"""Set a new set of included purposes for bounding box calculations."""
if not isinstance(value, set):
raise ValueError(
"Expected set of included purposes, got: {}".format(
repr(value)))
for purpose in value:
if purpose not in IncludedPurposes:
raise ValueError("Unknown included purpose: {}".format(
repr(purpose)))
self._bboxCache.SetIncludedPurposes(value)
def computeWorldBound(self, prim):
"""Compute the world-space bounds of a prim."""
if not isinstance(prim, Usd.Prim):
raise ValueError("Expected Usd.Prim object, got: {}".format(
repr(prim)))
return self._bboxCache.ComputeWorldBound(prim)
def getLocalToWorldTransform(self, prim):
"""Compute the transformation matrix of a prim."""
if not isinstance(prim, Usd.Prim):
raise ValueError("Expected Usd.Prim object, got: {}".format(
repr(prim)))
return self._xformCache.GetLocalToWorldTransform(prim)
def computeBoundMaterial(self, prim, purpose):
"""Compute the material that the prim is bound to, for the given value
of material purpose.
"""
if not isinstance(prim, Usd.Prim):
raise ValueError("Expected Usd.Prim object, got: {}".format(
repr(prim)))
# We don't use the binding cache yet since it isn't exposed to python.
return UsdShade.MaterialBindingAPI(
prim).ComputeBoundMaterial(purpose)
| 8,129 | Python | 34.194805 | 82 | 0.638578 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/adjustDefaultMaterial.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets
from .adjustDefaultMaterialUI import Ui_AdjustDefaultMaterial
class AdjustDefaultMaterial(QtWidgets.QDialog):
"""Popup widget to adjust the default material used for rendering.
`datamodel` should be a ViewSettingsDataModel.
"""
def __init__(self, parent, dataModel):
QtWidgets.QDialog.__init__(self,parent)
self._ui = Ui_AdjustDefaultMaterial()
self._ui.setupUi(self)
self._dataModel = dataModel
self._ambientCache = None
self._specularCache = None
self._ui.ambientIntSpinBox.valueChanged['double'].connect(self._ambientChanged)
self._ui.specularIntSpinBox.valueChanged['double'].connect(self._specularChanged)
dataModel.signalDefaultMaterialChanged.connect(self._updateFromData)
self._ui.resetButton.clicked[bool].connect(self._reset)
self._ui.doneButton.clicked[bool].connect(self._done)
self._updateFromData()
def _updateFromData(self):
if self._dataModel.defaultMaterialAmbient != self._ambientCache:
self._ambientCache = self._dataModel.defaultMaterialAmbient
self._ui.ambientIntSpinBox.setValue(self._ambientCache)
if self._dataModel.defaultMaterialSpecular != self._specularCache:
self._specularCache = self._dataModel.defaultMaterialSpecular
self._ui.specularIntSpinBox.setValue(self._specularCache)
def _ambientChanged(self, val):
if val != self._ambientCache:
# Must do update cache first to prevent update cycle
self._ambientCache = val
self._dataModel.defaultMaterialAmbient = val
def _specularChanged(self, val):
if val != self._specularCache:
# Must do update cache first to prevent update cycle
self._specularCache = val
self._dataModel.defaultMaterialSpecular = val
def _reset(self, unused):
self._dataModel.resetDefaultMaterial()
def _done(self, unused):
self.close()
def closeEvent(self, event):
event.accept()
# Since the dialog is the immediate-edit kind, we consider
# window-close to be an accept, so our clients can know the dialog is
# done
self.accept()
| 3,333 | Python | 37.321839 | 89 | 0.70087 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/qt.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
def GetPySideModule():
"""Returns name of PySide module used by usdview,
e.g. 'PySide' or 'PySide2'"""
# Inspect objects imported in a UI module generated by uic to determine
# which PySide module they come from (e.g. PySide.QtCore, PySide2.QtCore).
# This insulates the code from assuming that the generated code will
# import something specific.
from . import attributeValueEditorUI
import inspect
for name in dir(attributeValueEditorUI):
obj = getattr(attributeValueEditorUI, name)
module = inspect.getmodule(obj)
if module and module.__name__.startswith('PySide'):
return module.__name__.split('.')[0]
return None
PySideModule = GetPySideModule()
if PySideModule == 'PySide':
from PySide import QtCore, QtGui, QtOpenGL
from PySide import QtGui as QtWidgets
# Patch missing functions to make PySide look like PySide2
if not hasattr(QtGui.QApplication, 'devicePixelRatio'):
QtGui.QApplication.devicePixelRatio = lambda self: 1
if not hasattr(QtOpenGL.QGLWidget, 'devicePixelRatioF'):
QtOpenGL.QGLWidget.devicePixelRatioF = lambda self: 1.0
if not hasattr(QtWidgets.QHeaderView, 'setSectionResizeMode'):
QtWidgets.QHeaderView.setSectionResizeMode = \
QtWidgets.QHeaderView.setResizeMode
if not hasattr(QtGui.QMenu, 'setToolTipsVisible'):
QtGui.QMenu.setToolTipsVisible = lambda self, _: None
if hasattr(QtGui.QWheelEvent, 'delta') \
and not hasattr(QtGui.QWheelEvent, 'angleDelta'):
def angleDelta(self):
return QtCore.QPoint(0, self.delta())
QtGui.QWheelEvent.angleDelta = angleDelta
# Patch missing classes to make PySide look like PySide2
if not hasattr(QtCore, 'QItemSelectionModel'):
QtCore.QItemSelectionModel = QtGui.QItemSelectionModel
if not hasattr(QtCore, 'QStringListModel'):
QtCore.QStringListModel = QtGui.QStringListModel
elif PySideModule == 'PySide2':
from PySide2 import QtCore, QtGui, QtWidgets, QtOpenGL
# Older versions still have QtGui.QStringListModel - this
# is apparently a bug:
# https://bugreports.qt.io/browse/PYSIDE-614
if not hasattr(QtCore, 'QStringListModel'):
QtCore.QStringListModel = QtGui.QStringListModel
else:
raise ImportError('Unrecognized PySide module "{}"'.format(PySideModule))
| 3,467 | Python | 40.285714 | 78 | 0.720508 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/headerContextMenu.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtWidgets
from .usdviewContextMenuItem import UsdviewContextMenuItem
#
# Specialized context menu for adding and removing columns
# in the prim browser and attribute inspector.
#
class HeaderContextMenu(QtWidgets.QMenu):
def __init__(self, parent):
QtWidgets.QMenu.__init__(self, "Columns", parent)
self._menuItems = _GetContextMenuItems(parent)
for menuItem in self._menuItems:
if menuItem.isValid():
# create menu actions. Associate them with each Item, so that
# we can update them when we show, since column visibility can
# change.
action = self.addAction(menuItem.GetText(), menuItem.RunCommand)
action.setCheckable(True)
menuItem.action = action
self.aboutToShow.connect(self._prepForShow)
def _prepForShow(self):
for menuItem in self._menuItems:
if menuItem.action:
menuItem.action.setChecked(menuItem.IsChecked())
menuItem.action.setEnabled(menuItem.IsEnabled())
def _GetContextMenuItems(parent):
# create a list of HeaderContextMenuItem classes
# initialized with the parent object and column
itemList = []
return [HeaderContextMenuItem(parent, column) \
for column in range(parent.columnCount())]
# The base class for header context menus
class HeaderContextMenuItem(UsdviewContextMenuItem):
def __init__(self, parent, column):
self._parent = parent
self._column = column
self._action = None
if isinstance(parent, QtWidgets.QTreeWidget):
self._text = parent.headerItem().text(column)
else:
self._text = parent.horizontalHeaderItem(column).text()
def GetText(self):
# returns the text to be displayed in menu
return self._text
def IsEnabled(self):
# Enable context menu item for columns except the "Name" column.
return 'Name' not in self.GetText()
def IsChecked(self):
# true if the column is visible, false otherwise
return not self._parent.isColumnHidden(self._column)
def RunCommand(self):
# show or hide the column depending on its previous state
self._parent.setColumnHidden(self._column, self.IsChecked())
@property
def action(self):
return self._action
@action.setter
def action(self, action):
self._action = action
| 3,548 | Python | 34.49 | 80 | 0.683484 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/legendUtil.py | #
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# Functionality for expanding and collapsing legend components in usdview
LEGEND_BUTTON_SELECTEDSTYLE = ('background: rgb(189, 155, 84); '
'color: rgb(227, 227, 227);')
# Set the start/end points of an animation
def _SetAnimValues(anim, a1, a2):
anim.setStartValue(a1)
anim.setEndValue(a2)
# A function which takes a two-pane area and transforms it to
# open or close the bottom pane.
#
# legendHeight
# | separator height
# | | browser height
# | | |-> ___________ ___________
# | | | | | | |
# | | | | | | |
# | | |-> | | <---> | |
# |---|-------> +++++++++++++ | |
# | | | <---> | |
# | | | | |
# |-----------> ----------- +++++++++++
def ToggleLegendWithBrowser(legend, button, anim):
legend.ToggleMinimized()
# We are dragging downward, so collapse the legend and expand the
# attribute viewer panel to take up the remaining space.
if legend.IsMinimized():
button.setStyleSheet('')
_SetAnimValues(anim, legend.GetHeight(), 0)
# We are expanding, so do the opposite.
else:
button.setStyleSheet(LEGEND_BUTTON_SELECTEDSTYLE)
_SetAnimValues(anim, legend.GetHeight(), legend.GetResetHeight())
anim.start()
| 2,568 | Python | 39.777777 | 74 | 0.588006 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/adjustDefaultMaterialUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'adjustDefaultMaterialUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_AdjustDefaultMaterial(object):
def setupUi(self, AdjustDefaultMaterial):
if not AdjustDefaultMaterial.objectName():
AdjustDefaultMaterial.setObjectName(u"AdjustDefaultMaterial")
AdjustDefaultMaterial.resize(238, 123)
sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(AdjustDefaultMaterial.sizePolicy().hasHeightForWidth())
AdjustDefaultMaterial.setSizePolicy(sizePolicy)
self.verticalLayout = QVBoxLayout(AdjustDefaultMaterial)
self.verticalLayout.setObjectName(u"verticalLayout")
self.verticalLayout_4 = QVBoxLayout()
self.verticalLayout_4.setObjectName(u"verticalLayout_4")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.horizontalSpacer_4 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(self.horizontalSpacer_4)
self.ambientInt = QLabel(AdjustDefaultMaterial)
self.ambientInt.setObjectName(u"ambientInt")
self.ambientInt.setFocusPolicy(Qt.NoFocus)
self.horizontalLayout.addWidget(self.ambientInt)
self.ambientIntSpinBox = QDoubleSpinBox(AdjustDefaultMaterial)
self.ambientIntSpinBox.setObjectName(u"ambientIntSpinBox")
self.ambientIntSpinBox.setDecimals(1)
self.ambientIntSpinBox.setMaximum(1.000000000000000)
self.ambientIntSpinBox.setSingleStep(0.100000000000000)
self.horizontalLayout.addWidget(self.ambientIntSpinBox)
self.horizontalSpacer_5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(self.horizontalSpacer_5)
self.verticalLayout_4.addLayout(self.horizontalLayout)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.horizontalSpacer_6 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer_6)
self.specularInt = QLabel(AdjustDefaultMaterial)
self.specularInt.setObjectName(u"specularInt")
self.specularInt.setFocusPolicy(Qt.NoFocus)
self.horizontalLayout_2.addWidget(self.specularInt)
self.specularIntSpinBox = QDoubleSpinBox(AdjustDefaultMaterial)
self.specularIntSpinBox.setObjectName(u"specularIntSpinBox")
self.specularIntSpinBox.setDecimals(1)
self.specularIntSpinBox.setMaximum(1.000000000000000)
self.specularIntSpinBox.setSingleStep(0.100000000000000)
self.horizontalLayout_2.addWidget(self.specularIntSpinBox)
self.horizontalSpacer_7 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(self.horizontalSpacer_7)
self.verticalLayout_4.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.resetButton = QPushButton(AdjustDefaultMaterial)
self.resetButton.setObjectName(u"resetButton")
self.resetButton.setAutoDefault(False)
self.horizontalLayout_3.addWidget(self.resetButton)
self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(self.horizontalSpacer_2)
self.doneButton = QPushButton(AdjustDefaultMaterial)
self.doneButton.setObjectName(u"doneButton")
self.horizontalLayout_3.addWidget(self.doneButton)
self.verticalLayout_4.addLayout(self.horizontalLayout_3)
self.verticalLayout.addLayout(self.verticalLayout_4)
self.retranslateUi(AdjustDefaultMaterial)
QMetaObject.connectSlotsByName(AdjustDefaultMaterial)
# setupUi
def retranslateUi(self, AdjustDefaultMaterial):
AdjustDefaultMaterial.setProperty("comment", QCoreApplication.translate("AdjustDefaultMaterial", u"\n"
" Copyright 2017 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
AdjustDefaultMaterial.setWindowTitle(QCoreApplication.translate("AdjustDefaultMaterial", u"Adjust Default Material", None))
self.ambientInt.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Ambient Intensity", None))
self.specularInt.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Specular Intensity", None))
self.resetButton.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Reset", None))
self.doneButton.setText(QCoreApplication.translate("AdjustDefaultMaterial", u"Done", None))
# retranslateUi
| 7,259 | Python | 49.068965 | 131 | 0.635211 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primViewItem.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
from .qt import QtCore, QtGui, QtWidgets
from pxr import Sdf, Usd, UsdGeom
from ._usdviewq import Utils
from .common import UIPrimTypeColors, UIFonts
HALF_DARKER = 150
# Pulled out as a wrapper to facilitate cprofile tracking
def _GetPrimInfo(prim, time):
return Utils.GetPrimInfo(prim, time)
# This class extends QTreeWidgetItem to also contain all the stage
# prim data associated with it and populate itself with that data.
class PrimViewItem(QtWidgets.QTreeWidgetItem):
def __init__(self, prim, appController, primHasChildren):
# Do *not* pass a parent. The client must build the hierarchy.
# This can dramatically improve performance when building a
# large hierarchy.
super(PrimViewItem, self).__init__()
self.prim = prim
self._appController = appController
self._needsPull = True
self._needsPush = True
self._needsChildrenPopulated = primHasChildren
# Initialize these now so loadVis(), _visData() and onClick() can
# use them without worrying if _pull() has been called.
self.imageable = False
self.active = False
# True if this item is an ancestor of a selected item.
self.ancestorOfSelected = False
# If we know we'll have children show a norgie, otherwise don't.
if primHasChildren:
self.setChildIndicatorPolicy(
QtWidgets.QTreeWidgetItem.ShowIndicator)
else:
self.setChildIndicatorPolicy(
QtWidgets.QTreeWidgetItem.DontShowIndicator)
# If this item includes a persistent drawMode widget, it is stored here.
self.drawModeWidget = None
def push(self):
"""Pushes prim data to the UI."""
# Push to UI.
if self._needsPush:
self._needsPush = False
self._pull()
def _pull(self):
"""Extracts and stores prim data."""
if self._needsPull:
# Only do this once.
self._needsPull = False
# Visibility is recursive so the parent must pull before us.
parent = self.parent()
if isinstance(parent, PrimViewItem):
parent._pull()
# Get our prim info.
# To avoid Python overhead, request data in batch from C++.
info = _GetPrimInfo(
self.prim, self._appController._dataModel.currentFrame)
self._extractInfo(info)
self.emitDataChanged()
@staticmethod
def _HasAuthoredDrawMode(prim):
modelAPI = UsdGeom.ModelAPI(prim)
drawModeAttr = modelAPI.GetModelDrawModeAttr()
return drawModeAttr and drawModeAttr.HasAuthoredValue()
def _isComputedDrawModeInherited(self, parentDrawModeIsInherited=None):
"""Returns true if the computed draw mode for this item is inherited
from an authored "model:drawMode" value on an ancestor prim.
"""
if PrimViewItem._HasAuthoredDrawMode(self.prim):
return False
parent = self.prim.GetParent()
while parent and parent.GetPath() != Sdf.Path.absoluteRootPath:
if PrimViewItem._HasAuthoredDrawMode(parent):
return True
# Stop the upward traversal if we know whether the parent's draw
# mode is inherited.
if parentDrawModeIsInherited is not None:
return parentDrawModeIsInherited
parent = parent.GetParent()
return False
def _extractInfo(self, info):
( self.hasArcs,
self.active,
self.imageable,
self.defined,
self.abstract,
self.isInMaster,
self.isInstance,
self.supportsDrawMode,
isVisibilityInherited,
self.visVaries,
self.name,
self.typeName ) = info
parent = self.parent()
parentIsPrimViewItem = isinstance(parent, PrimViewItem)
self.computedVis = parent.computedVis if parentIsPrimViewItem \
else UsdGeom.Tokens.inherited
if self.imageable and self.active:
if isVisibilityInherited:
self.vis = UsdGeom.Tokens.inherited
else:
self.vis = self.computedVis = UsdGeom.Tokens.invisible
# If this is the invisible root item, initialize fallback values for
# the drawMode related parameters.
if not parentIsPrimViewItem:
self.computedDrawMode = ''
self.isDrawModeInherited = False
return
# We don't need to compute drawMode related parameters for primViewItems
# that don't support draw mode.
if not self.supportsDrawMode:
return
self.computedDrawMode = UsdGeom.ModelAPI(self.prim).ComputeModelDrawMode(
parent.computedDrawMode) if parentIsPrimViewItem else ''
parentDrawModeIsInherited = parent.isDrawModeInherited if \
parentIsPrimViewItem else None
self.isDrawModeInherited = self._isComputedDrawModeInherited(
parentDrawModeIsInherited)
def addChildren(self, children):
"""Adds children to the end of this item. This is the only
method clients should call to manage an item's children."""
self._needsChildrenPopulated = False
super(PrimViewItem, self).addChildren(children)
def data(self, column, role):
# All Qt queries that affect the display of this item (label, font,
# color, etc) will come through this method. We set that data
# lazily because it's expensive to do and (for the most part) Qt
# only needs the data for items that are visible.
self.push()
# We report data directly rather than use set...() and letting
# super().data() return it because Qt can be pathological during
# calls to set...() when the item hierarchy is attached to a view,
# making thousands of calls to data().
result = None
if column == 0:
result = self._nameData(role)
elif column == 1:
result = self._typeData(role)
elif column == 2:
result = self._visData(role)
elif column == 3 and self.supportsDrawMode:
result = self._drawModeData(role)
if not result:
result = super(PrimViewItem, self).data(column, role)
return result
def _GetForegroundColor(self):
self.push()
if self.isInstance:
color = UIPrimTypeColors.INSTANCE
elif self.hasArcs:
color = UIPrimTypeColors.HAS_ARCS
elif self.isInMaster:
color = UIPrimTypeColors.MASTER
else:
color = UIPrimTypeColors.NORMAL
return color.color() if self.active else color.color().darker(HALF_DARKER)
def _nameData(self, role):
if role == QtCore.Qt.DisplayRole:
return self.name
elif role == QtCore.Qt.FontRole:
# Abstract prims are also considered defined; since we want
# to distinguish abstract defined prims from non-abstract
# defined prims, we check for abstract first.
if self.abstract:
return UIFonts.ABSTRACT_PRIM
elif not self.defined:
return UIFonts.OVER_PRIM
else:
return UIFonts.DEFINED_PRIM
elif role == QtCore.Qt.ForegroundRole:
return self._GetForegroundColor()
elif role == QtCore.Qt.ToolTipRole:
toolTip = 'Prim'
if len(self.typeName) > 0:
toolTip = self.typeName + ' ' + toolTip
if self.isInMaster:
toolTip = 'Master ' + toolTip
if not self.defined:
toolTip = 'Undefined ' + toolTip
elif self.abstract:
toolTip = 'Abstract ' + toolTip
else:
toolTip = 'Defined ' + toolTip
if not self.active:
toolTip = 'Inactive ' + toolTip
elif self.isInstance:
toolTip = 'Instanced ' + toolTip
if self.hasArcs:
toolTip = toolTip + "<br>Has composition arcs"
return toolTip
else:
return None
def _drawModeData(self, role):
if role == QtCore.Qt.DisplayRole:
return self.computedDrawMode
elif role == QtCore.Qt.FontRole:
return UIFonts.BOLD_ITALIC if self.isDrawModeInherited else \
UIFonts.DEFINED_PRIM
elif role == QtCore.Qt.ForegroundRole:
color = self._GetForegroundColor()
return color.darker(110) if self.isDrawModeInherited else \
color
def _typeData(self, role):
if role == QtCore.Qt.DisplayRole:
return self.typeName
else:
return self._nameData(role)
def _isVisInherited(self):
return self.imageable and self.active and \
self.vis != UsdGeom.Tokens.invisible and \
self.computedVis == UsdGeom.Tokens.invisible
def _visData(self, role):
if role == QtCore.Qt.DisplayRole:
if self.imageable and self.active:
return "I" if self.vis == UsdGeom.Tokens.invisible else "V"
else:
return ""
elif role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignCenter
elif role == QtCore.Qt.FontRole:
return UIFonts.BOLD_ITALIC if self._isVisInherited() \
else UIFonts.BOLD
elif role == QtCore.Qt.ForegroundRole:
fgColor = self._GetForegroundColor()
return fgColor.darker() if self._isVisInherited() \
else fgColor
else:
return None
def needsChildrenPopulated(self):
return self._needsChildrenPopulated
def canChangeVis(self):
if not self.imageable:
print("WARNING: The prim <" + str(self.prim.GetPath()) + \
"> is not imageable. Cannot change visibility.")
return False
elif self.isInMaster:
print("WARNING: The prim <" + str(self.prim.GetPath()) + \
"> is in a master. Cannot change visibility.")
return False
return True
def loadVis(self, inheritedVis, visHasBeenAuthored):
if not (self.imageable and self.active):
return inheritedVis
time = self._appController._dataModel.currentFrame
# If visibility-properties have changed on the stage, then
# we must re-evaluate our variability before deciding whether
# we can avoid re-reading our visibility
visAttr = UsdGeom.Imageable(self.prim).GetVisibilityAttr()
if visHasBeenAuthored:
self.visVaries = visAttr.ValueMightBeTimeVarying()
if not self.visVaries:
self.vis = visAttr.Get(time)
if self.visVaries:
self.vis = visAttr.Get(time)
self.computedVis = UsdGeom.Tokens.invisible \
if self.vis == UsdGeom.Tokens.invisible \
else inheritedVis
self.emitDataChanged()
return self.computedVis
@staticmethod
def propagateDrawMode(item, primView, parentDrawMode='',
parentDrawModeIsInherited=None):
# If this item does not support draw mode, none of its descendants
# can support it. Hence, stop recursion here.
#
# Call push() here to ensure that supportsDrawMode has been populated
# for the item.
item.push()
if not item.supportsDrawMode:
return
from .primTreeWidget import DrawModeWidget
drawModeWidget = item.drawModeWidget
if drawModeWidget:
drawModeWidget.RefreshDrawMode()
else:
modelAPI = UsdGeom.ModelAPI(item.prim)
item.computedDrawMode = modelAPI.ComputeModelDrawMode(parentDrawMode)
item.isDrawModeInherited = item._isComputedDrawModeInherited(
parentDrawModeIsInherited=parentDrawModeIsInherited)
item.emitDataChanged()
# Traverse down to children to update their drawMode.
for child in [item.child(i) for i in range(item.childCount())]:
PrimViewItem.propagateDrawMode(child, primView,
parentDrawMode=item.computedDrawMode,
parentDrawModeIsInherited=item.isDrawModeInherited)
@staticmethod
def propagateVis(item, authoredVisHasChanged=True):
parent = item.parent()
inheritedVis = parent._resetAncestorsRecursive(authoredVisHasChanged) \
if isinstance(parent, PrimViewItem) \
else UsdGeom.Tokens.inherited
# This may be called on the "InvisibleRootItem" that is an ordinary
# QTreeWidgetItem, in which case we need to process its children
# individually
if isinstance(item, PrimViewItem):
item._pushVisRecursive(inheritedVis, authoredVisHasChanged)
else:
for child in [item.child(i) for i in range(item.childCount())]:
child._pushVisRecursive(inheritedVis, authoredVisHasChanged)
def _resetAncestorsRecursive(self, authoredVisHasChanged):
parent = self.parent()
inheritedVis = parent._resetAncestorsRecursive(authoredVisHasChanged) \
if isinstance(parent, PrimViewItem) \
else UsdGeom.Tokens.inherited
return self.loadVis(inheritedVis, authoredVisHasChanged)
def _pushVisRecursive(self, inheritedVis, authoredVisHasChanged):
myComputedVis = self.loadVis(inheritedVis, authoredVisHasChanged)
for child in [self.child(i) for i in range(self.childCount())]:
child._pushVisRecursive(myComputedVis, authoredVisHasChanged)
def setLoaded(self, loaded):
if self.prim.IsMaster():
print("WARNING: The prim <" + str(self.prim.GetPath()) + \
"> is a master prim. Cannot change load state.")
return
if self.prim.IsActive():
if loaded:
self.prim.Load()
else:
self.prim.Unload()
def setVisible(self, visible):
if self.canChangeVis():
UsdGeom.Imageable(self.prim).GetVisibilityAttr().Set(UsdGeom.Tokens.inherited
if visible else UsdGeom.Tokens.invisible)
self.visChanged()
def makeVisible(self):
if self.canChangeVis():
# It is in general not kosher to use an Sdf.ChangeBlock around
# operations at the Usd API level. We have carefully arranged
# (with insider knowledge) to have only "safe" mutations
# happening inside the ChangeBlock. We do this because
# UsdImaging updates itself independently for each
# Usd.Notice.ObjectsChanged it receives. We hope to eliminate
# the performance need for this by addressing bug #121992
from pxr import Sdf
with Sdf.ChangeBlock():
UsdGeom.Imageable(self.prim).MakeVisible()
self.visChanged()
def visChanged(self):
# called when user authors a new visibility value
# we must re-determine if visibility is varying over time
self.loadVis(self.parent().computedVis, True)
def toggleVis(self):
"""Return True if the the prim's visibility state was toggled. """
if self.imageable and self.active:
self.setVisible(self.vis == UsdGeom.Tokens.invisible)
return True
return False
| 16,874 | Python | 38.0625 | 89 | 0.619237 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/adjustClipping.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtCore, QtGui, QtWidgets
from .adjustClippingUI import Ui_AdjustClipping
from .common import FixableDoubleValidator
class AdjustClipping(QtWidgets.QDialog):
"""The dataModel provided to this VC must conform to the following
interface:
Editable properties:
overrideNear (float or None, which indicates the override is disabled)
overrideFar (float or None, which indicates the override is disabled)
Readable properties:
cameraFrustum (Gf.Frustum, or struct that has a Gf.Range1d 'nearFar' member)
Signals:
signalFrustumChanged() - whenever the near/far clipping values
may have changed.
"""
def __init__(self, parent, dataModel):
QtWidgets.QDialog.__init__(self,parent)
self._ui = Ui_AdjustClipping()
self._ui.setupUi(self)
self._dataModel = dataModel
clipRange = self._dataModel.cameraFrustum.nearFar
self._nearCache = self._dataModel.overrideNear or clipRange.min
self._farCache = self._dataModel.overrideFar or clipRange.max
self._dataModel.signalFrustumChanged.connect(self.update)
# When the checkboxes change, we want to update instantly
self._ui.overrideNear.stateChanged.connect(self._overrideNearToggled)
self._ui.overrideFar.stateChanged.connect(self._overrideFarToggled)
# we also want to update the clipping planes as the user is typing
self._ui.nearEdit.textChanged.connect(self._nearChanged)
self._ui.farEdit.textChanged.connect(self._farChanged)
def AddValidation(lineEdit):
dv = FixableDoubleValidator(lineEdit)
dv.setDecimals(3)
dv.setBottom(0)
lineEdit.setValidator(dv)
# Make sure only human-readable doubles can be typed in the text boxes
AddValidation(self._ui.nearEdit)
AddValidation(self._ui.farEdit)
# Set the checkboxes to their initial state
self._ui.overrideNear.setChecked(self._dataModel.overrideNear \
is not None)
self._ui.overrideFar.setChecked(self._dataModel.overrideFar \
is not None)
# load the initial values for the text boxes, but first deactivate them
# if their corresponding checkbox is off.
self._ui.nearEdit.setEnabled(self._ui.overrideNear.isChecked())
self._ui.nearEdit.validator().fixup(str(self._nearCache))
self._ui.farEdit.setEnabled(self._ui.overrideFar.isChecked())
self._ui.farEdit.validator().fixup(str(self._farCache))
def _updateEditorsFromDataModel(self):
"""Read the dataModel-computed clipping planes and put them
in the text boxes when they are deactivated."""
clipRange = self._dataModel.cameraFrustum.nearFar
if (not self._ui.overrideNear.isChecked()) and \
self._nearCache != clipRange.min :
self._nearCache = clipRange.min
nearStr = str(self._nearCache)
self._ui.nearEdit.validator().fixup(nearStr)
if (not self._ui.overrideFar.isChecked()) and \
self._farCache != clipRange.max :
self._farCache = clipRange.max
farStr = str(self._farCache)
self._ui.farEdit.validator().fixup(farStr)
def paintEvent(self, paintEvent):
"""Overridden from base class so we can perform JIT updating
of editors to limit the number of redraws we perform"""
self._updateEditorsFromDataModel()
super(AdjustClipping, self).paintEvent(paintEvent)
def _overrideNearToggled(self, state):
"""Called when the "Override Near" checkbox is toggled"""
self._ui.nearEdit.setEnabled(state)
if state:
self._dataModel.overrideNear = self._nearCache
else:
self._dataModel.overrideNear = None
def _overrideFarToggled(self, state):
"""Called when the "Override Far" checkbox is toggled"""
self._ui.farEdit.setEnabled(state)
if state:
self._dataModel.overrideFar = self._farCache
else:
self._dataModel.overrideFar = None
def _nearChanged(self, text):
"""Called when the Near text box changed. This can happen when we
are updating the value but the widget is actually inactive - don't
do anything in that case."""
if len(text) == 0 or not self._ui.nearEdit.isEnabled():
return
try:
self._dataModel.overrideNear = float(text)
except ValueError:
pass
def _farChanged(self, text):
"""Called when the Far text box changed. This can happen when we
are updating the value but the widget is actually inactive - don't
do anything in that case."""
if len(text) == 0 or not self._ui.farEdit.isEnabled():
return
try:
self._dataModel.overrideFar = float(text)
except ValueError:
pass
def closeEvent(self, event):
# Ensure that even if the dialog doesn't get destroyed right away,
# we'll stop doing work.
self._dataModel.signalFrustumChanged.disconnect(self.update)
event.accept()
# Since the dialog is the immediate-edit kind, we consider
# window-close to be an accept, so our clients can know the dialog is
# done by listening for the finished(int) signal
self.accept()
| 6,576 | Python | 39.850931 | 83 | 0.660128 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/adjustClippingUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'adjustClippingUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_AdjustClipping(object):
def setupUi(self, AdjustClipping):
if not AdjustClipping.objectName():
AdjustClipping.setObjectName(u"AdjustClipping")
AdjustClipping.resize(331, 86)
self.verticalLayout = QVBoxLayout(AdjustClipping)
self.verticalLayout.setObjectName(u"verticalLayout")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.verticalLayout_2 = QVBoxLayout()
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
self.overrideNear = QCheckBox(AdjustClipping)
self.overrideNear.setObjectName(u"overrideNear")
self.overrideNear.setFocusPolicy(Qt.NoFocus)
self.verticalLayout_2.addWidget(self.overrideNear)
self.overrideFar = QCheckBox(AdjustClipping)
self.overrideFar.setObjectName(u"overrideFar")
self.overrideFar.setFocusPolicy(Qt.NoFocus)
self.verticalLayout_2.addWidget(self.overrideFar)
self.horizontalLayout.addLayout(self.verticalLayout_2)
self.verticalLayout_3 = QVBoxLayout()
self.verticalLayout_3.setObjectName(u"verticalLayout_3")
self.nearEdit = QLineEdit(AdjustClipping)
self.nearEdit.setObjectName(u"nearEdit")
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.nearEdit.sizePolicy().hasHeightForWidth())
self.nearEdit.setSizePolicy(sizePolicy)
self.verticalLayout_3.addWidget(self.nearEdit)
self.farEdit = QLineEdit(AdjustClipping)
self.farEdit.setObjectName(u"farEdit")
sizePolicy.setHeightForWidth(self.farEdit.sizePolicy().hasHeightForWidth())
self.farEdit.setSizePolicy(sizePolicy)
self.verticalLayout_3.addWidget(self.farEdit)
self.horizontalLayout.addLayout(self.verticalLayout_3)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(AdjustClipping)
QMetaObject.connectSlotsByName(AdjustClipping)
# setupUi
def retranslateUi(self, AdjustClipping):
AdjustClipping.setProperty("comment", QCoreApplication.translate("AdjustClipping", u"\n"
" Copyright 2016 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
AdjustClipping.setWindowTitle(QCoreApplication.translate("AdjustClipping", u"Adjust Clipping Planes", None))
self.overrideNear.setText(QCoreApplication.translate("AdjustClipping", u"Override Near", None))
self.overrideFar.setText(QCoreApplication.translate("AdjustClipping", u"Override Far", None))
# retranslateUi
| 5,182 | Python | 49.320388 | 116 | 0.578155 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primLegendUI.py | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'primLegendUI.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
class Ui_PrimLegend(object):
def setupUi(self, PrimLegend):
if not PrimLegend.objectName():
PrimLegend.setObjectName(u"PrimLegend")
PrimLegend.resize(438, 131)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(PrimLegend.sizePolicy().hasHeightForWidth())
PrimLegend.setSizePolicy(sizePolicy)
self.primLegendLayoutContainer = QVBoxLayout(PrimLegend)
self.primLegendLayoutContainer.setObjectName(u"primLegendLayoutContainer")
self.primLegendLayout = QGridLayout()
self.primLegendLayout.setObjectName(u"primLegendLayout")
self.primLegendColorHasArcs = QGraphicsView(PrimLegend)
self.primLegendColorHasArcs.setObjectName(u"primLegendColorHasArcs")
self.primLegendColorHasArcs.setMaximumSize(QSize(20, 15))
self.primLegendLayout.addWidget(self.primLegendColorHasArcs, 0, 0, 1, 1)
self.primLegendLabelHasArcs = QLabel(PrimLegend)
self.primLegendLabelHasArcs.setObjectName(u"primLegendLabelHasArcs")
font = QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.primLegendLabelHasArcs.setFont(font)
self.primLegendLayout.addWidget(self.primLegendLabelHasArcs, 0, 1, 1, 1)
self.primLegendColorInstance = QGraphicsView(PrimLegend)
self.primLegendColorInstance.setObjectName(u"primLegendColorInstance")
self.primLegendColorInstance.setMaximumSize(QSize(20, 15))
self.primLegendLayout.addWidget(self.primLegendColorInstance, 0, 2, 1, 1)
self.primLegendLabelInstance = QLabel(PrimLegend)
self.primLegendLabelInstance.setObjectName(u"primLegendLabelInstance")
self.primLegendLabelInstance.setFont(font)
self.primLegendLayout.addWidget(self.primLegendLabelInstance, 0, 3, 1, 1)
self.primLegendColorMaster = QGraphicsView(PrimLegend)
self.primLegendColorMaster.setObjectName(u"primLegendColorMaster")
self.primLegendColorMaster.setMaximumSize(QSize(20, 15))
self.primLegendLayout.addWidget(self.primLegendColorMaster, 0, 4, 1, 1)
self.primLegendLabelMaster = QLabel(PrimLegend)
self.primLegendLabelMaster.setObjectName(u"primLegendLabelMaster")
self.primLegendLabelMaster.setFont(font)
self.primLegendLayout.addWidget(self.primLegendLabelMaster, 0, 5, 1, 1)
self.primLegendColorNormal = QGraphicsView(PrimLegend)
self.primLegendColorNormal.setObjectName(u"primLegendColorNormal")
self.primLegendColorNormal.setMaximumSize(QSize(20, 15))
self.primLegendLayout.addWidget(self.primLegendColorNormal, 0, 6, 1, 1)
self.primLegendLabelNormal = QLabel(PrimLegend)
self.primLegendLabelNormal.setObjectName(u"primLegendLabelNormal")
self.primLegendLabelNormal.setFont(font)
self.primLegendLayout.addWidget(self.primLegendLabelNormal, 0, 7, 1, 1)
self.primLegendLayoutContainer.addLayout(self.primLegendLayout)
self.primLegendLabelContainer = QVBoxLayout()
self.primLegendLabelContainer.setObjectName(u"primLegendLabelContainer")
self.primLegendLabelDimmed = QLabel(PrimLegend)
self.primLegendLabelDimmed.setObjectName(u"primLegendLabelDimmed")
self.primLegendLabelContainer.addWidget(self.primLegendLabelDimmed)
self.primLegendLabelFontsAbstract = QLabel(PrimLegend)
self.primLegendLabelFontsAbstract.setObjectName(u"primLegendLabelFontsAbstract")
self.primLegendLabelContainer.addWidget(self.primLegendLabelFontsAbstract)
self.primLegendLabelFontsUndefined = QLabel(PrimLegend)
self.primLegendLabelFontsUndefined.setObjectName(u"primLegendLabelFontsUndefined")
self.primLegendLabelContainer.addWidget(self.primLegendLabelFontsUndefined)
self.primLegendLabelFontsDefined = QLabel(PrimLegend)
self.primLegendLabelFontsDefined.setObjectName(u"primLegendLabelFontsDefined")
self.primLegendLabelContainer.addWidget(self.primLegendLabelFontsDefined)
self.primLegendLayoutContainer.addLayout(self.primLegendLabelContainer)
self.retranslateUi(PrimLegend)
QMetaObject.connectSlotsByName(PrimLegend)
# setupUi
def retranslateUi(self, PrimLegend):
PrimLegend.setProperty("comment", QCoreApplication.translate("PrimLegend", u"\n"
" Copyright 2017 Pixar \n"
" \n"
" Licensed under the Apache License, Version 2.0 (the \"Apache License\") \n"
" with the following modification; you may not use this file except in \n"
" compliance with the Apache License and the following modification to it: \n"
" Section 6. Trademarks. is deleted and replaced with: \n"
" \n"
" 6. Trademarks. This License does not grant permission to use the trade \n"
" names, trademarks, service marks, or product names of the Licensor \n"
" and its affiliates, except as required to comply with Section 4(c) of \n"
" the License and to reproduce the content of the NOTI"
"CE file. \n"
" \n"
" You may obtain a copy of the Apache License at \n"
" \n"
" http://www.apache.org/licenses/LICENSE-2.0 \n"
" \n"
" Unless required by applicable law or agreed to in writing, software \n"
" distributed under the Apache License with the above modification is \n"
" distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY \n"
" KIND, either express or implied. See the Apache License for the specific \n"
" language governing permissions and limitations under the Apache License. \n"
" ", None))
self.primLegendLabelHasArcs.setText(QCoreApplication.translate("PrimLegend", u"HasArcs", None))
self.primLegendLabelInstance.setText(QCoreApplication.translate("PrimLegend", u"Instance", None))
self.primLegendLabelMaster.setText(QCoreApplication.translate("PrimLegend", u"Master", None))
self.primLegendLabelNormal.setText(QCoreApplication.translate("PrimLegend", u"Normal", None))
self.primLegendLabelDimmed.setText(QCoreApplication.translate("PrimLegend", u"Dimmed colors denote inactive prims", None))
self.primLegendLabelFontsAbstract.setText(QCoreApplication.translate("PrimLegend", u"Normal font indicates abstract prims(class and children)", None))
self.primLegendLabelFontsUndefined.setText(QCoreApplication.translate("PrimLegend", u"Italic font indicates undefined prims(declared with over)", None))
self.primLegendLabelFontsDefined.setText(QCoreApplication.translate("PrimLegend", u"Bold font indicates defined prims(declared with def)", None))
# retranslateUi
| 8,092 | Python | 52.596026 | 160 | 0.652373 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/usdviewContextMenuItem.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
#
# A base class for all context menu items.
# This provides a simple behavior to ensure that a chosen
# context menu item is valid. This helps us avoid a situation
# in which a user right-clicks in an area with no item but still
# receives a context menu.
#
class UsdviewContextMenuItem():
def isValid(self):
''' Menu items which have an invalid internal item are considered invalid.
Header menus don't contain an internal _item attribute, so we
return true in the case of the attribute being undefined.
We use this function to give this state a clearer name.
'''
return not hasattr(self, "_item") or self._item is not None
| 1,748 | Python | 43.846153 | 82 | 0.736842 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/primContextMenu.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from .qt import QtWidgets
from .primContextMenuItems import _GetContextMenuItems
#
# Specialized context menu for prim selection.
#
# It uses the per-prim context menus referenced by the _GetContextMenuItems
# function in primContextMenuItems. To add a new context menu item,
# see comments in that file.
#
class PrimContextMenu(QtWidgets.QMenu):
def __init__(self, parent, item, appController):
QtWidgets.QMenu.__init__(self, parent)
self._menuItems = _GetContextMenuItems(appController, item)
for menuItem in self._menuItems:
if menuItem.IsSeparator():
self.addSeparator()
continue
elif not menuItem.isValid():
continue
action = self.addAction(menuItem.GetText(),
menuItem.RunCommand)
if not menuItem.IsEnabled():
action.setEnabled( False )
| 1,984 | Python | 36.45283 | 75 | 0.703629 |
USwampertor/OmniverseJS/ov/python/pxr/Usdviewq/customAttributes.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Usd, UsdGeom, UsdShade
from .constantGroup import ConstantGroup
class ComputedPropertyNames(ConstantGroup):
"""Names of all available computed properties."""
WORLD_BBOX = "World Bounding Box"
LOCAL_WORLD_XFORM = "Local to World Xform"
RESOLVED_PREVIEW_MATERIAL = "Resolved Preview Material"
RESOLVED_FULL_MATERIAL = "Resolved Full Material"
#
# Edit the following to alter the set of custom attributes.
#
# Every entry should be an object derived from CustomAttribute,
# defined below.
#
def _GetCustomAttributes(currentPrim, rootDataModel):
currentPrimIsImageable = currentPrim.IsA(UsdGeom.Imageable)
# If the currentPrim is imageable or if it is a typeless def, it
# participates in imageable computations.
currentPrimGetsImageableComputations = currentPrim.IsA(UsdGeom.Imageable) \
or not currentPrim.GetTypeName()
if currentPrimGetsImageableComputations:
return [BoundingBoxAttribute(currentPrim, rootDataModel),
LocalToWorldXformAttribute(currentPrim,
rootDataModel),
ResolvedPreviewMaterial(currentPrim, rootDataModel),
ResolvedFullMaterial(currentPrim, rootDataModel)]
return []
#
# The base class for per-prim custom attributes.
#
class CustomAttribute:
def __init__(self, currentPrim, rootDataModel):
self._currentPrim = currentPrim
self._rootDataModel = rootDataModel
def IsVisible(self):
return True
# GetName function to match UsdAttribute API
def GetName(self):
return ""
# Get function to match UsdAttribute API
def Get(self, frame):
return ""
# convenience function to make this look more like a UsdAttribute
def GetTypeName(self):
return ""
# GetPrimPath function to match UsdAttribute API
def GetPrimPath(self):
return self._currentPrim.GetPath()
#
# Displays the bounding box of a prim
#
class BoundingBoxAttribute(CustomAttribute):
def __init__(self, currentPrim, rootDataModel):
CustomAttribute.__init__(self, currentPrim, rootDataModel)
def GetName(self):
return ComputedPropertyNames.WORLD_BBOX
def Get(self, frame):
try:
bbox = self._rootDataModel.computeWorldBound(self._currentPrim)
bbox = bbox.ComputeAlignedRange()
except RuntimeError as err:
bbox = "Invalid: " + str(err)
return bbox
#
# Displays the Local to world xform of a prim
#
class LocalToWorldXformAttribute(CustomAttribute):
def __init__(self, currentPrim, rootDataModel):
CustomAttribute.__init__(self, currentPrim, rootDataModel)
def GetName(self):
return ComputedPropertyNames.LOCAL_WORLD_XFORM
def Get(self, frame):
try:
pwt = self._rootDataModel.getLocalToWorldTransform(self._currentPrim)
except RuntimeError as err:
pwt = "Invalid: " + str(err)
return pwt
class ResolvedBoundMaterial(CustomAttribute):
def __init__(self, currentPrim, rootDataModel, purpose):
CustomAttribute.__init__(self, currentPrim, rootDataModel)
self._purpose = purpose
def GetName(self):
if self._purpose == UsdShade.Tokens.full:
return ComputedPropertyNames.RESOLVED_FULL_MATERIAL
elif self._purpose == UsdShade.Tokens.preview:
return ComputedPropertyNames.RESOLVED_PREVIEW_MATERIAL
else:
raise ValueError("Invalid purpose '{}'.".format(self._purpose))
def Get(self, frame):
try:
(boundMaterial, bindingRel) = \
self._rootDataModel.computeBoundMaterial(self._currentPrim,
self._purpose)
boundMatPath = boundMaterial.GetPrim().GetPath() if boundMaterial \
else "<unbound>"
except RuntimeError as err:
boundMatPath = "Invalid: " + str(err)
return boundMatPath
class ResolvedFullMaterial(ResolvedBoundMaterial):
def __init__(self, currentPrim, rootDataModel):
ResolvedBoundMaterial.__init__(self, currentPrim, rootDataModel,
UsdShade.Tokens.full)
class ResolvedPreviewMaterial(ResolvedBoundMaterial):
def __init__(self, currentPrim, rootDataModel):
ResolvedBoundMaterial.__init__(self, currentPrim, rootDataModel,
UsdShade.Tokens.preview)
class ComputedPropertyFactory:
"""Creates computed properties."""
def __init__(self, rootDataModel):
self._rootDataModel = rootDataModel
def getComputedProperty(self, prim, propName):
"""Create a new computed property from a prim and property name."""
if propName == ComputedPropertyNames.WORLD_BBOX:
return BoundingBoxAttribute(prim, self._rootDataModel)
elif propName == ComputedPropertyNames.LOCAL_WORLD_XFORM:
return LocalToWorldXformAttribute(prim, self._rootDataModel)
elif propName == ComputedPropertyNames.RESOLVED_FULL_MATERIAL:
return ResolvedFullMaterial(prim, self._rootDataModel)
elif propName == ComputedPropertyNames.RESOLVED_PREVIEW_MATERIAL:
return ResolvedPreviewMaterial(prim, self._rootDataModel)
else:
raise ValueError("Cannot create computed property '{}'.".format(
propName))
| 6,465 | Python | 35.325842 | 81 | 0.685538 |
USwampertor/OmniverseJS/ov/python/pxr/Tf/__init__.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
"""
Tf -- Tools Foundation
"""
def PrepareModule(module, result):
"""PrepareModule(module, result) -- Prepare an extension module at import
time. Generally, this should only be called by the __init__.py script for a
module upon loading a boost python module (generally '_LibName.so')."""
# inject into result.
ignore = frozenset(['__name__', '__builtins__',
'__doc__', '__file__', '__path__'])
newModuleName = result.get('__name__')
for key, value in list(module.__dict__.items()):
if not key in ignore:
result[key] = value
# Lie about the module from which value came.
if newModuleName and hasattr(value, '__module__'):
try:
setattr(value, '__module__', newModuleName)
except AttributeError as e:
# The __module__ attribute of Boost.Python.function
# objects is not writable, so we get this exception
# a lot. Just ignore it. We're really only concerned
# about the data objects like enum values and such.
#
pass
def GetCodeLocation(framesUp):
"""Returns a tuple (moduleName, functionName, fileName, lineNo).
To trace the current location of python execution, use GetCodeLocation().
By default, the information is returned at the current stack-frame; thus
info = GetCodeLocation()
will return information about the line that GetCodeLocation() was called
from. One can write:
def genericDebugFacility():
info = GetCodeLocation(1)
# print out data
def someCode():
...
if bad:
genericDebugFacility()
and genericDebugFacility() will get information associated with its caller,
i.e. the function someCode()."""
import sys
f_back = sys._getframe(framesUp).f_back
return (f_back.f_globals['__name__'], f_back.f_code.co_name,
f_back.f_code.co_filename, f_back.f_lineno)
# for some strange reason, this errors out when we try to reload it,
# which is odd since _tf is a DSO and can't be reloaded anyway:
import sys
if "pxr.Tf._tf" not in sys.modules:
from . import _tf
PrepareModule(_tf, locals())
del _tf
del sys
# Need to provide an exception type that tf errors will show up as.
class ErrorException(RuntimeError):
def __init__(self, *args):
RuntimeError.__init__(self, *args)
self.__TfException = True
def __str__(self):
return '\n\t' + '\n\t'.join([str(e) for e in self.args])
__SetErrorExceptionClass(ErrorException)
try:
from . import __DOC
__DOC.Execute(locals())
del __DOC
except Exception:
pass
def Warn(msg, template=""):
"""Issue a warning via the TfDiagnostic system.
At this time, template is ignored.
"""
codeInfo = GetCodeLocation(framesUp=1)
_Warn(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
def Status(msg, verbose=True):
"""Issues a status update to the Tf diagnostic system.
If verbose is True (the default) then information about where in the code
the status update was issued from is included.
"""
if verbose:
codeInfo = GetCodeLocation(framesUp=1)
_Status(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
else:
_Status(msg, "", "", "", 0)
def RaiseCodingError(msg):
"""Raise a coding error to the Tf Diagnostic system."""
codeInfo = GetCodeLocation(framesUp=1)
_RaiseCodingError(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
def RaiseRuntimeError(msg):
"""Raise a runtime error to the Tf Diagnostic system."""
codeInfo = GetCodeLocation(framesUp=1)
_RaiseRuntimeError(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
def Fatal(msg):
"""Raise a fatal error to the Tf Diagnostic system."""
codeInfo = GetCodeLocation(framesUp=1)
_Fatal(msg, codeInfo[0], codeInfo[1], codeInfo[2], codeInfo[3])
class NamedTemporaryFile(object):
"""A named temporary file which keeps the internal file handle closed.
A class which constructs a temporary file(that isn't open) on __enter__,
provides its name as an attribute, and deletes it on __exit__.
Note: The constructor args for this object match those of
python's tempfile.mkstemp() function, and will have the same effect on
the underlying file created."""
def __init__(self, suffix='', prefix='', dir=None, text=False):
# Note that we defer creation until the enter block to
# prevent users from unintentionally creating a bunch of
# temp files that don't get cleaned up.
self._args = (suffix, prefix, dir, text)
def __enter__(self):
from tempfile import mkstemp
from os import close
fd, path = mkstemp(*self._args)
close(fd)
# XXX: We currently only expose the name attribute
# more can be added based on client needs in the future.
self._name = path
return self
def __exit__(self, *args):
import os
os.remove(self.name)
@property
def name(self):
"""The path for the temporary file created."""
return self._name
| 6,386 | Python | 34.681564 | 80 | 0.644065 |
USwampertor/OmniverseJS/ov/python/pxr/Tf/testenv/testTfScriptModuleLoader_Unknown.py | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Tf
# Register this library with a new, previously unknown dependency. Note, we're
# just using 'sys' as the module to load here, which is a lie. It should really
# be this module, but it doesn't matter, and it's not trivial to come up with a
# robust, correct module name for this module.
Tf.ScriptModuleLoader()._RegisterLibrary('Unknown', 'sys',
['NewDynamicDependency'])
# Register the dependency. In this case we use 'sys' just because it saves us
# from creating a real module called NewDynamicDependency.
Tf.ScriptModuleLoader()._RegisterLibrary('NewDynamicDependency', 'sys', [])
# Load dependencies for this module, which includes the
# NewDynamicDependency. This is a reentrant load that will be handled
# immediately by TfScriptModuleLoader.
Tf.ScriptModuleLoader()._LoadModulesForLibrary('Unknown')
| 1,934 | Python | 43.999999 | 80 | 0.751293 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.