add usd-21-11-win64_py39

This commit is contained in:
Sébastien Albert committed 2021-12-07 17:43:55 +01:00
1 parent 41d23e71ba
commit ba5e1f7e67
15684 files changed
+3069957

No files matched your search

+353
View File
@@ -0,0 +1,353 @@
#
# 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
Tf.PreparePythonModule()
import sys, argparse, os
from .qt import QtWidgets, QtCore
from .common import Timer
from .appController import AppController
from pxr import UsdAppUtils
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()
if arg_parse_result.tracePython:
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
UsdAppUtils.rendererArgs.AddCmdlineArgs(parser,
altHelpText=("Which render backend to use (named as it "
"appears in the menu). Use '%s' to "
"turn off Hydra renderers." %
UsdAppUtils.rendererArgs.HYDRA_DISABLED_OPTION_STRING
),
allowHydraDisabled=True)
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 --memstats 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('--tracePython', action='store_true',
dest='tracePython',
help='Enable python trace collection, '
'requires --traceToFile to be set.')
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()
# ConfigureResolverForAsset no longer exists under Ar 2.0; this
# is here for backwards compatibility with Ar 1.0.
if hasattr(r, "ConfigureResolverForAsset"):
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)
# XXX Override HdPrman's defaults using the env var. In the
# future we expect there may be more formal ways to represent
# per-app settings for particular Hydra plugins.
os.environ.setdefault('HD_PRMAN_MAX_SAMPLES', '1024')
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_()
Binary file not shown.
Binary file not shown.
+160
View File
@@ -0,0 +1,160 @@
#
# 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()
Binary file not shown.
+102
View File
@@ -0,0 +1,102 @@
# -*- 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
@@ -0,0 +1,86 @@
#
# 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()
Binary file not shown.
@@ -0,0 +1,144 @@
# -*- 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
File diff suppressed because it is too large. Load diff
Binary file not shown.
+172
View File
@@ -0,0 +1,172 @@
#
# 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
Binary file not shown.
@@ -0,0 +1,245 @@
#
# 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()))
Binary file not shown.
@@ -0,0 +1,129 @@
#
# 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)
Binary file not shown.
@@ -0,0 +1,69 @@
# -*- 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
@@ -0,0 +1,264 @@
#
# 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)
Binary file not shown.
+693
View File
@@ -0,0 +1,693 @@
#
# 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 pxr.UsdUtils.constantsGroup import ConstantsGroup
DEBUG_CLIPPING = "USDVIEWQ_DEBUG_CLIPPING"
class ClearColors(ConstantsGroup):
"""Names of available background colors."""
BLACK = "Black"
DARK_GREY = "Grey (Dark)"
LIGHT_GREY = "Grey (Light)"
WHITE = "White"
class DefaultFontFamily(ConstantsGroup):
"""Names of the default font family and monospace font family to be used
with usdview"""
FONT_FAMILY = "Roboto"
MONOSPACE_FONT_FAMILY = "Roboto Mono"
class HighlightColors(ConstantsGroup):
"""Names of available highlight colors for selected objects."""
WHITE = "White"
YELLOW = "Yellow"
CYAN = "Cyan"
class UIBaseColors(ConstantsGroup):
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(ConstantsGroup):
HAS_ARCS = UIBaseColors.DARK_YELLOW
NORMAL = QtGui.QBrush(QtGui.QColor(227, 227, 227))
INSTANCE = UIBaseColors.LIGHT_SKY_BLUE
PROTOTYPE = QtGui.QBrush(QtGui.QColor(118, 136, 217))
class UIPrimTreeColors(ConstantsGroup):
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(ConstantsGroup):
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(ConstantsGroup):
# 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(ConstantsGroup):
FramingKey = QtCore.Qt.Key_F
class PropertyViewIndex(ConstantsGroup):
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(ConstantsGroup):
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(ConstantsGroup):
ATTRIBUTE = "Attr"
RELATIONSHIP = "Rel"
ATTRIBUTE_WITH_CONNNECTIONS = "Attr_"
RELATIONSHIP_WITH_TARGETS = "Rel_"
TARGET = "Tgt"
CONNECTION = "Conn"
COMPOSED = "Cmp"
class RenderModes(ConstantsGroup):
# 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(ConstantsGroup):
# 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(ConstantsGroup):
# Color correction used when render is presented to screen
# These strings should match HdxColorCorrectionTokens
DISABLED = "disabled"
SRGB = "sRGB"
OPENCOLORIO = "openColorIO"
class PickModes(ConstantsGroup):
# Pick modes
PRIMS = "Prims"
MODELS = "Models"
INSTANCES = "Instances"
PROTOTYPES = "Prototypes"
class SelectionHighlightModes(ConstantsGroup):
# Selection highlight modes
NEVER = "Never"
ONLY_WHEN_PAUSED = "Only when paused"
ALWAYS = "Always"
class CameraMaskModes(ConstantsGroup):
NONE = "none"
PARTIAL = "partial"
FULL = "full"
class IncludedPurposes(ConstantsGroup):
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".
If assetInfo.identifier is not set in any layer, assumes the weakest
layer is the defining layer. We then retrieve the creation time for
the asset by stat'ing the defining 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').get('identifier')
if identifier and identifier.path == assetIdentifier.path:
definingLayer = spec.layer
break
if definingLayer:
definingFile = definingLayer.realPath
else:
definingFile = primStack[-1].layer.realPath
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
Binary file not shown.
+177
View File
@@ -0,0 +1,177 @@
#
# 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 pxr.UsdUtils.constantsGroup import ConstantsGroup
class ComputedPropertyNames(ConstantsGroup):
"""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))
Binary file not shown.
+114
View File
@@ -0,0 +1,114 @@
#
# 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)
Binary file not shown.
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Binary file not shown.
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+85
View File
@@ -0,0 +1,85 @@
#
# 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)
Binary file not shown.
+563
View File
@@ -0,0 +1,563 @@
#
# 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
Binary file not shown.
@@ -0,0 +1,99 @@
#
# 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
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 219 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 243 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

@@ -0,0 +1,219 @@
#
# 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")
Binary file not shown.
+62
View File
@@ -0,0 +1,62 @@
#
# 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()
Binary file not shown.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,66 @@
#
# 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)
Binary file not shown.
+347
View File
@@ -0,0 +1,347 @@
#
# 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
Binary file not shown.
+73
View File
@@ -0,0 +1,73 @@
#
# 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 .preferencesUI import Ui_Preferences
from .common import FixableDoubleValidator
class Preferences(QtWidgets.QDialog):
"""The dataModel provided to this VC must conform to the following
interface:
Editable properties:
fontSize, int
Readable properties:
Signals:
viewSettings.signalSettingChanged() - whenever any view setting
may have changed.
"""
def __init__(self, parent, dataModel):
super(Preferences, self).__init__(parent)
self._ui = Ui_Preferences()
self._ui.setupUi(self)
self._dataModel = dataModel
self._dataModel.viewSettings.signalSettingChanged.connect(self._updateEditorsFromDataModel)
self._muteUpdates = False
# When the checkboxes change, we want to update instantly
self._ui.buttonBox.clicked.connect(self._buttonBoxButtonClicked)
self._updateEditorsFromDataModel()
def _updateEditorsFromDataModel(self):
if self._muteUpdates:
return
self._ui.fontSizeSpinBox.setValue(self._dataModel.viewSettings.fontSize)
self.update()
def _apply(self):
self._muteUpdates = True
self._dataModel.viewSettings.fontSize = self._ui.fontSizeSpinBox.value()
self._muteUpdates = False
def _buttonBoxButtonClicked(self, button):
role = self._ui.buttonBox.buttonRole(button)
Roles = QtWidgets.QDialogButtonBox.ButtonRole
if role == Roles.AcceptRole or role == Roles.ApplyRole:
self._apply()
if role == Roles.AcceptRole or role == Roles.RejectRole:
self.close()
Binary file not shown.
+109
View File
@@ -0,0 +1,109 @@
# -*- 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
+78
View File
@@ -0,0 +1,78 @@
#
# 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
Binary file not shown.
@@ -0,0 +1,52 @@
#
# 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 )
Binary file not shown.
@@ -0,0 +1,439 @@
#
# 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()) == 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)
Binary file not shown.
+99
View File
@@ -0,0 +1,99 @@
#
# 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.primLegendColorPrototype.setScene(graphicsScene)
self._ui.primLegendColorHasArcs.setForegroundBrush(UIPrimTypeColors.HAS_ARCS)
self._ui.primLegendColorNormal.setForegroundBrush(UIPrimTypeColors.NORMAL)
self._ui.primLegendColorInstance.setForegroundBrush(UIPrimTypeColors.INSTANCE)
self._ui.primLegendColorPrototype.setForegroundBrush(UIPrimTypeColors.PROTOTYPE)
legendTextUpdate = lambda t, c: (('<font color=\"%s\">' % c.color().name())
+ t.text() + '</font>')
normalLegend = self._ui.primLegendLabelNormal
normalLegend.setText(legendTextUpdate(normalLegend, UIPrimTypeColors.NORMAL))
prototypeLegend = self._ui.primLegendLabelPrototype
prototypeLegend.setText(legendTextUpdate(prototypeLegend, UIPrimTypeColors.PROTOTYPE))
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()
Binary file not shown.
+150
View File
@@ -0,0 +1,150 @@
# -*- 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.primLegendColorPrototype = QGraphicsView(PrimLegend)
self.primLegendColorPrototype.setObjectName(u"primLegendColorPrototype")
self.primLegendColorPrototype.setMaximumSize(QSize(20, 15))
self.primLegendLayout.addWidget(self.primLegendColorPrototype, 0, 4, 1, 1)
self.primLegendLabelPrototype = QLabel(PrimLegend)
self.primLegendLabelPrototype.setObjectName(u"primLegendLabelPrototype")
self.primLegendLabelPrototype.setFont(font)
self.primLegendLayout.addWidget(self.primLegendLabelPrototype, 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.primLegendLabelPrototype.setText(QCoreApplication.translate("PrimLegend", u"Prototype", 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
+511
View File
@@ -0,0 +1,511 @@
#
# 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 pxr.UsdUtils.constantsGroup import ConstantsGroup
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(ConstantsGroup):
NAME, TYPE, VIS, DRAWMODE = range(4)
class DrawModes(ConstantsGroup):
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()
Binary file not shown.
+431
View File
@@ -0,0 +1,431 @@
#
# 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.isInPrototype,
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.isInPrototype:
color = UIPrimTypeColors.PROTOTYPE
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.isInPrototype:
toolTip = 'Prototype ' + 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.isInPrototype:
print("WARNING: The prim <" + str(self.prim.GetPath()) + \
"> is in a prototype. 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.IsPrototype():
print("WARNING: The prim <" + str(self.prim.GetPath()) + \
"> is a prototype 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
Binary file not shown.
+129
View File
@@ -0,0 +1,129 @@
#
# 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()
Binary file not shown.
+406
View File
@@ -0,0 +1,406 @@
# -*- 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
@@ -0,0 +1,960 @@
#
# 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 .common import DefaultFontFamily
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(DefaultFontFamily.MONOSPACE_FONT_FAMILY)
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
Binary file not shown.
+83
View File
@@ -0,0 +1,83 @@
#
# 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))
Binary file not shown.
+230
View File
@@ -0,0 +1,230 @@
#
# 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 pxr.UsdUtils.constantsGroup import ConstantsGroup
class ChangeNotice(ConstantsGroup):
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.IsAbsoluteRootOrPrimPath():
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)
Binary file not shown.
+137
View File
@@ -0,0 +1,137 @@
#
# 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)
Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.
+127
View File
@@ -0,0 +1,127 @@
#
# 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)
Binary file not shown.
+261
View File
@@ -0,0 +1,261 @@
#
# 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
Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.
+222
View File
@@ -0,0 +1,222 @@
#!/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)
Binary file not shown.
Loaded 100 of 15684 files, more files were not shown because too many files have changed in this diff. Show more